Monero
device_trezor_base.hpp
Go to the documentation of this file.
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 "device/device.hpp"
38 #include "device/device_cold.hpp"
39 #include <boost/scope_exit.hpp>
40 #include <boost/thread/mutex.hpp>
41 #include <boost/thread/recursive_mutex.hpp>
42 #include "cryptonote_config.h"
43 #include "trezor.hpp"
44 
45 #ifdef WITH_TREZOR_DEBUGGING
46 #include "trezor/debug_link.hpp"
47 #endif
48 
49 //automatic lock one more level on device ensuring the current thread is allowed to use it
50 #define TREZOR_AUTO_LOCK_CMD() \
51  /* lock both mutexes without deadlock*/ \
52  boost::lock(device_locker, command_locker); \
53  /* make sure both already-locked mutexes are unlocked at the end of scope */ \
54  boost::lock_guard<boost::recursive_mutex> lock1(device_locker, boost::adopt_lock); \
55  boost::lock_guard<boost::mutex> lock2(command_locker, boost::adopt_lock)
56 
57 #define TREZOR_AUTO_LOCK_DEVICE() boost::lock_guard<boost::recursive_mutex> lock1_device(device_locker)
58 
59 namespace hw {
60 namespace trezor {
61 
62 #ifdef WITH_DEVICE_TREZOR
63  class device_trezor_base;
64 
65 #ifdef WITH_TREZOR_DEBUGGING
66  class trezor_debug_callback : public hw::i_device_callback {
67  public:
68  trezor_debug_callback()=default;
69  explicit trezor_debug_callback(std::shared_ptr<Transport> & debug_transport);
70 
71  void on_button_request(uint64_t code=0) override;
72  boost::optional<epee::wipeable_string> on_pin_request() override;
73  boost::optional<epee::wipeable_string> on_passphrase_request(bool & on_device) override;
74  void on_passphrase_state_request(const std::string &state);
75  void on_disconnect();
76  protected:
77  std::shared_ptr<DebugLink> m_debug_link;
78  };
79 
80 #endif
81 
85  class device_trezor_base : public hw::core::device_default {
86  protected:
87 
88  // Locker for concurrent access
89  mutable boost::recursive_mutex device_locker;
90  mutable boost::mutex command_locker;
91 
92  std::shared_ptr<Transport> m_transport;
93  i_device_callback * m_callback;
94 
95  std::string m_full_name;
96  std::vector<unsigned int> m_wallet_deriv_path;
97  epee::wipeable_string m_device_session_id; // returned after passphrase entry, session
98  std::shared_ptr<messages::management::Features> m_features; // features from the last device reset
99  boost::optional<epee::wipeable_string> m_pin;
100  boost::optional<epee::wipeable_string> m_passphrase;
101  messages::MessageType m_last_msg_type;
102 
104  bool m_reply_with_empty_passphrase;
105  bool m_always_use_empty_passphrase;
106  bool m_seen_passphrase_entry_message;
107 
108 #ifdef WITH_TREZOR_DEBUGGING
109  std::shared_ptr<trezor_debug_callback> m_debug_callback;
110  bool m_debug;
111 
112  void setup_debug();
113 #endif
114 
115  //
116  // Internal methods
117  //
118 
119  void require_connected() const;
120  void require_initialized() const;
121  void call_ping_unsafe();
122  void test_ping();
123  virtual void device_state_initialize_unsafe();
124  void ensure_derivation_path() noexcept;
125 
126  // Communication methods
127 
128  void write_raw(const google::protobuf::Message * msg);
129  GenericMessage read_raw();
130  GenericMessage call_raw(const google::protobuf::Message * msg);
131 
132  // Trezor message protocol handler. Handles specific signalling messages.
133  bool message_handler(GenericMessage & input);
134 
141  template<class t_message=google::protobuf::Message>
142  std::shared_ptr<t_message>
143  client_exchange(const std::shared_ptr<const google::protobuf::Message> &req,
144  const boost::optional<messages::MessageType> & resp_type = boost::none,
145  const boost::optional<std::vector<messages::MessageType>> & resp_types = boost::none,
146  const boost::optional<messages::MessageType*> & resp_type_ptr = boost::none,
147  bool open_session = false)
148  {
149  // Require strictly protocol buffers response in the template.
152  if (resp_types && !accepting_base){
153  throw std::invalid_argument("Cannot specify list of accepted types and not using generic response");
154  }
155 
156  // Determine type of expected message response
157  const messages::MessageType required_type = accepting_base ? messages::MessageType_Success :
158  (resp_type ? resp_type.get() : MessageMapper::get_message_wire_number<t_message>());
159 
160  // Open session if required
161  if (open_session){
162  try {
163  m_transport->open();
164  } catch (const std::exception& e) {
165  std::throw_with_nested(exc::SessionException("Could not open session"));
166  }
167  }
168 
169  // Scoped session closer
170  BOOST_SCOPE_EXIT_ALL(&, this) {
171  if (open_session && this->get_transport()){
172  this->get_transport()->close();
173  }
174  };
175 
176  // Write/read the request
177  CHECK_AND_ASSERT_THROW_MES(req, "Request is null");
178  auto msg_resp = call_raw(req.get());
179 
180  bool processed = false;
181  do {
182  processed = message_handler(msg_resp);
183  } while(processed);
184 
185  // Response section
186  if (resp_type_ptr){
187  *(resp_type_ptr.get()) = msg_resp.m_type;
188  }
189 
190  if (msg_resp.m_type == messages::MessageType_Failure) {
191  throw_failure_exception(dynamic_cast<messages::common::Failure *>(msg_resp.m_msg.get()));
192 
193  } else if (!accepting_base && msg_resp.m_type == required_type) {
194  return message_ptr_retype<t_message>(msg_resp.m_msg);
195 
196  } else if (accepting_base && (!resp_types ||
197  std::find(resp_types.get().begin(), resp_types.get().end(), msg_resp.m_type) != resp_types.get().end())) {
198  return message_ptr_retype<t_message>(msg_resp.m_msg);
199 
200  } else {
201  throw exc::UnexpectedMessageException(msg_resp.m_type, msg_resp.m_msg);
202  }
203  }
204 
208  template<class t_message>
209  void set_msg_addr(t_message * msg,
210  const boost::optional<std::vector<uint32_t>> & path = boost::none,
211  const boost::optional<cryptonote::network_type> & network_type = boost::none)
212  {
213  CHECK_AND_ASSERT_THROW_MES(msg, "Message is null");
214  msg->clear_address_n();
215  if (path){
216  for(auto x : path.get()){
217  msg->add_address_n(x);
218  }
219  } else {
220  ensure_derivation_path();
221  for (unsigned int i : DEFAULT_BIP44_PATH) {
222  msg->add_address_n(i);
223  }
224  for (unsigned int i : m_wallet_deriv_path) {
225  msg->add_address_n(i);
226  }
227  }
228 
229  if (network_type){
230  msg->set_network_type(static_cast<uint32_t>(network_type.get()));
231  } else {
232  msg->set_network_type(static_cast<uint32_t>(this->network_type));
233  }
234  }
235 
236  public:
237  device_trezor_base();
238  ~device_trezor_base() override;
239 
240  device_trezor_base(const device_trezor_base &device) = delete ;
241  device_trezor_base& operator=(const device_trezor_base &device) = delete;
242 
243  explicit operator bool() const override {return true;}
244  device_type get_type() const override {return device_type::TREZOR;};
245 
246  bool reset();
247 
248  // Default derivation path for Monero
249  static const uint32_t DEFAULT_BIP44_PATH[2];
250 
251  std::shared_ptr<Transport> get_transport(){
252  return m_transport;
253  }
254 
255  void set_callback(i_device_callback * callback) override {
256  m_callback = callback;
257  }
258 
259  i_device_callback * get_callback(){
260  return m_callback;
261  }
262 
263  std::shared_ptr<messages::management::Features> & get_features() {
264  return m_features;
265  }
266 
267  uint64_t get_version() const {
268  CHECK_AND_ASSERT_THROW_MES(m_features, "Features not loaded");
269  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");
270  return pack_version(m_features->major_version(), m_features->minor_version(), m_features->patch_version());
271  }
272 
273  void set_derivation_path(const std::string &deriv_path) override;
274 
275  virtual bool has_ki_live_refresh(void) const override { return false; }
276 
277  virtual void set_pin(const epee::wipeable_string & pin) override {
278  m_pin = pin;
279  }
280  virtual void set_passphrase(const epee::wipeable_string & passphrase) override {
281  m_passphrase = passphrase;
282  }
283 
284  /* ======================================================================= */
285  /* SETUP/TEARDOWN */
286  /* ======================================================================= */
287  bool set_name(const std::string &name) override;
288 
289  const std::string get_name() const override;
290  bool init() override;
291  bool release() override;
292  bool connect() override;
293  bool disconnect() override;
294 
295  /* ======================================================================= */
296  /* LOCKER */
297  /* ======================================================================= */
298  void lock() override;
299  void unlock() override;
300  bool try_lock() override;
301 
302  /* ======================================================================= */
303  /* TREZOR PROTOCOL */
304  /* ======================================================================= */
305 
309  bool ping();
310 
314  void device_state_reset();
315 
316  // Protocol callbacks
317  void on_button_request(GenericMessage & resp, const messages::common::ButtonRequest * msg);
318  void on_button_pressed();
319  void on_pin_request(GenericMessage & resp, const messages::common::PinMatrixRequest * msg);
320  void on_passphrase_request(GenericMessage & resp, const messages::common::PassphraseRequest * msg);
321  void on_passphrase_state_request(GenericMessage & resp, const messages::common::Deprecated_PassphraseStateRequest * msg);
322 
323 #ifdef WITH_TREZOR_DEBUGGING
324  void set_debug(bool debug){
325  m_debug = debug;
326  }
327 
328  void set_debug_callback(std::shared_ptr<trezor_debug_callback> & debug_callback){
329  m_debug_callback = debug_callback;
330  }
331 
332  void wipe_device();
333  void init_device();
334  void load_device(const std::string & mnemonic, const std::string & pin="", bool passphrase_protection=false,
335  const std::string & label="test", const std::string & language="english",
336  bool skip_checksum=false, bool expand=false);
337 
338 #endif
339  };
340 
341 #endif
342 
343 }
344 }
345 #endif //MONERO_DEVICE_TREZOR_BASE_H
static int init(int argc, char **argv, struct runtime_vars *v)
Definition: miniupnpd.c:1149
def release
Definition: support.py:307
int i
Definition: pymoduletest.py:23
::std::string string
Definition: gtest-port.h:1097
Definition: minissdpd.c:75
e
Definition: pymoduletest.py:79
const portMappingElt code
Definition: portlistingparse.c:22
unsigned int uint32_t
Definition: stdint.h:126
unsigned __int64 uint64_t
Definition: stdint.h:136
get_version
Definition: console.py:54
Definition: device.cpp:38
void throw_failure_exception(const messages::common::Failure *failure)
Definition: transport.cpp:1244
uint64_t pack_version(uint32_t major, uint32_t minor, uint32_t patch)
Definition: transport.cpp:100
network_type
Definition: cryptonote_config.h:301
Definition: blake256.h:36
const GenericPointer< typename T::ValueType > T2 value
Definition: pointer.h:1225
int bool
Definition: stdbool.h:35
Definition: device_default.hpp:40
Definition: wipeable_string.h:40
const char * name
Definition: options.c:30
Definition: device.hpp:77