Debian Codegraph @

monero/src/device_trezor/device_trezor_base.hpp

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