-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecall.rs
1491 lines (1300 loc) · 49.8 KB
/
ecall.rs
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
use core::{cell::RefCell, cmp::min, fmt};
use alloc::{format, rc::Rc, string::String, vec};
use common::{
client_commands::{
Message, MessageDeserializationError, ReceiveBufferMessage, ReceiveBufferResponse,
SendBufferMessage, SendPanicBufferMessage,
},
ecall_constants::{self, *},
manifest::Manifest,
vm::{Cpu, CpuError, EcallHandler, MemoryError},
};
use ledger_device_sdk::hash::HashInit;
use ledger_secure_sdk_sys::{
cx_ripemd160_t, cx_sha256_t, cx_sha512_t, CX_OK, CX_RIPEMD160, CX_SHA256, CX_SHA512,
};
use crate::{AppSW, Instruction};
use super::outsourced_mem::OutsourcedMemory;
use zeroize::Zeroizing;
// BIP32 supports up to 255, but we don't want that many, and it would be very slow anyway
const MAX_BIP32_PATH: usize = 16;
#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
enum Register {
Zero, // x0, constant zero
Ra, // x1, return address
Sp, // x2, stack pointer
Gp, // x3, global pointer
Tp, // x4, thread pointer
T0, // x5, temporary register
T1, // x6, temporary register
T2, // x7, temporary register
S0, // x8, saved register (frame pointer)
S1, // x9, saved register
A0, // x10, function argument/return value
A1, // x11, function argument/return value
A2, // x12, function argument
A3, // x13, function argument
A4, // x14, function argument
A5, // x15, function argument
A6, // x16, function argument
A7, // x17, function argument
S2, // x18, saved register
S3, // x19, saved register
S4, // x20, saved register
S5, // x21, saved register
S6, // x22, saved register
S7, // x23, saved register
S8, // x24, saved register
S9, // x25, saved register
S10, // x26, saved register
S11, // x27, saved register
T3, // x28, temporary register
T4, // x29, temporary register
T5, // x30, temporary register
T6, // x31, temporary register
}
impl Register {
// To get the register's index as a number (x0 to x31)
pub fn as_index(&self) -> u8 {
match self {
Register::Zero => 0,
Register::Ra => 1,
Register::Sp => 2,
Register::Gp => 3,
Register::Tp => 4,
Register::T0 => 5,
Register::T1 => 6,
Register::T2 => 7,
Register::S0 => 8,
Register::S1 => 9,
Register::A0 => 10,
Register::A1 => 11,
Register::A2 => 12,
Register::A3 => 13,
Register::A4 => 14,
Register::A5 => 15,
Register::A6 => 16,
Register::A7 => 17,
Register::S2 => 18,
Register::S3 => 19,
Register::S4 => 20,
Register::S5 => 21,
Register::S6 => 22,
Register::S7 => 23,
Register::S8 => 24,
Register::S9 => 25,
Register::S10 => 26,
Register::S11 => 27,
Register::T3 => 28,
Register::T4 => 29,
Register::T5 => 30,
Register::T6 => 31,
}
}
}
// A pointer in the V-app's address space
#[derive(Debug, Clone, Copy)]
struct GuestPointer(pub u32);
#[derive(Debug, Clone, Copy)]
enum LedgerHashContextError {
InvalidHashId,
UnsupportedHashId,
}
impl fmt::Display for LedgerHashContextError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LedgerHashContextError::InvalidHashId => write!(f, "Invalid hash id"),
LedgerHashContextError::UnsupportedHashId => write!(f, "Unsupported hash id"),
}
}
}
impl core::error::Error for LedgerHashContextError {}
// A union of all the supported hash contexts, in the same memory layout used in the Ledger SDK
#[repr(C)]
union LedgerHashContext {
ripemd160: cx_ripemd160_t,
sha256: cx_sha256_t,
sha512: cx_sha512_t,
}
impl LedgerHashContext {
const MAX_HASH_CONTEXT_SIZE: usize = core::mem::size_of::<LedgerHashContext>();
const MAX_DIGEST_LEN: usize = 64;
// in-memory size of the hash context struct for the corresponding hash type
fn get_size_from_id(hash_id: u32) -> Result<usize, LedgerHashContextError> {
if hash_id > 255 {
return Err(LedgerHashContextError::InvalidHashId);
}
let res = match hash_id as u8 {
CX_RIPEMD160 => core::mem::size_of::<cx_ripemd160_t>(),
CX_SHA256 => core::mem::size_of::<cx_sha256_t>(),
CX_SHA512 => core::mem::size_of::<cx_sha512_t>(),
_ => return Err(LedgerHashContextError::UnsupportedHashId),
};
assert!(res <= Self::MAX_HASH_CONTEXT_SIZE);
Ok(res)
}
fn get_digest_len_from_id(hash_id: u32) -> Result<usize, LedgerHashContextError> {
if hash_id > 255 {
return Err(LedgerHashContextError::InvalidHashId);
}
let res = match hash_id as u8 {
CX_RIPEMD160 => 20,
CX_SHA256 => 32,
CX_SHA512 => 64,
_ => return Err(LedgerHashContextError::UnsupportedHashId),
};
assert!(res <= Self::MAX_DIGEST_LEN);
Ok(res)
}
}
pub enum CommEcallError {
Exit(i32),
Panic,
InvalidParameters(&'static str),
GenericError(&'static str),
WrongINS,
WrongP1P2,
Overflow,
HashError(LedgerHashContextError),
MessageDeserializationError(MessageDeserializationError),
InvalidResponse(&'static str),
CpuError(String),
MemoryError(MemoryError),
UnhandledEcall,
}
impl core::fmt::Display for CommEcallError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
CommEcallError::Exit(code) => write!(f, "Exit with code {}", code),
CommEcallError::Panic => write!(f, "Panic occurred"),
CommEcallError::InvalidParameters(msg) => {
write!(f, "Invalid parameters: {}", msg)
}
CommEcallError::GenericError(msg) => write!(f, "Error: {}", msg),
CommEcallError::WrongINS => write!(f, "Wrong INS"),
CommEcallError::WrongP1P2 => write!(f, "Wrong P1/P2"),
CommEcallError::Overflow => write!(f, "Buffer overflow"),
CommEcallError::HashError(e) => write!(f, "Hash error: {:?}", e),
CommEcallError::MessageDeserializationError(e) => {
write!(f, "Message deserialization error: {:?}", e)
}
CommEcallError::InvalidResponse(msg) => {
write!(f, "Invalid response from host: {}", msg)
}
CommEcallError::CpuError(e) => write!(f, "Cpu error: {:?}", e),
CommEcallError::MemoryError(e) => write!(f, "Memory error: {:?}", e),
CommEcallError::UnhandledEcall => write!(f, "Unhandled ecall"),
}
}
}
impl core::fmt::Debug for CommEcallError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Display::fmt(self, f)
}
}
impl<E: fmt::Debug> From<CpuError<E>> for CommEcallError {
fn from(error: CpuError<E>) -> Self {
CommEcallError::CpuError(format!("{:?}", error))
}
}
impl From<LedgerHashContextError> for CommEcallError {
fn from(error: LedgerHashContextError) -> Self {
CommEcallError::HashError(error)
}
}
impl From<MemoryError> for CommEcallError {
fn from(error: MemoryError) -> Self {
CommEcallError::MemoryError(error)
}
}
impl From<MessageDeserializationError> for CommEcallError {
fn from(error: MessageDeserializationError) -> Self {
CommEcallError::MessageDeserializationError(error)
}
}
impl core::error::Error for CommEcallError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
CommEcallError::MemoryError(e) => Some(e),
CommEcallError::MessageDeserializationError(e) => Some(e),
CommEcallError::HashError(e) => Some(e),
// since we convert CpuError to a string, we don't keep the original error
_ => None,
}
}
}
pub struct CommEcallHandler<'a> {
comm: Rc<RefCell<&'a mut ledger_device_sdk::io::Comm>>,
manifest: &'a Manifest,
}
impl<'a> CommEcallHandler<'a> {
pub fn new(
comm: Rc<RefCell<&'a mut ledger_device_sdk::io::Comm>>,
manifest: &'a Manifest,
) -> Self {
Self { comm, manifest }
}
// TODO: can we refactor this and handle_xsend? They are almost identical
fn handle_panic<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
buffer: GuestPointer,
mut size: usize,
) -> Result<(), CommEcallError> {
if size == 0 {
// We must not read the pointer for an empty buffer; Rust always uses address 0x01 for
// an empty buffer
let mut comm = self.comm.borrow_mut();
SendPanicBufferMessage::new(size as u32, vec![]).serialize_to_comm(&mut comm);
comm.reply(AppSW::InterruptedExecution);
let Instruction::Continue(p1, p2) = comm.next_command() else {
return Err(CommEcallError::WrongINS); // expected "Continue"
};
if (p1, p2) != (0, 0) {
return Err(CommEcallError::WrongP1P2);
}
return Ok(());
}
if buffer.0.checked_add(size as u32).is_none() {
return Err(CommEcallError::Overflow);
}
let mut g_ptr = buffer.0;
let segment = cpu.get_segment::<E>(g_ptr)?;
// loop while size > 0
while size > 0 {
let copy_size = min(size, 255 - 4); // send maximum 251 bytes per message
let mut buffer = vec![0; copy_size];
segment.read_buffer(g_ptr, &mut buffer)?;
let mut comm = self.comm.borrow_mut();
SendPanicBufferMessage::new(size as u32, buffer).serialize_to_comm(&mut comm);
comm.reply(AppSW::InterruptedExecution);
let Instruction::Continue(p1, p2) = comm.next_command() else {
return Err(CommEcallError::WrongINS); // expected "Continue"
};
if (p1, p2) != (0, 0) {
return Err(CommEcallError::WrongP1P2);
}
size -= copy_size;
g_ptr += copy_size as u32;
}
Ok(())
}
// Sends exactly size bytes from the buffer in the V-app memory to the host
// TODO: we might want to revise the protocol, not as optimized as it could be
fn handle_xsend<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
buffer: GuestPointer,
mut size: usize,
) -> Result<(), CommEcallError> {
if size == 0 {
// We must not read the pointer for an empty buffer; Rust always uses address 0x01 for
// an empty buffer
let mut comm = self.comm.borrow_mut();
SendBufferMessage::new(size as u32, vec![]).serialize_to_comm(&mut comm);
comm.reply(AppSW::InterruptedExecution);
let Instruction::Continue(p1, p2) = comm.next_command() else {
return Err(CommEcallError::WrongINS); // expected "Continue"
};
if (p1, p2) != (0, 0) {
return Err(CommEcallError::WrongP1P2);
}
return Ok(());
}
if buffer.0.checked_add(size as u32).is_none() {
return Err(CommEcallError::Overflow);
}
let mut g_ptr = buffer.0;
let segment = cpu.get_segment::<E>(g_ptr)?;
// loop while size > 0
while size > 0 {
let copy_size = min(size, 255 - 4); // send maximum 251 bytes per message
let mut buffer = vec![0; copy_size];
segment.read_buffer(g_ptr, &mut buffer)?;
let mut comm = self.comm.borrow_mut();
SendBufferMessage::new(size as u32, buffer).serialize_to_comm(&mut comm);
comm.reply(AppSW::InterruptedExecution);
let Instruction::Continue(p1, p2) = comm.next_command() else {
return Err(CommEcallError::WrongINS); // expected "Continue"
};
if (p1, p2) != (0, 0) {
return Err(CommEcallError::WrongP1P2);
}
size -= copy_size;
g_ptr += copy_size as u32;
}
Ok(())
}
// Receives up to max_size bytes from the host into the buffer in the V-app memory
// Returns the catual of bytes received.
fn handle_xrecv<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
buffer: GuestPointer,
max_size: usize,
) -> Result<usize, CommEcallError> {
let mut g_ptr = buffer.0;
let segment = cpu.get_segment::<E>(g_ptr)?;
let mut remaining_length = None;
let mut total_received: usize = 0;
while remaining_length != Some(0) {
let mut comm = self.comm.borrow_mut();
ReceiveBufferMessage::new().serialize_to_comm(&mut comm);
comm.reply(AppSW::InterruptedExecution);
let Instruction::Continue(p1, p2) = comm.next_command() else {
return Err(CommEcallError::WrongINS); // expected "Data"
};
if (p1, p2) != (0, 0) {
return Err(CommEcallError::WrongP1P2);
}
let raw_data = comm
.get_data()
.map_err(|_| CommEcallError::InvalidResponse(""))?;
let response = ReceiveBufferResponse::deserialize(raw_data)?;
drop(comm); // TODO: figure out how to avoid having to deal with this drop explicitly
match remaining_length {
None => {
// first chunk, check if the total length is acceptable
if response.remaining_length > max_size as u32 {
return Err(CommEcallError::InvalidResponse(
"Received data is too large",
));
}
remaining_length = Some(response.remaining_length);
}
Some(remaining) => {
if remaining != response.remaining_length {
return Err(CommEcallError::InvalidResponse(
"Mismatching remaining length",
));
}
}
}
segment.write_buffer(g_ptr, &response.content)?;
remaining_length = Some(remaining_length.unwrap() - response.content.len() as u32);
g_ptr += response.content.len() as u32;
total_received += response.content.len();
}
Ok(total_received)
}
fn handle_bn_modm<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
r: GuestPointer,
n: GuestPointer,
len: usize,
m: GuestPointer,
m_len: usize,
) -> Result<(), CommEcallError> {
if len > MAX_BIGNUMBER_SIZE || m_len > MAX_BIGNUMBER_SIZE {
return Err(CommEcallError::InvalidParameters(
"len or m_len is too large",
));
}
// copy inputs to local memory
// we use r_local both for the input and for the result
let mut r_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(n.0)?
.read_buffer(n.0, &mut r_local[0..len])?;
let mut m_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(m.0)?
.read_buffer(m.0, &mut m_local[0..m_len])?;
unsafe {
let res = ledger_secure_sdk_sys::cx_math_modm_no_throw(
r_local.as_mut_ptr(),
len,
m_local.as_ptr(),
m_len,
);
if res != CX_OK {
return Err(CommEcallError::GenericError("modm failed"));
}
}
// copy r_local to r
let segment = cpu.get_segment::<E>(r.0)?;
segment.write_buffer(r.0, &r_local[0..len])?;
Ok(())
}
fn handle_bn_addm<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
r: GuestPointer,
a: GuestPointer,
b: GuestPointer,
m: GuestPointer,
len: usize,
) -> Result<(), CommEcallError> {
if len > MAX_BIGNUMBER_SIZE {
return Err(CommEcallError::InvalidParameters("len is too large"));
}
// copy inputs to local memory
let mut a_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(a.0)?
.read_buffer(a.0, &mut a_local[0..len])?;
let mut b_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(b.0)?
.read_buffer(b.0, &mut b_local[0..len])?;
let mut m_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(m.0)?
.read_buffer(m.0, &mut m_local[0..len])?;
let mut r_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
unsafe {
let res = ledger_secure_sdk_sys::cx_math_addm_no_throw(
r_local.as_mut_ptr(),
a_local.as_ptr(),
b_local.as_ptr(),
m_local.as_ptr(),
len,
);
if res != CX_OK {
return Err(CommEcallError::GenericError("addm failed"));
}
}
// copy r_local to r
let segment = cpu.get_segment::<E>(r.0)?;
segment.write_buffer(r.0, &r_local[0..len])?;
Ok(())
}
fn handle_bn_subm<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
r: GuestPointer,
a: GuestPointer,
b: GuestPointer,
m: GuestPointer,
len: usize,
) -> Result<(), CommEcallError> {
if len > MAX_BIGNUMBER_SIZE {
return Err(CommEcallError::InvalidParameters("len is too large"));
}
// copy inputs to local memory
let mut a_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(a.0)?
.read_buffer(a.0, &mut a_local[0..len])?;
let mut b_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(b.0)?
.read_buffer(b.0, &mut b_local[0..len])?;
let mut m_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(m.0)?
.read_buffer(m.0, &mut m_local[0..len])?;
let mut r_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
unsafe {
let res = ledger_secure_sdk_sys::cx_math_subm_no_throw(
r_local.as_mut_ptr(),
a_local.as_ptr(),
b_local.as_ptr(),
m_local.as_ptr(),
len,
);
if res != CX_OK {
return Err(CommEcallError::GenericError("subm failed"));
}
}
// copy r_local to r
let segment = cpu.get_segment::<E>(r.0)?;
segment.write_buffer(r.0, &r_local[0..len])?;
Ok(())
}
fn handle_bn_multm<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
r: GuestPointer,
a: GuestPointer,
b: GuestPointer,
m: GuestPointer,
len: usize,
) -> Result<(), CommEcallError> {
if len > MAX_BIGNUMBER_SIZE {
return Err(CommEcallError::InvalidParameters("len is too large"));
}
// copy inputs to local memory
let mut a_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(a.0)?
.read_buffer(a.0, &mut a_local[0..len])?;
let mut b_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(b.0)?
.read_buffer(b.0, &mut b_local[0..len])?;
let mut m_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(m.0)?
.read_buffer(m.0, &mut m_local[0..len])?;
let mut r_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
unsafe {
let res = ledger_secure_sdk_sys::cx_math_multm_no_throw(
r_local.as_mut_ptr(),
a_local.as_ptr(),
b_local.as_ptr(),
m_local.as_ptr(),
len,
);
if res != CX_OK {
return Err(CommEcallError::GenericError("multm failed"));
}
}
// copy r_local to r
let segment = cpu.get_segment::<E>(r.0)?;
segment.write_buffer(r.0, &r_local[0..len])?;
Ok(())
}
fn handle_bn_powm<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
r: GuestPointer,
a: GuestPointer,
e: GuestPointer,
len_e: usize,
m: GuestPointer,
len: usize,
) -> Result<(), CommEcallError> {
if len_e > MAX_BIGNUMBER_SIZE {
return Err(CommEcallError::InvalidParameters("len_e is too large"));
}
if len > MAX_BIGNUMBER_SIZE {
return Err(CommEcallError::InvalidParameters("len is too large"));
}
// copy inputs to local memory
let mut a_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(a.0)?
.read_buffer(a.0, &mut a_local[0..len])?;
let mut e_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(e.0)?
.read_buffer(e.0, &mut e_local[0..len_e])?;
let mut m_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
cpu.get_segment::<E>(m.0)?
.read_buffer(m.0, &mut m_local[0..len])?;
let mut r_local: [u8; MAX_BIGNUMBER_SIZE] = [0; MAX_BIGNUMBER_SIZE];
unsafe {
let res = ledger_secure_sdk_sys::cx_math_powm_no_throw(
r_local.as_mut_ptr(),
a_local.as_ptr(),
e_local.as_ptr(),
len_e,
m_local.as_ptr(),
len,
);
if res != CX_OK {
return Err(CommEcallError::GenericError("addm failed"));
}
}
// copy r_local to r
let segment = cpu.get_segment::<E>(r.0)?;
segment.write_buffer(r.0, &r_local[0..len])?;
Ok(())
}
fn handle_hash_init<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
hash_id: u32,
ctx: GuestPointer,
) -> Result<(), CommEcallError> {
// in-memory size of the hash context struct
let ctx_size = LedgerHashContext::get_size_from_id(hash_id)?;
// copy context to local memory
let mut ctx_local: [u8; LedgerHashContext::MAX_HASH_CONTEXT_SIZE] =
[0; LedgerHashContext::MAX_HASH_CONTEXT_SIZE];
cpu.get_segment::<E>(ctx.0)?
.read_buffer(ctx.0, &mut ctx_local[0..ctx_size])?;
unsafe {
ledger_secure_sdk_sys::cx_hash_init(
ctx_local.as_mut_ptr() as *mut ledger_secure_sdk_sys::cx_hash_header_s,
hash_id as u8,
);
}
// copy context back to V-App memory
let segment = cpu.get_segment::<E>(ctx.0)?;
segment.write_buffer(ctx.0, &ctx_local[0..ctx_size])?;
Ok(())
}
fn handle_hash_update<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
hash_id: u32,
ctx: GuestPointer,
data: GuestPointer,
data_len: usize,
) -> Result<(), CommEcallError> {
// in-memory size of the hash context struct
let ctx_size = LedgerHashContext::get_size_from_id(hash_id)?;
if data_len == 0 {
return Ok(());
}
// copy context to local memory
let mut ctx_local: [u8; LedgerHashContext::MAX_HASH_CONTEXT_SIZE] =
[0; LedgerHashContext::MAX_HASH_CONTEXT_SIZE];
cpu.get_segment::<E>(ctx.0)?
.read_buffer(ctx.0, &mut ctx_local[0..ctx_size])?;
// copy data to local memory in chanks of at most 256 bytes
let mut data_local: [u8; 256] = [0; 256];
let mut data_remaining = data_len;
let mut data_ptr = data.0;
let data_seg = cpu.get_segment::<E>(data_ptr)?;
while data_remaining > 0 {
let copy_size = min(data_remaining, 256);
data_seg.read_buffer(data_ptr, &mut data_local[0..copy_size])?;
unsafe {
ledger_secure_sdk_sys::cx_hash_update(
ctx_local.as_mut_ptr() as *mut ledger_secure_sdk_sys::cx_hash_header_s,
data_local.as_ptr(),
copy_size as usize,
);
}
data_remaining -= copy_size;
data_ptr += copy_size as u32;
}
// copy context back to V-App memory
cpu.get_segment::<E>(ctx.0)?
.write_buffer(ctx.0, &ctx_local[0..ctx_size])?;
Ok(())
}
fn handle_hash_digest<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
hash_id: u32,
ctx: GuestPointer,
digest: GuestPointer,
) -> Result<(), CommEcallError> {
// in-memory size of the hash context struct
let ctx_size = LedgerHashContext::get_size_from_id(hash_id)?;
// copy context to local memory
let mut ctx_local: [u8; LedgerHashContext::MAX_HASH_CONTEXT_SIZE] =
[0; LedgerHashContext::MAX_HASH_CONTEXT_SIZE];
cpu.get_segment::<E>(ctx.0)?
.read_buffer(ctx.0, &mut ctx_local[0..ctx_size])?;
// compute the digest; no supported hash function has a digest bigger than 64 bytes
let mut digest_local: [u8; 64] = [0; 64];
unsafe {
ledger_secure_sdk_sys::cx_hash_final(
ctx_local.as_mut_ptr() as *mut ledger_secure_sdk_sys::cx_hash_header_s,
digest_local.as_mut_ptr(),
);
}
// actual length of the digest
let digest_len = LedgerHashContext::get_digest_len_from_id(hash_id)?;
// copy digest to V-App memory
let segment = cpu.get_segment::<E>(digest.0)?;
segment.write_buffer(digest.0, &digest_local[0..digest_len])?;
Ok(())
}
fn handle_derive_hd_node<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
curve: u32,
path: GuestPointer,
path_len: usize,
private_key: GuestPointer,
chain_code: GuestPointer,
) -> Result<(), CommEcallError> {
if curve != CurveKind::Secp256k1 as u32 {
return Err(CommEcallError::InvalidParameters("Unsupported curve"));
}
if path_len > MAX_BIP32_PATH {
return Err(CommEcallError::InvalidParameters("path_len is too large"));
}
// copy path to local memory (if path_len == 0, the pointer is invalid,
// so we don't want to read from the segment)
let mut path_local_raw: [u8; MAX_BIP32_PATH * 4] = [0; MAX_BIP32_PATH * 4];
if path_len > 0 {
cpu.get_segment::<E>(path.0)?
.read_buffer(path.0, &mut path_local_raw[0..(path_len * 4)])?;
}
// convert to a slice of u32, by taking 4 bytes at the time as big-endian integers
let path_local = unsafe {
core::slice::from_raw_parts(path_local_raw.as_ptr() as *const u32, path_len as usize)
};
// derive the key
let mut private_key_local = Zeroizing::new([0u8; 32]);
let mut chain_code_local: [u8; 32] = [0; 32];
unsafe {
ledger_secure_sdk_sys::os_perso_derive_node_bip32(
curve as u8,
path_local.as_ptr(),
path_len as u32,
private_key_local.as_mut_ptr(),
chain_code_local.as_mut_ptr(),
);
}
// copy private_key and chain_code to V-App memory
cpu.get_segment::<E>(private_key.0)?
.write_buffer(private_key.0, &private_key_local[..])?;
cpu.get_segment::<E>(chain_code.0)?
.write_buffer(chain_code.0, &chain_code_local)?;
Ok(())
}
fn handle_get_master_fingerprint<E: fmt::Debug>(
&self,
_cpu: &mut Cpu<OutsourcedMemory<'_>>,
curve: u32,
) -> Result<u32, CommEcallError> {
if curve != CurveKind::Secp256k1 as u32 {
return Err(CommEcallError::InvalidParameters("Unsupported curve"));
}
// derive the key
let mut private_key_local = Zeroizing::new([0u8; 32]);
let mut chain_code_local: [u8; 32] = [0; 32];
let mut pubkey: ledger_secure_sdk_sys::cx_ecfp_public_key_t = Default::default();
unsafe {
ledger_secure_sdk_sys::os_perso_derive_node_bip32(
CurveKind::Secp256k1 as u8,
[].as_ptr(),
0,
private_key_local.as_mut_ptr(),
chain_code_local.as_mut_ptr(),
);
// generate the corresponding public key
let mut privkey: ledger_secure_sdk_sys::cx_ecfp_private_key_t = Default::default();
let ret1 = ledger_secure_sdk_sys::cx_ecfp_init_private_key_no_throw(
curve as u8,
private_key_local.as_ptr(),
private_key_local.len(),
&mut privkey,
);
let ret2 = ledger_secure_sdk_sys::cx_ecfp_generate_pair_no_throw(
curve as u8,
&mut pubkey,
&mut privkey,
true,
);
if ret1 != CX_OK || ret2 != CX_OK {
return Err(CommEcallError::GenericError("Failed to generate key pair"));
}
}
let mut sha_hasher = ledger_device_sdk::hash::sha2::Sha2_256::new();
sha_hasher.update(&[02u8 + (pubkey.W[64] % 2)]).unwrap();
sha_hasher.update(&pubkey.W[1..33]).unwrap();
let mut sha256hash = [0u8; 32];
sha_hasher.finalize(&mut sha256hash).unwrap();
let mut ripemd160_hasher = ledger_device_sdk::hash::ripemd::Ripemd160::new();
ripemd160_hasher.update(&sha256hash).unwrap();
let mut rip = [0u8; 20];
ripemd160_hasher.finalize(&mut rip).unwrap();
Ok(u32::from_be_bytes([rip[0], rip[1], rip[2], rip[3]]))
}
fn handle_ecfp_add_point<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
curve: u32,
r: GuestPointer,
p: GuestPointer,
q: GuestPointer,
) -> Result<u32, CommEcallError> {
if curve != CurveKind::Secp256k1 as u32 {
return Err(CommEcallError::InvalidParameters("Unsupported curve"));
}
// copy inputs to local memory
let mut p_local: ledger_secure_sdk_sys::cx_ecfp_public_key_t = Default::default();
p_local.curve = curve as u8;
p_local.W_len = 65;
cpu.get_segment::<E>(p.0)?
.read_buffer(p.0, &mut p_local.W)?;
let mut q_local: ledger_secure_sdk_sys::cx_ecfp_public_key_t = Default::default();
q_local.curve = curve as u8;
q_local.W_len = 65;
cpu.get_segment::<E>(q.0)?
.read_buffer(q.0, &mut q_local.W)?;
let mut r_local: ledger_secure_sdk_sys::cx_ecfp_public_key_t = Default::default();
unsafe {
let res = ledger_secure_sdk_sys::cx_ecfp_add_point_no_throw(
curve as u8,
r_local.W.as_mut_ptr(),
p_local.W.as_ptr(),
q_local.W.as_ptr(),
);
if res != CX_OK {
return Err(CommEcallError::GenericError("add_point failed"));
}
}
// copy r_local to r
let segment = cpu.get_segment::<E>(r.0)?;
segment.write_buffer(r.0, &r_local.W)?;
Ok(1)
}
fn handle_ecfp_scalar_mult<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
curve: u32,
r: GuestPointer,
p: GuestPointer,
k: GuestPointer,
k_len: usize,
) -> Result<u32, CommEcallError> {
if curve != CurveKind::Secp256k1 as u32 {
return Err(CommEcallError::InvalidParameters("Unsupported curve"));
}
if k_len > 32 {
// TODO: do we need to support any larger?
return Err(CommEcallError::InvalidParameters("k_len is too large"));
}
// copy inputs to local memory
// we use r_local also for the final result
let mut r_local: ledger_secure_sdk_sys::cx_ecfp_public_key_t = Default::default();
r_local.curve = curve as u8;
r_local.W_len = 65;
cpu.get_segment::<E>(p.0)?
.read_buffer(p.0, &mut r_local.W)?;
let mut k_local: [u8; 32] = [0; 32];
cpu.get_segment::<E>(k.0)?
.read_buffer(k.0, &mut k_local[0..k_len])?;
unsafe {
let res = ledger_secure_sdk_sys::cx_ecfp_scalar_mult_no_throw(
curve as u8,
r_local.W.as_mut_ptr(),
k_local.as_ptr(),
k_len,
);
if res != CX_OK {
return Err(CommEcallError::GenericError("scalar_mult failed"));
}
}
// copy r_local to r
let segment = cpu.get_segment::<E>(r.0)?;
segment.write_buffer(r.0, &r_local.W)?;
Ok(1)
}
fn handle_ecdsa_sign<E: fmt::Debug>(
&self,
cpu: &mut Cpu<OutsourcedMemory<'_>>,
curve: u32,
mode: u32,
hash_id: u32,
privkey: GuestPointer,
msg_hash: GuestPointer,
signature: GuestPointer,
) -> Result<usize, CommEcallError> {
if curve != CurveKind::Secp256k1 as u32 {