Skip to main content

sgxs/crypto/
mod.rs

1/* Copyright (c) Fortanix, Inc.
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7pub type Hash = [u8; 32];
8
9pub trait SgxHashOps {
10    fn new() -> Self;
11    fn update(&mut self, data: &[u8]);
12    fn finish(self) -> Hash;
13}
14
15pub trait SgxRsaOps {
16    type Error: ::std::error::Error;
17
18    /// Return the number of bits in the RSA key
19    fn len(&self) -> usize;
20
21    /// Generate an RSASSA-PKCS1-v1_5 signature over a SHA256 hash. Also
22    /// compute
23    /// - `q1 = s^2 / n`
24    /// - `q2 = (s^3 - q1*s*n) / n`
25    /// where `/` is integer division.
26    ///
27    /// Returns `(s, q1, q2)` in little-endian format.
28    ///
29    /// ### Panics
30    /// May panic if the input length is not 32, or if the key does not contain
31    /// the private component.
32    fn sign_sha256_pkcs1v1_5_with_q1_q2<H: AsRef<[u8]>>(
33        &self,
34        hash: H,
35    ) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>), Self::Error>;
36
37    /// Verify an RSASSA-PKCS1-v1_5 signature `s` over a SHA256 hash.
38    ///
39    /// Supply `s` in little-endian format.
40    ///
41    /// ### Panics
42    /// May panic if the hash input length is not 32.
43    fn verify_sha256_pkcs1v1_5<S: AsRef<[u8]>, H: AsRef<[u8]>>(
44        &self,
45        sig: S,
46        hash: H,
47    ) -> Result<(), Self::Error>;
48
49    /// Retrieve the public key exponent in little-endian format
50    fn e(&self) -> Vec<u8>;
51
52    /// Retrieve the modulus in little-endian format
53    fn n(&self) -> Vec<u8>;
54}
55
56pub trait SgxRsaPubOps {
57    type Error: ::std::error::Error;
58    
59    /// Given a signature, compute
60    /// - `q1 = s^2 / n`
61    /// - `q2 = (s^3 - q1*s*n) / n`
62    /// where `/` is integer division.
63    ///
64    /// Returns `(q1, q2)` in little-endian format.
65    ///
66    /// ### Panics
67    /// May panic if the input length is not 32, or if the key does not contain
68    /// the private component.
69    fn calculate_q1_q2(&self, s: &[u8]) -> Result<(Vec<u8>, Vec<u8>), Self::Error>;
70}
71
72#[cfg(feature = "crypto-openssl")]
73mod openssl {
74    use super::*;
75
76    use foreign_types::ForeignTypeRef;
77    use openssl::bn::{BigNum, BigNumRef, BigNumContext};
78    use openssl::error::ErrorStack as SslError;
79    use openssl::hash::{Hasher, MessageDigest};
80    use openssl::nid::Nid;
81    use openssl::pkey::{HasPublic, Private, Public};
82    use openssl::rsa::RsaRef;
83    use openssl_sys as ffi;
84
85    pub fn calculate_q1_q2(n: &BigNumRef, s_slice: &[u8]) -> Result<(Vec<u8>, Vec<u8>), SslError> {
86        // Compute Q1 and Q2
87        let mut s_2 = BigNum::new()?;
88        let mut s_3 = BigNum::new()?;
89        let mut q1 = BigNum::new()?;
90        let mut tmp1 = BigNum::new()?;
91        let mut tmp2 = BigNum::new()?;
92        let mut tmp3 = BigNum::new()?;
93        let mut q2 = BigNum::new()?;
94
95        let mut ctx = BigNumContext::new()?;
96        let s = BigNum::from_slice(s_slice)?;
97        s_2.sqr(&s, &mut ctx)?;
98        q1.checked_div(&s_2, &n, &mut ctx)?;
99
100        s_3.checked_mul(&s_2, &s, &mut ctx)?;
101        tmp1.checked_mul(&q1, &s, &mut ctx)?;
102        tmp2.checked_mul(&tmp1, &n, &mut ctx)?;
103        tmp3.checked_sub(&s_3, &tmp2)?;
104        q2.checked_div(&tmp3, &n, &mut ctx)?;
105        let mut q1 = q1.to_vec();
106        let mut q2 = q2.to_vec();
107
108        // Return in little-endian format
109        q1.reverse();
110        q2.reverse();
111        Ok((q1, q2))
112    }
113
114
115    impl SgxHashOps for Hasher {
116        fn new() -> Self {
117            Hasher::new(MessageDigest::sha256()).expect("failed to create openssl hasher")
118        }
119
120        fn update(&mut self, data: &[u8]) {
121            self.update(data).expect("failed to update openssl hasher");
122        }
123
124        fn finish(mut self) -> Hash {
125            let mut hash = [0u8; 32];
126            hash.copy_from_slice(
127                &Hasher::finish(&mut self).expect("failed to finish openssl hasher"),
128            );
129            hash
130        }
131    }
132
133    pub trait MaybePrivate: Sized {
134        fn as_private(rsa: &RsaRef<Self>) -> &RsaRef<Private>;
135    }
136
137    impl MaybePrivate for Private {
138        fn as_private(rsa: &RsaRef<Self>) -> &RsaRef<Private> {
139            rsa
140        }
141    }
142
143    impl MaybePrivate for Public {
144        fn as_private(_rsa: &RsaRef<Self>) -> &RsaRef<Private> {
145            panic!("Requires private key!")
146        }
147    }
148
149    impl<T: HasPublic + MaybePrivate> SgxRsaOps for RsaRef<T> {
150        type Error = SslError;
151
152        fn len(&self) -> usize {
153            self.n().num_bits() as _
154        }
155
156        fn sign_sha256_pkcs1v1_5_with_q1_q2<H: AsRef<[u8]>>(
157            &self,
158            hash: H,
159        ) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>), Self::Error> {
160            // The following `unsafe` block was copied from `fn sign_with_hash`
161            // https://github.com/sfackler/rust-openssl/tree/7515272692ea30ee320667563027f75508f1dc60.
162            let mut s_vec = unsafe {
163                // OpenSSL wrapper does not expose a function to sign hashes,
164                // only unhashed data.
165                // man RSA_sign: "sigret must point to RSA_size(rsa) bytes of memory."
166                let mut r = vec![0; self.size() as _];
167
168                let mut len = 0;
169                let rv = ffi::RSA_sign(
170                    Nid::SHA256.as_raw(),
171                    hash.as_ref().as_ptr(),
172                    hash.as_ref().len() as _,
173                    r.as_mut_ptr(),
174                    &mut len,
175                    self.as_ptr(),
176                );
177
178                if rv < 0 {
179                    return Err(SslError::get());
180                } else {
181                    r.truncate(len as _);
182                    r
183                }
184            };
185
186            let (q1, q2) = calculate_q1_q2(self.n(), &s_vec)?;
187            s_vec.reverse();
188            Ok((s_vec, q1, q2))
189        }
190
191        fn verify_sha256_pkcs1v1_5<S: AsRef<[u8]>, H: AsRef<[u8]>>(
192            &self,
193            sig: S,
194            hash: H,
195        ) -> Result<(), Self::Error> {
196            // Convert to big-endian format
197            let mut sig = sig.as_ref().to_owned();
198            sig.reverse();
199
200            let ret = unsafe {
201                // OpenSSL wrapper does not expose a function to verify hashes,
202                // only unhashed data.
203                ffi::RSA_verify(
204                    Nid::SHA256.as_raw(),
205                    hash.as_ref().as_ptr(),
206                    hash.as_ref().len() as _,
207                    sig.as_mut_ptr(),
208                    sig.len() as _,
209                    self.as_ptr(),
210                )
211            };
212
213            if ret == 1 {
214                Ok(())
215            } else {
216                Err(SslError::get())
217            }
218        }
219
220        fn e(&self) -> Vec<u8> {
221            let mut v = self.e().to_vec();
222            v.reverse();
223            v
224        }
225
226        fn n(&self) -> Vec<u8> {
227            let mut v = self.n().to_vec();
228            v.reverse();
229            v
230        }
231    }
232
233    impl<T: HasPublic> SgxRsaPubOps for RsaRef<T> {
234        type Error = SslError;
235
236        fn calculate_q1_q2(&self, s: &[u8]) -> Result<(Vec<u8>, Vec<u8>), Self::Error> {
237            calculate_q1_q2(self.n(), s)
238        }
239    }
240}
241
242#[cfg(feature = "sha2")]
243mod sha2 {
244    use super::*;
245    use sha2::{Digest, Sha256};
246
247    impl SgxHashOps for Sha256 {
248        fn new() -> Self {
249            <Sha256 as Digest>::new()
250        }
251        fn update(&mut self, data: &[u8]) {
252            self.input(data)
253        }
254        fn finish(self) -> Hash {
255            let mut hash = [0u8; 32];
256            hash.copy_from_slice(self.result().as_slice());
257            hash
258        }
259    }
260}
261
262#[cfg(all(test))]
263mod tests;