Debian Codegraph @

third_party/rust/neqo-crypto/src/aead.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use std::{
8 fmt,
9 ops::{Deref, DerefMut},
10 os::raw::{c_char, c_uint},
11 ptr::null_mut,
12 };
13
14 use crate::{
15 constants::{Cipher, Version},
16 err::Res,
17 experimental_api,
18 p11::{PK11SymKey, SymKey},
19 scoped_ptr,
20 ssl::{PRUint16, PRUint64, PRUint8, SSLAeadContext},
21 };
22
23 experimental_api!(SSL_MakeAead(
24 version: PRUint16,
25 cipher: PRUint16,
26 secret: *mut PK11SymKey,
27 label_prefix: *const c_char,
28 label_prefix_len: c_uint,
29 ctx: *mut *mut SSLAeadContext,
30 ));
31 experimental_api!(SSL_AeadEncrypt(
32 ctx: *const SSLAeadContext,
33 counter: PRUint64,
34 aad: *const PRUint8,
35 aad_len: c_uint,
36 input: *const PRUint8,
37 input_len: c_uint,
38 output: *const PRUint8,
39 output_len: *mut c_uint,
40 max_output: c_uint
41 ));
42 experimental_api!(SSL_AeadDecrypt(
43 ctx: *const SSLAeadContext,
44 counter: PRUint64,
45 aad: *const PRUint8,
46 aad_len: c_uint,
47 input: *const PRUint8,
48 input_len: c_uint,
49 output: *const PRUint8,
50 output_len: *mut c_uint,
51 max_output: c_uint
52 ));
53 experimental_api!(SSL_DestroyAead(ctx: *mut SSLAeadContext));
54 scoped_ptr!(AeadContext, SSLAeadContext, SSL_DestroyAead);
55
56 pub struct RealAead {
57 ctx: AeadContext,
58 }
59
60 impl RealAead {
61 /// Create a new AEAD based on the indicated TLS version and cipher suite.
62 ///
63 /// # Errors
64 ///
65 /// Returns `Error` when the supporting NSS functions fail.
66 pub fn new(version: Version, cipher: Cipher, secret: &SymKey, prefix: &str) -> Res<Self> {
67 let s: *mut PK11SymKey = **secret;
68 unsafe { Self::from_raw(version, cipher, s, prefix) }
69 }
70
71 #[must_use]
72 pub const fn expansion(&self) -> usize {
73 16
74 }
75
76 unsafe fn from_raw(
77 version: Version,
78 cipher: Cipher,
79 secret: *mut PK11SymKey,
80 prefix: &str,
81 ) -> Res<Self> {
82 let p = prefix.as_bytes();
83 let mut ctx: *mut SSLAeadContext = null_mut();
84 SSL_MakeAead(
85 version,
86 cipher,
87 secret,
88 p.as_ptr().cast(),
89 c_uint::try_from(p.len())?,
90 &mut ctx,
91 )?;
92 Ok(Self {
93 ctx: AeadContext::from_ptr(ctx)?,
94 })
95 }
96
97 /// Encrypt a plaintext.
98 ///
99 /// The space provided in `output` needs to be larger than `input` by
100 /// the value provided in `Aead::expansion`.
101 ///
102 /// # Errors
103 ///
104 /// If the input can't be protected or any input is too large for NSS.
105 pub fn encrypt<'a>(
106 &self,
107 count: u64,
108 aad: &[u8],
109 input: &[u8],
110 output: &'a mut [u8],
111 ) -> Res<&'a [u8]> {
112 let mut l: c_uint = 0;
113 unsafe {
114 SSL_AeadEncrypt(
115 *self.ctx,
116 count,
117 aad.as_ptr(),
118 c_uint::try_from(aad.len())?,
119 input.as_ptr(),
120 c_uint::try_from(input.len())?,
121 output.as_mut_ptr(),
122 &mut l,
123 c_uint::try_from(output.len())?,
124 )
125 }?;
126 Ok(&output[..l.try_into()?])
127 }
128
129 /// Encrypt `data` consisting of `aad` and plaintext `data` in place.
130 ///
131 /// The last `Aead::expansion` of `data` is overwritten by the AEAD tag by this function.
132 /// Therefore, a buffer should be provided that is that much larger than the plaintext.
133 ///
134 /// # Panics
135 ///
136 /// If `data` is shorter than `<self as Aead>::expansion()`.
137 ///
138 /// # Errors
139 ///
140 /// If the input can't be protected or any input is too large for NSS.
141 pub fn encrypt_in_place<'a>(
142 &self,
143 count: u64,
144 aad: &[u8],
145 data: &'a mut [u8],
146 ) -> Res<&'a mut [u8]> {
147 let mut l: c_uint = 0;
148 unsafe {
149 SSL_AeadEncrypt(
150 *self.ctx,
151 count,
152 aad.as_ptr(),
153 c_uint::try_from(aad.len())?,
154 data.as_ptr(),
155 c_uint::try_from(data.len() - self.expansion())?,
156 data.as_ptr(),
157 &mut l,
158 c_uint::try_from(data.len())?,
159 )
160 }?;
161 Ok(&mut data[..l.try_into()?])
162 }
163
164 /// Decrypt a ciphertext.
165 ///
166 /// # Errors
167 ///
168 /// If the input isn't authenticated or any input is too large for NSS.
169 pub fn decrypt<'a>(
170 &self,
171 count: u64,
172 aad: &[u8],
173 input: &[u8],
174 output: &'a mut [u8],
175 ) -> Res<&'a [u8]> {
176 let mut l: c_uint = 0;
177 unsafe {
178 // Note that NSS insists upon having extra space available for decryption, so
179 // the buffer for `output` should be the same length as `input`, even though
180 // the final result will be shorter.
181 SSL_AeadDecrypt(
182 *self.ctx,
183 count,
184 aad.as_ptr(),
185 c_uint::try_from(aad.len())?,
186 input.as_ptr(),
187 c_uint::try_from(input.len())?,
188 output.as_mut_ptr(),
189 &mut l,
190 c_uint::try_from(output.len())?,
191 )
192 }?;
193 Ok(&output[..l.try_into()?])
194 }
195
196 /// Decrypt a ciphertext in place.
197 /// Returns a subslice of `data` (without the last `<self as Aead>::expansion()` bytes),
198 /// that has been decrypted in place.
199 ///
200 /// # Errors
201 ///
202 /// If the input isn't authenticated or any input is too large for NSS.
203 pub fn decrypt_in_place<'a>(
204 &self,
205 count: u64,
206 aad: &[u8],
207 data: &'a mut [u8],
208 ) -> Res<&'a mut [u8]> {
209 let mut l: c_uint = 0;
210 unsafe {
211 // Note that NSS insists upon having extra space available for decryption, so
212 // the buffer for `output` should be the same length as `input`, even though
213 // the final result will be shorter.
214 SSL_AeadDecrypt(
215 *self.ctx,
216 count,
217 aad.as_ptr(),
218 c_uint::try_from(aad.len())?,
219 data.as_ptr(),
220 c_uint::try_from(data.len())?,
221 data.as_ptr(),
222 &mut l,
223 c_uint::try_from(data.len())?,
224 )
225 }?;
226 debug_assert_eq!(usize::try_from(l)?, data.len() - self.expansion());
227 Ok(&mut data[..l.try_into()?])
228 }
229 }
230
231 impl fmt::Debug for RealAead {
232 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
233 write!(f, "[AEAD Context]")
234 }
235 }