1 // Copyright 2015-2016 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 use crate::{bits, digest, error, rand};
16 
17 mod pkcs1;
18 mod pss;
19 
20 pub use self::{
21     pkcs1::{PKCS1, RSA_PKCS1_SHA256, RSA_PKCS1_SHA384, RSA_PKCS1_SHA512},
22     pss::{PSS, RSA_PSS_SHA256, RSA_PSS_SHA384, RSA_PSS_SHA512},
23 };
24 pub(super) use pkcs1::RSA_PKCS1_SHA1_FOR_LEGACY_USE_ONLY;
25 
26 /// Common features of both RSA padding encoding and RSA padding verification.
27 pub trait Padding: 'static + Sync + crate::sealed::Sealed + core::fmt::Debug {
28     // The digest algorithm used for digesting the message (and maybe for
29     // other things).
digest_alg(&self) -> &'static digest::Algorithm30     fn digest_alg(&self) -> &'static digest::Algorithm;
31 }
32 
33 /// An RSA signature encoding as described in [RFC 3447 Section 8].
34 ///
35 /// [RFC 3447 Section 8]: https://tools.ietf.org/html/rfc3447#section-8
36 #[cfg(feature = "alloc")]
37 pub trait RsaEncoding: Padding {
38     #[doc(hidden)]
encode( &self, m_hash: digest::Digest, m_out: &mut [u8], mod_bits: bits::BitLength, rng: &dyn rand::SecureRandom, ) -> Result<(), error::Unspecified>39     fn encode(
40         &self,
41         m_hash: digest::Digest,
42         m_out: &mut [u8],
43         mod_bits: bits::BitLength,
44         rng: &dyn rand::SecureRandom,
45     ) -> Result<(), error::Unspecified>;
46 }
47 
48 /// Verification of an RSA signature encoding as described in
49 /// [RFC 3447 Section 8].
50 ///
51 /// [RFC 3447 Section 8]: https://tools.ietf.org/html/rfc3447#section-8
52 pub trait Verification: Padding {
verify( &self, m_hash: digest::Digest, m: &mut untrusted::Reader, mod_bits: bits::BitLength, ) -> Result<(), error::Unspecified>53     fn verify(
54         &self,
55         m_hash: digest::Digest,
56         m: &mut untrusted::Reader,
57         mod_bits: bits::BitLength,
58     ) -> Result<(), error::Unspecified>;
59 }
60 
61 // Masks `out` with the output of the mask-generating function MGF1 as
62 // described in https://tools.ietf.org/html/rfc3447#appendix-B.2.1.
mgf1(digest_alg: &'static digest::Algorithm, seed: &[u8], out: &mut [u8])63 fn mgf1(digest_alg: &'static digest::Algorithm, seed: &[u8], out: &mut [u8]) {
64     let digest_len = digest_alg.output_len();
65 
66     // Maximum counter value is the value of (mask_len / digest_len) rounded up.
67     for (i, out) in out.chunks_mut(digest_len).enumerate() {
68         let mut ctx = digest::Context::new(digest_alg);
69         ctx.update(seed);
70         // The counter will always fit in a `u32` because we reject absurdly
71         // long inputs very early.
72         ctx.update(&u32::to_be_bytes(i.try_into().unwrap()));
73         let digest = ctx.finish();
74         // `zip` does the right thing as the the last chunk may legitimately be
75         // shorter than `digest`, and `digest` will never be shorter than `out`.
76         for (m, &d) in out.iter_mut().zip(digest.as_ref().iter()) {
77             *m ^= d;
78         }
79     }
80 }
81 
82 #[cfg(test)]
83 mod test {
84     use super::*;
85     use crate::{digest, error, test};
86     use alloc::vec;
87 
88     #[test]
test_pss_padding_verify()89     fn test_pss_padding_verify() {
90         test::run(
91             test_file!("rsa_pss_padding_tests.txt"),
92             |section, test_case| {
93                 assert_eq!(section, "");
94 
95                 let digest_name = test_case.consume_string("Digest");
96                 let alg = match digest_name.as_ref() {
97                     "SHA256" => &RSA_PSS_SHA256,
98                     "SHA384" => &RSA_PSS_SHA384,
99                     "SHA512" => &RSA_PSS_SHA512,
100                     _ => panic!("Unsupported digest: {}", digest_name),
101                 };
102 
103                 let msg = test_case.consume_bytes("Msg");
104                 let msg = untrusted::Input::from(&msg);
105                 let m_hash = digest::digest(alg.digest_alg(), msg.as_slice_less_safe());
106 
107                 let encoded = test_case.consume_bytes("EM");
108                 let encoded = untrusted::Input::from(&encoded);
109 
110                 // Salt is recomputed in verification algorithm.
111                 let _ = test_case.consume_bytes("Salt");
112 
113                 let bit_len = test_case.consume_usize_bits("Len");
114                 let is_valid = test_case.consume_string("Result") == "P";
115 
116                 let actual_result =
117                     encoded.read_all(error::Unspecified, |m| alg.verify(m_hash, m, bit_len));
118                 assert_eq!(actual_result.is_ok(), is_valid);
119 
120                 Ok(())
121             },
122         );
123     }
124 
125     // Tests PSS encoding for various public modulus lengths.
126     #[cfg(feature = "alloc")]
127     #[test]
test_pss_padding_encode()128     fn test_pss_padding_encode() {
129         test::run(
130             test_file!("rsa_pss_padding_tests.txt"),
131             |section, test_case| {
132                 assert_eq!(section, "");
133 
134                 let digest_name = test_case.consume_string("Digest");
135                 let alg = match digest_name.as_ref() {
136                     "SHA256" => &RSA_PSS_SHA256,
137                     "SHA384" => &RSA_PSS_SHA384,
138                     "SHA512" => &RSA_PSS_SHA512,
139                     _ => panic!("Unsupported digest: {}", digest_name),
140                 };
141 
142                 let msg = test_case.consume_bytes("Msg");
143                 let salt = test_case.consume_bytes("Salt");
144                 let encoded = test_case.consume_bytes("EM");
145                 let bit_len = test_case.consume_usize_bits("Len");
146                 let expected_result = test_case.consume_string("Result");
147 
148                 // Only test the valid outputs
149                 if expected_result != "P" {
150                     return Ok(());
151                 }
152 
153                 let rng = test::rand::FixedSliceRandom { bytes: &salt };
154 
155                 let mut m_out = vec![0u8; bit_len.as_usize_bytes_rounded_up()];
156                 let digest = digest::digest(alg.digest_alg(), &msg);
157                 alg.encode(digest, &mut m_out, bit_len, &rng).unwrap();
158                 assert_eq!(m_out, encoded);
159 
160                 Ok(())
161             },
162         );
163     }
164 }
165