Debian Codegraph @

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