| 1 | // Copyright (c) 2017-2022, The Monero Project |
| 2 | // |
| 3 | // All rights reserved. |
| 4 | // |
| 5 | // Redistribution and use in source and binary forms, with or without modification, are |
| 6 | // permitted provided that the following conditions are met: |
| 7 | // |
| 8 | // 1. Redistributions of source code must retain the above copyright notice, this list of |
| 9 | // conditions and the following disclaimer. |
| 10 | // |
| 11 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list |
| 12 | // of conditions and the following disclaimer in the documentation and/or other |
| 13 | // materials provided with the distribution. |
| 14 | // |
| 15 | // 3. Neither the name of the copyright holder nor the names of its contributors may be |
| 16 | // used to endorse or promote products derived from this software without specific |
| 17 | // prior written permission. |
| 18 | // |
| 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 20 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 21 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 22 | // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 24 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 25 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |
| 26 | // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF |
| 27 | // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 28 | // |
| 29 | |
| 30 | #ifndef MONERO_DEVICE_TREZOR_BASE_H |
| 31 | #define MONERO_DEVICE_TREZOR_BASE_H |
| 32 | |
| 33 | |
| 34 | #include <cstddef> |
| 35 | #include <string> |
| 36 | #include <type_traits> |
| 37 | #include "device/device.hpp" |
| 38 | #include "device/device_default.hpp" |
| 39 | #include "device/device_cold.hpp" |
| 40 | #include <boost/scope_exit.hpp> |
| 41 | #include <boost/thread/mutex.hpp> |
| 42 | #include <boost/thread/recursive_mutex.hpp> |
| 43 | #include "cryptonote_config.h" |
| 44 | #include "trezor.hpp" |
| 45 | |
| 46 | #ifdef WITH_TREZOR_DEBUGGING |
| 47 | #include "trezor/debug_link.hpp" |
| 48 | #endif |
| 49 | |
| 50 | //automatic lock one more level on device ensuring the current thread is allowed to use it |
| 51 | #define TREZOR_AUTO_LOCK_CMD() \ |
| 52 | /* lock both mutexes without deadlock*/ \ |
| 53 | boost::lock(device_locker, command_locker); \ |
| 54 | /* make sure both already-locked mutexes are unlocked at the end of scope */ \ |
| 55 | boost::lock_guard<boost::recursive_mutex> lock1(device_locker, boost::adopt_lock); \ |
| 56 | boost::lock_guard<boost::mutex> lock2(command_locker, boost::adopt_lock) |
| 57 | |
| 58 | #define TREZOR_AUTO_LOCK_DEVICE() boost::lock_guard<boost::recursive_mutex> lock1_device(device_locker) |
| 59 | |
| 60 | namespace hw { |
| 61 | namespace trezor { |
| 62 | |
| 63 | #ifdef WITH_DEVICE_TREZOR |
| 64 | class device_trezor_base; |
| 65 | |
| 66 | #ifdef WITH_TREZOR_DEBUGGING |
| 67 | class trezor_debug_callback : public hw::i_device_callback { |
| 68 | public: |
| 69 | trezor_debug_callback()=default; |
| 70 | explicit trezor_debug_callback(std::shared_ptr<Transport> & debug_transport); |
| 71 | |
| 72 | void on_button_request(uint64_t code=0) override; |
| 73 | boost::optional<epee::wipeable_string> on_pin_request() override; |
| 74 | boost::optional<epee::wipeable_string> on_passphrase_request(bool & on_device) override; |
| 75 | void on_passphrase_state_request(const std::string &state); |
| 76 | void on_disconnect(); |
| 77 | protected: |
| 78 | std::shared_ptr<DebugLink> m_debug_link; |
| 79 | }; |
| 80 | |
| 81 | #endif |
| 82 | |
| 83 | /** |
| 84 | * TREZOR device template with basic functions |
| 85 | */ |
| 86 | class device_trezor_base : public hw::core::device_default { |
| 87 | protected: |
| 88 | |
| 89 | // Locker for concurrent access |
| 90 | mutable boost::recursive_mutex device_locker; |
| 91 | mutable boost::mutex command_locker; |
| 92 | |
| 93 | std::shared_ptr<Transport> m_transport; |
| 94 | i_device_callback * m_callback; |
| 95 | |
| 96 | std::string m_full_name; |
| 97 | std::vector<unsigned int> m_wallet_deriv_path; |
| 98 | epee::wipeable_string m_device_session_id; // returned after passphrase entry, session |
| 99 | std::shared_ptr<messages::management::Features> m_features; // features from the last device reset |
| 100 | boost::optional<epee::wipeable_string> m_pin; |
| 101 | boost::optional<epee::wipeable_string> m_passphrase; |
| 102 | messages::MessageType m_last_msg_type; |
| 103 | |
| 104 | cryptonote::network_type network_type; |
| 105 | bool m_reply_with_empty_passphrase; |
| 106 | bool m_always_use_empty_passphrase; |
| 107 | bool m_seen_passphrase_entry_message; |
| 108 | |
| 109 | #ifdef WITH_TREZOR_DEBUGGING |
| 110 | std::shared_ptr<trezor_debug_callback> m_debug_callback; |
| 111 | bool m_debug; |
| 112 | |
| 113 | void setup_debug(); |
| 114 | #endif |
| 115 | |
| 116 | // |
| 117 | // Internal methods |
| 118 | // |
| 119 | |
| 120 | void require_connected() const; |
| 121 | void require_initialized() const; |
| 122 | void call_ping_unsafe(); |
| 123 | void test_ping(); |
| 124 | virtual void device_state_initialize_unsafe(); |
| 125 | void ensure_derivation_path() noexcept; |
| 126 | |
| 127 | // Communication methods |
| 128 | |
| 129 | void write_raw(const google::protobuf::Message * msg); |
| 130 | GenericMessage read_raw(); |
| 131 | GenericMessage call_raw(const google::protobuf::Message * msg); |
| 132 | |
| 133 | // Trezor message protocol handler. Handles specific signalling messages. |
| 134 | bool message_handler(GenericMessage & input); |
| 135 | |
| 136 | /** |
| 137 | * Client communication wrapper, handles specific Trezor protocol. |
| 138 | * |
| 139 | * @throws UnexpectedMessageException if the response message type is different than expected. |
| 140 | * Exception contains message type and the message itself. |
| 141 | */ |
| 142 | template<class t_message=google::protobuf::Message> |
| 143 | std::shared_ptr<t_message> |
| 144 | client_exchange(const std::shared_ptr<const google::protobuf::Message> &req, |
| 145 | const boost::optional<messages::MessageType> & resp_type = boost::none, |
| 146 | const boost::optional<std::vector<messages::MessageType>> & resp_types = boost::none, |
| 147 | const boost::optional<messages::MessageType*> & resp_type_ptr = boost::none, |
| 148 | bool open_session = false) |
| 149 | { |
| 150 | // Require strictly protocol buffers response in the template. |
| 151 | static_assert(std::is_base_of<google::protobuf::Message, t_message>::value); |
| 152 | const bool accepting_base = boost::is_same<google::protobuf::Message, t_message>::value; |
| 153 | if (resp_types && !accepting_base){ |
| 154 | throw std::invalid_argument("Cannot specify list of accepted types and not using generic response"); |
| 155 | } |
| 156 | |
| 157 | // Determine type of expected message response |
| 158 | const messages::MessageType required_type = accepting_base ? messages::MessageType_Success : |
| 159 | (resp_type ? resp_type.get() : MessageMapper::get_message_wire_number<t_message>()); |
| 160 | |
| 161 | // Open session if required |
| 162 | if (open_session){ |
| 163 | try { |
| 164 | m_transport->open(); |
| 165 | } catch (const std::exception& e) { |
| 166 | std::throw_with_nested(exc::SessionException("Could not open session")); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | // Scoped session closer |
| 171 | BOOST_SCOPE_EXIT_ALL(&, this) { |
| 172 | if (open_session && this->get_transport()){ |
| 173 | this->get_transport()->close(); |
| 174 | } |
| 175 | }; |
| 176 | |
| 177 | // Write/read the request |
| 178 | CHECK_AND_ASSERT_THROW_MES(req, "Request is null"); |
| 179 | auto msg_resp = call_raw(req.get()); |
| 180 | |
| 181 | bool processed = false; |
| 182 | do { |
| 183 | processed = message_handler(msg_resp); |
| 184 | } while(processed); |
| 185 | |
| 186 | // Response section |
| 187 | if (resp_type_ptr){ |
| 188 | *(resp_type_ptr.get()) = msg_resp.m_type; |
| 189 | } |
| 190 | |
| 191 | if (msg_resp.m_type == messages::MessageType_Failure) { |
| 192 | throw_failure_exception(dynamic_cast<messages::common::Failure *>(msg_resp.m_msg.get())); |
| 193 | |
| 194 | } else if (!accepting_base && msg_resp.m_type == required_type) { |
| 195 | return message_ptr_retype<t_message>(msg_resp.m_msg); |
| 196 | |
| 197 | } else if (accepting_base && (!resp_types || |
| 198 | std::find(resp_types.get().begin(), resp_types.get().end(), msg_resp.m_type) != resp_types.get().end())) { |
| 199 | return message_ptr_retype<t_message>(msg_resp.m_msg); |
| 200 | |
| 201 | } else { |
| 202 | throw exc::UnexpectedMessageException(msg_resp.m_type, msg_resp.m_msg); |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | /** |
| 207 | * Utility method to set address_n and network type to the message requets. |
| 208 | */ |
| 209 | template<class t_message> |
| 210 | void set_msg_addr(t_message * msg, |
| 211 | const boost::optional<std::vector<uint32_t>> & path = boost::none, |
| 212 | const boost::optional<cryptonote::network_type> & network_type = boost::none) |
| 213 | { |
| 214 | CHECK_AND_ASSERT_THROW_MES(msg, "Message is null"); |
| 215 | msg->clear_address_n(); |
| 216 | if (path){ |
| 217 | for(auto x : path.get()){ |
| 218 | msg->add_address_n(x); |
| 219 | } |
| 220 | } else { |
| 221 | ensure_derivation_path(); |
| 222 | for (unsigned int i : DEFAULT_BIP44_PATH) { |
| 223 | msg->add_address_n(i); |
| 224 | } |
| 225 | for (unsigned int i : m_wallet_deriv_path) { |
| 226 | msg->add_address_n(i); |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | if (network_type){ |
| 231 | msg->set_network_type(static_cast<uint32_t>(network_type.get())); |
| 232 | } else { |
| 233 | msg->set_network_type(static_cast<uint32_t>(this->network_type)); |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | public: |
| 238 | device_trezor_base(); |
| 239 | ~device_trezor_base() override; |
| 240 | |
| 241 | device_trezor_base(const device_trezor_base &device) = delete ; |
| 242 | device_trezor_base& operator=(const device_trezor_base &device) = delete; |
| 243 | |
| 244 | explicit operator bool() const override {return true;} |
| 245 | device_type get_type() const override {return device_type::TREZOR;}; |
| 246 | |
| 247 | bool reset(); |
| 248 | |
| 249 | // Default derivation path for Monero |
| 250 | static const uint32_t DEFAULT_BIP44_PATH[2]; |
| 251 | |
| 252 | std::shared_ptr<Transport> get_transport(){ |
| 253 | return m_transport; |
| 254 | } |
| 255 | |
| 256 | void set_callback(i_device_callback * callback) override { |
| 257 | m_callback = callback; |
| 258 | } |
| 259 | |
| 260 | i_device_callback * get_callback(){ |
| 261 | return m_callback; |
| 262 | } |
| 263 | |
| 264 | std::shared_ptr<messages::management::Features> & get_features() { |
| 265 | return m_features; |
| 266 | } |
| 267 | |
| 268 | uint64_t get_version() const { |
| 269 | CHECK_AND_ASSERT_THROW_MES(m_features, "Features not loaded"); |
| 270 | CHECK_AND_ASSERT_THROW_MES(m_features->has_major_version() && m_features->has_minor_version() && m_features->has_patch_version(), "Invalid Trezor firmware version information"); |
| 271 | return pack_version(m_features->major_version(), m_features->minor_version(), m_features->patch_version()); |
| 272 | } |
| 273 | |
| 274 | void set_derivation_path(const std::string &deriv_path) override; |
| 275 | |
| 276 | virtual bool has_ki_live_refresh(void) const override { return false; } |
| 277 | |
| 278 | virtual void set_pin(const epee::wipeable_string & pin) override { |
| 279 | m_pin = pin; |
| 280 | } |
| 281 | virtual void set_passphrase(const epee::wipeable_string & passphrase) override { |
| 282 | m_passphrase = passphrase; |
| 283 | } |
| 284 | |
| 285 | /* ======================================================================= */ |
| 286 | /* SETUP/TEARDOWN */ |
| 287 | /* ======================================================================= */ |
| 288 | bool set_name(const std::string &name) override; |
| 289 | |
| 290 | const std::string get_name() const override; |
| 291 | bool init() override; |
| 292 | bool release() override; |
| 293 | bool connect() override; |
| 294 | bool disconnect() override; |
| 295 | |
| 296 | /* ======================================================================= */ |
| 297 | /* LOCKER */ |
| 298 | /* ======================================================================= */ |
| 299 | void lock() override; |
| 300 | void unlock() override; |
| 301 | bool try_lock() override; |
| 302 | |
| 303 | /* ======================================================================= */ |
| 304 | /* TREZOR PROTOCOL */ |
| 305 | /* ======================================================================= */ |
| 306 | |
| 307 | /** |
| 308 | * Device ping, no-throw |
| 309 | */ |
| 310 | bool ping(); |
| 311 | |
| 312 | /** |
| 313 | * Performs Initialize call to the Trezor, resets to known state. |
| 314 | */ |
| 315 | void device_state_reset(); |
| 316 | |
| 317 | // Protocol callbacks |
| 318 | void on_button_request(GenericMessage & resp, const messages::common::ButtonRequest * msg); |
| 319 | void on_button_pressed(); |
| 320 | void on_pin_request(GenericMessage & resp, const messages::common::PinMatrixRequest * msg); |
| 321 | void on_passphrase_request(GenericMessage & resp, const messages::common::PassphraseRequest * msg); |
| 322 | void on_passphrase_state_request(GenericMessage & resp, const messages::common::Deprecated_PassphraseStateRequest * msg); |
| 323 | |
| 324 | #ifdef WITH_TREZOR_DEBUGGING |
| 325 | void set_debug(bool debug){ |
| 326 | m_debug = debug; |
| 327 | } |
| 328 | |
| 329 | void set_debug_callback(std::shared_ptr<trezor_debug_callback> & debug_callback){ |
| 330 | m_debug_callback = debug_callback; |
| 331 | } |
| 332 | |
| 333 | void wipe_device(); |
| 334 | void init_device(); |
| 335 | void load_device(const std::string & mnemonic, const std::string & pin="", bool passphrase_protection=false, |
| 336 | const std::string & label="test", const std::string & language="english", |
| 337 | bool skip_checksum=false, bool expand=false); |
| 338 | |
| 339 | #endif |
| 340 | }; |
| 341 | |
| 342 | #endif |
| 343 | |
| 344 | } |
| 345 | } |
| 346 | #endif //MONERO_DEVICE_TREZOR_BASE_H |