-
Notifications
You must be signed in to change notification settings - Fork 5
/
baking.rs
560 lines (462 loc) · 17.3 KB
/
baking.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
/*******************************************************************************
* (c) 2021 Zondax GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
use std::convert::TryFrom;
use zemu_sys::{Show, ViewError, Viewable};
use bolos::{
crypto::bip32::BIP32Path,
hash::{Blake2b, Hasher},
};
use crate::{
constants::{ApduError as Error, BIP32_MAX_LENGTH},
crypto::Curve,
dispatcher::ApduHandler,
handlers::{
hwm::{WaterMark, HWM},
signing::Sign,
},
parser::{
baking::{BlockData, EndorsementData},
operations::{Delegation, Reveal},
DisplayableItem, Preemble,
},
sys::{flash_slot::Wear, new_flash_slot},
utils::{ApduBufferRead, ApduPanic, Uploader},
};
const N_PAGES_BAKINGPATH: usize = 1;
type WearLeveller = Wear<'static, N_PAGES_BAKINGPATH>;
#[bolos::lazy_static]
static mut BAKINGPATH: WearLeveller =
new_flash_slot!(N_PAGES_BAKINGPATH).apdu_expect("NVM might be corrupted");
#[derive(PartialEq, Clone)]
#[cfg_attr(test, derive(Debug))]
/// Utility struct to store and read BIP32Path and Curve from NVM slots
///
/// # Codec
///
/// [0] = 0x00 | 0x2A; 0x00 indicates that the data left blank
///
/// [1] = `Curve`; byte representation of (`Curve`)[crypto::Curve]
///
/// [2] = number of components in the path (i)
///
/// [3..3+i*4] = `BIP32Path`;
/// byte representation of (`BIP32Path`)[sys::crypto::bip32::BIP32Path]
struct Bip32PathAndCurve {
curve: Curve,
path: BIP32Path<BIP32_MAX_LENGTH>,
}
impl Bip32PathAndCurve {
pub fn new(curve: Curve, path: BIP32Path<BIP32_MAX_LENGTH>) -> Self {
Self { curve, path }
}
/// Attempt to read a Bip32PathAndCurve from some bytes
pub fn try_from_bytes(from: &[u8; 52]) -> Result<Option<Self>, Error> {
//the slot could have been purposely emptied of data
// for example when we deauthorize
if from[0] == 0 {
return Ok(None);
}
let curve = Curve::try_from(from[1]).map_err(|_| Error::DataInvalid)?;
let components_length = from[2];
if components_length > BIP32_MAX_LENGTH as u8 {
return Err(Error::WrongLength);
}
//we reread from 2 since `read` expectes
// the components prefixed with the number of components,
// so we also + 1 to get that prefix
let path =
BIP32Path::<BIP32_MAX_LENGTH>::read(&from[2..2 + 1 + 4 * components_length as usize])
.map_err(|_| Error::DataInvalid)?;
Ok(Some(Self { curve, path }))
}
///Used to set a slot as empty when writing to NVM
///
/// Useful on deauthorization
pub fn empty() -> [u8; 52] {
[0; 52]
}
}
impl From<Bip32PathAndCurve> for [u8; 52] {
fn from(from: Bip32PathAndCurve) -> Self {
let mut out = [0; 52];
out[0] = 42; //we write to indicate that we actually have data here
let curve = from.curve.into();
out[1] = curve;
let components = from.path.components();
out[2] = components.len() as u8;
out[3..]
.chunks_exact_mut(4)
.zip(components)
.for_each(|(chunk, comp)| chunk.copy_from_slice(&comp.to_be_bytes()[..]));
out
}
}
pub struct Baking;
impl Baking {
#[inline(never)]
fn blake2b_digest_into(
buffer: &[u8],
out: &mut [u8; Sign::SIGN_HASH_SIZE],
) -> Result<(), Error> {
Blake2b::digest_into(buffer, out).map_err(|_| Error::ExecutionError)
}
#[inline(never)]
fn check_with_stored(curve: Curve, path: &BIP32Path<BIP32_MAX_LENGTH>) -> Result<bool, Error> {
//Check if the current baking path in NVM is initialized
let current_path =
unsafe { BAKINGPATH.read() }.map_err(|_| Error::ApduCodeConditionsNotSatisfied)?;
//path seems to be initialized so we can return it
//check if it is a good path
//TODO: otherwise return an error and show that on screen (corrupted NVM??)
let nvm_bip = Bip32PathAndCurve::try_from_bytes(current_path)?
.ok_or(Error::ApduCodeConditionsNotSatisfied)?;
Ok(nvm_bip.path == *path && nvm_bip.curve == curve)
}
/// Will store a curve and path in NVM memory
pub fn store_baking_key(curve: Curve, path: BIP32Path<BIP32_MAX_LENGTH>) -> Result<(), Error> {
let path_and_curve = Bip32PathAndCurve::new(curve, path);
unsafe { BAKINGPATH.write(path_and_curve.into()) }.map_err(|_| Error::ExecutionError)
}
/// Will remove the stored baking key
pub fn remove_baking_key() -> Result<(), Error> {
unsafe { BAKINGPATH.write(Bip32PathAndCurve::empty()) }.map_err(|_| Error::ExecutionError)
}
/// Will attempt to read a curve and path stored in NVM memory
pub fn read_baking_key() -> Result<Option<(Curve, BIP32Path<BIP32_MAX_LENGTH>)>, Error> {
let current =
unsafe { BAKINGPATH.read() }.map_err(|_| Error::ApduCodeConditionsNotSatisfied)?;
let path_and_curve = Bip32PathAndCurve::try_from_bytes(current)?;
Ok(path_and_curve.map(|both| (both.curve, both.path)))
}
#[inline(never)]
fn sign(digest: &[u8; 32]) -> Result<(usize, [u8; 100]), Error> {
let current_path = unsafe { BAKINGPATH.read() }.map_err(|_| Error::ExecutionError)?;
//path seems to be initialized so we can return it
//check if it is a good path
//TODO: otherwise return an error and show that on screen (corrupted NVM??)
let bip32_nvm = match Bip32PathAndCurve::try_from_bytes(current_path) {
Ok(Some(bip)) => bip,
Ok(None) => return Err(Error::ApduCodeConditionsNotSatisfied as _),
Err(e) => return Err(e),
};
let secret = bip32_nvm.curve.to_secret(&bip32_nvm.path);
let mut sig = [0; 100];
secret
.sign(digest, &mut sig[..])
.map_err(|_| Error::ExecutionError)
.map(|sz| (sz, sig))
}
#[inline(never)]
fn handle_endorsement(
input: &'static [u8],
send_hash: bool,
digest: [u8; 32],
out: &mut [u8],
) -> Result<usize, Error> {
let hw = HWM::read()?;
let (_, endorsement) =
EndorsementData::from_bytes(input).map_err(|_| Error::DataInvalid)?;
if !endorsement.validate_with_watermark(&hw) {
return Err(Error::DataInvalid);
//TODO: show endorsement data on screen
}
HWM::write(WaterMark {
level: endorsement.level,
endorsement: true,
})
.map_err(|_| Error::ExecutionError)?;
let (sz, sig) = Self::sign(&digest)?;
let mut tx = 0;
if send_hash {
//write unsigned_hash to buffer
out[tx..tx + 32].copy_from_slice(&digest[..]);
tx += 32;
}
//wrte signature to buffer
out[tx..tx + sz].copy_from_slice(&sig[..sz]);
tx += sz;
Ok(tx)
}
#[inline(never)]
fn handle_blockdata(
input: &'static [u8],
send_hash: bool,
digest: [u8; 32],
out: &mut [u8],
) -> Result<usize, Error> {
let hw = HWM::read()?;
let (_, blockdata) = BlockData::from_bytes(input).map_err(|_| Error::DataInvalid)?;
if !blockdata.validate_with_watermark(&hw) {
return Err(Error::DataInvalid);
}
HWM::write(WaterMark {
level: blockdata.level,
endorsement: false,
})
.map_err(|_| Error::ExecutionError)?;
let (sz, sig) = Self::sign(&digest)?;
let mut tx = 0;
if send_hash {
//write unsigned_hash to buffer
out[tx..tx + 32].copy_from_slice(&digest[..]);
tx += 32;
}
//wrte signature to buffer
out[tx..tx + sz].copy_from_slice(&sig[..sz]);
tx += sz;
Ok(tx)
}
#[inline(never)]
fn handle_delegation(
input: &'static [u8],
send_hash: bool,
digest: [u8; 32],
flags: &mut u32,
) -> Result<u32, Error> {
crate::sys::zemu_log_stack("Baking::handle_delegation\x00");
use crate::parser::operations::{Operation, OperationType};
let mut op = core::mem::MaybeUninit::uninit();
let mut operation = Operation::new(input).map_err(|_| Error::DataInvalid)?;
operation
.mut_ops()
.parse_next_into(&mut op)
.map_err(|_| Error::DataInvalid)?
.ok_or(Error::DataInvalid)?;
let (data, branch) = match unsafe { op.assume_init() } {
OperationType::Delegation(deleg) => {
//verify that delegation.source == delegation.delegate
// and it matches the authorized key for baking
// (BAKINGPATH)
Ok((BakingTransactionType::Delegation(deleg), operation.branch()))
}
OperationType::Reveal(reveal) => {
//TODO: what checks do we need here?
Ok((BakingTransactionType::Reveal(reveal), operation.branch()))
}
_ => Err(Error::CommandNotAllowed),
}?;
let ui = BakingSignUI {
send_hash,
digest,
branch,
data,
};
unsafe { ui.show(flags).map(|_| 0).map_err(|_| Error::ExecutionError) }
}
#[inline(never)]
pub fn baker_sign(
send_hash: bool,
p2: u8,
init_data: &[u8],
cdata: &'static [u8],
out: &mut [u8],
flags: &mut u32,
) -> Result<u32, Error> {
crate::sys::zemu_log_stack("Baking::baker_sign\x00");
let curve = Curve::try_from(p2).map_err(|_| Error::InvalidP1P2)?;
let path =
BIP32Path::<BIP32_MAX_LENGTH>::read(init_data).map_err(|_| Error::DataInvalid)?;
if !Self::check_with_stored(curve, &path)? {
return Err(Error::DataInvalid);
}
let mut digest = [0; Sign::SIGN_HASH_SIZE];
Self::blake2b_digest_into(cdata, &mut digest)?;
let (rem, preemble) = Preemble::from_bytes(cdata).map_err(|_| Error::DataInvalid)?;
//endorses and bakes are automatically signed without any review
match preemble {
Preemble::Endorsement => {
Self::handle_endorsement(rem, send_hash, digest, out).map(|n| n as u32)
}
Preemble::Block => {
Self::handle_blockdata(rem, send_hash, digest, out).map(|n| n as u32)
}
Preemble::Operation => Self::handle_delegation(rem, send_hash, digest, flags),
_ => Err(Error::CommandNotAllowed),
}
}
}
enum BakingTransactionType<'b> {
Delegation(Delegation<'b>),
Reveal(Reveal<'b>),
}
struct BakingSignUI {
send_hash: bool,
digest: [u8; 32],
branch: &'static [u8; 32],
data: BakingTransactionType<'static>,
}
impl Viewable for BakingSignUI {
fn num_items(&mut self) -> Result<u8, ViewError> {
let n = match self.data {
BakingTransactionType::Delegation(data) => data.num_items(),
BakingTransactionType::Reveal(data) => data.num_items(),
} + 1;
Ok(n as u8)
}
#[inline(never)]
fn render_item(
&mut self,
item_n: u8,
title: &mut [u8],
message: &mut [u8],
page: u8,
) -> Result<u8, ViewError> {
crate::sys::zemu_log_stack("Baking::render_item\x00");
if let 0 = item_n {
use crate::parser::operations::Operation;
use bolos::{pic_str, PIC};
let title_content = pic_str!(b"Operation");
title[..title_content.len()].copy_from_slice(title_content);
let mut mex = [0; Operation::BASE58_BRANCH_LEN];
let len = Operation::base58_branch_into(self.branch, &mut mex)
.map_err(|_| ViewError::Unknown)?;
crate::handlers::handle_ui_message(&mex[..len], message, page)
} else {
match self.data {
BakingTransactionType::Delegation(data) => {
data.render_item(item_n - 1, title, message, page)
}
BakingTransactionType::Reveal(data) => {
data.render_item(item_n - 1, title, message, page)
}
}
}
}
#[inline(never)]
fn accept(&mut self, out: &mut [u8]) -> (usize, u16) {
let (sz, sig) = match Baking::sign(&self.digest) {
Ok(ok) => ok,
Err(e) => return (0, e as _),
};
let mut tx = 0;
if self.send_hash {
//write unsigned_hash to buffer
out[tx..tx + 32].copy_from_slice(&self.digest[..]);
tx += 32;
}
//wrte signature to buffer
out[tx..tx + sz].copy_from_slice(&sig[..sz]);
tx += sz;
(tx, Error::Success as _)
}
fn reject(&mut self, _: &mut [u8]) -> (usize, u16) {
(0, Error::CommandNotAllowed as _)
}
}
mod authorization;
pub use authorization::{AuthorizeBaking, DeAuthorizeBaking};
mod queryauth;
pub use queryauth::{QueryAuthKey, QueryAuthKeyWithCurve};
mod hmac;
pub use hmac::HMAC;
impl ApduHandler for Baking {
#[inline(never)]
fn handle<'apdu>(
flags: &mut u32,
tx: &mut u32,
buffer: ApduBufferRead<'apdu>,
) -> Result<(), Error> {
crate::sys::zemu_log_stack("Baking::handle\x00");
if let Some(upload) = Uploader::new(Self).upload(&buffer)? {
*tx = Self::baker_sign(
true,
upload.p2,
upload.first,
upload.data,
buffer.write(),
flags,
)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::{crypto, utils::MaybeNullTerminatedToString};
use bolos::crypto::bip32::BIP32Path;
use arrayref::array_ref;
use zuit::{MockDriver, Page};
use super::*;
#[test]
fn check_bip32andpath_frombytes() {
let curve = crypto::Curve::Ed25519;
let pathdata = &[44, 1729, 0, 0];
let path =
BIP32Path::<BIP32_MAX_LENGTH>::new(pathdata.iter().map(|n| 0x8000_0000 + n)).unwrap();
let path_and_curve = Bip32PathAndCurve::new(curve, path);
let data: [u8; 52] = path_and_curve.clone().into();
let derived = Bip32PathAndCurve::try_from_bytes(&data);
assert!(derived.is_ok());
assert_eq!(derived.unwrap().unwrap(), path_and_curve);
}
#[test]
fn test_endorsement_data() {
let mut v = std::vec::Vec::with_capacity(1 + 4 + 32);
v.push(0x00); //invalid preemble
v.extend_from_slice(&1_u32.to_be_bytes());
v.extend_from_slice(&[0u8; 32]);
v.push(0x05);
v.extend_from_slice(&15_u32.to_be_bytes());
let (_, endorsement) = EndorsementData::from_bytes(&v[1..]).unwrap();
assert_eq!(endorsement.chain_id, 1);
assert_eq!(endorsement.branch, &[0u8; 32]);
assert_eq!(endorsement.tag, 5);
assert_eq!(endorsement.level, 15);
}
#[test]
fn known_delegation() {
const PARTIAL_INPUT_HEX: &str = "0035e993d8c7aaa42b5e3ccd86a33390ececc73abd\
904e\
01\
0a\
0a\
ff\
00";
const KNOWN_BAKER_ADDR: &str = "tz1RV1MBbZMR68tacosb7Mwj6LkbPSUS1er1";
const KNOWN_BAKER_NAME: &str = "Baking Tacos";
let addr = bs58::decode(KNOWN_BAKER_ADDR)
.into_vec()
.apdu_expect("unable to decode known baker addr base58");
let hash = array_ref!(&addr[3..], 0, 20);
let mut input = hex::decode(PARTIAL_INPUT_HEX).expect("invalid input hex");
input.extend_from_slice(hash); //add the known baker hash data to the input
let input = &*input.leak();
let (_, delegation) = Delegation::from_bytes(input).expect("couldn't parse delegation");
let ui = BakingSignUI {
send_hash: false,
digest: [0; 32],
branch: &[0; 32],
data: BakingTransactionType::Delegation(delegation),
};
let mut driver = MockDriver::<_, 18, 4096>::new(ui);
driver.drive();
let produced_ui = driver.out_ui();
let delegation_item = produced_ui
.into_iter()
.find(|item_pages| {
item_pages
.iter()
.all(|Page { title, .. }| title.starts_with("Delegation".as_bytes()))
})
.expect("Couldn't find delegation item in UI");
let title = delegation_item[0]
.message
.to_string_with_check_null()
.expect("message was invalid UTF8");
//verify that the message is the same as the name we expect in the test
assert_eq!(title, KNOWN_BAKER_NAME);
}
}