diff --git a/buildpush.bat b/buildpush.bat index b2770df13..69907c00f 100644 --- a/buildpush.bat +++ b/buildpush.bat @@ -8,7 +8,7 @@ CertUtil -hashfile precursors/soc_csr.bin MD5 CertUtil -hashfile target/riscv32imac-unknown-xous-elf/release/loader.bin MD5 CertUtil -hashfile target/riscv32imac-unknown-xous-elf/release/xous.img MD5 -scp -i c:/users/bunnie/.ssh/id_pi target/riscv32imac-unknown-xous-elf/release/xous.img target/riscv32imac-unknown-xous-elf/release/loader.bin precursors/soc_csr.bin precursors/bbram-test1.nky pi@10.0.245.90:code/precursors/ +scp -i c:/users/bunnie/.ssh/id_pi target/riscv32imac-unknown-xous-elf/release/xous.img target/riscv32imac-unknown-xous-elf/release/loader.bin precursors/soc_csr.bin precursors/bbram1_soc_csr.bin precursors/bbram-test1.nky pi@10.0.245.90:code/precursors/ REM CertUtil -hashfile target/riscv32imac-unknown-none-elf/release/loader.bin MD5 REM CertUtil -hashfile target/riscv32imac-unknown-none-elf/release/xous.img MD5 diff --git a/loader/src/secboot.rs b/loader/src/secboot.rs index 9f880401b..52f5181eb 100755 --- a/loader/src/secboot.rs +++ b/loader/src/secboot.rs @@ -286,73 +286,107 @@ pub fn validate_xous_img(xous_img_offset: *const u32) -> bool { // select the public key let mut keyrom = Keyrom::new(); - let keyloc = - if !keyrom.key_is_zero(KeyLoc::SelfSignPub) { // self-signing key takes priority - if keyrom.key_is_dev(KeyLoc::SelfSignPub) { - println!("Self-signed key slot, but with developer public key."); + let mut keyloc = KeyLoc::SelfSignPub; // start from the self-sign key first, then work your way to less secure options + loop { + match keyloc { + KeyLoc::SelfSignPub => { + if !keyrom.key_is_zero(KeyLoc::SelfSignPub) { // self-signing key takes priority + if keyrom.key_is_dev(KeyLoc::SelfSignPub) { + println!("Self-signed key slot, but with developer public key."); + // mainly to protect against devs who were debugging and just stuck a dev key in the secure slot, and forgot to remove it. + gfx.msg("DEVELOPER KEY DETECTED\n\r", &mut cursor); + gfx.set_devboot(); + } + } else { + keyloc = KeyLoc::ThirdPartyPub; + continue; + } + }, + KeyLoc::ThirdPartyPub => { + // policy note: set the devboot flag also if we're doing a thirdparty pubkey boot + // reasoning: the purpose of the hash mark is to indicate if someone could have tampered + // with the device. Once an update is installed, it should always be self-signed, as it + // protects against the third party pubkey from being compromised and an alternate firmware + // being installed with no visible warning. Hence, even tho thirdparty pubkey boots could + // be more trusted, let's still flag it. + gfx.set_devboot(); + if !keyrom.key_is_zero(KeyLoc::ThirdPartyPub) { // third party key is second in line + if keyrom.key_is_dev(KeyLoc::ThirdPartyPub) { + println!("Third party public key slot, but with developer public key."); + gfx.msg("DEVELOPER KEY DETECTED\n\r", &mut cursor); + } + } else { + keyloc = KeyLoc::DevPub; + continue; + } + }, + KeyLoc::DevPub => { + if keyrom.key_is_zero(KeyLoc::DevPub) { + gfx.msg("Can't boot: No valid keys!", &mut cursor); + loop {} + } gfx.msg("DEVELOPER KEY DETECTED\n\r", &mut cursor); + println!("Using developer public key"); gfx.set_devboot(); } - println!("Using self-signed public key"); - KeyLoc::SelfSignPub - } else if !keyrom.key_is_zero(KeyLoc::ThirdPartyPub) { // third party key is second in line - if keyrom.key_is_dev(KeyLoc::ThirdPartyPub) { - println!("Third party public key slot, but with developer public key."); - gfx.msg("DEVELOPER KEY DETECTED\n\r", &mut cursor); - gfx.set_devboot(); - } - println!("Using third-party public key"); - KeyLoc::ThirdPartyPub + } + let pubkey = keyrom.read_ed25519(keyloc).unwrap_or_else(|e| { + gfx.msg("Unable to read key: ", &mut cursor); + gfx.msg(e, &mut cursor); + gfx.msg("\n\r", &mut cursor); + panic!("Unable to read key: {}", e) + }); + + println!("Public key bytes: {:x?}", pubkey.as_bytes()); + + if sig.version != 1 { + println!("Warning: mismatch on signature record version numbering. Ignoring and moving on...") + } + let signed_len = sig.signed_len; + let image: &[u8] = unsafe{core::slice::from_raw_parts((xous_img_offset as usize + SIGBLOCK_SIZE) as *const u8, signed_len as usize)}; + let ed25519_signature = ed25519_dalek::Signature::from(sig.signature); + + use ed25519_dalek::Verifier; + if pubkey.verify(image, &ed25519_signature).is_ok() { + gfx.msg("Signature check passed\n\r", &mut cursor); + println!("Signature check passed"); + break; } else { - if keyrom.key_is_zero(KeyLoc::DevPub) { - gfx.msg("Can't boot: No valid keys!", &mut cursor); - loop {} - } - gfx.msg("DEVELOPER KEY DETECTED\n\r", &mut cursor); - println!("Using developer public key"); - gfx.set_devboot(); - KeyLoc::DevPub - }; - let pubkey = keyrom.read_ed25519(keyloc).unwrap_or_else(|e| { - gfx.msg("Unable to read key: ", &mut cursor); - gfx.msg(e, &mut cursor); - gfx.msg("\n\r", &mut cursor); - panic!("Unable to read key: {}", e) - }); + // signature didn't work out, setup the next key and try it + match keyloc { + KeyLoc::SelfSignPub => { + keyloc = KeyLoc::ThirdPartyPub; + continue; + } + KeyLoc::ThirdPartyPub => { + // try another key and move on + keyloc = KeyLoc::DevPub; + continue; + } + KeyLoc::DevPub => { + // we're out of keys, display a message and try to power down + gfx.msg("Signature check failed, powering down\n\r", &mut cursor); + println!("Signature check failed"); + let ticktimer = CSR::new(utra::ticktimer::HW_TICKTIMER_BASE as *mut u32); + let mut power = CSR::new(utra::power::HW_POWER_BASE as *mut u32); + let mut com = CSR::new(utra::com::HW_COM_BASE as *mut u32); + let mut start = ticktimer.rf(utra::ticktimer::TIME0_TIME); + loop { + // every 15 seconds, attempt to send a power down command + // any attempt to re-flash the system must halt the CPU before we time-out to this point! + if ticktimer.rf(utra::ticktimer::TIME0_TIME) - start > 15_000 { + println!("Powering down..."); + power.rmwf(utra::power::POWER_STATE, 0); + power.rmwf(utra::power::POWER_SELF, 0); - println!("Public key bytes: {:x?}", pubkey.as_bytes()); - - if sig.version != 1 { - println!("Warning: mismatch on signature record version numbering. Ignoring and moving on...") - } - let signed_len = sig.signed_len; - let image: &[u8] = unsafe{core::slice::from_raw_parts((xous_img_offset as usize + SIGBLOCK_SIZE) as *const u8, signed_len as usize)}; - let ed25519_signature = ed25519_dalek::Signature::from(sig.signature); - - use ed25519_dalek::Verifier; - if pubkey.verify(image, &ed25519_signature).is_ok() { - gfx.msg("Signature check passed\n\r", &mut cursor); - println!("Signature check passed"); - } else { - gfx.msg("Signature check failed, powering down\n\r", &mut cursor); - println!("Signature check failed"); - let ticktimer = CSR::new(utra::ticktimer::HW_TICKTIMER_BASE as *mut u32); - let mut power = CSR::new(utra::power::HW_POWER_BASE as *mut u32); - let mut com = CSR::new(utra::com::HW_COM_BASE as *mut u32); - let mut start = ticktimer.rf(utra::ticktimer::TIME0_TIME); - loop { - // every 15 seconds, attempt to send a power down command - // any attempt to re-flash the system must halt the CPU before we time-out to this point! - if ticktimer.rf(utra::ticktimer::TIME0_TIME) - start > 15_000 { - println!("Powering down..."); - power.rmwf(utra::power::POWER_STATE, 0); - power.rmwf(utra::power::POWER_SELF, 0); - - // ship mode is the safest mode -- suitable for long-term storage (~years) - com.wfo(utra::com::TX_TX, com_rs::ComState::POWER_SHIPMODE.verb as u32); - while com.rf(utra::com::STATUS_TIP) == 1 {} - let _ = com.rf(utra::com::RX_RX); // discard the RX result - start = ticktimer.rf(utra::ticktimer::TIME0_TIME); + // ship mode is the safest mode -- suitable for long-term storage (~years) + com.wfo(utra::com::TX_TX, com_rs::ComState::POWER_SHIPMODE.verb as u32); + while com.rf(utra::com::STATUS_TIP) == 1 {} + let _ = com.rf(utra::com::RX_RX); // discard the RX result + start = ticktimer.rf(utra::ticktimer::TIME0_TIME); + } + } + } } } } diff --git a/precursors/rom.db b/precursors/rom.db index 21af47436..820a353c5 100755 --- a/precursors/rom.db +++ b/precursors/rom.db @@ -1,128 +1,128 @@ -KEYROM 0 A SLICE_X36Y50 b'ed9040309fce38f4' -KEYROM 0 B SLICE_X36Y50 b'34b83a94e4408416' -KEYROM 0 C SLICE_X36Y50 b'8f088d95d0241a29' -KEYROM 0 D SLICE_X36Y50 b'71976c7c19e9b004' -KEYROM 1 A SLICE_X37Y50 b'23147e30bff2ec9a' -KEYROM 1 B SLICE_X37Y50 b'1fd3c7d928865270' -KEYROM 1 C SLICE_X37Y50 b'69affdc0d64bce09' -KEYROM 1 D SLICE_X37Y50 b'7a5d619fdd90768c' -KEYROM 2 A SLICE_X36Y51 b'e6a75fea68b97646' -KEYROM 2 B SLICE_X36Y51 b'3bbe4fd7491feae7' -KEYROM 2 C SLICE_X36Y51 b'8f1ce05eb6df82cf' -KEYROM 2 D SLICE_X36Y51 b'27262a3adbb299bb' -KEYROM 3 A SLICE_X37Y51 b'f51fe08930b42539' -KEYROM 3 B SLICE_X37Y51 b'fe0f77932c0955be' -KEYROM 3 C SLICE_X37Y51 b'75b2d1f824733c6e' -KEYROM 3 D SLICE_X37Y51 b'd7d7ba4db2a43551' -KEYROM 4 A SLICE_X36Y52 b'01adb0f69b2445b6' -KEYROM 4 B SLICE_X36Y52 b'f9615dc2835077a9' -KEYROM 4 C SLICE_X36Y52 b'48b9726cdadf5f5c' -KEYROM 4 D SLICE_X36Y52 b'b04e43398e8a5a48' -KEYROM 5 A SLICE_X37Y52 b'ff7bd4295aabdd2d' -KEYROM 5 B SLICE_X37Y52 b'71ed1b78bf6abef1' -KEYROM 5 C SLICE_X37Y52 b'711b0d7da395db20' -KEYROM 5 D SLICE_X37Y52 b'bab4a809cb8d5749' -KEYROM 6 A SLICE_X36Y53 b'4d30fac41aa32b0f' -KEYROM 6 B SLICE_X36Y53 b'43b00f6dcac70852' -KEYROM 6 C SLICE_X36Y53 b'ad4003d496e1977f' -KEYROM 6 D SLICE_X36Y53 b'4ae9ec045604171d' -KEYROM 7 A SLICE_X37Y53 b'926d630da7b7a38f' -KEYROM 7 B SLICE_X37Y53 b'ea9dcfbcee0e3e27' -KEYROM 7 C SLICE_X37Y53 b'331310550f7be1a3' -KEYROM 7 D SLICE_X37Y53 b'86654bf903647983' -KEYROM 8 A SLICE_X36Y54 b'5faf7f97fd1adda9' -KEYROM 8 B SLICE_X36Y54 b'bd9e98995dfeb80e' -KEYROM 8 C SLICE_X36Y54 b'ccc154e624fa6d30' -KEYROM 8 D SLICE_X36Y54 b'6d4cf1460bbcc9d7' -KEYROM 9 A SLICE_X37Y54 b'61a5187dac4451d5' -KEYROM 9 B SLICE_X37Y54 b'b0ad0aeed2998bc1' -KEYROM 9 C SLICE_X37Y54 b'f21d761d350fc65c' -KEYROM 9 D SLICE_X37Y54 b'b12550f563825b1e' -KEYROM 10 A SLICE_X36Y55 b'fd44ec8a47c67607' -KEYROM 10 B SLICE_X36Y55 b'6f73609c3f474a99' -KEYROM 10 C SLICE_X36Y55 b'97f3f40b00eff415' -KEYROM 10 D SLICE_X36Y55 b'd9a8030e01d2e969' -KEYROM 11 A SLICE_X37Y55 b'b69db3f2c7383567' -KEYROM 11 B SLICE_X37Y55 b'c84e2d58eed1667f' -KEYROM 11 C SLICE_X37Y55 b'8de4bf137da8b4a5' -KEYROM 11 D SLICE_X37Y55 b'4b44f068e3b6e954' -KEYROM 12 A SLICE_X36Y56 b'9f9dfa17fd8f813b' -KEYROM 12 B SLICE_X36Y56 b'd7e2dc46e49beed5' -KEYROM 12 C SLICE_X36Y56 b'3c147b86326a0df7' -KEYROM 12 D SLICE_X36Y56 b'6de9236fe18c43bb' -KEYROM 13 A SLICE_X37Y56 b'f96f763f484a7293' -KEYROM 13 B SLICE_X37Y56 b'ea9d3dc73170641a' -KEYROM 13 C SLICE_X37Y56 b'2045bb3e568b0ef8' -KEYROM 13 D SLICE_X37Y56 b'2ce220df70dfe05d' -KEYROM 14 A SLICE_X36Y57 b'0fd2db99d978d460' -KEYROM 14 B SLICE_X36Y57 b'83ce09c09327ae22' -KEYROM 14 C SLICE_X36Y57 b'195e32c556a026fd' -KEYROM 14 D SLICE_X36Y57 b'23627d617f5baf71' -KEYROM 15 A SLICE_X37Y57 b'c7f24e5f55a9cca9' -KEYROM 15 B SLICE_X37Y57 b'7820cea9a62feef3' -KEYROM 15 C SLICE_X37Y57 b'baf6949fc5db190d' -KEYROM 15 D SLICE_X37Y57 b'c208af523a7d55ef' -KEYROM 16 A SLICE_X36Y58 b'b1445a38b8cec3ec' -KEYROM 16 B SLICE_X36Y58 b'2e694e04676b83c6' -KEYROM 16 C SLICE_X36Y58 b'33b1fbd89e0b2d53' -KEYROM 16 D SLICE_X36Y58 b'74d20b1bc8765902' -KEYROM 17 A SLICE_X37Y58 b'65bdef7af5c88f77' -KEYROM 17 B SLICE_X37Y58 b'182f425b728098e6' -KEYROM 17 C SLICE_X37Y58 b'26a6e4b72e49a038' -KEYROM 17 D SLICE_X37Y58 b'476e499924be15c0' -KEYROM 18 A SLICE_X36Y59 b'b78c1c5cc2aa57a1' -KEYROM 18 B SLICE_X36Y59 b'31384d4342a6fda5' -KEYROM 18 C SLICE_X36Y59 b'05ae9c252ac885ce' -KEYROM 18 D SLICE_X36Y59 b'c96968631e3f7f78' -KEYROM 19 A SLICE_X37Y59 b'634d2885ce6e5855' -KEYROM 19 B SLICE_X37Y59 b'a3cf9e2e72e6e792' -KEYROM 19 C SLICE_X37Y59 b'581ffd047adcc9ea' -KEYROM 19 D SLICE_X37Y59 b'2f64b2ce422d5531' -KEYROM 20 A SLICE_X36Y60 b'7e329f3ca0aaa48e' -KEYROM 20 B SLICE_X36Y60 b'aea96c4e160d7c23' -KEYROM 20 C SLICE_X36Y60 b'6ae6580d67e7ff89' -KEYROM 20 D SLICE_X36Y60 b'5474386b42cab7f1' -KEYROM 21 A SLICE_X37Y60 b'3f9bd1bd08d4aff4' -KEYROM 21 B SLICE_X37Y60 b'e56106594063c796' -KEYROM 21 C SLICE_X37Y60 b'2195de30ceb285a2' -KEYROM 21 D SLICE_X37Y60 b'6334c328f262238f' -KEYROM 22 A SLICE_X36Y61 b'c7864968fa48d4fb' -KEYROM 22 B SLICE_X36Y61 b'539340a6115a09de' -KEYROM 22 C SLICE_X36Y61 b'5a481886017ce135' -KEYROM 22 D SLICE_X36Y61 b'53ab6dd8014367e1' -KEYROM 23 A SLICE_X37Y61 b'a96ce894e8ef46bc' -KEYROM 23 B SLICE_X37Y61 b'1bb558f3736ff921' -KEYROM 23 C SLICE_X37Y61 b'5f317c906fda756e' -KEYROM 23 D SLICE_X37Y61 b'a09db3281b82fcf1' -KEYROM 24 A SLICE_X36Y62 b'916fb25b3c623029' -KEYROM 24 B SLICE_X36Y62 b'3c36f54ab0b983c3' -KEYROM 24 C SLICE_X36Y62 b'564c5c49176dccd2' -KEYROM 24 D SLICE_X36Y62 b'6b2a7d1cb3402096' -KEYROM 25 A SLICE_X37Y62 b'dfd1cc0ccc9d6375' -KEYROM 25 B SLICE_X37Y62 b'773dc64635af690c' -KEYROM 25 C SLICE_X37Y62 b'87958a06b32192f6' -KEYROM 25 D SLICE_X37Y62 b'a9f627a1e12ff5fb' -KEYROM 26 A SLICE_X36Y63 b'e848ef1676025ddb' -KEYROM 26 B SLICE_X36Y63 b'631c42f2972d8f4e' -KEYROM 26 C SLICE_X36Y63 b'e1ba5f1db6c1213e' -KEYROM 26 D SLICE_X36Y63 b'd0a6beb90ebfa1ad' -KEYROM 27 A SLICE_X37Y63 b'aa6f2108de94b9d7' -KEYROM 27 B SLICE_X37Y63 b'94fdad0d7e5e032a' -KEYROM 27 C SLICE_X37Y63 b'cb3a7ed9fa0c188c' -KEYROM 27 D SLICE_X37Y63 b'd9115aa51962339f' -KEYROM 28 A SLICE_X36Y64 b'88825ff323665a51' -KEYROM 28 B SLICE_X36Y64 b'6e49b5862e6533ac' -KEYROM 28 C SLICE_X36Y64 b'32fed356801273ab' -KEYROM 28 D SLICE_X36Y64 b'37904b87d81a652a' -KEYROM 29 A SLICE_X37Y64 b'4b5361b16868f5bd' -KEYROM 29 B SLICE_X37Y64 b'ba9596094f9e43b9' -KEYROM 29 C SLICE_X37Y64 b'ddabe807f246ff41' -KEYROM 29 D SLICE_X37Y64 b'8815407bf7b4e684' -KEYROM 30 A SLICE_X36Y65 b'0165ea750602f2be' -KEYROM 30 B SLICE_X36Y65 b'3c62683258a88ef9' -KEYROM 30 C SLICE_X36Y65 b'cc0c02f8539bf6d8' -KEYROM 30 D SLICE_X36Y65 b'a1caffc2420bc6de' -KEYROM 31 A SLICE_X37Y65 b'2a2894ffa957b03c' -KEYROM 31 B SLICE_X37Y65 b'958c5490ad6c2e9b' -KEYROM 31 C SLICE_X37Y65 b'f76c75011cdc2737' -KEYROM 31 D SLICE_X37Y65 b'a734aab8e4d7f6eb' +KEYROM 0 A SLICE_X36Y50 b'7139253efdee5437' +KEYROM 0 B SLICE_X36Y50 b'971240e7cb57d092' +KEYROM 0 C SLICE_X36Y50 b'1dd9845c5beaed5f' +KEYROM 0 D SLICE_X36Y50 b'b3b9d3cf5df61115' +KEYROM 1 A SLICE_X37Y50 b'406106417c8c7a65' +KEYROM 1 B SLICE_X37Y50 b'90c050c8b1e6af8c' +KEYROM 1 C SLICE_X37Y50 b'4894ab9eff8c8120' +KEYROM 1 D SLICE_X37Y50 b'b2eebf9478771fc9' +KEYROM 2 A SLICE_X36Y51 b'04286997eaf93401' +KEYROM 2 B SLICE_X36Y51 b'7e96f2c01e044565' +KEYROM 2 C SLICE_X36Y51 b'5a1e7c59ba4eeefb' +KEYROM 2 D SLICE_X36Y51 b'ed892258d64749ae' +KEYROM 3 A SLICE_X37Y51 b'7ea1b6851d9cb941' +KEYROM 3 B SLICE_X37Y51 b'6dfc6d5e02565f98' +KEYROM 3 C SLICE_X37Y51 b'5e3f36393b0d8d31' +KEYROM 3 D SLICE_X37Y51 b'ce2d479fa075d0f6' +KEYROM 4 A SLICE_X36Y52 b'ea97bf9e2e05b6ea' +KEYROM 4 B SLICE_X36Y52 b'a4e6631085dc8aed' +KEYROM 4 C SLICE_X36Y52 b'7eeb7b41817d34bf' +KEYROM 4 D SLICE_X36Y52 b'5912d16b8f528ecd' +KEYROM 5 A SLICE_X37Y52 b'0f1f162a35644658' +KEYROM 5 B SLICE_X37Y52 b'f984ab0d583d99ee' +KEYROM 5 C SLICE_X37Y52 b'ade3aa1429ca0183' +KEYROM 5 D SLICE_X37Y52 b'26bb13534f96d856' +KEYROM 6 A SLICE_X36Y53 b'8a6d0ef306aa6667' +KEYROM 6 B SLICE_X36Y53 b'c2bbdf7002d5be1d' +KEYROM 6 C SLICE_X36Y53 b'567dd7a83e29038d' +KEYROM 6 D SLICE_X36Y53 b'763405f2b1815c60' +KEYROM 7 A SLICE_X37Y53 b'7ceb7ca31ca9613e' +KEYROM 7 B SLICE_X37Y53 b'e075bde3985aa0c9' +KEYROM 7 C SLICE_X37Y53 b'fa698ee2b6dccd3f' +KEYROM 7 D SLICE_X37Y53 b'c5f451b0972f6ed1' +KEYROM 8 A SLICE_X36Y54 b'6f2da448148a8f49' +KEYROM 8 B SLICE_X36Y54 b'140c9ad2ae031c7b' +KEYROM 8 C SLICE_X36Y54 b'01fe3806885c92b9' +KEYROM 8 D SLICE_X36Y54 b'0fabd3bcc7b48917' +KEYROM 9 A SLICE_X37Y54 b'a325c72db086a6f6' +KEYROM 9 B SLICE_X37Y54 b'3bfd6fec12deecca' +KEYROM 9 C SLICE_X37Y54 b'3f1c20a20c7f9634' +KEYROM 9 D SLICE_X37Y54 b'67e4119d7c96a841' +KEYROM 10 A SLICE_X36Y55 b'17d01d48c0af1b80' +KEYROM 10 B SLICE_X36Y55 b'637e8ad69ee66cd3' +KEYROM 10 C SLICE_X36Y55 b'4b92d8a3bed42d84' +KEYROM 10 D SLICE_X36Y55 b'18b8ee879ba38a7e' +KEYROM 11 A SLICE_X37Y55 b'cce61555a1c8dcd6' +KEYROM 11 B SLICE_X37Y55 b'ac96df91741b0e43' +KEYROM 11 C SLICE_X37Y55 b'90ca2278f5a39578' +KEYROM 11 D SLICE_X37Y55 b'0684d8d2a065f6be' +KEYROM 12 A SLICE_X36Y56 b'808d9d0a5a7b01a4' +KEYROM 12 B SLICE_X36Y56 b'd4b3c9e452c72cb3' +KEYROM 12 C SLICE_X36Y56 b'970c458641fce1d1' +KEYROM 12 D SLICE_X36Y56 b'b4648f6136e64267' +KEYROM 13 A SLICE_X37Y56 b'29683729d8d7ee49' +KEYROM 13 B SLICE_X37Y56 b'da772edc07a0f23b' +KEYROM 13 C SLICE_X37Y56 b'8b09fdf54713dc4f' +KEYROM 13 D SLICE_X37Y56 b'84a8ffb1f1d83030' +KEYROM 14 A SLICE_X36Y57 b'7d31c2576a245640' +KEYROM 14 B SLICE_X36Y57 b'26712a039b8a397e' +KEYROM 14 C SLICE_X36Y57 b'a6f8f7be4f11002a' +KEYROM 14 D SLICE_X36Y57 b'8307e7557577111e' +KEYROM 15 A SLICE_X37Y57 b'fad7bc009408da13' +KEYROM 15 B SLICE_X37Y57 b'543fa23206dbe7b8' +KEYROM 15 C SLICE_X37Y57 b'ffcda1667acce717' +KEYROM 15 D SLICE_X37Y57 b'33cc4d7182ae9814' +KEYROM 16 A SLICE_X36Y58 b'4183a9f725df0ea1' +KEYROM 16 B SLICE_X36Y58 b'255004c9126605fd' +KEYROM 16 C SLICE_X36Y58 b'8eb282956cf6f85b' +KEYROM 16 D SLICE_X36Y58 b'32a4abd08e03f3a3' +KEYROM 17 A SLICE_X37Y58 b'5f33a858a287c5d8' +KEYROM 17 B SLICE_X37Y58 b'0197ed73c600a445' +KEYROM 17 C SLICE_X37Y58 b'6ba1e43c71757825' +KEYROM 17 D SLICE_X37Y58 b'b55b5d9ac9534337' +KEYROM 18 A SLICE_X36Y59 b'4ba57b36af113d3d' +KEYROM 18 B SLICE_X36Y59 b'c44455dec99281b1' +KEYROM 18 C SLICE_X36Y59 b'5ff51d04a2e23c93' +KEYROM 18 D SLICE_X36Y59 b'903a750c19dbbd7d' +KEYROM 19 A SLICE_X37Y59 b'de7b79327ea2009f' +KEYROM 19 B SLICE_X37Y59 b'2c83e749de6bdbab' +KEYROM 19 C SLICE_X37Y59 b'c9099a49e0a7962e' +KEYROM 19 D SLICE_X37Y59 b'4e0506ce2c222f53' +KEYROM 20 A SLICE_X36Y60 b'd3547cebff1734b2' +KEYROM 20 B SLICE_X36Y60 b'c77c0610cc2f3391' +KEYROM 20 C SLICE_X36Y60 b'a74034f532b4f128' +KEYROM 20 D SLICE_X36Y60 b'69f1ca4530332a1d' +KEYROM 21 A SLICE_X37Y60 b'50c0a9850d7d9510' +KEYROM 21 B SLICE_X37Y60 b'790e363c1fa363e0' +KEYROM 21 C SLICE_X37Y60 b'5c7ae6a5dc6e0a25' +KEYROM 21 D SLICE_X37Y60 b'a477b153a4dce16d' +KEYROM 22 A SLICE_X36Y61 b'befde63548ca8db3' +KEYROM 22 B SLICE_X36Y61 b'8dd6865f2a7d2c84' +KEYROM 22 C SLICE_X36Y61 b'a340c5dd4ee12769' +KEYROM 22 D SLICE_X36Y61 b'53c4ff8c438a27a7' +KEYROM 23 A SLICE_X37Y61 b'a71e06f0e983c86d' +KEYROM 23 B SLICE_X37Y61 b'874dfb61381f6aed' +KEYROM 23 C SLICE_X37Y61 b'92a40f86bad5a032' +KEYROM 23 D SLICE_X37Y61 b'fdd5969e64d3c1bc' +KEYROM 24 A SLICE_X36Y62 b'613906ed3d19211f' +KEYROM 24 B SLICE_X36Y62 b'800fbaba78d3d7f4' +KEYROM 24 C SLICE_X36Y62 b'f7f74840480f9d67' +KEYROM 24 D SLICE_X36Y62 b'09bac089a69da8c3' +KEYROM 25 A SLICE_X37Y62 b'882292c3377103d2' +KEYROM 25 B SLICE_X37Y62 b'aaebf2003815bf39' +KEYROM 25 C SLICE_X37Y62 b'8afaa0c9b4b61b5c' +KEYROM 25 D SLICE_X37Y62 b'42682e75cc042514' +KEYROM 26 A SLICE_X36Y63 b'aa394990a60fafdc' +KEYROM 26 B SLICE_X36Y63 b'bad8c1e3576df432' +KEYROM 26 C SLICE_X36Y63 b'11e72091a52b86dd' +KEYROM 26 D SLICE_X36Y63 b'cb67b8e302736449' +KEYROM 27 A SLICE_X37Y63 b'821a9549e8b1abe8' +KEYROM 27 B SLICE_X37Y63 b'ed911d6cf4a2911e' +KEYROM 27 C SLICE_X37Y63 b'400c3f94f9068455' +KEYROM 27 D SLICE_X37Y63 b'65f6d884b2053c8e' +KEYROM 28 A SLICE_X36Y64 b'b3f027e3ac1624c5' +KEYROM 28 B SLICE_X36Y64 b'35829056dfe53606' +KEYROM 28 C SLICE_X36Y64 b'ae55134511cb97f9' +KEYROM 28 D SLICE_X36Y64 b'4f1f9333a74027aa' +KEYROM 29 A SLICE_X37Y64 b'6efeeab089a09501' +KEYROM 29 B SLICE_X37Y64 b'7b2e802098b11a60' +KEYROM 29 C SLICE_X37Y64 b'7f63244980975d0d' +KEYROM 29 D SLICE_X37Y64 b'0eccde94c05979f7' +KEYROM 30 A SLICE_X36Y65 b'4ac3eecf185df444' +KEYROM 30 B SLICE_X36Y65 b'75e82366f18c159f' +KEYROM 30 C SLICE_X36Y65 b'aeffd4c4b8974f63' +KEYROM 30 D SLICE_X36Y65 b'64637baa3d0ff963' +KEYROM 31 A SLICE_X37Y65 b'f59b2721520d2513' +KEYROM 31 B SLICE_X37Y65 b'f004c1a5acb4a035' +KEYROM 31 C SLICE_X37Y65 b'4200431f9a9fe273' +KEYROM 31 D SLICE_X37Y65 b'9e17232480cc6907' diff --git a/precursors/soc.svd b/precursors/soc.svd index 6f01064bc..c2e7af9ac 100755 --- a/precursors/soc.svd +++ b/precursors/soc.svd @@ -3,7 +3,7 @@ litex SOC - + 8 32 @@ -1238,10 +1238,10 @@ register to disable individual events.]]> GIT_GITREV 0x0014 - 0x890b90e7 + 0x94b0064b 32 @@ -1258,7 +1258,7 @@ the exact git version used to build this firmware.]]> is ``1``, then the repository this was built from has one additional commit beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> 0x0018 - 0x46 + 0x48 32 @@ -3584,7 +3584,7 @@ inject too fast.]]> SEED1 0x0000 - 0x4f340196 + 0x356326ec 32 @@ -3599,7 +3599,7 @@ inject too fast.]]> SEED0 0x0004 - 0x77c237e8 + 0x6d0d21ea 32 diff --git a/precursors/soc_csr.bin b/precursors/soc_csr.bin index 45cd228ea..56dc9523e 100755 Binary files a/precursors/soc_csr.bin and b/precursors/soc_csr.bin differ diff --git a/services/gam/src/api.rs b/services/gam/src/api.rs index 90fc872c1..3a70460c9 100644 --- a/services/gam/src/api.rs +++ b/services/gam/src/api.rs @@ -167,4 +167,4 @@ pub(crate) enum Return { // small wart -- we have to reset the size of a modal to max size for resize computations // reveal the max size globally, since it's a constant -pub const MODAL_Y_MAX: i16 = 450; // in absolute screen coords, not relative to top pad +pub const MODAL_Y_MAX: i16 = 350; // in absolute screen coords, not relative to top pad diff --git a/services/gam/src/modal.rs b/services/gam/src/modal.rs index 5d1296e2f..2bb05293a 100644 --- a/services/gam/src/modal.rs +++ b/services/gam/src/modal.rs @@ -755,6 +755,7 @@ pub struct Notification { pub action_conn: xous::CID, pub action_opcode: u32, pub is_password: bool, + pub manual_dismiss: bool, } impl Notification { pub fn new(action_conn: xous::CID, action_opcode: u32) -> Self { @@ -762,6 +763,7 @@ impl Notification { action_conn, action_opcode, is_password: false, + manual_dismiss: true, } } pub fn set_is_password(&mut self, setting: bool) { @@ -770,57 +772,66 @@ impl Notification { // set because they can't achieve a high enough trust level. self.is_password = setting; } + pub fn set_manual_dismiss(&mut self, setting: bool) { + self.manual_dismiss = setting; + } } impl ActionApi for Notification { fn set_action_opcode(&mut self, op: u32) {self.action_opcode = op} fn height(&self, glyph_height: i16, margin: i16) -> i16 { - glyph_height + margin * 2 + 5 + if self.manual_dismiss { + glyph_height + margin * 2 + 5 + } else { + margin + 5 + } } fn redraw(&self, at_height: i16, modal: &Modal) { - // prime a textview with the correct general style parameters - let mut tv = TextView::new( - modal.canvas, - TextBounds::BoundingBox(Rectangle::new_coords(0, 0, 1, 1)) - ); - tv.ellipsis = true; - tv.style = modal.style; - tv.invert = self.is_password; - tv.draw_border= false; - tv.margin = Point::new(0, 0,); - tv.insertion = None; + if self.manual_dismiss { + // prime a textview with the correct general style parameters + let mut tv = TextView::new( + modal.canvas, + TextBounds::BoundingBox(Rectangle::new_coords(0, 0, 1, 1)) + ); + tv.ellipsis = true; + tv.style = modal.style; + tv.invert = self.is_password; + tv.draw_border= false; + tv.margin = Point::new(0, 0,); + tv.insertion = None; - tv.bounds_computed = None; - tv.bounds_hint = TextBounds::GrowableFromTl( - Point::new(modal.margin, at_height + modal.margin * 2), - (modal.canvas_width - modal.margin * 2) as u16 - ); - write!(tv, "{}", t!("notification.dismiss", xous::LANG)).unwrap(); - modal.gam.bounds_compute_textview(&mut tv).expect("couldn't simulate text size"); - let textwidth = if let Some(bounds) = tv.bounds_computed { - bounds.br.x - bounds.tl.x - } else { - modal.canvas_width - modal.margin * 2 - }; - let offset = (modal.canvas_width - textwidth) / 2; - tv.bounds_computed = None; - tv.bounds_hint = TextBounds::BoundingBox(Rectangle::new( - Point::new(offset, at_height + modal.margin * 2), - Point::new(modal.canvas_width - modal.margin, at_height + modal.line_height + modal.margin * 2) - )); - modal.gam.post_textview(&mut tv).expect("couldn't post tv"); + tv.bounds_computed = None; + tv.bounds_hint = TextBounds::GrowableFromTl( + Point::new(modal.margin, at_height + modal.margin * 2), + (modal.canvas_width - modal.margin * 2) as u16 + ); + write!(tv, "{}", t!("notification.dismiss", xous::LANG)).unwrap(); + modal.gam.bounds_compute_textview(&mut tv).expect("couldn't simulate text size"); + let textwidth = if let Some(bounds) = tv.bounds_computed { + bounds.br.x - bounds.tl.x + } else { + modal.canvas_width - modal.margin * 2 + }; + let offset = (modal.canvas_width - textwidth) / 2; + tv.bounds_computed = None; + tv.bounds_hint = TextBounds::BoundingBox(Rectangle::new( + Point::new(offset, at_height + modal.margin * 2), + Point::new(modal.canvas_width - modal.margin, at_height + modal.line_height + modal.margin * 2) + )); + modal.gam.post_textview(&mut tv).expect("couldn't post tv"); - // divider lines - let color = if self.is_password { - PixelColor::Light - } else { - PixelColor::Dark - }; + // divider lines + let color = if self.is_password { + PixelColor::Light + } else { + PixelColor::Dark + }; - modal.gam.draw_line(modal.canvas, Line::new_with_style( - Point::new(modal.margin, at_height + modal.margin), - Point::new(modal.canvas_width - modal.margin, at_height + modal.margin), - DrawStyle::new(color, color, 1)) + modal.gam.draw_line(modal.canvas, Line::new_with_style( + Point::new(modal.margin, at_height + modal.margin), + Point::new(modal.canvas_width - modal.margin, at_height + modal.margin), + DrawStyle::new(color, color, 1)) ).expect("couldn't draw entry line"); + } } fn key_action(&mut self, k: char) -> (Option>, bool) { log::trace!("key_action: {}", k); @@ -829,8 +840,10 @@ impl ActionApi for Notification { // ignore null messages } _ => { - send_message(self.action_conn, xous::Message::new_scalar(self.action_opcode as usize, 0, 0, 0, 0)).expect("couldn't pass on dismissal"); - return(None, true) + if self.manual_dismiss { + send_message(self.action_conn, xous::Message::new_scalar(self.action_opcode as usize, 0, 0, 0, 0)).expect("couldn't pass on dismissal"); + return(None, true) + } } } (None, false) @@ -1109,7 +1122,7 @@ fn recompute_canvas(modal: &mut Modal, action: ActionType, top_text: Option<&str if let Some(top_str) = top_text { let mut top_tv = TextView::new(modal.canvas, TextBounds::GrowableFromTl( - Point::new(modal.margin, total_height), + Point::new(modal.margin, modal.margin), (modal.canvas_width - modal.margin * 2) as u16 )); top_tv.draw_border = false; @@ -1119,16 +1132,18 @@ fn recompute_canvas(modal: &mut Modal, action: ActionType, top_text: Option<&str top_tv.invert = modal.inverted; // specify a clip rect that's the biggest possible allowed. If we don't do this, the current canvas // bounds are used, and the operation will fail if the text has to get bigger. - top_tv.clip_rect = Some(Rectangle::new(Point::new(0, 0), Point::new(current_bounds.x, crate::api::MODAL_Y_MAX))); + top_tv.clip_rect = Some(Rectangle::new(Point::new(0, 0), Point::new(current_bounds.x, crate::api::MODAL_Y_MAX - 2 * modal.line_height))); write!(top_tv.text, "{}", top_str).unwrap(); log::trace!("posting top tv: {:?}", top_tv); modal.gam.bounds_compute_textview(&mut top_tv).expect("couldn't simulate top text size"); if let Some(bounds) = top_tv.bounds_computed { + log::trace!("top_tv bounds computed {}", bounds.br.y - bounds.tl.y); total_height += bounds.br.y - bounds.tl.y; } else { - log::error!("couldn't compute height for modal top_text: {:?}", top_tv); - panic!("couldn't compute height for modal top_text"); + log::warn!("couldn't compute height for modal top_text: {:?}", top_tv); + // probably should find a better way to deal with this. + total_height += crate::api::MODAL_Y_MAX - (modal.line_height * 2); } modal.top_text = Some(top_tv); } @@ -1154,7 +1169,7 @@ fn recompute_canvas(modal: &mut Modal, action: ActionType, top_text: Option<&str bot_tv.invert = modal.inverted; // specify a clip rect that's the biggest possible allowed. If we don't do this, the current canvas // bounds are used, and the operation will fail if the text has to get bigger. - bot_tv.clip_rect = Some(Rectangle::new(Point::new(0, 0), Point::new(current_bounds.x, crate::api::MODAL_Y_MAX))); + bot_tv.clip_rect = Some(Rectangle::new(Point::new(0, 0), Point::new(current_bounds.x, crate::api::MODAL_Y_MAX - 2 * modal.line_height))); write!(bot_tv.text, "{}", bot_str).unwrap(); log::trace!("posting bot tv: {:?}", bot_tv); @@ -1289,8 +1304,19 @@ impl<'a> Modal<'a> { if do_redraw { self.gam.post_textview(&mut tv).expect("couldn't draw text"); if let Some(bounds) = tv.bounds_computed { - cur_height += bounds.br.y - bounds.tl.y; - self.top_memoized_height = Some(bounds.br.y - bounds.tl.y); + let y = bounds.br.y - bounds.tl.y; + let y_clip = if y > MODAL_Y_MAX - self.line_height * 3 { + log::warn!("overside text, clipping back {}", MODAL_Y_MAX - (self.line_height * 2)); + MODAL_Y_MAX - (self.line_height * 2) + } else { + y + }; + cur_height += y_clip; + log::trace!("top_tv height: {}", y_clip); + self.top_memoized_height = Some(y_clip); + } else { + log::warn!("text bounds didn't compute setting to max"); + self.top_memoized_height = Some(MODAL_Y_MAX - (self.line_height * 2)); } self.top_dirty = false; } else { diff --git a/services/graphics-server/src/main.rs b/services/graphics-server/src/main.rs index dbb1c723c..45fd99c7f 100644 --- a/services/graphics-server/src/main.rs +++ b/services/graphics-server/src/main.rs @@ -224,7 +224,10 @@ fn xmain() -> ! { br )); } else { - tv.bounds_computed = None; + tv.bounds_computed = Some(Rectangle::new( + clip_rect.tl(), + br + )); } }, TextBounds::GrowableFromTl(tl, width) => { @@ -277,8 +280,11 @@ fn xmain() -> ! { )); log::trace!("intersects, bounds_computed: {:?}", tv.bounds_computed); } else { - log::trace!("does not intersect, clip_rect: {:?}, br: {:?}", clip_rect, br); - tv.bounds_computed = None; + log::warn!("does not intersect, clip_rect: {:?}, br: {:?}", clip_rect, br); + tv.bounds_computed = Some(Rectangle::new( + tl, + clip_rect.br() + )); } }, TextBounds::GrowableFromBl(bl, width) => { @@ -331,7 +337,10 @@ fn xmain() -> ! { Point::new(bl.x + finalwidth, bl.y) )); } else { - tv.bounds_computed = None + tv.bounds_computed = Some(Rectangle::new( + clip_rect.tl(), + Point::new(bl.x + finalwidth, bl.y) + )); } }, } diff --git a/services/jtag/src/api.rs b/services/jtag/src/api.rs index e5f2ae2dc..28dc20958 100644 --- a/services/jtag/src/api.rs +++ b/services/jtag/src/api.rs @@ -1,5 +1,8 @@ pub(crate) const SERVER_NAME_JTAG: &str = "_JTAG Server_"; +#[allow(dead_code)] +pub const XCS750_IDCODE: u32 = 0x362F093; + #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] pub struct EfuseRecord { pub key: [u8; 32], diff --git a/services/jtag/src/lib.rs b/services/jtag/src/lib.rs index 9166d1e39..a4514a964 100644 --- a/services/jtag/src/lib.rs +++ b/services/jtag/src/lib.rs @@ -101,6 +101,10 @@ impl Jtag { let erec = self.efuse_fetch().expect("couldn't read efuse record"); if (erec.cntl & 0x20) != 0 { Ok(true) } else { Ok(false) } } + pub fn get_raw_control_bits(&self) -> Result { + let erec = self.efuse_fetch().expect("couldn't read efuse record"); + Ok(erec.cntl) + } fn mod_ctl_efuse(&self, bits_to_set: u8) -> Result { let erec = self.efuse_fetch().expect("couldn't read efuse record"); let response = send_message(self.conn, diff --git a/services/root-keys/Cargo.toml b/services/root-keys/Cargo.toml index 056c82fa3..16d03a279 100644 --- a/services/root-keys/Cargo.toml +++ b/services/root-keys/Cargo.toml @@ -62,7 +62,7 @@ utralib = { path = "../../utralib"} [features] hazardous-debug = [] # this feature enables the printing of secret materials for debug purposes -default = [] +default = ["hazardous-debug"] [lib] test = true diff --git a/services/root-keys/locales/i18n.json b/services/root-keys/locales/i18n.json index a19d96bbb..a20a1d9e9 100644 --- a/services/root-keys/locales/i18n.json +++ b/services/root-keys/locales/i18n.json @@ -90,9 +90,9 @@ "en-audio": "Verification failed, aborting" }, "rootkeys.init.fail_key": { - "en": "FPGA key is wrong,\nborting!", + "en": "FPGA key is wrong:\nPerhaps the update\npassword was entered\nincorrectly?", "zh": "*missing*正在初始化失败,中止!", - "en-audio": "FPGA key is wrong, aborting" + "en-audio": "FPGA key is wrong, perhaps the update password was entered incorrectly?" }, "rootkeys.init.fail_burn": { "en": "FLASH write problem,\naborting!", @@ -109,6 +109,91 @@ "zh": "这无法撤消,要继续吗?", "en-audio": "This cannot be undone. Continue?" }, + "rootkeys.gwup.no_update_found": { + "en": "No valid update found,\naborting!", + "zh": "未找到有效更新,正在中止!", + "en-audio": "No valid update found, aborting" + }, + "rootkeys.gwup.inspecting": { + "en": "Inspecting update,\nplease wait...", + "zh": "正在检查比特流,请稍候...", + "en-audio": "Inspecting update, please wait." + }, + "rootkeys.gwup.viewinfo_ss": { + "en": "Self-signed image found.\nReview details?", + "zh": "**missing**查看更新的详细信息?", + "en-audio": "Self-signed image found. Review details?" + }, + "rootkeys.gwup.viewinfo_tp": { + "en": "Third party image found.\nReview details?", + "zh": "**missing**查看更新的详细信息?", + "en-audio": "Self-signed image found. Review details?" + }, + "rootkeys.gwup.viewinfo_dk": { + "en": "Devkey image found.\nReview details?", + "zh": "**missing**查看更新的详细信息?", + "en-audio": "Self-signed image found. Review details?" + }, + "rootkeys.gwup.details": { + "en": "All details", + "zh": "所有细节", + "en-audio": "All details" + }, + "rootkeys.gwup.short": { + "en": "Short summary", + "zh": "简短的摘要", + "en-audio": "Short summary" + }, + "rootkeys.gwup.none": { + "en": "Skip", + "zh": "跳过这步", + "en-audio": "Skip" + }, + "rootkeys.gwup.proceed_confirm": { + "en": "Proceed with update?", + "zh": "继续更新?", + "en-audio": "Proceed with update?" + }, + "rootkeys.gwup.yes": { + "en": "Yes", + "zh": "确定", + "en-audio": "Yes" + }, + "rootkeys.gwup.no": { + "en": "No", + "zh": "取消", + "en-audio": "No" + }, + "rootkeys.gwup_starting": { + "en": "Updating gateware.\nThis takes a few minutes.\nDo not reset or sleep!", + "zh": "现在正在初始化\n可能还要等一下\n不要重置或睡眠!\n", + "en-audio": "Updating gateware. This may take a while, don't reset or sleep the device." + }, + "rootkeys.get_update_password": { + "en": "Password request\nSoftware update key\nSecurity: Critical\nWhy: Gateware update", + "zh": "输入密码\n软件更新\n安全含义:至关重要 ", + "en-audio": "Enter update password, in order to authorize a gateware update." + }, + "rootkeys.gwup.finished": { + "en": "Gateware update finished.\nReboot to apply.", + "zh": "更新完成重启应用", + "en-audio": "Gateware update finished. Reboot to apply." + }, + "rootkeys.get_signing_password": { + "en": "Password request\nSoftware update key\nSecurity: Critical\nWhy: Sign Xous", + "zh": "输入密码\n软件更新\n安全含义:至关重要 ", + "en-audio": "Enter update password, in order to authorize a gateware update." + }, + "rootkeys.signxous.finished": { + "en": "Xous signing finished.\nReboot to apply.", + "zh": "更新完成重启应用", + "en-audio": "Xous signing finished. Reboot to apply." + }, + "rootkeys.policy_request": { + "en": "Please pick a password\nretention policy:", + "zh": "请选择密码保留策略:", + "en-audio": "Please pick a passowrd retention policy." + }, "rootkeys.policy_clear": { "en": "Clear after use", "zh": "使用后删除", diff --git a/services/root-keys/src/api.rs b/services/root-keys/src/api.rs index 9c2092fd7..2fd07d694 100644 --- a/services/root-keys/src/api.rs +++ b/services/root-keys/src/api.rs @@ -11,6 +11,10 @@ pub(crate) enum Opcode { KeysInitialized, /// check that the digital signature on the gateware CheckGatewareSignature, + /// check if the efuse has been locked down + IsEfuseSecured, + /// quick check to see if the JTAG can read its IDCODE + IsJtagWorking, TestUx, @@ -20,15 +24,30 @@ pub(crate) enum Opcode { UxConfirmation, UxInitRequestPassword, UxInitPasswordReturn, + + /// provision a gateware update with our secret data + UxUpdateGateware, + UxUpdateGwCheckSig, + UxUpdateGwShowInfo, + UxUpdateGwShowLog, + UxUpdateGwShowStatus, + UxUpdateGwConfirm, + UxUpdateGwDecidePassword, + UxUpdateGwPasswordPolicy, + UxUpdateGwRun, + + /// self-sign kernel/loader + UxSelfSignXous, + UxSignXousPasswordPolicy, + UxSignXousRun, + + // General Ux calls UxGutter, // NOP for UX calls that require a destination UxGetPolicy, UxPolicyReturn, UxTryReboot, UxDoReboot, - /// provision a gateware update with our secret data - UxUpdateGateware, - /// self-sign kernel/loader - UxSelfSignXous, + /// UX opcodes MenuRedraw, MenuKeys, @@ -43,7 +62,7 @@ pub(crate) enum Opcode { Quit } -#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, PartialEq, Eq)] pub enum PasswordRetentionPolicy { AlwaysKeep, EraseOnSuspend, diff --git a/services/root-keys/src/implementation.rs b/services/root-keys/src/implementation.rs index e8c8e7ed5..ca3ced3cc 100644 --- a/services/root-keys/src/implementation.rs +++ b/services/root-keys/src/implementation.rs @@ -22,6 +22,8 @@ use core::cell::RefCell; use aes_xous::{Aes256, NewBlockCipher, BlockDecrypt, BlockEncrypt}; use cipher::generic_array::GenericArray; +use crate::{SignatureResult, GatewareRegion, MetadataInFlash}; + use root_keys::key2bits::*; // TODO: add hardware acceleration for BCRYPT so we can hit the OWASP target without excessive UX delay @@ -31,7 +33,12 @@ const BCRYPT_COST: u32 = 7; // 10 is the minimum recommended by OWASP; takes 5 /// increment that can be erased. const SIGBLOCK_SIZE: u32 = 0x1000; /// location of the csr.csv that's appended on gateware images, used for USB updates. -const CSR_CSV_OFFSET: usize = 0x27_8000; +const METADATA_OFFSET: usize = 0x27_6000; +#[allow(dead_code)] +/// location of the csr.csv that's appended on gateware images, used for USB updates. +const CSR_CSV_OFFSET: usize = 0x27_7000; +/// offset of the gateware self-signature area +const SELFSIG_OFFSET: usize = 0x27_F000; #[repr(C)] struct SignatureInFlash { @@ -96,7 +103,7 @@ pub(crate) mod keyrom_config { /// `user plaintext (up to first 72 bytes) -> bcrypt (24 bytes) -> sha512trunc256 -> [u8; 32]` /// The final sha512trunc256 expansion is because we will use this to XOR against secret keys stored in /// the KEYROM that may be up to 256 bits in length. For shorter keys, the hashed password is simply truncated. - #[repr(C)] +#[repr(C)] struct PasswordCache { hashed_boot_pw: [u8; 32], hashed_boot_pw_valid: u32, // non-zero for valid @@ -123,7 +130,21 @@ fn bitflip(input: &[u8], output: &mut [u8]) { } } +#[derive(Debug, Copy, Clone)] +enum FpgaKeySource { + Bbram, + Efuse, +} + const AES_BLOCKSIZE: usize = 16; +// a "slight" lie in that it's not literally the bitstream command, it's the fully encoded word + length of args. +const BITSTREAM_CTL0_CMD: u32 = 0x3000_a001; +const BITSTREAM_CTL0_CMD_FLIP: u32 = 0x8005_000c; +const BITSTREAM_MASK_CMD: u32 = 0x3000_c001; +#[allow(dead_code)] +const BITSTREAM_MASK_CMD_FLIP: u32 = 0x8005_000c; +const BITSTREAM_IV_CMD: u32 = 0x3001_6004; +const BITSTREAM_CIPHERTEXT_CMD: u32 = 0x3003_4001; /// This structure encapsulates the tools necessary to create an Oracle that can go from /// the encrypted bitstream to plaintext and back again, based on the position in the bitstream. /// It is a partial re-implementation of the Cbc crate from block-ciphers, and the reason we're @@ -144,12 +165,16 @@ struct BitstreamOracle<'a> { /// start of type2 data as an offset relative to the start of ciphertext type2_ciphertext_offset: usize, /// length of the undifferentiated plaintext header -- this is right up to the IV specifier + #[allow(dead_code)] pt_header_len: usize, + enc_to_key: FpgaKeySource, + dec_from_key: FpgaKeySource, } impl<'a> BitstreamOracle<'a> { /// oracle supports separate encryption and decryption keys, so that it may /// be used for re-encryption of bitstreams to a new key. If using it for patching, /// set the keys to the same value. + /// key_target selects what we want the encrypted target to be for boot key source; if None, we retain the bitstream settings pub fn new(dec_key: &'a[u8], enc_key: &'a[u8], bitstream: &'a[u8], base: u32) -> Result, RootkeyResult> { let mut position: usize = 0; @@ -159,10 +184,10 @@ impl<'a> BitstreamOracle<'a> { let mut cwd = 0; while position < bitstream.len() { cwd = u32::from_be_bytes(bitstream[position..position+4].try_into().unwrap()); - if cwd == 0x3001_6004 { + if cwd == BITSTREAM_IV_CMD { iv_pos = position + 4 } - if cwd == 0x3003_4001 { + if cwd == BITSTREAM_CIPHERTEXT_CMD { break; } position += 1; @@ -198,6 +223,8 @@ impl<'a> BitstreamOracle<'a> { type2_absolute_offset: 0, type2_ciphertext_offset: 0, pt_header_len: iv_pos, // plaintext header goes all the way up to the IV + enc_to_key: FpgaKeySource::Efuse, // these get set later + dec_from_key: FpgaKeySource::Efuse, }; // search forward for the "type 2" region in the first kilobyte of plaintext @@ -238,8 +265,40 @@ impl<'a> BitstreamOracle<'a> { oracle.type2_ciphertext_offset = pt_pos; log::debug!("type2 absolute: {}, relative to ct start: {}", oracle.type2_absolute_offset, oracle.type2_ciphertext_offset); + // read the boot source out of the ciphertext + let mut bytes = first_block.chunks(4).into_iter(); + let mut ctl0_enc: Option = None; + loop { + if let Some(b) = bytes.next() { + let word = u32::from_be_bytes(b.try_into().unwrap()); + if word == BITSTREAM_CTL0_CMD_FLIP { + if let Some(val) = bytes.next() { + let mut flip: [u8; 4] = [0; 4]; + bitflip(val, &mut flip); + let w = u32::from_be_bytes(flip.try_into().unwrap()); + ctl0_enc = Some(w); + } else { + log::error!("didn't decrypt enough memory to find the ctl0 encrypted settings"); + return Err(RootkeyResult::IntegrityError); + } + break; + } + } else { + break; + } + } + if (ctl0_enc.unwrap() & 0x8000_0000) == 0x8000_0000 { + oracle.dec_from_key = FpgaKeySource::Efuse; + } else { + oracle.dec_from_key = FpgaKeySource::Bbram; + } + // by default, we always re-encrypt to the same key type + oracle.enc_to_key = oracle.dec_from_key; + Ok(oracle) } + + #[allow(dead_code)] pub fn pt_header_len(&self) -> usize {self.pt_header_len as usize} pub fn base(&self) -> u32 {self.base} pub fn ciphertext_offset(&self) -> usize { @@ -248,6 +307,12 @@ impl<'a> BitstreamOracle<'a> { pub fn ciphertext(&self) -> &[u8] { self.ciphertext } + pub fn get_original_key_type(&self) -> FpgaKeySource {self.dec_from_key} + /// the main use case for this API is changing from a BBRAM->eFuse source + /// we can't go eFuse->BBRAM because, unfortunately, we can't program BBRAM keys natively; the bitstream will have to have been constructed for BBRAM already for a good boot + pub fn set_target_key_type(&mut self, keytype: FpgaKeySource) { + self.enc_to_key = keytype; + } pub fn ciphertext_offset_to_frame(&self, offset: usize) -> (usize, usize) { let type2_offset = offset - self.type2_ciphertext_offset; @@ -313,7 +378,8 @@ impl<'a> BitstreamOracle<'a> { /// chaining value. It is up to the caller to manage the linear order of the calls. /// ASSUME: `from` + `self.ct_absolute_offset` is a multiple of an erase block /// returns the actual number of bytes processed - pub fn encrypt_sector(&self, from: i32, input_plaintext: &[u8], output_sector: &mut [u8]) -> usize { + /// NOTE: input plaintext can be changed by this function -- the first block is modified based on the requested encryption type + pub fn encrypt_sector(&self, from: i32, input_plaintext: &mut [u8], output_sector: &mut [u8]) -> usize { assert!(output_sector.len() & (AES_BLOCKSIZE - 1) == 0, "output length must be a multiple of AES block size"); assert!(input_plaintext.len() & (AES_BLOCKSIZE - 1) == 0, "input length must be a multiple of AES block size"); assert!((from + self.ct_absolute_offset as i32) & (spinor::SPINOR_ERASE_SIZE as i32 - 1) == 0, "request address must line up with an erase block boundary"); @@ -326,28 +392,117 @@ impl<'a> BitstreamOracle<'a> { let mut out_start_offset = 0; if from < 0 { - // copy the plaintext header as-is: we don't modify it, once it's in the device (e.g. we won't switch - // from eFuse to BBRAM or back again). Later on if such a switching is desired, I believe it's just a couple - // bytes patched in the plaintext header to change this, but, for now, let's assume once you're on a given - // encryption train, you're staying on it. BBRAM requires external provisioning anyways, and BBRAM users - // would be using this feature because they don't trust eFuse. eFuse users can't switch to BBRAM without an - // external programmer that would burn the key in the first place. + // A bit of a nightmare, but we have to patch over the efuse/bbram selection settings + // on the fly, because a user might be using bbram, but updates are by default set to use efuse. + // // the plaintext header already has: - // - all the fuse and config settings + // - one copy of the fuse and config settings // - padding // - IV for cipher // - length of ciphertext region + // slightly into the ciphertext region is another set of bits that re-confirm the key settings. + // we need to flip the bits that control bbram vs aes key boot as part of the re-encryption process. + // + // So: 1. check to see what type of boot we are doing + // 2. update the header bits to match it. + // 3. update the ciphertext (in two places) to match. + // + // The instruction that selects eFuse/BBRAM is 'Control Register 0' (00101) + // It has the in-bitstream hex code of 0x3000a001 and is set to 0x80000040 for efuse boot and + // 0x00000040 for bbram boot. The byte to patch is at offset 88 decimal in the bitstream headers + // generated by our tools, but it would be more reliable to search for the instruction and patch the + // byte after it. The `mask` register (00110) is also set, hex code 0x3000c001, set to 0x80000040 + // to allow for the control register write to "take" + + // copy the plaintext header over to the destination, as-is for (&src, dst) in self.bitstream[..self.ct_absolute_offset].iter() .zip(output_sector[..self.ct_absolute_offset].iter_mut()) { *dst = src; } out_start_offset = self.ct_absolute_offset; + + // now, make sure that the new settings match the settings indicated by the oracle. + // 1. patch the plaintext header + let mut pos = 0; + let mut patchcount = 0; + while pos < self.ct_absolute_offset { + let cwd = u32::from_be_bytes(output_sector[pos..pos+4].try_into().unwrap()); + if (cwd == BITSTREAM_CTL0_CMD) || (cwd == BITSTREAM_MASK_CMD) { + pos += 4; + // the bit we want to patch is in MSB of the value, just patch it directly since + // the pos pointer is at this byte. + log::debug!("output_sector: {:x?}", &output_sector[pos..pos+4]); + match self.enc_to_key { + FpgaKeySource::Bbram => output_sector[pos] &= 0x7f, + FpgaKeySource::Efuse => output_sector[pos] |= 0x80, + } + log::debug!("patched {:x?}", &output_sector[pos..pos+4]); + patchcount += 1; + if patchcount >= 2 { + break; // short circuit the checking when we're done + } + } + pos += 4; + } + + // 2. set the commands that will eventually be encrypted, by patching the input plaintext + pos = 64; // start from after the hmac header + while pos < input_plaintext.len() { + let cwd = u32::from_be_bytes(input_plaintext[pos..pos+4].try_into().unwrap()); + // the mask is always 0xffff_ffff for the bitstreams as generated by vivado...so need to modify that + if cwd == BITSTREAM_CTL0_CMD_FLIP { + pos += 4; + // the bit we want to patch is in MSB of the value, just patch it directly since + // the pos pointer is at this byte. + log::debug!("patching ct header orig: {:x}", input_plaintext[pos+3]); + log::debug!("{:x?}", &input_plaintext[pos..pos+4]); + if cwd == BITSTREAM_CTL0_CMD_FLIP { + match self.enc_to_key { + FpgaKeySource::Bbram => input_plaintext[pos+3] &= 0xfe, + FpgaKeySource::Efuse => input_plaintext[pos+3] |= 0x01, // bit 31 is at byte 3 "lsb" in the flipped version + } + } + log::debug!("{:x?}", &input_plaintext[pos..pos+4]); + break; + } + pos += 4; + } } let mut chain: [u8; AES_BLOCKSIZE] = self.iv; if from > 0 { bitflip(&self.ciphertext[from as usize - AES_BLOCKSIZE..from as usize], &mut chain); } + // 3. search for the encryption key source setting only in the last blocks + if from > ((self.type2_count as i32 * 4 + self.type2_ciphertext_offset as i32) & 0x7FFF_F000) - 0x1000 { + // maybe that complex math above would be better replaced with the the constant 0x21_5000. it never changes...? + // I guess it might be helpful if someone ported this code to a new FPGA type. + log::debug!("type2 count: {} offset: {}", self.type2_count, self.type2_ciphertext_offset); + log::debug!("searching for second key setting starting from 0x{:x}", from); + let mut bytes = input_plaintext.chunks_mut(4).into_iter(); + loop { + if let Some(b) = bytes.next() { + let word = u32::from_be_bytes(b[..4].try_into().unwrap()); + if word == BITSTREAM_CTL0_CMD_FLIP { + log::debug!("patching the second key setting inside block starting at 0x{:x}", from); + if let Some(val) = bytes.next() { + log::debug!("{:x?}", val); + match self.enc_to_key { + FpgaKeySource::Bbram => val[3] &= 0xfe, + FpgaKeySource::Efuse => val[3] |= 0x01, // bit 31 is at byte 3 "lsb" in the flipped version + } + log::debug!("{:x?}", val); + } else { + log::error!("didn't decrypt enough memory to find the ctl0 encrypted settings"); + } + break; + } + } else { + break; + } + } + } + let mut bytes_processed = 0; let mut temp_block = [0; AES_BLOCKSIZE]; for (iblock, oblock) in input_plaintext.chunks(AES_BLOCKSIZE).into_iter() @@ -441,18 +596,25 @@ impl<'a> RootKeys { xous::MemoryFlags::R, ).expect("couldn't map in the kernel region"); - let sensitive_data = xous::syscall::map_memory( + let mut sensitive_data = xous::syscall::map_memory( None, None, 0x1000, xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map sensitive data page"); - let pass_cache = xous::syscall::map_memory( + let mut pass_cache = xous::syscall::map_memory( None, None, 0x1000, xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map sensitive data page"); + // make sure the caches start out as zeros + for w in pass_cache.as_slice_mut::().iter_mut() { + *w = 0; + } + for w in sensitive_data.as_slice_mut::().iter_mut() { + *w = 0; + } let spinor = spinor::Spinor::new(&xns).expect("couldn't connect to spinor server"); spinor.register_soc_token().expect("couldn't register rootkeys as the one authorized writer to the gateware update area!"); @@ -501,6 +663,31 @@ impl<'a> RootKeys { } pub fn kernel_base(&self) -> u32 { self.kernel_base } + /// returns None if there is an obvious problem with the JTAG interface + /// otherwise returns the result. "secured" would be the most paranoid setting + /// which is all the bits burned. There are other combinations that are also + /// totally valid based on your usage scenario, however, but the have yet to + /// be implemented (see the JTAG crate for more info); however, we reflect + /// all of the calls through rootkeys so we aren't exposing JTAG attack surface + /// to the rest of the world. + pub fn is_efuse_secured(&self) -> Option { + if self.jtag.get_id().unwrap() != jtag::XCS750_IDCODE { + return None; + } + if (self.jtag.get_raw_control_bits().expect("couldn't get control bits") & 0x3f) != 0x3F { + return Some(false) + } else { + return Some(true) + } + } + pub fn is_jtag_working(&self) -> bool { + if self.jtag.get_id().unwrap() == jtag::XCS750_IDCODE { + true + } else { + false + } + } + fn xns_interlock(&self) { loop { if self.xns.trusted_init_done().expect("couldn't query init done status") { @@ -511,7 +698,7 @@ impl<'a> RootKeys { } } } - fn purge_password(&mut self, pw_type: PasswordType) { + pub fn purge_password(&mut self, pw_type: PasswordType) { unsafe { let pcache_ptr: *mut PasswordCache = self.pass_cache.as_mut_ptr() as *mut PasswordCache; match pw_type { @@ -536,12 +723,22 @@ impl<'a> RootKeys { } core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); } - fn purge_sensitive_data(&mut self) { + pub fn purge_sensitive_data(&mut self) { for d in self.sensitive_data.borrow_mut().as_slice_mut::().iter_mut() { *d = 0; } core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); } + fn populate_sensitive_data(&mut self) { + for (addr, d) in self.sensitive_data.borrow_mut().as_slice_mut::().iter_mut().enumerate() { + if addr > 255 { + break; + } + self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, addr as u32); + let keyword = self.keyrom.rf(utra::keyrom::DATA_DATA); + *d = keyword; + } + } pub fn suspend(&mut self) { match self.boot_password_policy { @@ -699,6 +896,15 @@ impl<'a> RootKeys { } } + pub fn is_pcache_update_password_valid(&self) -> bool { + let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; + if pcache.hashed_update_pw_valid == 0 { + false + } else { + true + } + } + /// Called by the UX layer to set up a key init run. It disables suspend/resume for the duration /// of the run, and also sets up some missing fields of KEYROM necessary to encrypt passwords. pub fn setup_key_init(&mut self) { @@ -785,6 +991,7 @@ impl<'a> RootKeys { // get access to the pcache and generate a keypair let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; let keypair = if true { // true for production, false for debug (uses dev keys, so we can compare results) + // keypair zeroizes on drop Keypair::generate(&mut self.trng) } else { Keypair::from_bytes( @@ -821,6 +1028,7 @@ impl<'a> RootKeys { // allocate a decryption oracle for the FPGA bitstream. This will fail early if the FPGA key is wrong. assert!(pcache.fpga_key_valid == 1); + log::debug!("making destination oracle"); let mut dst_oracle = match BitstreamOracle::new(&pcache.fpga_key, &pcache.fpga_key, self.gateware(), self.gateware_base()) { Ok(o) => o, Err(e) => { @@ -837,7 +1045,7 @@ impl<'a> RootKeys { .zip(self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::SELFSIGN_PUBKEY as usize..KeyRomLocs::SELFSIGN_PUBKEY as usize + 256/(size_of::()*8)].iter_mut()) { *dst = u32::from_be_bytes(src.try_into().unwrap()) } - log::info!("public key as computed: {:x?}", public_key); + log::debug!("public key as computed: {:x?}", public_key); // extract the update password key from the cache, and apply it to the private key #[cfg(feature = "hazardous-debug")] @@ -847,7 +1055,7 @@ impl<'a> RootKeys { } // private key must XOR with password before storing let mut private_key_enc: [u8; ed25519_dalek::SECRET_KEY_LENGTH] = [0; ed25519_dalek::SECRET_KEY_LENGTH]; - // we do this from to try and avoid making as few copies of the hashed password as possible + // I don't think this loop should make any extra copies of the secret key, but might be good to check in godbolt! for (dst, (plain, key)) in private_key_enc.iter_mut() .zip(keypair.secret.to_bytes().iter() @@ -917,6 +1125,7 @@ impl<'a> RootKeys { pb.rebase_subtask_percentage(30, 50); self.make_gateware_backup(Some(&mut pb))?; + log::debug!("making source oracle"); let mut src_oracle = match BitstreamOracle::new(&pcache.fpga_key, &pcache.fpga_key, self.staging(), self.staging_base()) { Ok(o) => o, Err(e) => { @@ -933,6 +1142,11 @@ impl<'a> RootKeys { self.gateware_copy_and_patch(&src_oracle, &dst_oracle, Some(&mut pb))?; + // make a copy of the plaintext metadata and csr records + self.spinor.patch(self.gateware(), self.gateware_base(), + &self.staging()[METADATA_OFFSET..SELFSIG_OFFSET], METADATA_OFFSET as u32 + ).map_err(|_| RootkeyResult::FlashError)?; + // verify that the patch worked pb.update_text(t!("rootkeys.init.verifying_gateware", xous::LANG)); pb.rebase_subtask_percentage(70, 90); @@ -946,21 +1160,24 @@ impl<'a> RootKeys { self.commit_signature(kernel_sig, kernel_len, SignatureType::Kernel)?; pb.set_percentage(95); - if !self.verify_selfsign_kernel() { - log::error!("kernel signature failed to verify, probably should not try to reboot!"); - src_oracle.clear(); - dst_oracle.clear(); - return Err(RootkeyResult::IntegrityError); - } - - pb.set_percentage(98); - let (gateware_sig, gateware_len) = self.sign_gateware(&keypair); - log::debug!("gateware signature ({}): {:x?}", gateware_len, gateware_sig.to_bytes()); - self.commit_signature(gateware_sig, gateware_len, SignatureType::Gateware)?; - - // clean up the oracles + // clean up the oracles as soon as we're done to avoid some borrow checker issues src_oracle.clear(); dst_oracle.clear(); + + // as a sanity check, check the kernel self signature + let ret = if !self.verify_selfsign_kernel(false) { + log::error!("kernel signature failed to verify, probably should not try to reboot!"); + Err(RootkeyResult::IntegrityError) + } else { + // sign the gateware + pb.set_percentage(98); + let (gateware_sig, gateware_len) = self.sign_gateware(&keypair); + log::debug!("gateware signature ({}): {:x?}", gateware_len, gateware_sig.to_bytes()); + self.commit_signature(gateware_sig, gateware_len, SignatureType::Gateware)?; + Ok(()) + }; + + // clear the write protects self.spinor.set_staging_write_protect(false).expect("couldn't un-protect the staging area"); // finalize the progress bar on exit -- always leave at 100% @@ -968,12 +1185,19 @@ impl<'a> RootKeys { self.ticktimer.sleep_ms(500).expect("couldn't show final message"); - // the stop emoji, when sent to the slider action bar in progress mode, will cause it to close and relinquish focus - rootkeys_modal.key_event(['🛑', '\u{0000}', '\u{0000}', '\u{0000}']); + // always purge, we're going to reboot; and if we don't, then there's shenanigans + for w in private_key_enc.iter_mut() { // it's encrypted. but i still want it turned to zeroes. + *w = 0; + } + self.purge_password(PasswordType::Boot); + self.purge_password(PasswordType::Update); + self.purge_sensitive_data(); + // ed25519 keypair zeroizes on drop - Ok(()) + ret } + #[allow(dead_code)] #[cfg(feature = "hazardous-debug")] pub fn printkeys(&mut self) { // dump the keystore -- used to confirm that patching worked right. does not get compiled in when hazardous-debug is not enable. @@ -984,6 +1208,259 @@ impl<'a> RootKeys { } } + pub fn do_gateware_update(&mut self, rootkeys_modal: &mut Modal, main_cid: xous::CID) -> Result<(), RootkeyResult> { + // make sure the system is sane + self.xns_interlock(); + self.spinor.set_staging_write_protect(true).expect("couldn't protect the staging area"); + + // setup Ux + let mut progress_action = Slider::new(main_cid, Opcode::UxGutter.to_u32().unwrap(), + 0, 100, 10, Some("%"), 0, true, true + ); + progress_action.set_is_password(true); + // now show the init wait note... + rootkeys_modal.modify( + Some(ActionType::Slider(progress_action)), + Some(t!("rootkeys.gwup_starting", xous::LANG)), false, + None, true, None); + rootkeys_modal.activate(); + xous::yield_slice(); // give some time to the GAM to render + let mut pb = ProgressBar::new(rootkeys_modal, &mut progress_action); + pb.set_percentage(1); + + // decrypt the FPGA key using the stored password + let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; + if pcache.hashed_update_pw_valid == 0 { + self.purge_password(PasswordType::Update); + log::error!("no password was set going into the update routine"); + #[cfg(feature = "hazardous-debug")] + log::debug!("key: {:x?}", pcache.hashed_update_pw); + log::debug!("valid: {}", pcache.hashed_update_pw_valid); + + return Err(RootkeyResult::KeyError); + } + for (&src, dst) in self.read_key_256(KeyRomLocs::FPGA_KEY).iter().zip(pcache.fpga_key.iter_mut()) { + *dst = src; + } + log::debug!("fpga key (encrypted): {:x?}", &pcache.fpga_key); + for (fkey, &pw) in pcache.fpga_key.iter_mut().zip(pcache.hashed_update_pw.iter()) { + *fkey = *fkey ^ pw; + } + pcache.fpga_key_valid = 1; + #[cfg(feature = "hazardous-debug")] + log::debug!("fpga key (reconstituted): {:x?}", &pcache.fpga_key); + + // derive signing key + let mut keypair_bytes: [u8; ed25519_dalek::KEYPAIR_LENGTH] = [0; ed25519_dalek::KEYPAIR_LENGTH]; + let enc_signing_key = self.read_key_256(KeyRomLocs::SELFSIGN_PRIVKEY); + for (key, (&enc_key, &pw)) in + keypair_bytes[..ed25519_dalek::SECRET_KEY_LENGTH].iter_mut() + .zip(enc_signing_key.iter().zip(pcache.hashed_update_pw.iter())) { + *key = enc_key ^ pw; + } + for (key, &src) in keypair_bytes[ed25519_dalek::SECRET_KEY_LENGTH..].iter_mut() + .zip(self.read_key_256(KeyRomLocs::SELFSIGN_PUBKEY).iter()) { + *key = src; + } + #[cfg(feature = "hazardous-debug")] + log::debug!("trying to make a keypair from {:x?}", keypair_bytes); + // Keypair zeroizes on drop + let keypair = Keypair::from_bytes(&keypair_bytes).map_err(|_| RootkeyResult::KeyError)?; + log::debug!("keypair success"); + + // stage the keyrom data for patching + self.populate_sensitive_data(); + + pb.set_percentage(3); + log::debug!("making destination oracle"); + let mut dst_oracle = match BitstreamOracle::new(&pcache.fpga_key, &pcache.fpga_key, self.gateware(), self.gateware_base()) { + Ok(o) => o, + Err(e) => { + self.purge_password(PasswordType::Update); + log::error!("couldn't create oracle (most likely FPGA key mismatch): {:?}", e); + return Err(e); + } + }; + log::debug!("destination oracle success"); + let keysource = dst_oracle.get_original_key_type(); + dst_oracle.set_target_key_type(keysource); + pb.set_percentage(6); + // updates are always encrypted with the null key. + let dummy_key: [u8; 32] = [0; 32]; + log::debug!("making source oracle"); + let mut src_oracle = match BitstreamOracle::new(&dummy_key, &pcache.fpga_key, self.staging(), self.staging_base()) { + Ok(o) => o, + Err(e) => { + log::error!("couldn't create oracle (most likely FPGA key mismatch): {:?}", e); + dst_oracle.clear(); + self.purge_password(PasswordType::Update); + return Err(e); + } + }; + log::debug!("source oracle success"); + + pb.set_percentage(10); + pb.update_text(t!("rootkeys.init.patching_keys", xous::LANG)); + pb.rebase_subtask_percentage(10, 60); + self.gateware_copy_and_patch(&src_oracle, &dst_oracle, Some(&mut pb))?; + + // make a copy of the plaintext metadata and csr records + self.spinor.patch(self.gateware(), self.gateware_base(), + &self.staging()[METADATA_OFFSET..SELFSIG_OFFSET], METADATA_OFFSET as u32 + ).map_err(|_| RootkeyResult::FlashError)?; + + // verify that the patch worked + pb.update_text(t!("rootkeys.init.verifying_gateware", xous::LANG)); + pb.rebase_subtask_percentage(60, 90); + log::debug!("making verification oracle"); + let verify_oracle = match BitstreamOracle::new(&pcache.fpga_key, &pcache.fpga_key, self.gateware(), self.gateware_base()) { + Ok(o) => o, + Err(e) => { + log::error!("couldn't create oracle (most likely FPGA key mismatch): {:?}", e); + return Err(e); + } + }; + + self.verify_gateware(&verify_oracle, Some(&mut pb))?; + + pb.set_percentage(92); + + // commit signatures + pb.update_text(t!("rootkeys.init.commit_signatures", xous::LANG)); + let (gateware_sig, gateware_len) = self.sign_gateware(&keypair); + log::debug!("gateware signature ({}): {:x?}", gateware_len, gateware_sig.to_bytes()); + self.commit_signature(gateware_sig, gateware_len, SignatureType::Gateware)?; + + // clean up the oracles + pb.set_percentage(95); + src_oracle.clear(); + dst_oracle.clear(); + self.purge_sensitive_data(); + self.spinor.set_staging_write_protect(false).expect("couldn't un-protect the staging area"); + for b in keypair_bytes.iter_mut() { + *b = 0; + } + // ed25519 keypair zeroizes on drop + + // check signatures + pb.set_percentage(96); + if !self.verify_gateware_self_signature() { + return Err(RootkeyResult::IntegrityError); + } + + pb.set_percentage(100); + + // check if we're to purge the password on completion + if self.update_password_policy == PasswordRetentionPolicy::AlwaysPurge { + self.purge_password(PasswordType::Update); + } + Ok(()) + } + + pub fn do_sign_xous(&mut self, rootkeys_modal: &mut Modal, main_cid: xous::CID) -> Result<(), RootkeyResult> { + // make sure the system is sane + self.xns_interlock(); + + // setup Ux + let mut progress_action = Slider::new(main_cid, Opcode::UxGutter.to_u32().unwrap(), + 0, 100, 10, Some("%"), 0, true, true + ); + progress_action.set_is_password(true); + // now show the init wait note... + rootkeys_modal.modify( + Some(ActionType::Slider(progress_action)), + Some(t!("rootkeys.gwup_starting", xous::LANG)), false, + None, true, None); + rootkeys_modal.activate(); + xous::yield_slice(); // give some time to the GAM to render + let mut pb = ProgressBar::new(rootkeys_modal, &mut progress_action); + pb.set_percentage(1); + + // derive signing key + let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; + if pcache.hashed_update_pw_valid == 0 { + self.purge_password(PasswordType::Update); + log::error!("no password was set going into the update routine"); + #[cfg(feature = "hazardous-debug")] + log::debug!("key: {:x?}", pcache.hashed_update_pw); + log::debug!("valid: {}", pcache.hashed_update_pw_valid); + + return Err(RootkeyResult::KeyError); + } + let mut keypair_bytes: [u8; ed25519_dalek::KEYPAIR_LENGTH] = [0; ed25519_dalek::KEYPAIR_LENGTH]; + let enc_signing_key = self.read_key_256(KeyRomLocs::SELFSIGN_PRIVKEY); + for (key, (&enc_key, &pw)) in + keypair_bytes[..ed25519_dalek::SECRET_KEY_LENGTH].iter_mut() + .zip(enc_signing_key.iter().zip(pcache.hashed_update_pw.iter())) { + *key = enc_key ^ pw; + } + for (key, &src) in keypair_bytes[ed25519_dalek::SECRET_KEY_LENGTH..].iter_mut() + .zip(self.read_key_256(KeyRomLocs::SELFSIGN_PUBKEY).iter()) { + *key = src; + } + // Keypair zeroizes the secret key on drop. + let keypair = Keypair::from_bytes(&keypair_bytes).map_err(|_| RootkeyResult::KeyError)?; + + // check if the keypair is valid by signing and verifying a short message + let test_data = "whiskey made me do it"; + let test_sig = keypair.sign(test_data.as_bytes()); + match keypair.verify(&test_data.as_bytes(), &test_sig) { + Ok(_) => (), + Err(e) => { + log::warn!("update password was not connect ({:?})", e); + self.purge_password(PasswordType::Update); + for b in keypair_bytes.iter_mut() { + *b = 0; + } + return Err(RootkeyResult::KeyError); + } + } + + // sign the kernel + pb.update_text(t!("rootkeys.init.signing_kernel", xous::LANG)); + pb.set_percentage(35); + let (kernel_sig, kernel_len) = self.sign_kernel(&keypair); + + // sign the loader + pb.update_text(t!("rootkeys.init.signing_loader", xous::LANG)); + pb.rebase_subtask_percentage(35, 85); + let (loader_sig, loader_len) = self.sign_loader(&keypair, Some(&mut pb)); + log::debug!("loader signature: {:x?}", loader_sig.to_bytes()); + log::debug!("loader len: {} bytes", loader_len); + + // commit the signatures + pb.update_text(t!("rootkeys.init.commit_signatures", xous::LANG)); + self.commit_signature(loader_sig, loader_len, SignatureType::Loader)?; + log::debug!("loader {} bytes, sig: {:x?}", loader_len, loader_sig.to_bytes()); + pb.set_percentage(90); + self.commit_signature(kernel_sig, kernel_len, SignatureType::Kernel)?; + pb.set_percentage(92); + + // as a sanity check, check the kernel self signature + let ret = if !self.verify_selfsign_kernel(true) { + log::error!("kernel signature failed to verify, probably should not try to reboot!"); + Err(RootkeyResult::IntegrityError) + } else { + Ok(()) + }; + + // check if we're to purge the password on completion + if self.update_password_policy == PasswordRetentionPolicy::AlwaysPurge { + self.purge_password(PasswordType::Update); + } + // purge the temporaries that we can + for b in keypair_bytes.iter_mut() { + *b = 0; + } + // ed25519 keypair zeroizes on drop + + pb.set_percentage(100); + self.ticktimer.sleep_ms(250).expect("couldn't show final message"); + + ret + } + + pub fn test(&mut self, rootkeys_modal: &mut Modal, main_cid: xous::CID) -> Result<(), RootkeyResult> { let mut progress_action = Slider::new(main_cid, Opcode::UxGutter.to_u32().unwrap(), 0, 100, 10, Some("%"), 0, true, true @@ -1014,14 +1491,13 @@ impl<'a> RootKeys { let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; // setup the local cache - let sensitive_slice = self.sensitive_data.as_slice_mut::(); for addr in 0..256 { self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, addr); self.sensitive_data.borrow_mut().as_slice_mut::()[addr as usize] = self.keyrom.rf(utra::keyrom::DATA_DATA); log::info!("{:02x}: 0x{:08x}", addr, self.sensitive_data.borrow_mut().as_slice::()[addr as usize]); } - for (word, key) in sensitive_slice[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::()*8)].iter() + for (word, key) in self.sensitive_data.borrow().as_slice::()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::()*8)].iter() .zip(pcache.fpga_key.chunks_mut(4).into_iter()) { for (&s, d) in word.to_be_bytes().iter().zip(key.iter_mut()) { *d = s; @@ -1054,12 +1530,12 @@ impl<'a> RootKeys { // TEST if self.gateware_copy_and_patch(&src_oracle, &dst_oracle, None).is_err() { log::error!("error occured in patch_keys."); - return false; + return Err(RootkeyResult::FlashError); } if self.verify_gateware(&dst_oracle, None).is_err() { log::error!("error occurred in gateware verification"); - return false; + return Err(RootkeyResult::IntegrityError); } } @@ -1074,10 +1550,6 @@ impl<'a> RootKeys { /// ASSUME: CSR appendix does not change during the copy (it is not copied/updated) fn gateware_copy_and_patch(&self, src_oracle: &BitstreamOracle, dst_oracle: &BitstreamOracle, mut maybe_pb: Option<&mut ProgressBar>) -> Result<(), RootkeyResult> { - if self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::CONFIG as usize] & keyrom_config::INITIALIZED.ms(1) == 0 { - // the keys weren't initialized, or are wrong. abort! - return Err(RootkeyResult::KeyError); - } log::debug!("sanity checks: src_offset {}, dst_offset {}, src_len {}, dst_len {}", src_oracle.ciphertext_offset(), dst_oracle.ciphertext_offset(), src_oracle.ciphertext_len(), dst_oracle.ciphertext_len()); @@ -1105,28 +1577,23 @@ impl<'a> RootKeys { *dst = hm1 ^ mask; } log::debug!("recovered hmac: {:x?}", hmac_code); - // hash the decrypt data; we assume we're not patching anything in the first sector. + log::debug!("hmac constant: {:x?}", &pt_sector[32..64]); let mut bytes_hashed = spinor::SPINOR_ERASE_SIZE as usize - src_oracle.ciphertext_offset(); - bitflip(&pt_sector[..bytes_hashed], &mut flipper[..bytes_hashed]); - hasher.update(&flipper[..bytes_hashed]); - // now encrypt and patch the data to disk + // encrypt and patch the data to disk dst_oracle.encrypt_sector( -(dst_oracle.ciphertext_offset() as i32), - &pt_sector[..bytes_hashed], + &mut pt_sector[..bytes_hashed], &mut ct_sector // full array, for space for plaintext header ); - // restore the plaintext header from the *destination* -- in this case, the destination is the - // gateware boot location, and this contains the fuse configurations we need to boot from (e.g. eFuse - // or BBRAM). We also prefer our original header because we nominally trust in more than whatever header - // is being presented to us for the update. - assert!(src_oracle.pt_header_len() == dst_oracle.pt_header_len(), "source and destination gatewares have different header lengths. Check your vivado bitgen settings..."); - for (&src, dst) in dst_oracle.bitstream[..dst_oracle.pt_header_len()].iter().zip(ct_sector.iter_mut()) { - *dst = src; - } + // hash the first sector; the pt_sector could have been patched by encrypt_sector() to change the key soucre, + // so it must be done *after* we call encrypt_sector() + bitflip(&pt_sector[..bytes_hashed], &mut flipper[..bytes_hashed]); + hasher.update(&flipper[..bytes_hashed]); log::debug!("sector 0 patch len: {}", bytes_hashed); + log::debug!("sector 0 header: {:x?}", &ct_sector[..dst_oracle.ciphertext_offset()]); self.spinor.patch(dst_oracle.bitstream, dst_oracle.base(), &ct_sector, 0) .map_err(|_| RootkeyResult::FlashError)?; @@ -1150,6 +1617,14 @@ impl<'a> RootKeys { } else { hash_stop - bytes_hashed }; + + // encrypt before hashing, because a bit that selects the key type can be patched by the encryptor + dst_oracle.encrypt_sector( + from as i32, + &mut pt_sector[..decrypt_len], + &mut ct_sector[..decrypt_len], + ); + if hash_len > 0 { bitflip(&pt_sector[..hash_len], &mut flipper[..hash_len]); hasher.update(&flipper[..hash_len]); @@ -1159,11 +1634,6 @@ impl<'a> RootKeys { } } - dst_oracle.encrypt_sector( - from as i32, - &pt_sector[..decrypt_len], - &mut ct_sector[..decrypt_len], - ); self.spinor.patch(dst_oracle.bitstream, dst_oracle.base(), &ct_sector[..decrypt_len], from + dst_oracle.ciphertext_offset() as u32) .map_err(|_| RootkeyResult::FlashError)?; @@ -1222,7 +1692,7 @@ impl<'a> RootKeys { } log::debug!("last bytes patched: {:x?}", &pt_sector[pt_sector_len-256..pt_sector_len]); - dst_oracle.encrypt_sector(ct_last_block_loc as i32, &pt_sector[..pt_sector_len], &mut ct_sector[..pt_sector_len]); + dst_oracle.encrypt_sector(ct_last_block_loc as i32, &mut pt_sector[..pt_sector_len], &mut ct_sector[..pt_sector_len]); log::trace!("hash patching from 0x{:x} len {}", ct_last_block_loc, pt_sector_len); self.spinor.patch(dst_oracle.bitstream, dst_oracle.base(), &ct_sector[..pt_sector_len], ct_last_block_loc as u32 + dst_oracle.ciphertext_offset() as u32) @@ -1342,7 +1812,7 @@ impl<'a> RootKeys { } if matching { - log::info!("gateware verified"); + log::debug!("gateware verified"); Ok(()) } else { log::error!("gateware failed to verify"); @@ -1532,21 +2002,25 @@ impl<'a> RootKeys { (signing_key.sign(&kernel_region[SIGBLOCK_SIZE as usize..]), kernel_len as u32) } - /// the public key must already be in the cache - pub fn verify_selfsign_kernel(&self) -> bool { - if self.sensitive_data.borrow_mut().as_slice::()[KeyRomLocs::CONFIG as usize] & keyrom_config::INITIALIZED.ms(1) == 0 { - log::warn!("key cache was not initialized, can't verify the kernel with our self-signing key"); - return false; - } - - // read the public key directly out of the keyrom + /// the public key must already be in the cache -- this version is used by the init routine, before the keys are written + pub fn verify_selfsign_kernel(&mut self, is_system_initialized: bool) -> bool { let mut key: [u8; 32] = [0; 32]; - log::debug!("reading public key from cached area"); - for (word, &keyword) in key.chunks_mut(4).into_iter() - .zip(self.sensitive_data.borrow_mut().as_slice::()[KeyRomLocs::SELFSIGN_PUBKEY as usize..KeyRomLocs::SELFSIGN_PUBKEY as usize + 256/(size_of::()*8)].iter()) { - for (&byte, dst) in keyword.to_be_bytes().iter().zip(word.iter_mut()) { - *dst = byte; + if !is_system_initialized { + if self.sensitive_data.borrow_mut().as_slice::()[KeyRomLocs::CONFIG as usize] & keyrom_config::INITIALIZED.ms(1) == 0 { + log::warn!("key cache was not initialized, can't verify the kernel with our self-signing key"); + return false; } + + // read the public key directly out of the keyrom + log::debug!("reading public key from cached area"); + for (word, &keyword) in key.chunks_mut(4).into_iter() + .zip(self.sensitive_data.borrow_mut().as_slice::()[KeyRomLocs::SELFSIGN_PUBKEY as usize..KeyRomLocs::SELFSIGN_PUBKEY as usize + 256/(size_of::()*8)].iter()) { + for (&byte, dst) in keyword.to_be_bytes().iter().zip(word.iter_mut()) { + *dst = byte; + } + } + } else { + key = self.read_key_256(KeyRomLocs::SELFSIGN_PUBKEY); } log::debug!("pubkey as reconstituted: {:x?}", key); let pubkey = PublicKey::from_bytes(&key).expect("public key was not valid"); @@ -1571,35 +2045,20 @@ impl<'a> RootKeys { } pub fn sign_gateware(&self, signing_key: &Keypair) -> (Signature, u32) { - let mut hasher = Sha512::new_with_strategy(FallbackStrategy::WaitForHardware); let gateware_region = self.gateware(); - // sign everything except a hole just big enough to fit the digital signature record - let mut bytes_hashed = CSR_CSV_OFFSET - core::mem::size_of::(); - hasher.update(&gateware_region[..bytes_hashed]); - bytes_hashed += gateware_region.len() - CSR_CSV_OFFSET; - hasher.update(&gateware_region[CSR_CSV_OFFSET..]); - - // note that we use the *prehash* version here, this produces a different signature than a straightforward ed25519 sign - (signing_key.sign_prehashed(hasher, None).expect("couldn't sign the gateware"), bytes_hashed as u32) + (signing_key.sign(&gateware_region[..SELFSIG_OFFSET]), SELFSIG_OFFSET as u32) } + /// This is a fast check on the gateware meant to be called on boot just to confirm that we're using a self-signed gateware pub fn verify_gateware_self_signature(&mut self) -> bool { log::info!("verifying gateware self signature"); // read the public key directly out of the keyrom let pubkey = PublicKey::from_bytes(&self.read_key_256(KeyRomLocs::SELFSIGN_PUBKEY)).expect("public key was not valid"); - - let mut hasher = Sha512::new_with_strategy(FallbackStrategy::WaitForHardware); let gateware_region = self.gateware(); - // verify everything except a hole just big enough to fit the digital signature record - log::debug!("hashing gateware"); - hasher.update(&gateware_region[..CSR_CSV_OFFSET - core::mem::size_of::()]); - hasher.update(&gateware_region[CSR_CSV_OFFSET..]); - log::debug!("hash done"); - let mut sig_region: [u8; core::mem::size_of::()] = [0; core::mem::size_of::()]; - for (&src, dst) in gateware_region[CSR_CSV_OFFSET - core::mem::size_of::()..CSR_CSV_OFFSET].iter() + for (&src, dst) in gateware_region[SELFSIG_OFFSET..SELFSIG_OFFSET + core::mem::size_of::()].iter() .zip(sig_region.iter_mut()) { *dst = src; } @@ -1610,7 +2069,7 @@ impl<'a> RootKeys { log::debug!("pubkey: {:x?}", pubkey.to_bytes()); // note that we use the *prehash* version here, this has a different signature than a straightforward ed25519 - match pubkey.verify_prehashed(hasher, None, &sig) { + match pubkey.verify_strict(&gateware_region[..SELFSIG_OFFSET], &sig) { Ok(_) => { log::info!("gateware verified!"); true @@ -1622,6 +2081,87 @@ impl<'a> RootKeys { } } + /// This function does a comprehensive check of all the possible signature types in a specified gateware region + pub fn check_gateware_signature(&mut self, region_enum: GatewareRegion) -> SignatureResult { + let mut sig_region: [u8; core::mem::size_of::()] = [0; core::mem::size_of::()]; + { + let region = match region_enum { + GatewareRegion::Boot => self.gateware(), + GatewareRegion::Staging => self.staging(), + }; + for (&src, dst) in region[SELFSIG_OFFSET..SELFSIG_OFFSET + core::mem::size_of::()].iter() + .zip(sig_region.iter_mut()) { + *dst = src; + } + } + let sig_rec: &SignatureInFlash = unsafe{(sig_region.as_ptr() as *const SignatureInFlash).as_ref().unwrap()}; + let sig = Signature::new(sig_rec.signature); + + let mut sigtype = SignatureResult::SelfSignOk; + // check against all the known signature types in detail + loop { + let pubkey_bytes = match sigtype { + SignatureResult::SelfSignOk => { + self.read_key_256(KeyRomLocs::SELFSIGN_PUBKEY) + }, + SignatureResult::ThirdPartyOk => { + self.read_key_256(KeyRomLocs::THIRDPARTY_PUBKEY) + }, + SignatureResult::DevKeyOk => { + self.read_key_256(KeyRomLocs::DEVELOPER_PUBKEY) + }, + _ => { + panic!("Invalid state during check gateware signature") + } + }; + // check for uninitialized signature records + let mut all_zero = true; + for &b in pubkey_bytes.iter() { + if b != 0 { + all_zero = false; + break; + } + } + if all_zero { + match sigtype { + SignatureResult::SelfSignOk => sigtype = SignatureResult::ThirdPartyOk, + SignatureResult::ThirdPartyOk => sigtype = SignatureResult::DevKeyOk, + _ => return SignatureResult::Invalid + } + continue; + } + let pubkey = PublicKey::from_bytes(&pubkey_bytes).expect("public key was not valid"); + + let region = match region_enum { + GatewareRegion::Boot => self.gateware(), + GatewareRegion::Staging => self.staging(), + }; + match pubkey.verify_strict(®ion[..SELFSIG_OFFSET], &sig) { + Ok(_) => break, + Err(_e) => { + match sigtype { + SignatureResult::SelfSignOk => sigtype = SignatureResult::ThirdPartyOk, + SignatureResult::ThirdPartyOk => sigtype = SignatureResult::DevKeyOk, + _ => return SignatureResult::Invalid + } + continue; + } + } + } + sigtype + } + + pub fn fetch_gw_metadata(&self, region_enum: GatewareRegion) -> MetadataInFlash { + let region = match region_enum { + GatewareRegion::Boot => self.gateware(), + GatewareRegion::Staging => self.staging(), + }; + let md_ptr: *const MetadataInFlash = + (®ion[METADATA_OFFSET..METADATA_OFFSET + core::mem::size_of::()]).as_ptr() as *const MetadataInFlash; + + unsafe{*md_ptr}.clone() + } + pub fn commit_signature(&self, sig: Signature, len: u32, sig_type: SignatureType) -> Result<(), RootkeyResult> { let mut sig_region: [u8; core::mem::size_of::()] = [0; core::mem::size_of::()]; // map a structure onto the signature region, so we can do something sane when writing stuff to it @@ -1647,10 +2187,10 @@ impl<'a> RootKeys { log::info!("kernel sig area after: {:x?}", &(self.kernel()[..0x80])); } SignatureType::Gateware => { - log::info!("gateware sig area before: {:x?}", &(self.gateware()[CSR_CSV_OFFSET - core::mem::size_of::()..CSR_CSV_OFFSET])); - self.spinor.patch(self.gateware(), self.gateware_base(), &sig_region, (CSR_CSV_OFFSET - core::mem::size_of::()) as u32) + log::info!("gateware sig area before: {:x?}", &(self.gateware()[SELFSIG_OFFSET..SELFSIG_OFFSET + core::mem::size_of::()])); + self.spinor.patch(self.gateware(), self.gateware_base(), &sig_region, (SELFSIG_OFFSET) as u32) .map_err(|_| RootkeyResult::FlashError)?; - log::info!("gateware sig area after: {:x?}", &(self.gateware()[CSR_CSV_OFFSET - core::mem::size_of::()..CSR_CSV_OFFSET])); + log::info!("gateware sig area after: {:x?}", &(self.gateware()[SELFSIG_OFFSET..SELFSIG_OFFSET + core::mem::size_of::()])); } } Ok(()) diff --git a/services/root-keys/src/lib.rs b/services/root-keys/src/lib.rs index 5c2521dd5..bd9c26531 100644 --- a/services/root-keys/src/lib.rs +++ b/services/root-keys/src/lib.rs @@ -102,12 +102,7 @@ impl RootKeys { } /// this initiates an attempt to update passwords. User must unlock their device first, and can cancel out if not expected. - pub fn try_update_password(&mut self, which: PasswordType) -> Result<(), xous::Error> { - unimplemented!(); - } - - //// initiates a self-signing of the firmwares using the ed25519 private key stored in the enclave - pub fn self_sign(&mut self, which: ImageType) -> Result<(), xous::Error> { + pub fn try_update_password(&mut self, _which: PasswordType) -> Result<(), xous::Error> { unimplemented!(); } @@ -131,6 +126,37 @@ impl RootKeys { } } + pub fn is_efuse_secured(&self) -> Result, xous::Error> { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::IsEfuseSecured.to_usize().unwrap(), 0, 0, 0, 0) + )?; + if let xous::Result::Scalar1(result) = response { + if result == 2 { + Ok(None) + } else if result == 1 { + Ok(Some(true)) + } else { + Ok(Some(false)) + } + } else { + Err(xous::Error::InternalError) + } + } + pub fn is_jtag_working(&self) -> Result { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::IsJtagWorking.to_usize().unwrap(), 0, 0, 0, 0) + )?; + if let xous::Result::Scalar1(result) = response { + if result == 1 { + Ok(true) + } else { + Ok(false) + } + } else { + Err(xous::Error::InternalError) + } + } + pub fn test_ux(&mut self, arg: usize) { send_message(self.conn, Message::new_scalar(Opcode::TestUx.to_usize().unwrap(), diff --git a/services/root-keys/src/main.rs b/services/root-keys/src/main.rs index c9ffd26ea..1b12b8724 100644 --- a/services/root-keys/src/main.rs +++ b/services/root-keys/src/main.rs @@ -12,6 +12,8 @@ use gam::modal::*; use gam::menu::*; use locales::t; +use std::format; +use std::str; #[cfg(any(target_os = "none", target_os = "xous"))] mod implementation; @@ -21,6 +23,54 @@ use implementation::*; #[cfg(any(target_os = "none", target_os = "xous"))] mod bcrypt; +pub enum SignatureResult { + SelfSignOk, + ThirdPartyOk, + DevKeyOk, + Invalid, +} +#[allow(dead_code)] +pub enum GatewareRegion { + Boot, + Staging, +} + + +/// An "easily" parseable metadata structure in flash. There's nothing that guarantees the authenticity +/// of the metadata in and of itself, other than the digital signature that wraps the entire gateware record. +/// Thus we're relying on the person who signs the gateware to not inject false data here. +#[derive(Debug, Copy, Clone)] +#[repr(C)] +pub struct MetadataInFlash { + pub magic: u32, // 0x6174656d 'atem' + pub version: u32, + /// git data, but formatted as binary integers + pub git_additional: u32, // commits beyond the tag + pub git_rev: u32, + pub git_min: u32, + pub git_maj: u32, + pub git_commit: u32, + /// md5sum of the dummy-encrypted source file; not meant to be secure, just for human-ID purposes + pub bin_checksum: [u8; 16], + /// md5sum of 'betrusted_soc.py' + pub src_checksum: [u8; 16], + /// date as free-form string (for human readable purposes) + pub date_len: u32, + pub date_str: [u8; 64], + /// the host on which the image was built + pub host_len: u32, + pub host_str: [u8; 64], + /// git tag info as a free-form string + pub tag_len: u32, + pub tag_str: [u8; 64], + /// git log info of the last commit, as a free-form string. + pub log_len: u32, + pub log_str: [u8; 512], + /// status of the build tree, as a free-form string. + pub status_len: u32, + pub status_str: [u8; 1024], +} + // a stub to try to avoid breaking hosted mode for as long as possible. #[cfg(not(any(target_os = "none", target_os = "xous")))] mod implementation { @@ -32,12 +82,14 @@ mod implementation { use crate::api::*; use gam::{ActionType, ProgressBar}; use num_traits::*; + use crate::{SignatureResult, GatewareRegion, MetadataInFlash}; #[allow(dead_code)] pub struct RootKeys { password_type: Option, jtag: jtag::Jtag, xns: xous_names::XousNames, + ticktimer: ticktimer_server::Ticktimer, } #[allow(dead_code)] @@ -50,6 +102,7 @@ mod implementation { xns, // must occupy tihs connection for the system to boot properly jtag, + ticktimer: ticktimer_server::Ticktimer::new().unwrap(), } } pub fn suspend(&self) { @@ -66,7 +119,7 @@ mod implementation { pub fn set_ux_password_type(&mut self, cur_type: Option) { self.password_type = cur_type; } - pub fn is_initialized(&self) -> bool {false} + pub fn is_initialized(&self) -> bool {true} pub fn setup_key_init(&mut self) {} pub fn do_key_init(&mut self, rootkeys_modal: &mut Modal, main_cid: xous::CID) -> Result<(), RootkeyResult> { let mut progress_action = Slider::new(main_cid, Opcode::UxGutter.to_u32().unwrap(), @@ -100,6 +153,40 @@ mod implementation { pub fn test(&mut self, rootkeys_modal: &mut Modal, main_cid: xous::CID) -> Result<(), RootkeyResult> { Ok(()) } + pub fn is_jtag_working(&self) -> bool {false} + pub fn is_efuse_secured(&self) -> Option {None} + pub fn check_gateware_signature(&mut self, region_enum: GatewareRegion) -> SignatureResult { + log::info!("faking gateware check..."); + self.ticktimer.sleep_ms(4000).unwrap(); + log::info!("done"); + SignatureResult::DevKeyOk + } + pub fn is_pcache_update_password_valid(&self) -> bool { + false + } + pub fn fetch_gw_metadata(&self, _region_enum: GatewareRegion) -> MetadataInFlash { + MetadataInFlash { + magic: 0x6174656d, + version: 1, + git_additional: 27, + git_rev: 2, + git_min: 8, + git_maj: 0, + git_commit: 0x12345678, + bin_checksum: [0; 16], + src_checksum: [0; 16], + date_len: 26, + date_str: [50, 48, 50, 49, 45, 48, 56, 45, 49, 50, 32, 50, 50, 58, 49, 53, 58, 53, 51, 46, 56, 49, 55, 51, 53, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + host_len: 14, + host_str: [98, 117, 110, 110, 105, 101, 45, 100, 101, 115, 107, 116, 111, 112, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + tag_len: 19, + tag_str: [118, 48, 46, 56, 46, 50, 45, 55, 49, 45, 103, 102, 102, 98, 97, 52, 55, 102, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + log_len: 203, + log_str: [99, 111, 109, 109, 105, 116, 32, 102, 102, 98, 97, 52, 55, 102, 52, 98, 102, 55, 99, 52, 51, 50, 55, 54, 55, 50, 50, 56, 102, 101, 99, 52, 51, 53, 97, 56, 56, 48, 54, 54, 55, 53, 101, 52, 102, 49, 102, 10, 65, 117, 116, 104, 111, 114, 58, 32, 98, 117, 110, 110, 105, 101, 32, 60, 98, 117, 110, 110, 105, 101, 64, 107, 111, 115, 97, 103, 105, 46, 99, 111, 109, 62, 10, 68, 97, 116, 101, 58, 32, 32, 32, 84, 104, 117, 32, 65, 117, 103, 32, 49, 50, 32, 48, 52, 58, 52, 49, 58, 53, 49, 32, 50, 48, 50, 49, 32, 43, 48, 56, 48, 48, 10, 10, 32, 32, 32, 32, 109, 111, 100, 105, 102, 121, 32, 98, 111, 111, 116, 32, 116, 111, 32, 100, 111, 32, 102, 97, 108, 108, 98, 97, 99, 107, 32, 111, 110, 32, 115, 105, 103, 110, 97, 116, 117, 114, 101, 115, 10, 10, 77, 9, 98, 111, 111, 116, 47, 98, 101, 116, 114, 117, 115, 116, 101, 100, 45, 98, 111, 111, 116, 47, 115, 114, 99, 47, 109, 97, 105, 110, 46, 114, 115, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + status_len: 512, + status_str: [79, 110, 32, 98, 114, 97, 110, 99, 104, 32, 109, 97, 105, 110, 10, 89, 111, 117, 114, 32, 98, 114, 97, 110, 99, 104, 32, 105, 115, 32, 117, 112, 32, 116, 111, 32, 100, 97, 116, 101, 32, 119, 105, 116, 104, 32, 39, 111, 114, 105, 103, 105, 110, 47, 109, 97, 105, 110, 39, 46, 10, 10, 67, 104, 97, 110, 103, 101, 115, 32, 110, 111, 116, 32, 115, 116, 97, 103, 101, 100, 32, 102, 111, 114, 32, 99, 111, 109, 109, 105, 116, 58, 10, 32, 32, 40, 117, 115, 101, 32, 34, 103, 105, 116, 32, 97, 100, 100, 32, 60, 102, 105, 108, 101, 62, 46, 46, 46, 34, 32, 116, 111, 32, 117, 112, 100, 97, 116, 101, 32, 119, 104, 97, 116, 32, 119, 105, 108, 108, 32, 98, 101, 32, 99, 111, 109, 109, 105, 116, 116, 101, 100, 41, 10, 32, 32, 40, 117, 115, 101, 32, 34, 103, 105, 116, 32, 114, 101, 115, 116, 111, 114, 101, 32, 60, 102, 105, 108, 101, 62, 46, 46, 46, 34, 32, 116, 111, 32, 100, 105, 115, 99, 97, 114, 100, 32, 99, 104, 97, 110, 103, 101, 115, 32, 105, 110, 32, 119, 111, 114, 107, 105, 110, 103, 32, 100, 105, 114, 101, 99, 116, 111, 114, 121, 41, 10, 32, 32, 40, 99, 111, 109, 109, 105, 116, 32, 111, 114, 32, 100, 105, 115, 99, 97, 114, 100, 32, 116, 104, 101, 32, 117, 110, 116, 114, 97, 99, 107, 101, 100, 32, 111, 114, 32, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 32, 105, 110, 32, 115, 117, 98, 109, 111, 100, 117, 108, 101, 115, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 97, 112, 112, 101, 110, 100, 95, 99, 115, 114, 46, 112, 121, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 98, 101, 116, 114, 117, 115, 116, 101, 100, 95, 115, 111, 99, 46, 112, 121, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 98, 111, 111, 116, 47, 98, 101, 116, 114, 117, 115, 116, 101, 100, 45, 98, 111, 111, 116, 47, 97, 115, 115, 101, 109, 98, 108, 101, 46, 115, 104, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 98, 111, 111, 116, 95, 116, 101, 115, 116, 46, 112, 121, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 98, 117, 105, 108, 100, 45, 100, 111, 99, 115, 46, 115, 104, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 99, 104, 101, 99, 107, 45, 116, 105, 109, 105, 110, 103, 46, 115, 104, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 99, 111, 109, 112, 105, 108, 101, 114, 95, 114, 116, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 101, 110, 99, 114, 121, 112, 116, 45, 98, 105, 116, 115, 116, 114, 101, 97, 109, 45, 112, 121, 116, 104, 111, 110, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 103, 97, 116, 101, 119, 97, 114, 101, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 108, 105, 116, 101, 100, 114, 97, 109, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 108, 105, 116, 101, 115, 99, 111, 112, 101, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 108, 105, 116, 101, 120, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 109, 105, 103, 101, 110, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 111, 112, 101, 110, 116, 105, 116, 97, 110, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 112, 121, 115, 101, 114, 105, 97, 108, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 112, 121, 116, 104, 111, 110, 100, 97, 116, 97, 45, 99, 112, 117, 45, 118, 101, 120, 114, 105, 115, 99, 118, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102, 105, 101, 100, 58, 32, 32, 32, 100, 101, 112, 115, 47, 114, 111, 109, 45, 108, 111, 99, 97, 116, 101, 32, 40, 109, 111, 100, 105, 102, 105, 101, 100, 32, 99, 111, 110, 116, 101, 110, 116, 41, 10, 9, 109, 111, 100, 105, 102], + } + } } } @@ -165,6 +252,7 @@ fn xmain() -> ! { Opcode::MenuRedraw.to_u32().unwrap(), Opcode::MenuKeys.to_u32().unwrap(), Opcode::MenuDrop.to_u32().unwrap()); + let mut policy_followup_action: Option = None; let mut password_action = TextEntry { is_password: true, @@ -208,6 +296,24 @@ fn xmain() -> ! { xous::return_scalar(msg.sender, 0).unwrap(); } }), + Some(Opcode::IsEfuseSecured) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + if let Some(secured) = keys.is_efuse_secured() { + if secured { + xous::return_scalar(msg.sender, 1).unwrap(); + } else { + xous::return_scalar(msg.sender, 0).unwrap(); + } + } else { + xous::return_scalar(msg.sender, 2).unwrap(); + } + }), + Some(Opcode::IsJtagWorking) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + if keys.is_jtag_working() { + xous::return_scalar(msg.sender, 1).unwrap(); + } else { + xous::return_scalar(msg.sender, 0).unwrap(); + } + }), // UX flow opcodes Some(Opcode::UxTryInitKeys) => msg_scalar_unpack!(msg, _, _, _, _, { @@ -236,6 +342,7 @@ fn xmain() -> ! { // - self-signing public key // - user root key // - pepper + dismiss_modal_action.set_manual_dismiss(true); // because this can be side-effected from prior Ux arcs if keys.is_initialized() { dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); rootkeys_modal.modify( @@ -334,6 +441,8 @@ fn xmain() -> ! { // this routine will update the rootkeys_modal with the current Ux state let result = keys.do_key_init(&mut rootkeys_modal, main_cid); + // the stop emoji, when sent to the slider action bar in progress mode, will cause it to close and relinquish focus + rootkeys_modal.key_event(['🛑', '\u{0000}', '\u{0000}', '\u{0000}']); log::info!("set_ux_password result: {:?}", result); @@ -450,11 +559,350 @@ fn xmain() -> ! { ).expect("couldn't initiate dialog box"); } Some(Opcode::UxUpdateGateware) => { - unimplemented!(); + // steps: + // - check update signature "Inspecting gateware update, this will take a moment..." + // - if no signature found: "No valid update found! (ok -> exit out)" + // - inform user of signature status "Gatware signed with foo, do you want to see the metadata? (quick/all/no)" + // - option to show metadata (multiple pages) + // - proceed with update question "Proceed with update? (yes/no)" + // - do the update + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + dismiss_modal_action.set_manual_dismiss(false); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.gwup.inspecting", xous::LANG)), false, + None, true, None); + rootkeys_modal.activate(); + rootkeys_modal.redraw(); // the first raise requires a redraw to setup the memoized sizes + send_message(main_cid, + xous::Message::new_scalar(Opcode::UxUpdateGwCheckSig.to_usize().unwrap(), 0, 0, 0, 0) + ).unwrap(); + } + Some(Opcode::UxUpdateGwCheckSig) => { + let mut confirm_radiobox = gam::modal::RadioButtons::new( + main_cid, + Opcode::UxUpdateGwShowInfo.to_u32().unwrap() + ); + confirm_radiobox.is_password = true; + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.gwup.short", xous::LANG))); + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.gwup.details", xous::LANG))); + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.gwup.none", xous::LANG))); + + dismiss_modal_action.set_manual_dismiss(true); // this is a tricky bit of a side-effect we have to manage. could be done better... + let prompt = match keys.check_gateware_signature(GatewareRegion::Staging) { + SignatureResult::SelfSignOk => t!("rootkeys.gwup.viewinfo_ss", xous::LANG), + SignatureResult::ThirdPartyOk => t!("rootkeys.gwup.viewinfo_tp", xous::LANG), + SignatureResult::DevKeyOk => t!("rootkeys.gwup.viewinfo_dk", xous::LANG), + _ => { + rootkeys_modal.gam.relinquish_focus().unwrap(); + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.gwup.no_update_found", xous::LANG)), false, + None, true, None); + rootkeys_modal.activate(); + continue; + } + }; + rootkeys_modal.gam.relinquish_focus().unwrap(); + rootkeys_modal.modify( + Some(ActionType::RadioButtons(confirm_radiobox)), + Some(prompt), false, + None, true, None); + rootkeys_modal.activate(); }, + Some(Opcode::UxUpdateGwShowInfo) => { + let gw_info = keys.fetch_gw_metadata(GatewareRegion::Staging); + let info = format!("v{}.{}.{}+{}\ncommit: g{:x}\n@{}\n{}", + gw_info.git_maj, gw_info.git_min, gw_info.git_rev, gw_info.git_additional, + gw_info.git_commit, + str::from_utf8(&gw_info.host_str[..gw_info.host_len as usize]).unwrap(), + str::from_utf8(&gw_info.date_str[..gw_info.date_len as usize]).unwrap() + ); + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let payload = buffer.to_original::().unwrap(); + if payload.as_str() == t!("rootkeys.gwup.short", xous::LANG) { + dismiss_modal_action.set_action_opcode(Opcode::UxUpdateGwConfirm.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(&info), false, + None, true, None); + rootkeys_modal.activate(); + } else if payload.as_str() == t!("rootkeys.gwup.details", xous::LANG) { + dismiss_modal_action.set_action_opcode(Opcode::UxUpdateGwShowLog.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(&info), false, + None, true, None); + rootkeys_modal.activate(); + } else { + // skip -- forward the "yes" decision directly on that would come from the "are you sure" modal + let payload = gam::RadioButtonPayload::new(t!("rootkeys.gwup.yes", xous::LANG)); + let buf = Buffer::into_buf(payload).expect("couldn't convert message to payload"); + buf.send(main_cid, Opcode::UxUpdateGwDecidePassword.to_u32().unwrap()) + .map(|_| ()).expect("couldn't send action message"); + } + } + Some(Opcode::UxUpdateGwShowLog) => { + let gw_info = keys.fetch_gw_metadata(GatewareRegion::Staging); + // truncate the message to better fit in the rendering box + let info_len = if gw_info.log_len > 256 { 256 } else {gw_info.log_len}; + let info = format!("{}", str::from_utf8(&gw_info.log_str[..info_len as usize]).unwrap()); + dismiss_modal_action.set_action_opcode(Opcode::UxUpdateGwShowStatus.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(&info), false, + None, true, None); + rootkeys_modal.activate(); + }, + Some(Opcode::UxUpdateGwShowStatus) => { + let gw_info = keys.fetch_gw_metadata(GatewareRegion::Staging); + // truncate the message to better fit in the rendering box + let status_len = if gw_info.status_len > 256 { 256 } else {gw_info.status_len}; + let info = format!("{}", str::from_utf8(&gw_info.status_str[..status_len as usize]).unwrap()); + dismiss_modal_action.set_action_opcode(Opcode::UxUpdateGwConfirm.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(&info), false, + None, true, None); + rootkeys_modal.activate(); + }, + Some(Opcode::UxUpdateGwConfirm) => { + let mut confirm_radiobox = gam::modal::RadioButtons::new( + main_cid, + Opcode::UxUpdateGwDecidePassword.to_u32().unwrap() + ); + confirm_radiobox.is_password = true; + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.gwup.yes", xous::LANG))); + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.gwup.no", xous::LANG))); + rootkeys_modal.modify( + Some(ActionType::RadioButtons(confirm_radiobox)), + Some(t!("rootkeys.gwup.proceed_confirm", xous::LANG)), false, + None, true, None); + rootkeys_modal.activate(); + }, + Some(Opcode::UxUpdateGwDecidePassword) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let payload = buffer.to_original::().unwrap(); + if payload.as_str() == t!("rootkeys.gwup.yes", xous::LANG) { + if keys.is_pcache_update_password_valid() { + // indicate that there should be no change to the policy + let payload = gam::RadioButtonPayload::new("no change"); + let buf = Buffer::into_buf(payload).expect("couldn't convert message to payload"); + buf.send(main_cid, Opcode::UxUpdateGwRun.to_u32().unwrap()) + .map(|_| ()).expect("couldn't send action message"); + } else { + keys.set_ux_password_type(Some(PasswordType::Update)); + password_action.set_action_opcode(Opcode::UxUpdateGwPasswordPolicy.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::TextEntry(password_action)), + Some(t!("rootkeys.get_update_password", xous::LANG)), false, + None, true, None + ); + rootkeys_modal.activate(); + } + } else { + continue; + } + } + Some(Opcode::UxUpdateGwPasswordPolicy)=> { + let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let mut plaintext_pw = buf.to_original::().unwrap(); + + keys.hash_and_save_password(plaintext_pw.as_str()); + plaintext_pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave + buf.volatile_clear(); + + let mut confirm_radiobox = gam::modal::RadioButtons::new( + main_cid, + Opcode::UxUpdateGwRun.to_u32().unwrap() + ); + confirm_radiobox.is_password = true; + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_clear", xous::LANG))); + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_suspend", xous::LANG))); + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_keep", xous::LANG))); + rootkeys_modal.modify( + Some(ActionType::RadioButtons(confirm_radiobox)), + Some(t!("rootkeys.policy_request", xous::LANG)), false, + None, true, None); + rootkeys_modal.activate(); + } + Some(Opcode::UxUpdateGwRun) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let payload = buffer.to_original::().unwrap(); + if payload.as_str() == t!("rootkeys.policy_keep", xous::LANG) { + keys.update_policy(Some(PasswordRetentionPolicy::AlwaysKeep)); + } else if payload.as_str() == t!("rootkeys.policy_suspend", xous::LANG) { + keys.update_policy(Some(PasswordRetentionPolicy::EraseOnSuspend)); + } else if payload.as_str() == "no change" { + // don't change the policy + } else { + keys.update_policy(Some(PasswordRetentionPolicy::AlwaysPurge)); // default to the most paranoid level + } + keys.set_ux_password_type(None); + + let result = keys.do_gateware_update(&mut rootkeys_modal, main_cid); + // the stop emoji, when sent to the slider action bar in progress mode, will cause it to close and relinquish focus + rootkeys_modal.key_event(['🛑', '\u{0000}', '\u{0000}', '\u{0000}']); + + match result { + Ok(_) => { + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.gwup.finished", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + xous::yield_slice(); + } + Err(RootkeyResult::AlignmentError) => { + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.fail_alignment", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + xous::yield_slice(); + } + Err(RootkeyResult::KeyError) => { + // probably a bad password, purge it, so the user can try again + keys.purge_password(PasswordType::Update); + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.fail_key", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + xous::yield_slice(); + } + Err(RootkeyResult::IntegrityError) => { + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.fail_verify", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + xous::yield_slice(); + } + Err(RootkeyResult::FlashError) => { + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.fail_burn", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + xous::yield_slice(); + } + } + } Some(Opcode::UxSelfSignXous) => { - unimplemented!(); + if keys.is_pcache_update_password_valid() { + // indicate that there should be no change to the policy + let payload = gam::RadioButtonPayload::new("no change"); + let buf = Buffer::into_buf(payload).expect("couldn't convert message to payload"); + buf.send(main_cid, Opcode::UxSignXousRun.to_u32().unwrap()) + .map(|_| ()).expect("couldn't send action message"); + } else { + keys.set_ux_password_type(Some(PasswordType::Update)); + password_action.set_action_opcode(Opcode::UxSignXousPasswordPolicy.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::TextEntry(password_action)), + Some(t!("rootkeys.get_signing_password", xous::LANG)), false, + None, true, None + ); + rootkeys_modal.activate(); + } }, + Some(Opcode::UxSignXousPasswordPolicy) => { + let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let mut plaintext_pw = buf.to_original::().unwrap(); + + keys.hash_and_save_password(plaintext_pw.as_str()); + plaintext_pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave + buf.volatile_clear(); + + let mut confirm_radiobox = gam::modal::RadioButtons::new( + main_cid, + Opcode::UxSignXousRun.to_u32().unwrap() + ); + confirm_radiobox.is_password = true; + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_clear", xous::LANG))); + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_suspend", xous::LANG))); + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_keep", xous::LANG))); + rootkeys_modal.modify( + Some(ActionType::RadioButtons(confirm_radiobox)), + Some(t!("rootkeys.policy_request", xous::LANG)), false, + None, true, None); + rootkeys_modal.activate(); + }, + Some(Opcode::UxSignXousRun) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let payload = buffer.to_original::().unwrap(); + if payload.as_str() == t!("rootkeys.policy_keep", xous::LANG) { + keys.update_policy(Some(PasswordRetentionPolicy::AlwaysKeep)); + } else if payload.as_str() == t!("rootkeys.policy_suspend", xous::LANG) { + keys.update_policy(Some(PasswordRetentionPolicy::EraseOnSuspend)); + } else if payload.as_str() == "no change" { + // don't change the policy + } else { + keys.update_policy(Some(PasswordRetentionPolicy::AlwaysPurge)); // default to the most paranoid level + } + keys.set_ux_password_type(None); + + let result = keys.do_sign_xous(&mut rootkeys_modal, main_cid); + // the stop emoji, when sent to the slider action bar in progress mode, will cause it to close and relinquish focus + rootkeys_modal.key_event(['🛑', '\u{0000}', '\u{0000}', '\u{0000}']); + + match result { + Ok(_) => { + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.signxous.finished", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + xous::yield_slice(); + } + Err(RootkeyResult::AlignmentError) => { + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.fail_alignment", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + xous::yield_slice(); + } + Err(RootkeyResult::KeyError) => { + // probably a bad password, purge it, so the user can try again + keys.purge_password(PasswordType::Update); + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.fail_key", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + xous::yield_slice(); + } + Err(RootkeyResult::IntegrityError) => { + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.fail_verify", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + xous::yield_slice(); + } + Err(RootkeyResult::FlashError) => { + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.init.fail_burn", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + xous::yield_slice(); + } + } + } Some(Opcode::CheckGatewareSignature) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { if keys.is_initialized() { if keys.verify_gateware_self_signature() { @@ -474,6 +922,12 @@ fn xmain() -> ! { } Some(Opcode::UxPolicyReturn) => msg_scalar_unpack!(msg, policy_code, _, _, _, { keys.update_policy(FromPrimitive::from_usize(policy_code)); + if let Some(action) = policy_followup_action { + send_message(main_cid, + xous::Message::new_scalar(action, 0, 0, 0, 0) + ).unwrap(); + } + policy_followup_action = None; }), Some(Opcode::UxGutter) => { // an intentional NOP for UX actions that require a destintation but need no action diff --git a/services/status/src/main.rs b/services/status/src/main.rs index ae30ae05a..74c7b85f0 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -192,6 +192,7 @@ fn xmain() -> ! { sec_notes.lock().unwrap().insert("secnotes.no_keys".to_string(), t!("secnote.no_keys", xous::LANG).to_string()); } else { log::info!("checking gateware signature..."); + #[cfg(any(target_os = "none", target_os = "xous"))] // for now, threads don't work in hosted mode, but the result of this isn't important in hosted mode right now thread::spawn({ let clone = Arc::clone(&sec_notes); let keys = Arc::clone(&keys); diff --git a/tools/usb_update.py b/tools/usb_update.py index 3e528adc9..59dfd15cb 100755 --- a/tools/usb_update.py +++ b/tools/usb_update.py @@ -197,7 +197,7 @@ class PrecursorUsb: ) def load_csrs(self): - LOC_CSRCSV = 0x20278000 # this address shouldn't change because it's how we figure out our version number + LOC_CSRCSV = 0x20277000 # this address shouldn't change because it's how we figure out our version number csr_data = self.burst_read(LOC_CSRCSV, 0x8000) hasher = hashlib.sha512()