1 // Copyright 2015-2017 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15 #![forbid(
16     anonymous_parameters,
17     box_pointers,
18     missing_copy_implementations,
19     missing_debug_implementations,
20     missing_docs,
21     trivial_casts,
22     trivial_numeric_casts,
23     unsafe_code,
24     unstable_features,
25     unused_extern_crates,
26     unused_import_braces,
27     unused_qualifications,
28     unused_results,
29     variant_size_differences,
30     warnings
31 )]
32 
33 extern crate alloc;
34 
35 use ring::{agreement, error, rand, test, test_file};
36 
37 #[test]
agreement_traits()38 fn agreement_traits() {
39     use alloc::vec::Vec;
40 
41     let rng = rand::SystemRandom::new();
42     let private_key =
43         agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng).unwrap();
44 
45     test::compile_time_assert_send::<agreement::EphemeralPrivateKey>();
46     test::compile_time_assert_sync::<agreement::EphemeralPrivateKey>();
47 
48     assert_eq!(
49         format!("{:?}", &private_key),
50         "EphemeralPrivateKey { algorithm: Algorithm { curve: P256 } }"
51     );
52 
53     let public_key = private_key.compute_public_key().unwrap();
54 
55     test::compile_time_assert_clone::<agreement::PublicKey>();
56     test::compile_time_assert_send::<agreement::PublicKey>();
57     test::compile_time_assert_sync::<agreement::PublicKey>();
58 
59     // Verify `PublicKey` implements `Debug`.
60     //
61     // TODO: Test the actual output.
62     let _: &dyn core::fmt::Debug = &public_key;
63 
64     test::compile_time_assert_clone::<agreement::UnparsedPublicKey<&[u8]>>();
65     test::compile_time_assert_copy::<agreement::UnparsedPublicKey<&[u8]>>();
66     test::compile_time_assert_sync::<agreement::UnparsedPublicKey<&[u8]>>();
67 
68     test::compile_time_assert_clone::<agreement::UnparsedPublicKey<Vec<u8>>>();
69     test::compile_time_assert_sync::<agreement::UnparsedPublicKey<Vec<u8>>>();
70 
71     let unparsed_public_key =
72         agreement::UnparsedPublicKey::new(&agreement::X25519, &[0x01, 0x02, 0x03]);
73 
74     assert_eq!(
75         format!("{:?}", unparsed_public_key),
76         r#"UnparsedPublicKey { algorithm: Algorithm { curve: Curve25519 }, bytes: "010203" }"#
77     );
78 }
79 
80 #[allow(clippy::block_in_if_condition_stmt)]
81 #[test]
agreement_agree_ephemeral()82 fn agreement_agree_ephemeral() {
83     let rng = rand::SystemRandom::new();
84 
85     test::run(test_file!("agreement_tests.txt"), |section, test_case| {
86         assert_eq!(section, "");
87 
88         let curve_name = test_case.consume_string("Curve");
89         let alg = alg_from_curve_name(&curve_name);
90         let peer_public = agreement::UnparsedPublicKey::new(alg, test_case.consume_bytes("PeerQ"));
91 
92         match test_case.consume_optional_string("Error") {
93             None => {
94                 let my_private = test_case.consume_bytes("D");
95                 let my_private = {
96                     let rng = test::rand::FixedSliceRandom { bytes: &my_private };
97                     agreement::EphemeralPrivateKey::generate(alg, &rng)?
98                 };
99                 let my_public = test_case.consume_bytes("MyQ");
100                 let output = test_case.consume_bytes("Output");
101 
102                 assert_eq!(my_private.algorithm(), alg);
103 
104                 let computed_public = my_private.compute_public_key().unwrap();
105                 assert_eq!(computed_public.as_ref(), &my_public[..]);
106 
107                 assert_eq!(my_private.algorithm(), alg);
108 
109                 assert!(
110                     agreement::agree_ephemeral(my_private, &peer_public, (), |key_material| {
111                         assert_eq!(key_material, &output[..]);
112                         Ok(())
113                     })
114                     .is_ok()
115                 );
116             }
117 
118             Some(_) => {
119                 // In the no-heap mode, some algorithms aren't supported so
120                 // we have to skip those algorithms' test cases.
121                 let dummy_private_key = agreement::EphemeralPrivateKey::generate(alg, &rng)?;
122                 fn kdf_not_called(_: &[u8]) -> Result<(), ()> {
123                     panic!(
124                         "The KDF was called during ECDH when the peer's \
125                          public key is invalid."
126                     );
127                 }
128                 assert!(agreement::agree_ephemeral(
129                     dummy_private_key,
130                     &peer_public,
131                     (),
132                     kdf_not_called
133                 )
134                 .is_err());
135             }
136         }
137 
138         Ok(())
139     });
140 }
141 
142 #[test]
test_agreement_ecdh_x25519_rfc_iterated()143 fn test_agreement_ecdh_x25519_rfc_iterated() {
144     let mut k = h("0900000000000000000000000000000000000000000000000000000000000000");
145     let mut u = k.clone();
146 
147     fn expect_iterated_x25519(
148         expected_result: &str,
149         range: core::ops::Range<usize>,
150         k: &mut Vec<u8>,
151         u: &mut Vec<u8>,
152     ) {
153         for _ in range {
154             let new_k = x25519(k, u);
155             *u = k.clone();
156             *k = new_k;
157         }
158         assert_eq!(&h(expected_result), k);
159     }
160 
161     expect_iterated_x25519(
162         "422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079",
163         0..1,
164         &mut k,
165         &mut u,
166     );
167     expect_iterated_x25519(
168         "684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d99532c51",
169         1..1_000,
170         &mut k,
171         &mut u,
172     );
173 
174     // The spec gives a test vector for 1,000,000 iterations but it takes
175     // too long to do 1,000,000 iterations by default right now. This
176     // 10,000 iteration vector is self-computed.
177     expect_iterated_x25519(
178         "2c125a20f639d504a7703d2e223c79a79de48c4ee8c23379aa19a62ecd211815",
179         1_000..10_000,
180         &mut k,
181         &mut u,
182     );
183 
184     if cfg!(feature = "slow_tests") {
185         expect_iterated_x25519(
186             "7c3911e0ab2586fd864497297e575e6f3bc601c0883c30df5f4dd2d24f665424",
187             10_000..1_000_000,
188             &mut k,
189             &mut u,
190         );
191     }
192 }
193 
x25519(private_key: &[u8], public_key: &[u8]) -> Vec<u8>194 fn x25519(private_key: &[u8], public_key: &[u8]) -> Vec<u8> {
195     x25519_(private_key, public_key).unwrap()
196 }
197 
x25519_(private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, error::Unspecified>198 fn x25519_(private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, error::Unspecified> {
199     let rng = test::rand::FixedSliceRandom { bytes: private_key };
200     let private_key = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng)?;
201     let public_key = agreement::UnparsedPublicKey::new(&agreement::X25519, public_key);
202     agreement::agree_ephemeral(
203         private_key,
204         &public_key,
205         error::Unspecified,
206         |agreed_value| Ok(Vec::from(agreed_value)),
207     )
208 }
209 
h(s: &str) -> Vec<u8>210 fn h(s: &str) -> Vec<u8> {
211     match test::from_hex(s) {
212         Ok(v) => v,
213         Err(msg) => {
214             panic!("{} in {}", msg, s);
215         }
216     }
217 }
218 
alg_from_curve_name(curve_name: &str) -> &'static agreement::Algorithm219 fn alg_from_curve_name(curve_name: &str) -> &'static agreement::Algorithm {
220     if curve_name == "P-256" {
221         &agreement::ECDH_P256
222     } else if curve_name == "P-384" {
223         &agreement::ECDH_P384
224     } else if curve_name == "X25519" {
225         &agreement::X25519
226     } else {
227         panic!("Unsupported curve: {}", curve_name);
228     }
229 }
230