Debian Codegraph @

monero/src/device_trezor/device_trezor_base.cpp

raw symbols SCIP
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 #include "device_trezor_base.hpp"
31 #include "memwipe.h"
32 #include <boost/algorithm/string/classification.hpp>
33 #include <boost/algorithm/string/split.hpp>
34 #include <boost/algorithm/string/predicate.hpp>
35 #include <boost/regex.hpp>
36
37 namespace hw {
38 namespace trezor {
39
40 #ifdef WITH_DEVICE_TREZOR
41
42 #undef MONERO_DEFAULT_LOG_CATEGORY
43 #define MONERO_DEFAULT_LOG_CATEGORY "device.trezor"
44 #define TREZOR_BIP44_HARDENED_ZERO 0x80000000
45
46 const uint32_t device_trezor_base::DEFAULT_BIP44_PATH[] = {0x8000002c, 0x80000080};
47
48 device_trezor_base::device_trezor_base(): m_callback(nullptr), m_last_msg_type(messages::MessageType_Success),
49 m_reply_with_empty_passphrase(false),
50 m_always_use_empty_passphrase(false),
51 m_seen_passphrase_entry_message(false) {
52 #ifdef WITH_TREZOR_DEBUGGING
53 m_debug = false;
54 #endif
55 }
56
57 device_trezor_base::~device_trezor_base() {
58 try {
59 disconnect();
60 release();
61 } catch(std::exception const& e){
62 MERROR("Could not disconnect and release: " << e.what());
63 }
64 }
65
66 /* ======================================================================= */
67 /* SETUP/TEARDOWN */
68 /* ======================================================================= */
69
70 bool device_trezor_base::reset() {
71 return false;
72 }
73
74 bool device_trezor_base::set_name(const std::string & name) {
75 this->m_full_name = name;
76 this->name = "";
77
78 auto delim = name.find(':');
79 if (delim != std::string::npos && delim + 1 < name.length()) {
80 this->name = name.substr(delim + 1);
81 }
82
83 return true;
84 }
85
86 const std::string device_trezor_base::get_name() const {
87 if (this->m_full_name.empty()) {
88 return std::string("<disconnected:").append(this->name).append(">");
89 }
90 return this->m_full_name;
91 }
92
93 bool device_trezor_base::init() {
94 if (!release()){
95 MERROR("Release failed");
96 return false;
97 }
98
99 return true;
100 }
101
102 bool device_trezor_base::release() {
103 try {
104 disconnect();
105 return true;
106
107 } catch(std::exception const& e){
108 MERROR("Release exception: " << e.what());
109 return false;
110 }
111 }
112
113 bool device_trezor_base::connect() {
114 disconnect();
115
116 // Enumerate all available devices
117 TREZOR_AUTO_LOCK_DEVICE();
118 // try {
119 // Don't catch exceptions here, we want the error strings to propagate to the GUI
120 hw::trezor::t_transport_vect trans;
121
122 MDEBUG("Enumerating Trezor devices...");
123 enumerate(trans);
124 sort_transports_by_env(trans);
125
126 MDEBUG("Enumeration yielded " << trans.size() << " Trezor devices");
127 for (auto &cur : trans) {
128 MDEBUG(" device: " << *(cur.get()));
129 }
130
131 for (auto &cur : trans) {
132 std::string cur_path = cur->get_path();
133 if (boost::starts_with(cur_path, this->name)) {
134 MDEBUG("Device Match: " << cur_path);
135 m_transport = cur;
136 break;
137 }
138 }
139
140 if (!m_transport) {
141 MERROR("No matching Trezor device found. Device specifier: \"" + this->name + "\"");
142 return false;
143 }
144
145 m_transport->open();
146
147 #ifdef WITH_TREZOR_DEBUGGING
148 setup_debug();
149 #endif
150 return true;
151
152 // } catch(std::exception const& e){
153 // MERROR("Open exception: " << e.what());
154 // return false;
155 // }
156 }
157
158 bool device_trezor_base::disconnect() {
159 TREZOR_AUTO_LOCK_DEVICE();
160 m_device_session_id.clear();
161 m_features.reset();
162 m_seen_passphrase_entry_message = false;
163 m_reply_with_empty_passphrase = false;
164 m_always_use_empty_passphrase = false;
165
166 if (m_transport){
167 try {
168 m_transport->close();
169 m_transport = nullptr;
170
171 } catch(std::exception const& e){
172 MERROR("Disconnect exception: " << e.what());
173 m_transport = nullptr;
174 return false;
175 }
176 }
177
178 #ifdef WITH_TREZOR_DEBUGGING
179 if (m_debug_callback) {
180 m_debug_callback->on_disconnect();
181 m_debug_callback = nullptr;
182 }
183 #endif
184 return true;
185 }
186
187 /* ======================================================================= */
188 /* LOCKER */
189 /* ======================================================================= */
190
191 //lock the device for a long sequence
192 void device_trezor_base::lock() {
193 MTRACE("Ask for LOCKING for device " << this->name << " in thread ");
194 device_locker.lock();
195 MTRACE("Device " << this->name << " LOCKed");
196 }
197
198 //lock the device for a long sequence
199 bool device_trezor_base::try_lock() {
200 MTRACE("Ask for LOCKING(try) for device " << this->name << " in thread ");
201 bool r = device_locker.try_lock();
202 if (r) {
203 MTRACE("Device " << this->name << " LOCKed(try)");
204 } else {
205 MDEBUG("Device " << this->name << " not LOCKed(try)");
206 }
207 return r;
208 }
209
210 //unlock the device
211 void device_trezor_base::unlock() {
212 MTRACE("Ask for UNLOCKING for device " << this->name << " in thread ");
213 device_locker.unlock();
214 MTRACE("Device " << this->name << " UNLOCKed");
215 }
216
217 /* ======================================================================= */
218 /* Helpers */
219 /* ======================================================================= */
220
221 void device_trezor_base::require_connected() const {
222 if (!m_transport){
223 throw exc::NotConnectedException();
224 }
225 }
226
227 void device_trezor_base::require_initialized() const {
228 if (!m_features){
229 throw exc::TrezorException("Device state not initialized");
230 }
231
232 if (m_features->has_bootloader_mode() && m_features->bootloader_mode()){
233 throw exc::TrezorException("Device is in the bootloader mode");
234 }
235
236 if (m_features->has_firmware_present() && !m_features->firmware_present()){
237 throw exc::TrezorException("Device has no firmware loaded");
238 }
239
240 // Hard requirement on initialized field, has to be there.
241 if (!m_features->has_initialized() || !m_features->initialized()){
242 throw exc::TrezorException("Device is not initialized");
243 }
244 }
245
246 void device_trezor_base::call_ping_unsafe(){
247 auto pingMsg = std::make_shared<messages::management::Ping>();
248 pingMsg->set_message("PING");
249
250 auto success = this->client_exchange<messages::common::Success>(pingMsg); // messages::MessageType_Success
251 MDEBUG("Ping response " << success->message());
252 (void)success;
253 }
254
255 void device_trezor_base::test_ping(){
256 require_connected();
257
258 try {
259 this->call_ping_unsafe();
260
261 } catch(exc::TrezorException const& e){
262 MINFO("Trezor does not respond: " << e.what());
263 throw exc::DeviceNotResponsiveException(std::string("Trezor not responding: ") + e.what());
264 }
265 }
266
267 #ifdef WITH_TREZOR_DEBUGGING
268 #define TREZOR_CALLBACK(method, ...) do { \
269 if (m_debug_callback) m_debug_callback->method(__VA_ARGS__); \
270 if (m_callback) m_callback->method(__VA_ARGS__); \
271 }while(0)
272 #define TREZOR_CALLBACK_GET(VAR, method, ...) do { \
273 if (m_debug_callback) VAR = m_debug_callback->method(__VA_ARGS__); \
274 if (m_callback) VAR = m_callback->method(__VA_ARGS__); \
275 }while(0)
276
277 void device_trezor_base::setup_debug(){
278 if (!m_debug){
279 return;
280 }
281
282 if (!m_debug_callback){
283 CHECK_AND_ASSERT_THROW_MES(m_transport, "Transport does not exist");
284 auto debug_transport = m_transport->find_debug();
285 if (debug_transport) {
286 m_debug_callback = std::make_shared<trezor_debug_callback>(debug_transport);
287 } else {
288 MDEBUG("Transport does not have debug link option");
289 }
290 }
291 }
292
293 #else
294 #define TREZOR_CALLBACK(method, ...) do { if (m_callback) m_callback->method(__VA_ARGS__); } while(0)
295 #define TREZOR_CALLBACK_GET(VAR, method, ...) VAR = (m_callback ? m_callback->method(__VA_ARGS__) : boost::none)
296 #endif
297
298 void device_trezor_base::write_raw(const google::protobuf::Message * msg){
299 require_connected();
300 CHECK_AND_ASSERT_THROW_MES(msg, "Empty message");
301 try {
302 this->get_transport()->write(*msg);
303 }
304 catch (const exc::CommunicationException &e) {
305 TREZOR_CALLBACK(on_error, e.what());
306 }
307 }
308
309 GenericMessage device_trezor_base::read_raw(){
310 require_connected();
311 std::shared_ptr<google::protobuf::Message> msg_resp;
312 hw::trezor::messages::MessageType msg_resp_type;
313
314 this->get_transport()->read(msg_resp, &msg_resp_type);
315 return GenericMessage(msg_resp_type, msg_resp);
316 }
317
318 GenericMessage device_trezor_base::call_raw(const google::protobuf::Message * msg) {
319 write_raw(msg);
320 return read_raw();
321 }
322
323 bool device_trezor_base::message_handler(GenericMessage & input){
324 // Later if needed this generic message handler can be replaced by a pointer to
325 // a protocol message handler which by default points to the device class which implements
326 // the default handler.
327
328 if (m_last_msg_type == messages::MessageType_ButtonRequest){
329 on_button_pressed();
330 }
331 m_last_msg_type = input.m_type;
332
333 switch(input.m_type){
334 case messages::MessageType_ButtonRequest:
335 on_button_request(input, dynamic_cast<const messages::common::ButtonRequest*>(input.m_msg.get()));
336 return true;
337 case messages::MessageType_PassphraseRequest:
338 on_passphrase_request(input, dynamic_cast<const messages::common::PassphraseRequest*>(input.m_msg.get()));
339 return true;
340 case messages::MessageType_Deprecated_PassphraseStateRequest:
341 on_passphrase_state_request(input, dynamic_cast<const messages::common::Deprecated_PassphraseStateRequest*>(input.m_msg.get()));
342 return true;
343 case messages::MessageType_PinMatrixRequest:
344 on_pin_request(input, dynamic_cast<const messages::common::PinMatrixRequest*>(input.m_msg.get()));
345 return true;
346 default:
347 return false;
348 }
349 }
350
351 void device_trezor_base::ensure_derivation_path() noexcept {
352 if (m_wallet_deriv_path.empty()){
353 m_wallet_deriv_path.push_back(TREZOR_BIP44_HARDENED_ZERO); // default 0'
354 }
355 }
356
357 void device_trezor_base::set_derivation_path(const std::string &deriv_path){
358 this->m_wallet_deriv_path.clear();
359
360 if (deriv_path.empty() || deriv_path == "-"){
361 ensure_derivation_path();
362 return;
363 }
364
365 CHECK_AND_ASSERT_THROW_MES(deriv_path.size() <= 255, "Derivation path is too long");
366
367 std::vector<std::string> fields;
368 boost::split(fields, deriv_path, boost::is_any_of("/"));
369 CHECK_AND_ASSERT_THROW_MES(fields.size() <= 10, "Derivation path is too long");
370
371 boost::regex rgx("^([0-9]+)'?$");
372 boost::cmatch match;
373
374 this->m_wallet_deriv_path.reserve(fields.size());
375 for(const std::string & cur : fields){
376 const bool ok = boost::regex_match(cur.c_str(), match, rgx);
377 CHECK_AND_ASSERT_THROW_MES(ok, "Invalid wallet code: " << deriv_path << ". Invalid path element: " << cur);
378 CHECK_AND_ASSERT_THROW_MES(match[0].length() > 0, "Invalid wallet code: " << deriv_path << ". Invalid path element: " << cur);
379
380 const unsigned long cidx = std::stoul(match[0].str()) | TREZOR_BIP44_HARDENED_ZERO;
381 this->m_wallet_deriv_path.push_back((unsigned int)cidx);
382 }
383 }
384
385 /* ======================================================================= */
386 /* TREZOR PROTOCOL */
387 /* ======================================================================= */
388
389 bool device_trezor_base::ping() {
390 TREZOR_AUTO_LOCK_CMD();
391 if (!m_transport){
392 MINFO("Ping failed, device not connected");
393 return false;
394 }
395
396 try {
397 this->call_ping_unsafe();
398 return true;
399
400 } catch(std::exception const& e) {
401 MERROR("Ping failed, exception thrown " << e.what());
402 } catch(...){
403 MERROR("Ping failed, general exception thrown" << boost::current_exception_diagnostic_information());
404 }
405
406 return false;
407 }
408
409 void device_trezor_base::device_state_initialize_unsafe()
410 {
411 require_connected();
412 auto initMsg = std::make_shared<messages::management::Initialize>();
413 const auto data_cleaner = epee::misc_utils::create_scope_leave_handler([&]() {
414 if (initMsg->has_session_id())
415 memwipe(&(*initMsg->mutable_session_id())[0], initMsg->mutable_session_id()->size());
416 });
417
418 if(!m_device_session_id.empty()) {
419 initMsg->set_allocated_session_id(new std::string(m_device_session_id.data(), m_device_session_id.size()));
420 }
421
422 m_features = this->client_exchange<messages::management::Features>(initMsg);
423 if (m_features->has_session_id()){
424 m_device_session_id = m_features->session_id();
425 } else {
426 m_device_session_id.clear();
427 }
428 }
429
430 void device_trezor_base::device_state_reset()
431 {
432 TREZOR_AUTO_LOCK_CMD();
433 device_state_initialize_unsafe();
434 }
435
436 void device_trezor_base::on_button_request(GenericMessage & resp, const messages::common::ButtonRequest * msg)
437 {
438 CHECK_AND_ASSERT_THROW_MES(msg, "Empty message");
439 MDEBUG("on_button_request, code: " << msg->code());
440
441 TREZOR_CALLBACK(on_button_request, msg->code());
442
443 messages::common::ButtonAck ack;
444 write_raw(&ack);
445
446 resp = read_raw();
447 }
448
449 void device_trezor_base::on_button_pressed()
450 {
451 TREZOR_CALLBACK(on_button_pressed);
452 }
453
454 void device_trezor_base::on_pin_request(GenericMessage & resp, const messages::common::PinMatrixRequest * msg)
455 {
456 MDEBUG("on_pin_request");
457 CHECK_AND_ASSERT_THROW_MES(msg, "Empty message");
458
459 boost::optional<epee::wipeable_string> pin;
460 TREZOR_CALLBACK_GET(pin, on_pin_request);
461
462 if (!pin && m_pin){
463 pin = m_pin;
464 }
465
466 messages::common::PinMatrixAck m;
467 if (pin) {
468 m.set_allocated_pin(new std::string(pin->data(), pin->size()));
469 }
470
471 const auto data_cleaner = epee::misc_utils::create_scope_leave_handler([&]() {
472 if (m.has_pin())
473 memwipe(&(*m.mutable_pin())[0], m.mutable_pin()->size());
474 });
475
476 resp = call_raw(&m);
477 }
478
479 void device_trezor_base::on_passphrase_request(GenericMessage & resp, const messages::common::PassphraseRequest * msg)
480 {
481 CHECK_AND_ASSERT_THROW_MES(msg, "Empty message");
482 MDEBUG("on_passhprase_request");
483
484 // Backward compatibility, migration clause.
485 if (msg->has__on_device() && msg->_on_device()){
486 messages::common::PassphraseAck m;
487 resp = call_raw(&m);
488 return;
489 }
490
491 m_seen_passphrase_entry_message = true;
492 bool on_device = true;
493 if (msg->has__on_device() && !msg->_on_device()){
494 on_device = false; // do not enter on device, old devices.
495 }
496
497 if (on_device && m_features && m_features->capabilities_size() > 0){
498 on_device = false;
499 for (auto it = m_features->capabilities().begin(); it != m_features->capabilities().end(); it++) {
500 if (*it == messages::management::Features::Capability_PassphraseEntry){
501 on_device = true;
502 }
503 }
504 }
505
506 boost::optional<epee::wipeable_string> passphrase;
507 if (m_reply_with_empty_passphrase || m_always_use_empty_passphrase) {
508 MDEBUG("Answering passphrase prompt with an empty passphrase, always use empty: " << m_always_use_empty_passphrase);
509 on_device = false;
510 passphrase = epee::wipeable_string("");
511 } else if (m_passphrase){
512 MWARNING("Answering passphrase prompt with a stored passphrase (do not use; passphrase can be seen by a potential malware / attacker)");
513 on_device = false;
514 passphrase = epee::wipeable_string(m_passphrase.get());
515 } else {
516 TREZOR_CALLBACK_GET(passphrase, on_passphrase_request, on_device);
517 }
518
519 messages::common::PassphraseAck m;
520 m.set_on_device(on_device);
521 if (!on_device) {
522 if (passphrase) {
523 m.set_allocated_passphrase(new std::string(passphrase->data(), passphrase->size()));
524 }
525 }
526
527 const auto data_cleaner = epee::misc_utils::create_scope_leave_handler([&]() {
528 if (m.has_passphrase())
529 memwipe(&(*m.mutable_passphrase())[0], m.mutable_passphrase()->size());
530 });
531
532 resp = call_raw(&m);
533 }
534
535 void device_trezor_base::on_passphrase_state_request(GenericMessage & resp, const messages::common::Deprecated_PassphraseStateRequest * msg)
536 {
537 MDEBUG("on_passhprase_state_request");
538 CHECK_AND_ASSERT_THROW_MES(msg, "Empty message");
539
540 if (msg->has_state()) {
541 m_device_session_id = msg->state();
542 }
543 messages::common::Deprecated_PassphraseStateAck m;
544 resp = call_raw(&m);
545 }
546
547 #ifdef WITH_TREZOR_DEBUGGING
548 void device_trezor_base::wipe_device()
549 {
550 auto msg = std::make_shared<messages::management::WipeDevice>();
551 auto ret = client_exchange<messages::common::Success>(msg);
552 (void)ret;
553 init_device();
554 }
555
556 void device_trezor_base::init_device()
557 {
558 auto msg = std::make_shared<messages::management::Initialize>();
559 m_features = client_exchange<messages::management::Features>(msg);
560 }
561
562 void device_trezor_base::load_device(const std::string & mnemonic, const std::string & pin,
563 bool passphrase_protection, const std::string & label, const std::string & language,
564 bool skip_checksum, bool expand)
565 {
566 if (m_features && m_features->initialized()){
567 throw std::runtime_error("Device is initialized already. Call device.wipe() and try again.");
568 }
569
570 auto msg = std::make_shared<messages::management::LoadDevice>();
571 msg->add_mnemonics(mnemonic);
572 msg->set_pin(pin);
573 msg->set_passphrase_protection(passphrase_protection);
574 msg->set_label(label);
575 msg->set_language(language);
576 msg->set_skip_checksum(skip_checksum);
577 auto ret = client_exchange<messages::common::Success>(msg);
578 (void)ret;
579
580 init_device();
581 }
582
583 trezor_debug_callback::trezor_debug_callback(std::shared_ptr<Transport> & debug_transport){
584 m_debug_link = std::make_shared<DebugLink>();
585 m_debug_link->init(debug_transport);
586 }
587
588 void trezor_debug_callback::on_button_request(uint64_t code) {
589 if (m_debug_link) m_debug_link->press_yes();
590 }
591
592 boost::optional<epee::wipeable_string> trezor_debug_callback::on_pin_request() {
593 return boost::none;
594 }
595
596 boost::optional<epee::wipeable_string> trezor_debug_callback::on_passphrase_request(bool & on_device) {
597 on_device = true;
598 return boost::none;
599 }
600
601 void trezor_debug_callback::on_passphrase_state_request(const std::string &state) {
602
603 }
604
605 void trezor_debug_callback::on_disconnect(){
606 if (m_debug_link) m_debug_link->close();
607 }
608 #endif
609
610 #endif //WITH_DEVICE_TREZOR
611 }}