Debian Codegraph @

src/device_trezor/trezor/transport.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 #ifdef WITH_DEVICE_TREZOR_WEBUSB
31 #include <libusb.h>
32 #endif
33
34 #include <algorithm>
35 #include <functional>
36 #include <boost/endian/conversion.hpp>
37 #include <boost/asio/ip/udp.hpp>
38 #include <boost/date_time/posix_time/posix_time_types.hpp>
39 #include <boost/format.hpp>
40 #include <boost/algorithm/string/predicate.hpp>
41 #include "common/apply_permutation.h"
42 #include "transport.hpp"
43 #include "messages/messages-common.pb.h"
44
45 #undef MONERO_DEFAULT_LOG_CATEGORY
46 #define MONERO_DEFAULT_LOG_CATEGORY "device.trezor.transport"
47
48 using namespace std;
49 using json = rapidjson::Document;
50
51
52 namespace hw{
53 namespace trezor{
54
55 bool t_serialize(const std::string & in, std::string & out){
56 out = in;
57 return true;
58 }
59
60 bool t_serialize(const epee::wipeable_string & in, std::string & out){
61 out.assign(in.data(), in.size());
62 return true;
63 }
64
65 bool t_serialize(const json_val & in, std::string & out){
66 rapidjson::StringBuffer sb;
67 rapidjson::Writer<rapidjson::StringBuffer> writer(sb);
68 in.Accept(writer);
69 out = sb.GetString();
70 return true;
71 }
72
73 std::string t_serialize(const json_val & in){
74 std::string ret;
75 t_serialize(in, ret);
76 return ret;
77 }
78
79 bool t_deserialize(const std::string & in, std::string & out){
80 out = in;
81 return true;
82 }
83
84 bool t_deserialize(std::string & in, epee::wipeable_string & out){
85 out = epee::wipeable_string(in);
86 return true;
87 }
88
89 bool t_deserialize(const std::string & in, json & out){
90 if (out.Parse(in.c_str()).HasParseError()) {
91 throw exc::CommunicationException("JSON parse error");
92 }
93 return true;
94 }
95
96 static std::string json_get_string(const rapidjson::Value & in){
97 return std::string(in.GetString());
98 }
99
100 uint64_t pack_version(uint32_t major, uint32_t minor, uint32_t patch)
101 {
102 // packing (major, minor, patch) to 64 B: 16 B | 24 B | 24 B
103 const unsigned bits_1 = 16;
104 const unsigned bits_2 = 24;
105 const uint32_t mask_1 = (1 << bits_1) - 1;
106 const uint32_t mask_2 = (1 << bits_2) - 1;
107 CHECK_AND_ASSERT_THROW_MES(major <= mask_1 && minor <= mask_2 && patch <= mask_2, "Version numbers overflow packing scheme");
108 return patch | (((uint64_t)minor) << bits_2) | (((uint64_t)major) << (bits_1 + bits_2));
109 }
110
111 typedef struct {
112 uint16_t trezor_type;
113 uint16_t id_vendor;
114 uint16_t id_product;
115 } trezor_usb_desc_t;
116
117 static trezor_usb_desc_t TREZOR_DESC_T1 = {1, 0x534C, 0x0001};
118 static trezor_usb_desc_t TREZOR_DESC_T2 = {2, 0x1209, 0x53C1};
119 static trezor_usb_desc_t TREZOR_DESC_T2_BL = {3, 0x1209, 0x53C0};
120
121 static trezor_usb_desc_t TREZOR_DESCS[] = {
122 TREZOR_DESC_T1,
123 TREZOR_DESC_T2,
124 TREZOR_DESC_T2_BL,
125 };
126
127 static size_t TREZOR_DESCS_LEN = sizeof(TREZOR_DESCS)/sizeof(TREZOR_DESCS[0]);
128
129 static ssize_t get_device_idx(uint16_t id_vendor, uint16_t id_product){
130 for(size_t i = 0; i < TREZOR_DESCS_LEN; ++i){
131 if (TREZOR_DESCS[i].id_vendor == id_vendor && TREZOR_DESCS[i].id_product == id_product){
132 return i;
133 }
134 }
135
136 return -1;
137 }
138
139 static bool is_device_supported(ssize_t device_idx){
140 CHECK_AND_ASSERT_THROW_MES(device_idx < (ssize_t)TREZOR_DESCS_LEN, "Device desc idx too big");
141 if (device_idx < 0){
142 return false;
143 }
144
145 #ifdef TREZOR_1_SUPPORTED
146 return true;
147 #else
148 return TREZOR_DESCS[device_idx].trezor_type != 1;
149 #endif
150 }
151
152 //
153 // Helpers
154 //
155
156 #define PROTO_HEADER_SIZE 6
157
158 static size_t message_size(const google::protobuf::Message &req){
159 #if GOOGLE_PROTOBUF_VERSION < 3006001
160 return size_t(req.ByteSize());
161 #else
162 return req.ByteSizeLong();
163 #endif
164 }
165
166 static size_t serialize_message_buffer_size(size_t msg_size) {
167 return PROTO_HEADER_SIZE + msg_size; // tag 2B + len 4B
168 }
169
170 static void serialize_message_header(void * buff, uint16_t tag, uint32_t len){
171 uint16_t wire_tag = boost::endian::native_to_big(static_cast<uint16_t>(tag));
172 uint32_t wire_len = boost::endian::native_to_big(static_cast<uint32_t>(len));
173 memcpy(buff, (void *) &wire_tag, 2);
174 memcpy((uint8_t*)buff + 2, (void *) &wire_len, 4);
175 }
176
177 static void deserialize_message_header(const void * buff, uint16_t & tag, uint32_t & len){
178 uint16_t wire_tag;
179 uint32_t wire_len;
180 memcpy(&wire_tag, buff, 2);
181 memcpy(&wire_len, (uint8_t*)buff + 2, 4);
182
183 tag = boost::endian::big_to_native(wire_tag);
184 len = boost::endian::big_to_native(wire_len);
185 }
186
187 static void serialize_message(const google::protobuf::Message &req, size_t msg_size, uint8_t * buff, size_t buff_size) {
188 auto msg_wire_num = MessageMapper::get_message_wire_number(req);
189 const auto req_buffer_size = serialize_message_buffer_size(msg_size);
190 if (req_buffer_size > buff_size){
191 throw std::invalid_argument("Buffer too small");
192 }
193
194 serialize_message_header(buff, msg_wire_num, msg_size);
195 if (!req.SerializeToArray(buff + 6, msg_size)){
196 throw exc::EncodingException("Message serialization error");
197 }
198 }
199
200 //
201 // Communication protocol
202 //
203
204 #define REPLEN 64
205
206 void ProtocolV1::write(Transport & transport, const google::protobuf::Message & req){
207 const auto msg_size = message_size(req);
208 const auto buff_size = serialize_message_buffer_size(msg_size) + 2;
209
210 epee::wipeable_string req_buff;
211 epee::wipeable_string chunk_buff;
212
213 req_buff.resize(buff_size);
214 chunk_buff.resize(REPLEN);
215
216 uint8_t * req_buff_raw = reinterpret_cast<uint8_t *>(req_buff.data());
217 uint8_t * chunk_buff_raw = reinterpret_cast<uint8_t *>(chunk_buff.data());
218
219 req_buff_raw[0] = '#';
220 req_buff_raw[1] = '#';
221
222 serialize_message(req, msg_size, req_buff_raw + 2, buff_size - 2);
223
224 size_t offset = 0;
225
226 // Chunk by chunk upload
227 while(offset < buff_size){
228 auto to_copy = std::min((size_t)(buff_size - offset), (size_t)(REPLEN - 1));
229
230 chunk_buff_raw[0] = '?';
231 memcpy(chunk_buff_raw + 1, req_buff_raw + offset, to_copy);
232
233 // Pad with zeros
234 if (to_copy < REPLEN - 1){
235 memset(chunk_buff_raw + 1 + to_copy, 0, REPLEN - 1 - to_copy);
236 }
237
238 transport.write_chunk(chunk_buff_raw, REPLEN);
239 offset += REPLEN - 1;
240 }
241 }
242
243 void ProtocolV1::read(Transport & transport, std::shared_ptr<google::protobuf::Message> & msg, messages::MessageType * msg_type){
244 epee::wipeable_string chunk_buff;
245 chunk_buff.resize(REPLEN);
246 char * chunk_buff_raw = chunk_buff.data();
247
248 // Initial chunk read
249 size_t nread = transport.read_chunk(chunk_buff_raw, REPLEN);
250 if (nread != REPLEN){
251 throw exc::CommunicationException("Read chunk has invalid size");
252 }
253
254 if (memcmp(chunk_buff_raw, "?##", 3) != 0){
255 throw exc::CommunicationException("Malformed chunk");
256 }
257
258 uint16_t tag;
259 uint32_t len;
260 nread -= 3 + 6;
261 deserialize_message_header(chunk_buff_raw + 3, tag, len);
262
263 epee::wipeable_string data_acc(chunk_buff_raw + 3 + 6, nread);
264 data_acc.reserve(len);
265
266 while(nread < len){
267 const size_t cur = transport.read_chunk(chunk_buff_raw, REPLEN);
268 if (chunk_buff_raw[0] != '?'){
269 throw exc::CommunicationException("Chunk malformed");
270 }
271
272 data_acc.append(chunk_buff_raw + 1, cur - 1);
273 nread += cur - 1;
274 }
275
276 if (msg_type){
277 *msg_type = static_cast<messages::MessageType>(tag);
278 }
279
280 if (nread < len){
281 throw exc::CommunicationException("Response incomplete");
282 }
283
284 std::shared_ptr<google::protobuf::Message> msg_wrap(MessageMapper::get_message(tag));
285 if (!msg_wrap->ParseFromArray(data_acc.data(), len)){
286 throw exc::CommunicationException("Message could not be parsed");
287 }
288
289 msg = msg_wrap;
290 }
291
292 static void assert_port_number(uint32_t port)
293 {
294 CHECK_AND_ASSERT_THROW_MES(port >= 1024 && port < 65535, "Invalid port number: " << port);
295 }
296
297 Transport::Transport(): m_open_counter(0) {
298
299 }
300
301 bool Transport::pre_open(){
302 if (m_open_counter > 0){
303 MTRACE("Already opened, count: " << m_open_counter);
304 m_open_counter += 1;
305 return false;
306
307 } else if (m_open_counter < 0){
308 MTRACE("Negative open value: " << m_open_counter);
309
310 }
311
312 // Caller should set m_open_counter to 1 after open
313 m_open_counter = 0;
314 return true;
315 }
316
317 bool Transport::pre_close(){
318 m_open_counter -= 1;
319
320 if (m_open_counter < 0){
321 MDEBUG("Already closed. Counter " << m_open_counter);
322
323 } else if (m_open_counter == 0) {
324 return true;
325
326 }
327
328 return false;
329 }
330
331 //
332 // Bridge transport
333 //
334
335 const char * BridgeTransport::PATH_PREFIX = "bridge:";
336
337 BridgeTransport::BridgeTransport(
338 boost::optional<std::string> device_path,
339 boost::optional<std::string> bridge_host):
340 m_device_path(device_path),
341 m_bridge_host(bridge_host ? bridge_host.get() : DEFAULT_BRIDGE),
342 m_response(boost::none),
343 m_session(boost::none),
344 m_device_info(boost::none)
345 {
346 const char *env_bridge_port = nullptr;
347 if (!bridge_host && (env_bridge_port = getenv("TREZOR_BRIDGE_PORT")) != nullptr)
348 {
349 uint16_t bridge_port;
350 CHECK_AND_ASSERT_THROW_MES(epee::string_tools::get_xtype_from_string(bridge_port, env_bridge_port), "Invalid bridge port: " << env_bridge_port);
351 assert_port_number(bridge_port);
352
353 m_bridge_host = std::string("127.0.0.1:") + boost::lexical_cast<std::string>(env_bridge_port);
354 MDEBUG("Bridge host: " << m_bridge_host);
355 }
356
357 m_http_client.set_server(m_bridge_host, boost::none, epee::net_utils::ssl_support_t::e_ssl_support_disabled);
358 }
359
360 std::string BridgeTransport::get_path() const {
361 if (!m_device_path){
362 return "";
363 }
364
365 std::string path(PATH_PREFIX);
366 return path + m_device_path.get();
367 }
368
369 void BridgeTransport::enumerate(t_transport_vect & res) {
370 json bridge_res;
371 std::string req;
372
373 bool req_status = invoke_bridge_http("/enumerate", req, bridge_res, m_http_client);
374 if (!req_status){
375 throw exc::CommunicationException("Bridge enumeration failed");
376 }
377
378 for(rapidjson::Value::ConstValueIterator itr = bridge_res.Begin(); itr != bridge_res.End(); ++itr){
379 auto element = itr->GetObject();
380 auto t = std::make_shared<BridgeTransport>(boost::make_optional(json_get_string(element["path"])));
381
382 auto itr_vendor = element.FindMember("vendor");
383 auto itr_product = element.FindMember("product");
384 if (itr_vendor != element.MemberEnd() && itr_product != element.MemberEnd()
385 && itr_vendor->value.IsNumber() && itr_product->value.IsNumber()){
386 try {
387 const auto id_vendor = (uint16_t) itr_vendor->value.GetUint64();
388 const auto id_product = (uint16_t) itr_product->value.GetUint64();
389 const auto device_idx = get_device_idx(id_vendor, id_product);
390 if (!is_device_supported(device_idx)){
391 MDEBUG("Device with idx " << device_idx << " is not supported. Vendor: " << id_vendor << ", product: " << id_product);
392 continue;
393 }
394 } catch(const std::exception &e){
395 MERROR("Could not detect vendor & product: " << e.what());
396 }
397 }
398
399 t->m_device_info.emplace();
400 t->m_device_info->CopyFrom(*itr, t->m_device_info->GetAllocator());
401 res.push_back(t);
402 }
403 }
404
405 void BridgeTransport::open() {
406 if (!pre_open()){
407 return;
408 }
409
410 if (!m_device_path){
411 throw exc::CommunicationException("Coud not open, empty device path");
412 }
413
414 std::string uri = "/acquire/" + m_device_path.get() + "/null";
415 std::string req;
416 json bridge_res;
417 bool req_status = invoke_bridge_http(uri, req, bridge_res, m_http_client);
418 if (!req_status){
419 throw exc::CommunicationException("Failed to acquire device");
420 }
421
422 m_session = boost::make_optional(json_get_string(bridge_res["session"]));
423 m_open_counter = 1;
424 }
425
426 void BridgeTransport::close() {
427 if (!pre_close()){
428 return;
429 }
430
431 MTRACE("Closing Trezor:BridgeTransport");
432 if (!m_device_path || !m_session){
433 throw exc::CommunicationException("Device not open");
434 }
435
436 std::string uri = "/release/" + m_session.get();
437 std::string req;
438 json bridge_res;
439 bool req_status = invoke_bridge_http(uri, req, bridge_res, m_http_client);
440 if (!req_status){
441 throw exc::CommunicationException("Failed to release device");
442 }
443
444 m_session = boost::none;
445 }
446
447 void BridgeTransport::write(const google::protobuf::Message &req) {
448 m_response = boost::none;
449
450 const auto msg_size = message_size(req);
451 const auto buff_size = serialize_message_buffer_size(msg_size);
452 epee::wipeable_string req_buff;
453 req_buff.resize(buff_size);
454
455 uint8_t * req_buff_raw = reinterpret_cast<uint8_t *>(req_buff.data());
456
457 serialize_message(req, msg_size, req_buff_raw, buff_size);
458
459 std::string uri = "/call/" + m_session.get();
460 epee::wipeable_string res_hex;
461 epee::wipeable_string req_hex = epee::to_hex::wipeable_string(epee::span<const std::uint8_t>(req_buff_raw, buff_size));
462
463 bool req_status = invoke_bridge_http(uri, req_hex, res_hex, m_http_client);
464 if (!req_status){
465 throw exc::CommunicationException("Call method failed");
466 }
467
468 m_response = res_hex;
469 }
470
471 void BridgeTransport::read(std::shared_ptr<google::protobuf::Message> & msg, messages::MessageType * msg_type) {
472 if (!m_response){
473 throw exc::CommunicationException("Could not read, no response stored");
474 }
475
476 boost::optional<epee::wipeable_string> bin_data = m_response->parse_hexstr();
477 if (!bin_data){
478 throw exc::CommunicationException("Response is not well hexcoded");
479 }
480
481 uint16_t msg_tag;
482 uint32_t msg_len;
483 deserialize_message_header(bin_data->data(), msg_tag, msg_len);
484 if (bin_data->size() != msg_len + 6){
485 throw exc::CommunicationException("Response is not well hexcoded");
486 }
487
488 if (msg_type){
489 *msg_type = static_cast<messages::MessageType>(msg_tag);
490 }
491
492 std::shared_ptr<google::protobuf::Message> msg_wrap(MessageMapper::get_message(msg_tag));
493 if (!msg_wrap->ParseFromArray(bin_data->data() + 6, msg_len)){
494 throw exc::EncodingException("Response is not well hexcoded");
495 }
496 msg = msg_wrap;
497 }
498
499 const boost::optional<json> & BridgeTransport::device_info() const {
500 return m_device_info;
501 }
502
503 std::ostream& BridgeTransport::dump(std::ostream& o) const {
504 return o << "BridgeTransport<path=" << (m_device_path ? get_path() : "None")
505 << ", info=" << (m_device_info ? t_serialize(m_device_info.get()) : "None")
506 << ", session=" << (m_session ? m_session.get() : "None")
507 << ">";
508 }
509
510 //
511 // UdpTransport
512 //
513 const char * UdpTransport::PATH_PREFIX = "udp:";
514 const char * UdpTransport::DEFAULT_HOST = "127.0.0.1";
515 const int UdpTransport::DEFAULT_PORT = 21324;
516
517 static void parse_udp_path(std::string &host, int &port, std::string path)
518 {
519 if (boost::starts_with(path, UdpTransport::PATH_PREFIX))
520 {
521 path = path.substr(strlen(UdpTransport::PATH_PREFIX));
522 }
523
524 auto delim = path.find(':');
525 if (delim == std::string::npos) {
526 host = path;
527 } else {
528 host = path.substr(0, delim);
529 port = std::stoi(path.substr(delim + 1));
530 }
531 }
532
533 UdpTransport::UdpTransport(boost::optional<std::string> device_path,
534 boost::optional<std::shared_ptr<Protocol>> proto) :
535 m_io_service(), m_deadline(m_io_service)
536 {
537 m_device_host = DEFAULT_HOST;
538 m_device_port = DEFAULT_PORT;
539 const char *env_trezor_path = nullptr;
540
541 if (device_path) {
542 parse_udp_path(m_device_host, m_device_port, device_path.get());
543 } else if ((env_trezor_path = getenv("TREZOR_PATH")) != nullptr && boost::starts_with(env_trezor_path, UdpTransport::PATH_PREFIX)){
544 parse_udp_path(m_device_host, m_device_port, std::string(env_trezor_path));
545 MDEBUG("Applied TREZOR_PATH: " << m_device_host << ":" << m_device_port);
546 } else {
547 m_device_host = DEFAULT_HOST;
548 }
549
550 assert_port_number((uint32_t)m_device_port);
551 if (m_device_host != "localhost" && m_device_host != DEFAULT_HOST){
552 throw std::invalid_argument("Local endpoint allowed only");
553 }
554
555 m_proto = proto ? proto.get() : std::make_shared<ProtocolV1>();
556 }
557
558 std::string UdpTransport::get_path() const {
559 std::string path(PATH_PREFIX);
560 return path + m_device_host + ":" + std::to_string(m_device_port);
561 }
562
563 void UdpTransport::require_socket(){
564 if (!m_socket){
565 throw exc::NotConnectedException("Socket not connected");
566 }
567 }
568
569 bool UdpTransport::ping(){
570 return ping_int();
571 }
572
573 bool UdpTransport::ping_int(boost::posix_time::time_duration timeout){
574 require_socket();
575 try {
576 std::string req = "PINGPING";
577 char res[8];
578
579 const auto written = m_socket->send_to(boost::asio::buffer(req.c_str(), req.size()), m_endpoint);
580 if (written != req.size())
581 return false;
582 memset(res, 0, sizeof(res));
583 const auto received = receive(res, 8, nullptr, false, timeout);
584 if (received != 8)
585 return false;
586
587 return memcmp(res, "PONGPONG", 8) == 0;
588
589 } catch(...){
590 return false;
591 }
592 }
593
594 void UdpTransport::enumerate(t_transport_vect & res) {
595 std::shared_ptr<UdpTransport> t = std::make_shared<UdpTransport>();
596 bool t_works = false;
597
598 try{
599 t->open();
600 t_works = t->ping();
601 } catch(...) {
602
603 }
604 t->close();
605 if (t_works){
606 res.push_back(t);
607 }
608 }
609
610 void UdpTransport::open() {
611 if (!pre_open()){
612 return;
613 }
614
615 udp::resolver resolver(m_io_service);
616 m_endpoint = *resolver.resolve(udp::v4(), m_device_host, std::to_string(m_device_port)).begin();
617
618 m_socket.reset(new udp::socket(m_io_service));
619 m_socket->open(udp::v4());
620
621 m_deadline.expires_at(boost::posix_time::pos_infin);
622 check_deadline();
623
624 m_proto->session_begin(*this);
625 m_open_counter = 1;
626 }
627
628 void UdpTransport::close() {
629 if (!pre_close()){
630 return;
631 }
632
633 MTRACE("Closing Trezor:UdpTransport");
634 if (!m_socket) {
635 throw exc::CommunicationException("Socket is already closed");
636 }
637
638 m_proto->session_end(*this);
639 m_socket->close();
640 m_socket = nullptr;
641 }
642
643 std::shared_ptr<Transport> UdpTransport::find_debug() {
644 #ifdef WITH_TREZOR_DEBUGGING
645 std::shared_ptr<UdpTransport> t = std::make_shared<UdpTransport>();
646 t->m_proto = std::make_shared<ProtocolV1>();
647 t->m_device_host = m_device_host;
648 t->m_device_port = m_device_port + 1;
649 return t;
650 #else
651 MINFO("Debug link is disabled in production");
652 return nullptr;
653 #endif
654 }
655
656 void UdpTransport::write_chunk(const void * buff, size_t size){
657 require_socket();
658
659 if (size != 64){
660 throw exc::CommunicationException("Invalid chunk size");
661 }
662
663 auto written = m_socket->send_to(boost::asio::buffer(buff, size), m_endpoint);
664 if (size != written){
665 throw exc::CommunicationException("Could not send the whole chunk");
666 }
667 }
668
669 size_t UdpTransport::read_chunk(void * buff, size_t size){
670 require_socket();
671 if (size < 64){
672 throw std::invalid_argument("Buffer too small");
673 }
674
675 ssize_t len;
676 while(true) {
677 try {
678 boost::system::error_code ec;
679 len = receive(buff, size, &ec, true);
680 if (ec == boost::asio::error::operation_aborted) {
681 continue;
682 } else if (ec) {
683 throw exc::CommunicationException(std::string("Comm error: ") + ec.message());
684 }
685
686 if (len != 64) {
687 throw exc::CommunicationException("Invalid chunk size");
688 }
689
690 break;
691
692 } catch(exc::CommunicationException const& e){
693 throw;
694 } catch(std::exception const& e){
695 MWARNING("Error reading chunk, reason: " << e.what());
696 throw exc::CommunicationException(std::string("Chunk read error: ") + std::string(e.what()));
697 }
698 }
699
700 return static_cast<size_t>(len);
701 }
702
703 ssize_t UdpTransport::receive(void * buff, size_t size, boost::system::error_code * error_code, bool no_throw, boost::posix_time::time_duration timeout){
704 boost::system::error_code ec;
705 boost::asio::mutable_buffer buffer = boost::asio::buffer(buff, size);
706
707 require_socket();
708
709 // Set a deadline for the asynchronous operation.
710 m_deadline.expires_from_now(timeout);
711
712 // Set up the variables that receive the result of the asynchronous
713 // operation. The error code is set to would_block to signal that the
714 // operation is incomplete. Asio guarantees that its asynchronous
715 // operations will never fail with would_block, so any other value in
716 // ec indicates completion.
717 ec = boost::asio::error::would_block;
718 std::size_t length = 0;
719
720 // Start the asynchronous operation itself. The handle_receive function
721 // used as a callback will update the ec and length variables.
722 m_socket->async_receive_from(boost::asio::buffer(buffer), m_endpoint,
723 std::bind(&UdpTransport::handle_receive, std::placeholders::_1, std::placeholders::_2, &ec, &length));
724
725 // Block until the asynchronous operation has completed.
726 do {
727 m_io_service.run_one();
728 }
729 while (ec == boost::asio::error::would_block);
730
731 if (error_code){
732 *error_code = ec;
733 }
734
735 if (no_throw){
736 return length;
737 }
738
739 // Operation result
740 if (ec == boost::asio::error::operation_aborted){
741 throw exc::TimeoutException();
742
743 } else if (ec) {
744 MWARNING("Reading from UDP socket failed: " << ec.message());
745 throw exc::CommunicationException();
746
747 }
748
749 return length;
750 }
751
752 void UdpTransport::write(const google::protobuf::Message &req) {
753 m_proto->write(*this, req);
754 }
755
756 void UdpTransport::read(std::shared_ptr<google::protobuf::Message> & msg, messages::MessageType * msg_type) {
757 m_proto->read(*this, msg, msg_type);
758 }
759
760 void UdpTransport::check_deadline(){
761 if (!m_socket){
762 return; // no active socket.
763 }
764
765 // Check whether the deadline has passed. We compare the deadline against
766 // the current time since a new asynchronous operation may have moved the
767 // deadline before this actor had a chance to run.
768 if (m_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now())
769 {
770 // The deadline has passed. The outstanding asynchronous operation needs
771 // to be cancelled so that the blocked receive() function will return.
772 //
773 // Please note that cancel() has portability issues on some versions of
774 // Microsoft Windows, and it may be necessary to use close() instead.
775 // Consult the documentation for cancel() for further information.
776 m_socket->cancel();
777
778 // There is no longer an active deadline. The expiry is set to positive
779 // infinity so that the actor takes no action until a new deadline is set.
780 m_deadline.expires_at(boost::posix_time::pos_infin);
781 }
782
783 // Put the actor back to sleep.
784 m_deadline.async_wait(boost::bind(&UdpTransport::check_deadline, this));
785 }
786
787 void UdpTransport::handle_receive(const boost::system::error_code &ec, std::size_t length,
788 boost::system::error_code *out_ec, std::size_t *out_length) {
789 *out_ec = ec;
790 *out_length = length;
791 }
792
793 std::ostream& UdpTransport::dump(std::ostream& o) const {
794 return o << "UdpTransport<path=" << get_path()
795 << ", socket_alive=" << (m_socket ? "true" : "false")
796 << ">";
797 }
798
799 #ifdef WITH_DEVICE_TREZOR_WEBUSB
800
801 static bool is_trezor1(libusb_device_descriptor * info){
802 return info->idVendor == TREZOR_DESC_T1.id_vendor && info->idProduct == TREZOR_DESC_T1.id_product;
803 }
804
805 static bool is_trezor2(libusb_device_descriptor * info){
806 return info->idVendor == TREZOR_DESC_T2.id_vendor && info->idProduct == TREZOR_DESC_T2.id_product;
807 }
808
809 static bool is_trezor2_bl(libusb_device_descriptor * info){
810 return info->idVendor == TREZOR_DESC_T2_BL.id_vendor && info->idProduct == TREZOR_DESC_T2_BL.id_product;
811 }
812
813 static ssize_t get_trezor_dev_id(libusb_device_descriptor *info){
814 CHECK_AND_ASSERT_THROW_MES(info, "Empty device descriptor");
815 return get_device_idx(info->idVendor, info->idProduct);
816 }
817
818 static void set_libusb_log(libusb_context *ctx){
819 CHECK_AND_ASSERT_THROW_MES(ctx, "Null libusb context");
820
821 // http://libusb.sourceforge.net/api-1.0/group__libusb__lib.html
822 #if defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01000106)
823 # define TREZOR_LIBUSB_SET_DEBUG(ctx, level) libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level)
824 #else
825 # define TREZOR_LIBUSB_SET_DEBUG(ctx, level) libusb_set_debug(ctx, level)
826 #endif
827
828 if (ELPP->vRegistry()->allowed(el::Level::Debug, MONERO_DEFAULT_LOG_CATEGORY))
829 TREZOR_LIBUSB_SET_DEBUG(ctx, 3);
830 else if (ELPP->vRegistry()->allowed(el::Level::Warning, MONERO_DEFAULT_LOG_CATEGORY))
831 TREZOR_LIBUSB_SET_DEBUG(ctx, 2);
832 else if (ELPP->vRegistry()->allowed(el::Level::Error, MONERO_DEFAULT_LOG_CATEGORY))
833 TREZOR_LIBUSB_SET_DEBUG(ctx, 1);
834
835 #undef TREZOR_LIBUSB_SET_DEBUG
836 }
837
838 static int get_libusb_ports(libusb_device *dev, std::vector<uint8_t> &path){
839 uint8_t tmp_path[16];
840 int r = libusb_get_port_numbers(dev, tmp_path, sizeof(tmp_path));
841 CHECK_AND_ASSERT_MES(r != LIBUSB_ERROR_OVERFLOW, -1, "Libusb path array too small");
842 CHECK_AND_ASSERT_MES(r >= 0, -1, "Libusb path array error");
843
844 path.resize(r);
845 for (int i = 0; i < r; i++){
846 path[i] = tmp_path[i];
847 }
848
849 return 0;
850 }
851
852 static std::string get_usb_path(uint8_t bus_id, const std::vector<uint8_t> &path){
853 std::stringstream ss;
854 ss << WebUsbTransport::PATH_PREFIX << (boost::format("%03d") % ((int)bus_id));
855 for(uint8_t port : path){
856 ss << ":" << ((int) port);
857 }
858 return ss.str();
859 }
860
861 const char * WebUsbTransport::PATH_PREFIX = "webusb:";
862
863 WebUsbTransport::WebUsbTransport(
864 boost::optional<libusb_device_descriptor*> descriptor,
865 boost::optional<std::shared_ptr<Protocol>> proto
866 ): m_usb_session(nullptr), m_usb_device(nullptr), m_usb_device_handle(nullptr),
867 m_bus_id(-1), m_device_addr(-1)
868 {
869 if (descriptor){
870 libusb_device_descriptor * desc = new libusb_device_descriptor;
871 memcpy(desc, descriptor.get(), sizeof(libusb_device_descriptor));
872 this->m_usb_device_desc.reset(desc);
873 }
874
875 m_proto = proto ? proto.get() : std::make_shared<ProtocolV1>();
876
877 #ifdef WITH_TREZOR_DEBUGGING
878 m_debug_mode = false;
879 #endif
880 }
881
882 WebUsbTransport::~WebUsbTransport(){
883 if (m_usb_device){
884 close();
885 }
886
887 if (m_usb_session) {
888 libusb_exit(m_usb_session);
889 m_usb_session = nullptr;
890 }
891 }
892
893 void WebUsbTransport::require_device() const{
894 if (!m_usb_device_desc){
895 throw std::runtime_error("No USB device specified");
896 }
897 }
898
899 void WebUsbTransport::require_connected() const{
900 require_device();
901 if (!m_usb_device_handle){
902 throw std::runtime_error("USB Device not opened");
903 }
904 }
905
906 void WebUsbTransport::enumerate(t_transport_vect & res) {
907 int r;
908 libusb_device **devs;
909 libusb_context *ctx = nullptr;
910
911 r = libusb_init(&ctx);
912 CHECK_AND_ASSERT_THROW_MES(r >= 0, "Unable to init libusb");
913
914 set_libusb_log(ctx);
915
916 ssize_t cnt = libusb_get_device_list(ctx, &devs);
917 if (cnt < 0){
918 libusb_exit(ctx);
919 throw std::runtime_error("Unable to enumerate libusb devices");
920 }
921
922 MTRACE("Libusb devices: " << cnt);
923
924 for(ssize_t i = 0; i < cnt; i++) {
925 libusb_device_descriptor desc{};
926 r = libusb_get_device_descriptor(devs[i], &desc);
927 if (r < 0){
928 MERROR("Unable to get libusb device descriptor " << i);
929 continue;
930 }
931
932 const auto trezor_dev_idx = get_trezor_dev_id(&desc);
933 if (!is_device_supported(trezor_dev_idx)){
934 continue;
935 }
936
937 MTRACE("Found Trezor device: " << desc.idVendor << ":" << desc.idProduct << " dev_idx " << (int)trezor_dev_idx);
938
939 auto t = std::make_shared<WebUsbTransport>(boost::make_optional(&desc));
940 t->m_bus_id = libusb_get_bus_number(devs[i]);
941 t->m_device_addr = libusb_get_device_address(devs[i]);
942
943 // Port resolution may fail. Non-critical error, just addressing precision is decreased.
944 get_libusb_ports(devs[i], t->m_port_numbers);
945
946 res.push_back(t);
947 }
948
949 libusb_free_device_list(devs, 1);
950 libusb_exit(ctx);
951 }
952
953 std::string WebUsbTransport::get_path() const {
954 if (!m_usb_device_desc){
955 return "";
956 }
957
958 return get_usb_path(static_cast<uint8_t>(m_bus_id), m_port_numbers);
959 };
960
961 void WebUsbTransport::open() {
962 if (!pre_open()){
963 return;
964 }
965 const int interface = get_interface();
966
967 #define TREZOR_DESTROY_SESSION() do { libusb_exit(m_usb_session); m_usb_session = nullptr; } while(0)
968
969 int r;
970 libusb_device **devs = nullptr;
971
972 if (m_usb_session) {
973 TREZOR_DESTROY_SESSION();
974 }
975
976 r = libusb_init(&m_usb_session);
977 CHECK_AND_ASSERT_THROW_MES(r >= 0, "Unable to init libusb");
978 set_libusb_log(m_usb_session);
979
980 bool found = false;
981 int open_res = 0;
982
983 ssize_t cnt = libusb_get_device_list(m_usb_session, &devs);
984 if (cnt < 0){
985 TREZOR_DESTROY_SESSION();
986 throw std::runtime_error("Unable to enumerate libusb devices");
987 }
988
989 for (ssize_t i = 0; i < cnt; i++) {
990 libusb_device_descriptor desc{};
991 r = libusb_get_device_descriptor(devs[i], &desc);
992 if (r < 0){
993 MERROR("Unable to get libusb device descriptor " << i);
994 continue;
995 }
996
997 const auto trezor_dev_idx = get_trezor_dev_id(&desc);
998 if (!is_device_supported(trezor_dev_idx)){
999 continue;
1000 }
1001
1002 auto bus_id = libusb_get_bus_number(devs[i]);
1003 std::vector<uint8_t> path;
1004
1005 // Port resolution may fail. Non-critical error, just addressing precision is decreased.
1006 get_libusb_ports(devs[i], path);
1007
1008 MTRACE("Found Trezor device: " << desc.idVendor << ":" << desc.idProduct
1009 << ", dev_idx: " << (int)trezor_dev_idx
1010 << ". path: " << get_usb_path(bus_id, path));
1011
1012 if (bus_id == m_bus_id && path == m_port_numbers) {
1013 found = true;
1014 m_usb_device = devs[i];
1015 open_res = libusb_open(m_usb_device, &m_usb_device_handle);
1016 break;
1017 }
1018 }
1019
1020 libusb_free_device_list(devs, 1);
1021
1022 if (!found){
1023 TREZOR_DESTROY_SESSION();
1024 throw exc::DeviceAcquireException("Device not found");
1025
1026 } else if (found && open_res != 0) {
1027 m_usb_device_handle = nullptr;
1028 m_usb_device = nullptr;
1029 TREZOR_DESTROY_SESSION();
1030 throw exc::DeviceAcquireException("Unable to open libusb device");
1031 }
1032
1033 r = libusb_claim_interface(m_usb_device_handle, interface);
1034
1035 if (r != 0){
1036 libusb_close(m_usb_device_handle);
1037 m_usb_device_handle = nullptr;
1038 m_usb_device = nullptr;
1039 TREZOR_DESTROY_SESSION();
1040 throw exc::DeviceAcquireException("Unable to claim libusb device");
1041 }
1042
1043 m_open_counter = 1;
1044 m_proto->session_begin(*this);
1045
1046 #undef TREZOR_DESTROY_SESSION
1047 };
1048
1049 void WebUsbTransport::close() {
1050 if (!pre_close()){
1051 return;
1052 }
1053
1054 MTRACE("Closing Trezor:WebUsbTransport");
1055 m_proto->session_end(*this);
1056
1057 int r = libusb_release_interface(m_usb_device_handle, get_interface());
1058 if (r != 0){
1059 MERROR("Could not release libusb interface: " << r);
1060 }
1061
1062 m_usb_device = nullptr;
1063 if (m_usb_device_handle) {
1064 libusb_close(m_usb_device_handle);
1065 m_usb_device_handle = nullptr;
1066 }
1067
1068 if (m_usb_session) {
1069 libusb_exit(m_usb_session);
1070 m_usb_session = nullptr;
1071 }
1072 };
1073
1074 std::shared_ptr<Transport> WebUsbTransport::find_debug() {
1075 #ifdef WITH_TREZOR_DEBUGGING
1076 require_device();
1077 auto t = std::make_shared<WebUsbTransport>(boost::make_optional(m_usb_device_desc.get()));
1078 t->m_bus_id = m_bus_id;
1079 t->m_device_addr = m_device_addr;
1080 t->m_port_numbers = m_port_numbers;
1081 t->m_debug_mode = true;
1082 return t;
1083 #else
1084 MINFO("Debug link is disabled in production");
1085 return nullptr;
1086 #endif
1087 }
1088
1089 int WebUsbTransport::get_interface() const{
1090 const int INTERFACE_NORMAL = 0;
1091 #ifdef WITH_TREZOR_DEBUGGING
1092 const int INTERFACE_DEBUG = 1;
1093 return m_debug_mode ? INTERFACE_DEBUG : INTERFACE_NORMAL;
1094 #else
1095 return INTERFACE_NORMAL;
1096 #endif
1097 }
1098
1099 unsigned char WebUsbTransport::get_endpoint() const{
1100 const unsigned char ENDPOINT_NORMAL = 1;
1101 #ifdef WITH_TREZOR_DEBUGGING
1102 const unsigned char ENDPOINT_DEBUG = 2;
1103 return m_debug_mode ? ENDPOINT_DEBUG : ENDPOINT_NORMAL;
1104 #else
1105 return ENDPOINT_NORMAL;
1106 #endif
1107 }
1108
1109 void WebUsbTransport::write(const google::protobuf::Message &req) {
1110 m_proto->write(*this, req);
1111 };
1112
1113 void WebUsbTransport::read(std::shared_ptr<google::protobuf::Message> & msg, messages::MessageType * msg_type) {
1114 m_proto->read(*this, msg, msg_type);
1115 };
1116
1117 void WebUsbTransport::write_chunk(const void * buff, size_t size) {
1118 require_connected();
1119 if (size != REPLEN){
1120 throw exc::CommunicationException("Invalid chunk size: ");
1121 }
1122
1123 unsigned char endpoint = get_endpoint();
1124 endpoint = (endpoint & ~LIBUSB_ENDPOINT_DIR_MASK) | LIBUSB_ENDPOINT_OUT;
1125
1126 int transferred = 0;
1127 int r = libusb_interrupt_transfer(m_usb_device_handle, endpoint, (unsigned char*)buff, (int)size, &transferred, 0);
1128 CHECK_AND_ASSERT_THROW_MES(r == 0, "Unable to transfer, r: " << r);
1129 if (transferred != (int)size){
1130 throw exc::CommunicationException("Could not transfer chunk");
1131 }
1132 };
1133
1134 size_t WebUsbTransport::read_chunk(void * buff, size_t size) {
1135 require_connected();
1136 unsigned char endpoint = get_endpoint();
1137 endpoint = (endpoint & ~LIBUSB_ENDPOINT_DIR_MASK) | LIBUSB_ENDPOINT_IN;
1138
1139 int transferred = 0;
1140 int r = libusb_interrupt_transfer(m_usb_device_handle, endpoint, (unsigned char*)buff, (int)size, &transferred, 0);
1141 CHECK_AND_ASSERT_THROW_MES(r == 0, "Unable to transfer, r: " << r);
1142 if (transferred != (int)size){
1143 throw exc::CommunicationException("Could not read the chunk");
1144 }
1145
1146 return transferred;
1147 };
1148
1149 std::ostream& WebUsbTransport::dump(std::ostream& o) const {
1150 o << "WebUsbTransport<path=" << get_path()
1151 << ", vendorId=" << (m_usb_device_desc ? std::to_string(m_usb_device_desc->idVendor) : "?")
1152 << ", productId=" << (m_usb_device_desc ? std::to_string(m_usb_device_desc->idProduct) : "?")
1153 << ", deviceType=";
1154
1155 if (m_usb_device_desc){
1156 if (is_trezor1(m_usb_device_desc.get()))
1157 o << "TrezorOne";
1158 else if (is_trezor2(m_usb_device_desc.get()))
1159 o << "TrezorT";
1160 else if (is_trezor2_bl(m_usb_device_desc.get()))
1161 o << "TrezorT BL";
1162 } else {
1163 o << "?";
1164 }
1165
1166 return o << ">";
1167 };
1168
1169 #endif // WITH_DEVICE_TREZOR_WEBUSB
1170
1171 void enumerate(t_transport_vect & res){
1172 BridgeTransport bt;
1173 try{
1174 bt.enumerate(res);
1175 } catch (const std::exception & e){
1176 MERROR("BridgeTransport enumeration failed:" << e.what());
1177 }
1178
1179 #ifdef WITH_DEVICE_TREZOR_WEBUSB
1180 hw::trezor::WebUsbTransport btw;
1181 try{
1182 btw.enumerate(res);
1183 } catch (const std::exception & e){
1184 MERROR("WebUsbTransport enumeration failed:" << e.what());
1185 }
1186 #endif
1187
1188 #ifdef WITH_DEVICE_TREZOR_UDP
1189 hw::trezor::UdpTransport btu;
1190 try{
1191 btu.enumerate(res);
1192 } catch (const std::exception & e){
1193 MERROR("UdpTransport enumeration failed:" << e.what());
1194 }
1195 #endif
1196 }
1197
1198 void sort_transports_by_env(t_transport_vect & res){
1199 const char *env_trezor_path = getenv("TREZOR_PATH");
1200 if (!env_trezor_path){
1201 return;
1202 }
1203
1204 // Sort transports by the longest matching prefix with TREZOR_PATH
1205 std::string trezor_path(env_trezor_path);
1206 std::vector<size_t> match_idx(res.size());
1207 std::vector<size_t> path_permutation(res.size());
1208
1209 for(size_t i = 0; i < res.size(); ++i){
1210 auto cpath = res[i]->get_path();
1211 std::string * s1 = &trezor_path;
1212 std::string * s2 = &cpath;
1213
1214 // first has to be shorter in std::mismatch(). Returns first non-matching iterators.
1215 if (s1->size() >= s2->size()){
1216 std::swap(s1, s2);
1217 }
1218
1219 const auto mism = std::mismatch(s1->begin(), s1->end(), s2->begin());
1220 match_idx[i] = mism.first - s1->begin();
1221 path_permutation[i] = i;
1222 }
1223
1224 std::sort(path_permutation.begin(), path_permutation.end(), [&](const size_t i0, const size_t i1) {
1225 return match_idx[i0] > match_idx[i1];
1226 });
1227
1228 tools::apply_permutation(path_permutation, res);
1229 }
1230
1231 std::shared_ptr<Transport> transport(const std::string & path){
1232 if (boost::starts_with(path, BridgeTransport::PATH_PREFIX)){
1233 return std::make_shared<BridgeTransport>(path.substr(strlen(BridgeTransport::PATH_PREFIX)));
1234
1235 } else if (boost::starts_with(path, UdpTransport::PATH_PREFIX)){
1236 return std::make_shared<UdpTransport>(path.substr(strlen(UdpTransport::PATH_PREFIX)));
1237
1238 } else {
1239 throw std::invalid_argument("Unknown Trezor device path: " + path);
1240
1241 }
1242 }
1243
1244 void throw_failure_exception(const messages::common::Failure * failure) {
1245 if (failure == nullptr){
1246 throw std::invalid_argument("Failure message cannot be null");
1247 }
1248
1249 boost::optional<std::string> message = failure->has_message() ? boost::make_optional(failure->message()) : boost::none;
1250 boost::optional<uint32_t> code = failure->has_code() ? boost::make_optional(static_cast<uint32_t>(failure->code())) : boost::none;
1251 if (!code){
1252 throw exc::proto::FailureException(code, message);
1253 }
1254
1255 auto ecode = failure->code();
1256 if (ecode == messages::common::Failure_FailureType_Failure_UnexpectedMessage){
1257 throw exc::proto::UnexpectedMessageException(code, message);
1258 } else if (ecode == messages::common::Failure_FailureType_Failure_ActionCancelled){
1259 throw exc::proto::CancelledException(code, message);
1260 } else if (ecode == messages::common::Failure_FailureType_Failure_PinExpected){
1261 throw exc::proto::PinExpectedException(code, message);
1262 } else if (ecode == messages::common::Failure_FailureType_Failure_PinInvalid){
1263 throw exc::proto::InvalidPinException(code, message);
1264 } else if (ecode == messages::common::Failure_FailureType_Failure_NotEnoughFunds){
1265 throw exc::proto::NotEnoughFundsException(code, message);
1266 } else if (ecode == messages::common::Failure_FailureType_Failure_NotInitialized){
1267 throw exc::proto::NotInitializedException(code, message);
1268 } else if (ecode == messages::common::Failure_FailureType_Failure_FirmwareError){
1269 throw exc::proto::FirmwareErrorException(code, message);
1270 } else {
1271 throw exc::proto::FailureException(code, message);
1272 }
1273 }
1274
1275 GenericMessage::GenericMessage(messages::MessageType m_type, const shared_ptr<google::protobuf::Message> &m_msg)
1276 : m_type(m_type), m_msg(m_msg), m_empty(false) {}
1277
1278 std::ostream& operator<<(std::ostream& o, hw::trezor::Transport const& t){
1279 return t.dump(o);
1280 }
1281
1282 std::ostream& operator<<(std::ostream& o, std::shared_ptr<hw::trezor::Transport> const& t){
1283 if (!t){
1284 return o << "None";
1285 }
1286
1287 return t->dump(o);
1288 }
1289
1290 }
1291 }
1292