Commit 05ab014e authored by Fabio Utzig's avatar Fabio Utzig Committed by David Brown
Browse files

Update sim ecdsa testing to use ring signing

This removes the unsafe Tinycrypt bindings previously used for signing
with ECDSA, and relies on ring native support.

The ring library was updated to 0.14.1.

Signed-off-by: default avatarFabio Utzig <utzig@apache.org>
parent 006994b7
Loading
Loading
Loading
Loading
+3 −3
Changes for sim/Cargo.lock: 3 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -109,7 +109,7 @@ dependencies = [
 "mcuboot-sys 0.1.0",
 "pem 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "ring 0.13.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "ring 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)",
 "simflash 0.1.0",
@@ -358,7 +358,7 @@ dependencies = [

[[package]]
name = "ring"
version = "0.13.5"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cc 1.0.28 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -557,7 +557,7 @@ dependencies = [
"checksum regex 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "37e7cbbd370869ce2e8dff25c7018702d10b21a20ef7135316f8daecd6c25b7f"
"checksum regex-syntax 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7d707a4fa2637f2dca2ef9fd02225ec7661fe01a53623c1e6515b6916511f7a7"
"checksum regex-syntax 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "4e47a2ed29da7a9e1960e1639e7a982e6edc6d49be308a3b02daf511504a16d1"
"checksum ring 0.13.5 (registry+https://github.com/rust-lang/crates.io-index)" = "2c4db68a2e35f3497146b7e4563df7d4773a2433230c5e4b448328e31740458a"
"checksum ring 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0261e0bfe1ca5bd5010dd50851367eab17cee222c7f8c1842a1e0c4ff4f38d71"
"checksum rustc-demangle 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "adacaae16d02b6ec37fdc7acfcddf365978de76d1983d3ee22afc260e1ca9619"
"checksum safemem 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8dca453248a96cb0749e36ccdfe2b0b4e54a61bfef89fb97ec621eb8e0a93dd9"
"checksum serde 1.0.84 (registry+https://github.com/rust-lang/crates.io-index)" = "0e732ed5a5592c17d961555e3b552985baf98d50ce418b7b655f31f6ba7eb1b7"
+1 −1
Changes for sim/Cargo.toml: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -25,7 +25,7 @@ log = "0.4"
env_logger = "0.5"
simflash = { path = "simflash" }
mcuboot-sys = { path = "mcuboot-sys" }
ring = { version = "0.13.5", features = ["rsa_signing"] }
ring = "0.14.1"
untrusted = "0.6.2"
pem = "0.5"
aes-ctr = "0.2.0"
−18
Changes for sim/mcuboot-sys/csupport/run.c: 0 added lines, 18 removed lines.
Original line number Diff line number Diff line
@@ -13,10 +13,6 @@
#include "../../../boot/bootutil/src/bootutil_priv.h"
#include "bootsim.h"

#ifdef MCUBOOT_SIGN_EC256
#include "../../../ext/tinycrypt/lib/include/tinycrypt/ecc_dsa.h"
#endif

#ifdef MCUBOOT_ENCRYPT_RSA
#include "mbedtls/rsa.h"
#include "mbedtls/asn1.h"
@@ -44,20 +40,6 @@ int jumped = 0;
uint8_t c_asserts = 0;
uint8_t c_catch_asserts = 0;

int ecdsa256_sign_(const uint8_t *privkey, const uint8_t *hash,
                   unsigned hash_len, uint8_t *signature)
{
#ifdef MCUBOOT_SIGN_EC256
    return uECC_sign(privkey, hash, hash_len, signature, uECC_secp256r1());
#else
    (void)privkey;
    (void)hash;
    (void)hash_len;
    (void)signature;
    return 0;
#endif
}

#ifdef MCUBOOT_ENCRYPT_RSA
static int
parse_pubkey(mbedtls_rsa_context *ctx, uint8_t **p, uint8_t *end)
−15
Changes for sim/mcuboot-sys/src/c.rs: 0 added lines, 15 removed lines.
Original line number Diff line number Diff line
@@ -52,17 +52,6 @@ pub fn boot_max_align() -> usize {
    unsafe { raw::BOOT_MAX_ALIGN as usize }
}

pub fn ecdsa256_sign(privkey: &[u8], hash: &[u8]) -> Result<[u8; 64], &'static str> {
    unsafe {
        let mut signature: [u8; 64] = [0; 64];
        if raw::ecdsa256_sign_(privkey.as_ptr(), hash.as_ptr(),
                               hash.len() as u32, signature.as_mut_ptr()) == 1 {
            return Ok(signature);
        }
        return Err("Failed signature generation");
    }
}

pub fn rsa_oaep_encrypt(pubkey: &[u8], seckey: &[u8]) -> Result<[u8; 256], &'static str> {
    unsafe {
        let mut encbuf: [u8; 256] = [0; 256];
@@ -103,10 +92,6 @@ mod raw {
        pub static BOOT_MAGIC_SZ: u32;
        pub static BOOT_MAX_ALIGN: u32;

        pub fn ecdsa256_sign_(privkey: *const u8, hash: *const u8,
                              hash_len: libc::c_uint,
                              signature: *mut u8) -> libc::c_int;

        pub fn rsa_oaep_encrypt_(pubkey: *const u8, pubkey_len: libc::c_uint,
                                 seckey: *const u8, seckey_len: libc::c_uint,
                                 encbuf: *mut u8) -> libc::c_int;
+29 −70
Changes for sim/src/tlv.rs: 29 added lines, 70 removed lines.
Original line number Diff line number Diff line
@@ -8,10 +8,15 @@
//! Because of this header, we have to make two passes.  The first pass will compute the size of
//! the TLV, and the second pass will build the data for the TLV.

use std::sync::Arc;
use pem;
use base64;
use ring::{digest, rand, signature};
use ring::{digest, rand};
use ring::signature::{
    RsaKeyPair,
    RSA_PSS_SHA256,
    EcdsaKeyPair,
    ECDSA_P256_SHA256_ASN1_SIGNING,
};
use untrusted;
use mcuboot_sys::c;

@@ -142,37 +147,6 @@ impl TlvGen {
        self.payload.extend_from_slice(bytes);
    }

    /// Create a DER representation of one ec curve point
    fn _make_der_int(&self, x: &[u8]) -> Vec<u8> {
        assert!(x.len() == 32);

        let mut i: Vec<u8> = vec![0x02];
        if x[0] >= 0x7f {
            i.push(33);
            i.push(0);
        } else {
            i.push(32);
        }
        i.extend(x);
        i
    }

    /// Create an ecdsa256 TLV
    fn _make_der_sequence(&self, r: Vec<u8>, s: Vec<u8>) -> Vec<u8> {
        let mut der: Vec<u8> = vec![0x30];
        der.push(r.len() as u8 + s.len() as u8);
        der.extend(r);
        der.extend(s);
        let mut size = der.len();
        // must pad up to 72 bytes...
        while size <= 72 {
            der.push(0);
            der[1] += 1;
            size += 1;
        }
        der
    }

    /// Compute the TLV given the specified block of data.
    pub fn make_tlv(self) -> Vec<u8> {
        let mut result: Vec<u8> = vec![];
@@ -211,12 +185,11 @@ impl TlvGen {
            let key_bytes = pem::parse(include_bytes!("../../root-rsa-2048.pem").as_ref()).unwrap();
            assert_eq!(key_bytes.tag, "RSA PRIVATE KEY");
            let key_bytes = untrusted::Input::from(&key_bytes.contents);
            let key = signature::RSAKeyPair::from_der(key_bytes).unwrap();
            let mut signer = signature::RSASigningState::new(Arc::new(key)).unwrap();
            let key_pair = RsaKeyPair::from_der(key_bytes).unwrap();
            let rng = rand::SystemRandom::new();
            let mut signature = vec![0; signer.key_pair().public_modulus_len()];
            let mut signature = vec![0; key_pair.public_modulus_len()];
            assert_eq!(signature.len(), 256);
            signer.sign(&signature::RSA_PSS_SHA256, &rng, &self.payload, &mut signature).unwrap();
            key_pair.sign(&RSA_PSS_SHA256, &rng, &self.payload, &mut signature).unwrap();

            result.push(TlvKinds::RSA2048 as u8);
            result.push(0);
@@ -236,43 +209,29 @@ impl TlvGen {
            result.push(0);
            result.extend_from_slice(keyhash);

            let key_bytes = pem::parse(include_bytes!("../../root-ec-p256.pem").as_ref()).unwrap();
            assert_eq!(key_bytes.tag, "EC PRIVATE KEY");

            let hash = digest::digest(&digest::SHA256, &self.payload);
            let hash = hash.as_ref();
            assert!(hash.len() == 32);

            /* FIXME
             *
             * Although `ring` has an ASN1 parser, it hides access
             * to its low-level data, which was designed to be used
             * by its internal signing/verifying functions. Since it does
             * not yet support ecdsa signing, for the time being I am
             * manually loading the key from its index in the PEM and
             * building the TLV DER manually.
             *
             * Once ring gets ecdsa signing (hopefully soon!) this code
             * should be updated to leverage its functionality...
             */

            /* Load key directly from PEM */
            let key = &key_bytes.contents[7..39];

            let signature = match c::ecdsa256_sign(&key, &hash) {
                Ok(sign) => sign,
                Err(_) => panic!("Failed signature generation"),
            };
            let key_bytes = pem::parse(include_bytes!("../../root-ec-p256-pkcs8.pem").as_ref()).unwrap();
            assert_eq!(key_bytes.tag, "PRIVATE KEY");

            let r = self._make_der_int(&signature.to_vec()[..32]);
            let s = self._make_der_int(&signature.to_vec()[32..64]);
            let der = self._make_der_sequence(r, s);
            let key_bytes = untrusted::Input::from(&key_bytes.contents);
            let key_pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING,
                                                    key_bytes).unwrap();
            let rng = rand::SystemRandom::new();
            let payload = untrusted::Input::from(&self.payload);
            let signature = key_pair.sign(&rng, payload).unwrap();

            result.push(TlvKinds::ECDSA256 as u8);
            result.push(0);
            result.push(der.len() as u8);
            result.push(0);
            result.extend(der);

            // signature must be padded...
            let mut signature = signature.as_ref().to_vec();
            while signature.len() < 72 {
                signature.push(0);
                signature[1] += 1;
            }

            result.push((signature.len() & 0xFF) as u8);
            result.push(((signature.len() >> 8) & 0xFF) as u8);
            result.extend_from_slice(signature.as_ref());
        }

        if self.kinds.contains(&TlvKinds::ENCRSA2048) {