Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ doc/doc.css
*.rsproj
*.sln

# JetBrains Junk
.idea
*.iml

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I merged an earlier version of this change already, since .gitignore already contains these exact lines underneath "# Cargo Junk" below, so I removed this part of the change.


# Cargo Junk
Cargo.lock
target/
Expand Down
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,9 @@ rayon = "0.6"
[target.'cfg(any(target_os = "redox", all(unix, not(any(target_os = "macos", target_os = "ios")))))'.dependencies]
lazy_static = "0.2.1"

[dev-dependencies]

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When merging this, I put a blank line ahead of this new section.

base64 = "0.3.0"

[features]
# These features are documented in the top-level module's documentation.
default = ["use_heap", "dev_urandom_fallback"]
Expand Down
20 changes: 17 additions & 3 deletions mk/travis.sh
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,29 @@ arm-linux-androideabi)
cargo test -vv -j2 --no-run ${mode-} ${FEATURES_X-} --target=$TARGET_X
emulator @arm-18 -no-skin -no-boot-anim -no-audio -no-window &
adb wait-for-device
adb push $target_dir/ring-* /data/ring-test
for testfile in `find src crypto -name "*_test*.txt"`; do
adb shell mkdir -p /data/`dirname $testfile`
adb push $testfile /data/$testfile
done
for testfile in `find third-party/chromium -name "*.pem"`; do
adb shell mkdir -p /data/`dirname $testfile`
adb push $testfile /data/$testfile
done
for testfile in `find tests/test-data -type f`; do
adb shell mkdir -p /data/`dirname $testfile`
adb push $testfile /data/$testfile
done
adb shell mkdir -p /data/third-party/NIST
adb push third-party/NIST/SHAVS /data/third-party/NIST/SHAVS
adb shell 'cd /data && ./ring-test' 2>&1 | tee /tmp/ring-test
grep "test result: ok" /tmp/ring-test

for test_binary in `find $target_dir -maxdepth 1 -executable -type f`; do
adb push $test_binary /data/
test_binary_filename=`basename $test_binary`
log_file="/tmp/${test_binary_filename}-ring-test.out"
adb shell "cd /data && ./$test_binary_filename" 2>&1 | tee $log_file
grep "test result: ok" $log_file
done

;;
*)
cargo test -vv -j2 ${mode-} ${FEATURES_X-} --target=$TARGET_X
Expand Down
51 changes: 49 additions & 2 deletions src/der.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
//!
//! This module contains the foundational parts of an ASN.1 DER parser.

use untrusted;
use error;
use untrusted;

pub const CONSTRUCTED: u8 = 1 << 5;
pub const CONTEXT_SPECIFIC: u8 = 2 << 6;
Expand Down Expand Up @@ -168,6 +168,19 @@ pub fn small_nonnegative_integer(input: &mut untrusted::Reader)
})
}

pub fn bit_string_with_no_unused_bits<'a>(input: &mut untrusted::Reader<'a>)
-> Result<untrusted::Input<'a>,
error::Unspecified> {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returning Unspecified here just gets turned into BadDER elsewhere... maybe in the future it would be nice to have DER-related functions return a DER error for easier mapping?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I filed #379 for this.

nested(input, Tag::BitString, error::Unspecified, |value| {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note to self: reformat this, both the return value and the try! indention below.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When merging, I reformatting this and also moved it ahead of nonnegative_integer so that all the integer-parsing code stays grouped together.

let unused_bits_at_end =
try!(value.read_byte().map_err(|_| error::Unspecified));
if unused_bits_at_end != 0 {
return Err(error::Unspecified);
}
Ok(value.skip_to_end())
})
}

/// Parses a positive DER integer, returning the big-endian-encoded value, sans
/// any leading zero byte.
#[inline]
Expand All @@ -178,8 +191,9 @@ pub fn positive_integer<'a>(input: &mut untrusted::Reader<'a>)


#[cfg(test)]
mod tests {
pub mod tests {
use error;
use std::io::BufRead;
use super::*;
use untrusted;

Expand All @@ -197,6 +211,32 @@ mod tests {
assert!(r.is_err());
}

include!("../tests/common/pem.rs");

macro_rules! test_parse_bad_spki_der {
($fn_name:ident, $file_name:expr) => {
#[test]
fn $fn_name() {
test_parse_bad_spki_der($file_name)
}
}
}

fn test_parse_bad_spki_der(file_name: &str) {
let path =
std::path::PathBuf::from(
"third-party/chromium/data/verify_signed_data").join(file_name);
let file = std::fs::File::open(path).unwrap();
let mut lines = std::io::BufReader::new(&file).lines();

let spki = read_pem_section(&mut lines, "PUBLIC KEY");
let spki_input = untrusted::Input::from(&spki);
assert_eq!(Err(error::Unspecified),
spki_input.read_all(error::Unspecified, |input| {
expect_tag_and_get_value(input, Tag::Sequence)
}));
}

static ZERO_INTEGER: &'static [u8] = &[0x02, 0x01, 0x00];

static GOOD_POSITIVE_INTEGERS: &'static [(&'static [u8], u8)] =
Expand Down Expand Up @@ -277,4 +317,11 @@ mod tests {
});
}
}

test_parse_bad_spki_der!(test_rsa_pkcs1_sha256_key_encoded_ber,
"rsa-pkcs1-sha256-key-encoded-ber.pem" );
test_parse_bad_spki_der!(test_rsa_pkcs1_sha1_bad_key_der_length,
"rsa-pkcs1-sha1-bad-key-der-length.pem");
test_parse_bad_spki_der!(test_rsa_pkcs1_sha1_bad_key_der_null,
"rsa-pkcs1-sha1-bad-key-der-null.pem");

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are failing on android because the files are not present. I'll see if I can track down why.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like travis.sh needs to copy over the chromium *.pem files like it copies over the txt test files. However, the current setup also isn't running integration tests (like the new spki ones) since it only copies over target/(release|debug)/ring-* and the test file for spki is target/(release|debug)/signature_spki_tests-*.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Android tests are now running all test targets.

}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ mod rsa;
#[doc(hidden)]
pub use rsa::GFp_rand_mod;

#[path = "signature/signature.rs"]
pub mod signature;

#[cfg(any(feature = "use_heap", test))]
Expand Down
21 changes: 21 additions & 0 deletions src/signature/data/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
These files contain the binary DER encoding of the *values* of some

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copied from webpki.

ASN.1 [`AlgorithmIdentifier`]s, without the outer `SEQUENCE` tag or the outer
length component.

These files were encoded with the help of [der-ascii]. They can be decoded
using:

```sh
go get github.com/google/der-ascii/cmd/der2ascii
der2ascii -i <filename> -o <filename>.ascii
```

New or modified der-ascii files can be encoded using:

```sh
go get github.com/google/der-ascii/cmd/ascii2der
ascii2der i <filename>.ascii -o <filename>
```

[`AlgorithmIdentifier`]: https://tools.ietf.org/html/rfc5280#section-4.1.1.2]
[der-ascii]: https://github.com/google/der-ascii
1 change: 1 addition & 0 deletions src/signature/data/alg-ecdsa-p256.der
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*�H�=*�H�=
Binary file added src/signature/data/alg-ecdsa-p384.der
Binary file not shown.
Binary file added src/signature/data/alg-rsa-encryption.der
Binary file not shown.
8 changes: 8 additions & 0 deletions src/signature.rs → src/signature/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,11 @@ pub trait VerificationAlgorithm: Sync + private::Private {
/// Verify the signature `signature` of message `msg` with the public key
/// `public_key` using the algorithm `alg`.
///
/// `public_key` must be the DER-encoded ASN.1 of the key value only. Use
/// `ring::signature::spki::verify` for the case when you have the
/// `SubjectPublicKeyInfo` ASN.1, as is typically the case when using
/// public keys exported by OpenSSL.
///
/// # Examples
///
/// ## Verify a RSA PKCS#1 signature that uses the SHA-256 digest
Expand Down Expand Up @@ -362,6 +367,9 @@ pub fn verify(alg: &VerificationAlgorithm, public_key: untrusted::Input,
alg.verify(public_key, msg, signature)
}

/// Parse a public key in SPKI format
/// (https://tools.ietf.org/html/rfc5280#section-4.1).
pub mod spki;

#[cfg(test)]
mod tests {
Expand Down
202 changes: 202 additions & 0 deletions src/signature/spki.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
// Copyright 2015 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

use der;
use signature;
use untrusted;

/// An error that occurs while parsing an SPKI public key.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ParseSPKIError {
/// The encoding of some ASN.1 DER-encoded item is invalid.
BadDER,

/// The SignatureAlgorithm does not match the algorithm of the SPKI.
/// A mismatch could be because of the algorithm (RSA vs DSA, etc) or the
/// parameters (ECDSA_p256 vs ECDSA_384, etc).
UnsupportedSignatureAlgorithmForPublicKey,
}

/// Parse a public key in the DER-encoded ASN.1 `SubjectPublicKeyInfo`
/// format described in [RFC 5280 Section 4.1], which is a sequence of an
/// `AlgorithmIdentifier` and the key value.
///
/// If the `AlgorithmIdentifier` in the SPKI does not match the provided
/// `signature_alg`, or if the DER encoding is invalid, an error will be
/// returned.
///
/// If the function returns successfully, the `key_value` field in the
/// resulting `SubjectPublicKeyInfo` struct is suitable for use with
/// `signature::verify()`.
///
/// A common situation where this encoding is encountered is when using public
/// keys exported by OpenSSL. If you export an RSA or ECDSA public key from a
/// keypair with `-pubout` and friends, you will get DER-encoded
/// `SubjectPublicKeyInfo`.
///
/// [RFC 5280 Section 4.1]: https://tools.ietf.org/html/rfc5280#section-4.1
pub fn parse_spki<'a>(signature_alg: &Algorithm, public_key_spki: untrusted::Input<'a>)
-> Result<SubjectPublicKeyInfo<'a>, ParseSPKIError> {
let unwrapped_spki_der = try!(public_key_spki.read_all(ParseSPKIError::BadDER, |input| {
der::expect_tag_and_get_value(input, der::Tag::Sequence)
.map_err(|_| ParseSPKIError::BadDER)
}));

let spki = try!(parse_spki_value(unwrapped_spki_der));
if !signature_alg.public_key_alg_id
.matches_algorithm_id_value(spki.algorithm_id_value) {
return Err(ParseSPKIError::UnsupportedSignatureAlgorithmForPublicKey);
}

Ok(spki)
}

/// Represents the contents of `SubjectPublicKeyInfo` described in
/// RFC 5280 Section 4.1: https://tools.ietf.org/html/rfc5280#section-4.1
#[derive(Debug)]
pub struct SubjectPublicKeyInfo<'a> {
/// The algorithm id ASN.1.
pub algorithm_id_value: untrusted::Input<'a>,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I made this field public because it seemed like it might be generally useful.

/// The key ASN.1 bit string.
pub key_value: untrusted::Input<'a>,
}

// Parse the public key into an algorithm OID, an optional curve OID, and the
// key value. The caller needs to check whether these match the
// `PublicKeyAlgorithm` for the `SignatureAlgorithm` that is matched when
// parsing the signature.
fn parse_spki_value(input: untrusted::Input)
-> Result<SubjectPublicKeyInfo, ParseSPKIError> {
input.read_all(ParseSPKIError::BadDER, |input| {
let algorithm_id_value =
try!(der::expect_tag_and_get_value(input, der::Tag::Sequence)
.map_err(|_| ParseSPKIError::BadDER));
let key_value = try!(der::bit_string_with_no_unused_bits(input)
.map_err(|_| ParseSPKIError::BadDER));
Ok(SubjectPublicKeyInfo {
algorithm_id_value: algorithm_id_value,
key_value: key_value,
})
})
}

/// Groups an ASN.1 AlgorithmIdentifier and a `ring` VerificationAlgorithm.
pub struct Algorithm {
/// The `algorithm` member in SPKI from https://tools.ietf.org/html/rfc5280#section-4.1.
public_key_alg_id: AlgorithmIdentifier,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one I didn't make public because I'm not sure why anyone outside this library would need it. But on the other hand, it feels odd to have one private field in a public struct...

/// The verification algorithm corresponding to the algorithm id.
pub verification_alg: &'static signature::VerificationAlgorithm,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one I made public because now people need to access it to use with the result of parse_spki.

}

/// ECDSA signatures using the P-256 curve and SHA-256.
pub static ECDSA_P256_SHA256: Algorithm = Algorithm {
public_key_alg_id: ECDSA_P256,
verification_alg: &signature::ECDSA_P256_SHA256_ASN1,
};

/// ECDSA signatures using the P-256 curve and SHA-384. Deprecated.
pub static ECDSA_P256_SHA384: Algorithm = Algorithm {
public_key_alg_id: ECDSA_P256,
verification_alg: &signature::ECDSA_P256_SHA384_ASN1,
};

/// ECDSA signatures using the P-384 curve and SHA-256. Deprecated.
pub static ECDSA_P384_SHA256: Algorithm = Algorithm {
public_key_alg_id: ECDSA_P384,
verification_alg: &signature::ECDSA_P384_SHA256_ASN1,
};

/// ECDSA signatures using the P-384 curve and SHA-384.
pub static ECDSA_P384_SHA384: Algorithm = Algorithm {
public_key_alg_id: ECDSA_P384,
verification_alg: &signature::ECDSA_P384_SHA384_ASN1,
};

/// RSA PKCS#1 1.5 signatures using SHA-1 for keys of 2048-8192 bits.
/// Deprecated.
pub static RSA_PKCS1_2048_8192_SHA1: Algorithm = Algorithm {
public_key_alg_id: RSA_ENCRYPTION,
verification_alg: &signature::RSA_PKCS1_2048_8192_SHA1,
};

/// RSA PKCS#1 1.5 signatures using SHA-256 for keys of 2048-8192 bits.
pub static RSA_PKCS1_2048_8192_SHA256: Algorithm = Algorithm {
public_key_alg_id: RSA_ENCRYPTION,
verification_alg: &signature::RSA_PKCS1_2048_8192_SHA256,
};

/// RSA PKCS#1 1.5 signatures using SHA-384 for keys of 2048-8192 bits.
pub static RSA_PKCS1_2048_8192_SHA384: Algorithm = Algorithm {
public_key_alg_id: RSA_ENCRYPTION,
verification_alg: &signature::RSA_PKCS1_2048_8192_SHA384,
};

/// RSA PKCS#1 1.5 signatures using SHA-512 for keys of 2048-8192 bits.
pub static RSA_PKCS1_2048_8192_SHA512: Algorithm = Algorithm {
public_key_alg_id: RSA_ENCRYPTION,
verification_alg: &signature::RSA_PKCS1_2048_8192_SHA512,
};

/// RSA PKCS#1 1.5 signatures using SHA-384 for keys of 3072-8192 bits.
pub static RSA_PKCS1_3072_8192_SHA384: Algorithm = Algorithm {
public_key_alg_id: RSA_ENCRYPTION,
verification_alg: &signature::RSA_PKCS1_3072_8192_SHA384,
};

/// RSA PSS signatures using SHA-256 for keys of 2048-8192 bits and of
/// type rsaEncryption; see https://tools.ietf.org/html/rfc4055#section-1.2
pub static RSA_PSS_2048_8192_SHA256_LEGACY_KEY: Algorithm = Algorithm {
public_key_alg_id: RSA_ENCRYPTION,
verification_alg: &signature::RSA_PSS_2048_8192_SHA256,
};

/// RSA PSS signatures using SHA-384 for keys of 2048-8192 bits and of
/// type rsaEncryption; see https://tools.ietf.org/html/rfc4055#section-1.2
pub static RSA_PSS_2048_8192_SHA384_LEGACY_KEY: Algorithm = Algorithm {
public_key_alg_id: RSA_ENCRYPTION,
verification_alg: &signature::RSA_PSS_2048_8192_SHA384,
};

/// RSA PSS signatures using SHA-512 for keys of 2048-8192 bits and of
/// type rsaEncryption; see https://tools.ietf.org/html/rfc4055#section-1.2
pub static RSA_PSS_2048_8192_SHA512_LEGACY_KEY: Algorithm = Algorithm {
public_key_alg_id: RSA_ENCRYPTION,
verification_alg: &signature::RSA_PSS_2048_8192_SHA512,
};

struct AlgorithmIdentifier {
/// Binary DER for ASN.1 AlgorithmIdentifier without outer SEQUENCE or length.
asn1_id_value: &'static [u8],
}

impl AlgorithmIdentifier {
fn matches_algorithm_id_value(&self, encoded: untrusted::Input) -> bool {
encoded == self.asn1_id_value
}
}

// See src/data/README.md.

const ECDSA_P256: AlgorithmIdentifier = AlgorithmIdentifier {
asn1_id_value: include_bytes!("data/alg-ecdsa-p256.der"),
};

const ECDSA_P384: AlgorithmIdentifier = AlgorithmIdentifier {
asn1_id_value: include_bytes!("data/alg-ecdsa-p384.der"),
};

const RSA_ENCRYPTION: AlgorithmIdentifier = AlgorithmIdentifier {
asn1_id_value: include_bytes!("data/alg-rsa-encryption.der"),
};

1 change: 1 addition & 0 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod pem;
Loading