forked from someone42/hardware-bitcoin-wallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream_comm.c
2056 lines (1904 loc) · 62.1 KB
/
stream_comm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** \file stream_comm.c
*
* \brief Deals with packets sent over the stream device.
*
* The most important function in this file is processPacket(). It decodes
* packets from the stream and calls the relevant functions from wallet.c or
* transaction.c. Some validation of the received data is also handled in
* this file. Here is a general rule for what validation is done: if the
* validation can be done without knowing the internal details of how wallets
* are stored or how transactions are parsed, then the validation is done
* in this file. Finally, the functions in this file translate the return
* values from wallet.c and transaction.c into response packets which are
* sent over the stream device.
*
* This file is licensed as described by the file LICENCE.
*/
#ifdef TEST
#include <stdio.h>
#include <assert.h>
#endif // #ifdef TEST
#ifdef TEST_STREAM_COMM
#include <string.h>
#endif // #ifdef TEST_STREAM_COMM
#include <stdlib.h> // for definition of NULL
#include "common.h"
#include "endian.h"
#include "hwinterface.h"
#include "wallet.h"
#include "bignum256.h"
#include "stream_comm.h"
#include "prandom.h"
#include "xex.h"
#include "ecdsa.h"
#include "storage_common.h"
#include "pb.h"
#include "pb_decode.h"
#include "pb_encode.h"
#include "messages.pb.h"
#include "sha256.h"
#include "transaction.h"
#ifdef TEST_STREAM_COMM
#include "test_helpers.h"
#endif // #ifdef TEST_STREAM_COMM
// Prototypes for forward-referenced functions.
bool mainInputStreamCallback(pb_istream_t *stream, uint8_t *buf, size_t count);
bool mainOutputStreamCallback(pb_ostream_t *stream, const uint8_t *buf, size_t count);
static void writeFailureString(StringSet set, uint8_t spec);
bool hashFieldCallback(pb_istream_t *stream, const pb_field_t *field, void **arg);
/** Maximum size (in bytes) of any protocol buffer message sent by functions
* in this file. */
#define MAX_SEND_SIZE 255
/** Union of field buffers for all protocol buffer messages. They're placed
* in a union to make memory access more efficient, since the functions in
* this file only need to deal with one message at any one time. */
union MessageBufferUnion
{
Initialize initialize;
Features features;
Ping ping;
PingResponse ping_response;
DeleteWallet delete_wallet;
NewWallet new_wallet;
NewAddress new_address;
GetNumberOfAddresses get_number_of_addresses;
NumberOfAddresses number_of_addresses;
GetAddressAndPublicKey get_address_and_public_key;
LoadWallet load_wallet;
FormatWalletArea format_wallet_area;
ChangeEncryptionKey change_encryption_key;
ChangeWalletName change_wallet_name;
ListWallets list_wallets;
Wallets wallets;
BackupWallet backup_wallet;
RestoreWallet restore_wallet;
GetDeviceUUID get_device_uuid;
DeviceUUID device_uuid;
GetEntropy get_entropy;
GetMasterPublicKey get_master_public_key;
MasterPublicKey master_public_key;
};
/** Determines the string that writeStringCallback() will write. */
struct StringSetAndSpec
{
/** String set (see getString()) of string to be outputted. */
StringSet next_set;
/** String specifier (see getString()) of string to be outputted. */
uint8_t next_spec;
};
/** The transaction hash of the most recently approved transaction. This is
* stored so that if a transaction needs to be signed multiple times (eg.
* if it has more than one input), the user doesn't have to approve every
* one. */
static uint8_t prev_transaction_hash[32];
/** false means disregard #prev_transaction_hash, true means
* that #prev_transaction_hash is valid. */
static bool prev_transaction_hash_valid;
/** Length of current packet's payload. */
static uint32_t payload_length;
/** Argument for writeStringCallback() which determines what string it will
* write. Don't put this on the stack, otherwise the consequences of a
* dangling pointer are less secure. */
static struct StringSetAndSpec string_arg;
/** Alternate copy of #string_arg, for when more than one string needs to be
* written. */
static struct StringSetAndSpec string_arg_alt;
/** Current number of wallets; used for the listWalletsCallback() callback
* function. */
static uint32_t number_of_wallets;
/** Pointer to bytes of entropy to send to the host; used for
* the getEntropyCallback() callback function. */
static uint8_t *entropy_buffer;
/** Number of bytes of entropy to send to the host; used for
* the getEntropyCallback() callback function. */
static size_t num_entropy_bytes;
/** Storage for fields of SignTransaction message. Needed for the
* signTransactionCallback() callback function. */
static SignTransaction sign_transaction;
/** Double SHA-256 of a field parsed by hashFieldCallback(). */
static uint8_t field_hash[32];
/** Whether #field_hash has been set. */
static bool field_hash_set;
/** Number of valid bytes in #session_id. */
static size_t session_id_length;
/** Arbitrary host-supplied bytes which are sent to the host to assure it that
* a reset hasn't occurred. */
static uint8_t session_id[64];
/** nanopb input stream which uses mainInputStreamCallback() as a stream
* callback. */
pb_istream_t main_input_stream = {&mainInputStreamCallback, NULL, 0, NULL};
/** nanopb output stream which uses mainOutputStreamCallback() as a stream
* callback. */
pb_ostream_t main_output_stream = {&mainOutputStreamCallback, NULL, 0, 0, NULL};
#ifdef TEST_STREAM_COMM
/** When sending test packets, the OTP stored here will be used instead of
* a generated OTP. This allows the test cases to be static. */
static char test_otp[OTP_LENGTH] = {'1', '2', '3', '4', '\0'};
#endif // #ifdef TEST_STREAM_COMM
/** Read bytes from the stream.
* \param buffer The byte array where the bytes will be placed. This must
* have enough space to store length bytes.
* \param length The number of bytes to read.
*/
static void getBytesFromStream(uint8_t *buffer, uint8_t length)
{
uint8_t i;
for (i = 0; i < length; i++)
{
buffer[i] = streamGetOneByte();
}
payload_length -= length;
}
/** Write a number of bytes to the output stream.
* \param buffer The array of bytes to be written.
* \param length The number of bytes to write.
*/
static void writeBytesToStream(const uint8_t *buffer, size_t length)
{
size_t i;
for (i = 0; i < length; i++)
{
streamPutOneByte(buffer[i]);
}
}
/** nanopb input stream callback which uses streamGetOneByte() to get the
* requested bytes.
* \param stream Input stream object that issued the callback.
* \param buf Buffer to fill with requested bytes.
* \param count Requested number of bytes.
* \return true on success, false on failure (nanopb convention).
*/
bool mainInputStreamCallback(pb_istream_t *stream, uint8_t *buf, size_t count)
{
size_t i;
if (buf == NULL)
{
fatalError(); // this should never happen
}
for (i = 0; i < count; i++)
{
if (payload_length == 0)
{
// Attempting to read past end of payload.
stream->bytes_left = 0;
return false;
}
buf[i] = streamGetOneByte();
payload_length--;
}
return true;
}
/** nanopb output stream callback which uses streamPutOneByte() to send a byte
* buffer.
* \param stream Output stream object that issued the callback.
* \param buf Buffer with bytes to send.
* \param count Number of bytes to send.
* \return true on success, false on failure (nanopb convention).
*/
bool mainOutputStreamCallback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
{
writeBytesToStream(buf, count);
return true;
}
/** Read but ignore #payload_length bytes from input stream. This will also
* set #payload_length to 0 (if everything goes well). This function is
* useful for ensuring that the entire payload of a packet is read from the
* stream device.
*/
static void readAndIgnoreInput(void)
{
if (payload_length > 0)
{
for (; payload_length > 0; payload_length--)
{
streamGetOneByte();
}
}
}
/** Receive a message from the stream #main_input_stream.
* \param fields Field description array.
* \param dest_struct Where field data will be stored.
* \return false on success, true if a parse error occurred.
*/
static bool receiveMessage(const pb_field_t fields[], void *dest_struct)
{
bool r;
r = pb_decode(&main_input_stream, fields, dest_struct);
// In order for the message to be considered valid, it must also occupy
// the entire payload of the packet.
if ((payload_length > 0) || !r)
{
readAndIgnoreInput();
writeFailureString(STRINGSET_MISC, MISCSTR_INVALID_PACKET);
return true;
}
else
{
return false;
}
}
/** Send a packet.
* \param message_id The message ID of the packet.
* \param fields Field description array.
* \param src_struct Field data which will be serialised and sent.
*/
static void sendPacket(uint16_t message_id, const pb_field_t fields[], const void *src_struct)
{
uint8_t buffer[4];
pb_ostream_t substream;
#ifdef TEST_STREAM_COMM
// From PROTOCOL, the current received packet must be fully consumed
// before any response can be sent.
assert(payload_length == 0);
#endif
// Use a non-writing substream to get the length of the message without
// storing it anywhere.
substream.callback = NULL;
substream.state = NULL;
substream.max_size = MAX_SEND_SIZE;
substream.bytes_written = 0;
if (!pb_encode(&substream, fields, src_struct))
{
fatalError();
}
// Send packet header.
streamPutOneByte('#');
streamPutOneByte('#');
streamPutOneByte((uint8_t)(message_id >> 8));
streamPutOneByte((uint8_t)message_id);
writeU32BigEndian(buffer, substream.bytes_written);
writeBytesToStream(buffer, 4);
// Send actual message.
main_output_stream.bytes_written = 0;
main_output_stream.max_size = substream.bytes_written;
if (!pb_encode(&main_output_stream, fields, src_struct))
{
fatalError();
}
}
/** nanopb field callback which will write the string specified by arg.
* \param stream Output stream to write to.
* \param field Field which contains the string.
* \param arg Pointer to #StringSetAndSpec structure specifying the string
* to write.
* \return true on success, false on failure (nanopb convention).
*/
bool writeStringCallback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
{
uint16_t i;
uint16_t length;
char c;
struct StringSetAndSpec **ptr_arg_s;
struct StringSetAndSpec *arg_s;
ptr_arg_s = (struct StringSetAndSpec **)arg;
if (ptr_arg_s == NULL)
{
fatalError(); // this should never happen
}
arg_s = *ptr_arg_s;
if (arg_s == NULL)
{
fatalError(); // this should never happen
}
length = getStringLength(arg_s->next_set, arg_s->next_spec);
if (!pb_encode_tag_for_field(stream, field))
{
return false;
}
// Cannot use pb_encode_string() because it expects a pointer to the
// contents of an entire string; getString() does not return such a
// pointer.
if (!pb_encode_varint(stream, (uint64_t)length))
{
return false;
}
for (i = 0; i < length; i++)
{
c = getString(arg_s->next_set, arg_s->next_spec, i);
if (!pb_write(stream, (uint8_t *)&c, 1))
{
return false;
}
}
return true;
}
/** Sends a Failure message with the specified error message.
* \param set See getString().
* \param spec See getString().
*/
static void writeFailureString(StringSet set, uint8_t spec)
{
Failure message_buffer;
uint32_t code;
string_arg.next_set = set;
string_arg.next_spec = spec;
code = (uint32_t)spec & 0xffff;
code |= ((uint32_t)set & 0xffff) << 16;
message_buffer.error_code = code;
message_buffer.error_message.funcs.encode = &writeStringCallback;
message_buffer.error_message.arg = &string_arg;
sendPacket(PACKET_TYPE_FAILURE, Failure_fields, &message_buffer);
}
/** Translates a return value from one of the wallet functions into a Success
* or Failure response packet which is written to the stream.
* \param r The return value from the wallet function.
*/
static void translateWalletError(WalletErrors r)
{
Success message_buffer;
if (r == WALLET_NO_ERROR)
{
sendPacket(PACKET_TYPE_SUCCESS, Success_fields, &message_buffer);
}
else
{
writeFailureString(STRINGSET_WALLET, (uint8_t)r);
}
}
/** Receive packet header.
* \return Message ID (i.e. command type) of packet.
*/
static uint16_t receivePacketHeader(void)
{
uint8_t buffer[4];
uint16_t message_id;
getBytesFromStream(buffer, 2);
if ((buffer[0] != '#') || (buffer[1] != '#'))
{
fatalError(); // invalid header
}
getBytesFromStream(buffer, 2);
message_id = (uint16_t)(((uint16_t)buffer[0] << 8) | ((uint16_t)buffer[1]));
getBytesFromStream(buffer, 4);
payload_length = readU32BigEndian(buffer);
// TODO: size_t not generally uint32_t
main_input_stream.bytes_left = payload_length;
return message_id;
}
/** Begin ButtonRequest interjection. This asks the host whether it is okay
* to prompt the user and wait for a button press.
* \param command The action to ask the user about. See #AskUserCommandEnum.
* \return false if the user accepted, true if the user or host denied.
*/
static bool buttonInterjection(AskUserCommand command)
{
uint16_t message_id;
ButtonRequest button_request;
ButtonAck button_ack;
ButtonCancel button_cancel;
bool receive_failure;
memset(&button_request, 0, sizeof(button_request));
sendPacket(PACKET_TYPE_BUTTON_REQUEST, ButtonRequest_fields, &button_request);
message_id = receivePacketHeader();
if (message_id == PACKET_TYPE_BUTTON_ACK)
{
// Host will allow button press.
receive_failure = receiveMessage(ButtonAck_fields, &button_ack);
if (receive_failure)
{
return true;
}
else
{
if (userDenied(command))
{
writeFailureString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED_USER);
return true;
}
else
{
return false;
}
}
}
else if (message_id == PACKET_TYPE_BUTTON_CANCEL)
{
// Host will not allow button press. The only way to safely deal
// with this is to unconditionally deny permission for the
// requested action.
receive_failure = receiveMessage(ButtonCancel_fields, &button_cancel);
if (!receive_failure)
{
writeFailureString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED_HOST);
}
return true;
}
else
{
// Unexpected message.
readAndIgnoreInput();
writeFailureString(STRINGSET_MISC, MISCSTR_UNEXPECTED_PACKET);
return true;
}
}
/** Begin PinRequest interjection. This asks the host to submit a password
* to the device. If the host does submit a password, then #field_hash_set
* will be set and #field_hash updated.
* \return false if the host submitted a password, true on error.
*/
static bool pinInterjection(void)
{
uint16_t message_id;
PinRequest pin_request;
PinAck pin_ack;
PinCancel pin_cancel;
bool receive_failure;
memset(&pin_request, 0, sizeof(pin_request));
sendPacket(PACKET_TYPE_PIN_REQUEST, PinRequest_fields, &pin_request);
message_id = receivePacketHeader();
if (message_id == PACKET_TYPE_PIN_ACK)
{
// Host has just sent password.
field_hash_set = false;
memset(field_hash, 0, sizeof(field_hash));
pin_ack.password.funcs.decode = &hashFieldCallback;
pin_ack.password.arg = NULL;
receive_failure = receiveMessage(PinAck_fields, &pin_ack);
if (receive_failure)
{
return true;
}
else
{
if (!field_hash_set)
{
fatalError(); // should never happen since password is a required field
}
return false;
}
}
else if (message_id == PACKET_TYPE_PIN_CANCEL)
{
// Host does not want to send password.
receive_failure = receiveMessage(PinCancel_fields, &pin_cancel);
if (!receive_failure)
{
writeFailureString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED_HOST);
}
return true;
}
else
{
// Unexpected message.
readAndIgnoreInput();
writeFailureString(STRINGSET_MISC, MISCSTR_UNEXPECTED_PACKET);
return true;
}
}
/** Begin OtpRequest interjection. This asks the host to submit a one-time
* password that is displayed on the device.
* \return false if the host submitted a matching password, true on error.
*/
static bool otpInterjection(AskUserCommand command)
{
uint16_t message_id;
OtpRequest otp_request;
OtpAck otp_ack;
OtpCancel otp_cancel;
bool receive_failure;
char otp[OTP_LENGTH];
generateInsecureOTP(otp);
#ifdef TEST_STREAM_COMM
memcpy(otp, test_otp, OTP_LENGTH);
#endif // #ifdef TEST_STREAM_COMM
displayOTP(command, otp);
memset(&otp_request, 0, sizeof(otp_request));
sendPacket(PACKET_TYPE_OTP_REQUEST, OtpRequest_fields, &otp_request);
message_id = receivePacketHeader();
clearOTP();
if (message_id == PACKET_TYPE_OTP_ACK)
{
// Host has just sent OTP.
memset(&otp_ack, 0, sizeof(otp_ack));
receive_failure = receiveMessage(OtpAck_fields, &otp_ack);
if (receive_failure)
{
return true;
}
else
{
if (memcmp(otp, otp_ack.otp, MIN(OTP_LENGTH, sizeof(otp_ack.otp))))
{
writeFailureString(STRINGSET_MISC, MISCSTR_OTP_MISMATCH);
return true;
}
else
{
return false;
}
}
}
else if (message_id == PACKET_TYPE_OTP_CANCEL)
{
// Host does not want to send OTP.
receive_failure = receiveMessage(OtpCancel_fields, &otp_cancel);
if (!receive_failure)
{
writeFailureString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED_HOST);
}
return true;
}
else
{
// Unexpected message.
readAndIgnoreInput();
writeFailureString(STRINGSET_MISC, MISCSTR_UNEXPECTED_PACKET);
return true;
}
}
/** nanopb field callback for signature data of SignTransaction message. This
* does (or more accurately, delegates) all the "work" of transaction
* signing: parsing the transaction, asking the user for approval, generating
* the signature and sending the signature.
* \param stream Input stream to read from.
* \param field Field which contains the signature data.
* \param arg Unused.
* \return true on success, false on failure (nanopb convention).
*/
bool signTransactionCallback(pb_istream_t *stream, const pb_field_t *field, void **arg)
{
AddressHandle ah;
bool approved;
bool permission_denied;
TransactionErrors r;
WalletErrors wallet_return;
uint8_t transaction_hash[32];
uint8_t sig_hash[32];
uint8_t private_key[32];
uint8_t signature_length;
Signature message_buffer;
// Validate transaction and calculate hashes of it.
clearOutputsSeen();
r = parseTransaction(sig_hash, transaction_hash, stream->bytes_left);
// parseTransaction() always reads transaction_length bytes, even if parse
// errors occurs. These next two lines are a bit of a hack to account for
// differences between streamGetOneByte() and pb_read(stream, buf, 1).
// The intention is that transaction.c doesn't have to know anything about
// protocol buffers.
payload_length -= stream->bytes_left;
stream->bytes_left = 0;
if (r != TRANSACTION_NO_ERROR)
{
// Transaction parse error.
writeFailureString(STRINGSET_TRANSACTION, (uint8_t)r);
return true;
}
// Get permission from user.
approved = false;
// Does transaction_hash match previous approved transaction?
if (prev_transaction_hash_valid)
{
if (bigCompare(transaction_hash, prev_transaction_hash) == BIGCMP_EQUAL)
{
approved = true;
}
}
if (!approved)
{
// Need to explicitly get permission from user.
// The call to parseTransaction() should have logged all the outputs
// to the user interface.
permission_denied = buttonInterjection(ASKUSER_SIGN_TRANSACTION);
if (!permission_denied)
{
// User approved transaction.
approved = true;
memcpy(prev_transaction_hash, transaction_hash, 32);
prev_transaction_hash_valid = true;
}
} // if (!approved)
if (approved)
{
// Okay to sign transaction.
signature_length = 0;
ah = sign_transaction.address_handle;
if (getPrivateKey(private_key, ah) == WALLET_NO_ERROR)
{
if (sizeof(message_buffer.signature_data.bytes) < MAX_SIGNATURE_LENGTH)
{
// This should never happen.
fatalError();
}
signTransaction(message_buffer.signature_data.bytes, &signature_length, sig_hash, private_key);
message_buffer.signature_data.size = signature_length;
sendPacket(PACKET_TYPE_SIGNATURE, Signature_fields, &message_buffer);
}
else
{
wallet_return = walletGetLastError();
translateWalletError(wallet_return);
}
}
return true;
}
/** Send a packet containing an address and its corresponding public key.
* This can generate new addresses as well as obtain old addresses. Both
* use cases were combined into one function because they involve similar
* processes.
* \param generate_new If this is true, a new address will be generated
* and the address handle of the generated address will
* be prepended to the output packet.
* If this is false, the address handle specified by ah
* will be used.
* \param ah Address handle to use (if generate_new is false).
*/
static NOINLINE void getAndSendAddressAndPublicKey(bool generate_new, AddressHandle ah)
{
Address message_buffer;
PointAffine public_key;
WalletErrors r;
message_buffer.address.size = 20;
if (generate_new)
{
r = WALLET_NO_ERROR;
ah = makeNewAddress(message_buffer.address.bytes, &public_key);
if (ah == BAD_ADDRESS_HANDLE)
{
r = walletGetLastError();
}
}
else
{
r = getAddressAndPublicKey(message_buffer.address.bytes, &public_key, ah);
}
if (r == WALLET_NO_ERROR)
{
message_buffer.address_handle = ah;
if (sizeof(message_buffer.public_key.bytes) < ECDSA_MAX_SERIALISE_SIZE) // sanity check
{
fatalError();
return;
}
message_buffer.public_key.size = ecdsaSerialise(message_buffer.public_key.bytes, &public_key, true);
sendPacket(PACKET_TYPE_ADDRESS_PUBKEY, Address_fields, &message_buffer);
}
else
{
translateWalletError(r);
} // end if (r == WALLET_NO_ERROR)
}
/** nanopb field callback which will write repeated WalletInfo messages; one
* for each wallet on the device.
* \param stream Output stream to write to.
* \param field Field which contains the WalletInfo submessage.
* \param arg Unused.
* \return true on success, false on failure (nanopb convention).
*/
bool listWalletsCallback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
{
uint32_t version;
uint32_t i;
WalletInfo message_buffer;
for (i = 0; i < number_of_wallets; i++)
{
message_buffer.wallet_number = i;
message_buffer.wallet_name.size = NAME_LENGTH;
message_buffer.wallet_uuid.size = UUID_LENGTH;
if (getWalletInfo(
&version,
message_buffer.wallet_name.bytes,
message_buffer.wallet_uuid.bytes,
i) != WALLET_NO_ERROR)
{
// It's too late to return an error message, so cut off the
// array now.
return true;
}
if (version != VERSION_NOTHING_THERE)
{
if (!pb_encode_tag_for_field(stream, field))
{
return false;
}
if (!pb_encode_submessage(stream, WalletInfo_fields, &message_buffer))
{
return false;
}
}
}
return true;
}
/** nanopb field callback which will write out the contents
* of #entropy_buffer.
* \param stream Output stream to write to.
* \param field Field which contains the the entropy bytes.
* \param arg Unused.
* \return true on success, false on failure (nanopb convention).
*/
bool getEntropyCallback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
{
if (entropy_buffer == NULL)
{
return false;
}
if (!pb_encode_tag_for_field(stream, field))
{
return false;
}
if (!pb_encode_string(stream, entropy_buffer, num_entropy_bytes))
{
return false;
}
return true;
}
/** Return bytes of entropy from the random number generation system.
* \param num_bytes Number of bytes of entropy to send to stream.
*/
static NOINLINE void getBytesOfEntropy(uint32_t num_bytes)
{
Entropy message_buffer;
unsigned int random_bytes_index;
uint8_t random_bytes[1024]; // must be multiple of 32 bytes large
if (num_bytes > sizeof(random_bytes))
{
writeFailureString(STRINGSET_MISC, MISCSTR_PARAM_TOO_LARGE);
return;
}
// All bytes of entropy must be collected before anything can be sent.
// This is because it is only safe to send those bytes if every call
// to getRandom256() succeeded.
random_bytes_index = 0;
num_entropy_bytes = 0;
while (num_bytes--)
{
if (random_bytes_index == 0)
{
if (getRandom256(&(random_bytes[num_entropy_bytes])))
{
translateWalletError(WALLET_RNG_FAILURE);
return;
}
}
num_entropy_bytes++;
random_bytes_index++;
random_bytes_index &= 31;
}
message_buffer.entropy.funcs.encode = &getEntropyCallback;
entropy_buffer = random_bytes;
sendPacket(PACKET_TYPE_ENTROPY, Entropy_fields, &message_buffer);
num_entropy_bytes = 0;
entropy_buffer = NULL;
}
/** nanopb field callback which calculates the double SHA-256 of an arbitrary
* number of bytes. This is useful if we don't care about the contents of a
* field but want to compress an arbitrarily-sized field into a fixed-length
* variable.
* \param stream Input stream to read from.
* \param field Field which contains an arbitrary number of bytes.
* \param arg Unused.
* \return true on success, false on failure (nanopb convention).
*/
bool hashFieldCallback(pb_istream_t *stream, const pb_field_t *field, void **arg)
{
uint8_t one_byte;
HashState hs;
sha256Begin(&hs);
while (stream->bytes_left > 0)
{
if (!pb_read(stream, &one_byte, 1))
{
return false;
}
sha256WriteByte(&hs, one_byte);
}
sha256FinishDouble(&hs);
writeHashToByteArray(field_hash, &hs, true);
field_hash_set = true;
return true;
}
/** Get packet from stream and deal with it. This basically implements the
* protocol described in the file PROTOCOL.
*
* This function will always completely
* read a packet before sending a response packet. As long as the host
* does the same thing, deadlocks cannot occur. Thus a productive
* communication session between the hardware Bitcoin wallet and a host
* should consist of the wallet and host alternating between sending a
* packet and receiving a packet.
*/
void processPacket(void)
{
uint16_t message_id;
union MessageBufferUnion message_buffer;
PointAffine master_public_key;
bool receive_failure;
bool permission_denied;
bool invalid_otp;
unsigned int password_length;
WalletErrors wallet_return;
char ping_greeting[sizeof(message_buffer.ping.greeting)];
bool has_ping_greeting;
message_id = receivePacketHeader();
// Checklist for each case:
// 1. Have you checked or dealt with length?
// 2. Have you fully read the input stream before writing (to avoid
// deadlocks)?
// 3. Have you asked permission from the user (for potentially dangerous
// operations)?
// 4. Have you checked for errors from wallet functions?
// 5. Have you used the right check for the wallet functions?
memset(&message_buffer, 0, sizeof(message_buffer));
switch (message_id)
{
case PACKET_TYPE_INITIALIZE:
// Reset state and report features.
session_id_length = 0; // just in case receiveMessage() fails
receive_failure = receiveMessage(Initialize_fields, &(message_buffer.initialize));
if (!receive_failure)
{
session_id_length = message_buffer.initialize.session_id.size;
if (session_id_length >= sizeof(session_id))
{
fatalError(); // sanity check failed
}
memcpy(session_id, message_buffer.initialize.session_id.bytes, session_id_length);
prev_transaction_hash_valid = false;
sanitiseRam();
wallet_return = uninitWallet();
if (wallet_return == WALLET_NO_ERROR)
{
memset(&message_buffer, 0, sizeof(message_buffer));
message_buffer.features.echoed_session_id.size = session_id_length;
if (session_id_length >= sizeof(message_buffer.features.echoed_session_id.bytes))
{
fatalError(); // sanity check failed
}
memcpy(message_buffer.features.echoed_session_id.bytes, session_id, session_id_length);
string_arg.next_set = STRINGSET_MISC;
string_arg.next_spec = MISCSTR_VENDOR;
message_buffer.features.vendor.funcs.encode = &writeStringCallback;
message_buffer.features.vendor.arg = &string_arg;
message_buffer.features.has_major_version = true;
message_buffer.features.major_version = VERSION_MAJOR;
message_buffer.features.has_minor_version = true;
message_buffer.features.minor_version = VERSION_MINOR;
string_arg_alt.next_set = STRINGSET_MISC;
string_arg_alt.next_spec = MISCSTR_CONFIG;
message_buffer.features.config.funcs.encode = &writeStringCallback;
message_buffer.features.config.arg = &string_arg_alt;
message_buffer.features.has_otp = true;
message_buffer.features.otp = true;
message_buffer.features.has_pin = true;
message_buffer.features.pin = true;
message_buffer.features.has_spv = true;
message_buffer.features.spv = true;
message_buffer.features.algo_count = 1;
message_buffer.features.algo[0] = Algorithm_BIP32;
message_buffer.features.has_debug_link = true;
message_buffer.features.debug_link = false;
sendPacket(PACKET_TYPE_FEATURES, Features_fields, &(message_buffer.features));
}
else
{
translateWalletError(wallet_return);
}
}
break;
case PACKET_TYPE_PING:
// Ping request.
receive_failure = receiveMessage(Ping_fields, &(message_buffer.ping));
if (!receive_failure)
{
has_ping_greeting = message_buffer.ping.has_greeting;
if (sizeof(message_buffer.ping.greeting) != sizeof(ping_greeting))
{
fatalError(); // sanity check failed
}
if (has_ping_greeting)
{
memcpy(ping_greeting, message_buffer.ping.greeting, sizeof(ping_greeting));
}
ping_greeting[sizeof(ping_greeting) - 1] = '\0'; // ensure that string is terminated
// Generate ping response message.
memset(&message_buffer, 0, sizeof(message_buffer));
message_buffer.ping_response.has_echoed_greeting = has_ping_greeting;
if (sizeof(ping_greeting) != sizeof(message_buffer.ping_response.echoed_greeting))
{
fatalError(); // sanity check failed
}
if (has_ping_greeting)
{
memcpy(message_buffer.ping_response.echoed_greeting, ping_greeting, sizeof(message_buffer.ping_response.echoed_greeting));
}
message_buffer.ping_response.echoed_session_id.size = session_id_length;
if (session_id_length >= sizeof(message_buffer.ping_response.echoed_session_id.bytes))
{
fatalError(); // sanity check failed
}
memcpy(message_buffer.ping_response.echoed_session_id.bytes, session_id, session_id_length);
sendPacket(PACKET_TYPE_PING_RESPONSE, PingResponse_fields, &(message_buffer.ping_response));
}
break;
case PACKET_TYPE_DELETE_WALLET:
// Delete existing wallet.
receive_failure = receiveMessage(DeleteWallet_fields, &(message_buffer.delete_wallet));
if (!receive_failure)
{
permission_denied = buttonInterjection(ASKUSER_DELETE_WALLET);