Debian Codegraph @

third_party/rust/neqo-crypto/src/hp.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 #![allow(
8 clippy::module_name_repetitions,
9 reason = "<https://github.com/mozilla/neqo/issues/2284#issuecomment-2782711813>"
10 )]
11
12 use std::{
13 cell::RefCell,
14 fmt::{self, Debug},
15 os::raw::{c_char, c_int, c_uint},
16 ptr::{addr_of_mut, null, null_mut},
17 rc::Rc,
18 };
19
20 use crate::{
21 constants::{
22 Cipher, Version, TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384,
23 TLS_CHACHA20_POLY1305_SHA256,
24 },
25 err::{secstatus_to_res, Error, Res},
26 p11::{
27 Context, Item, PK11SymKey, PK11_CipherOp, PK11_CreateContextBySymKey, PK11_Encrypt,
28 PK11_GetBlockSize, SymKey, CKA_ENCRYPT, CKM_AES_ECB, CKM_CHACHA20, CK_ATTRIBUTE_TYPE,
29 CK_CHACHA20_PARAMS, CK_MECHANISM_TYPE,
30 },
31 };
32
33 experimental_api!(SSL_HkdfExpandLabelWithMech(
34 version: Version,
35 cipher: Cipher,
36 prk: *mut PK11SymKey,
37 handshake_hash: *const u8,
38 handshake_hash_len: c_uint,
39 label: *const c_char,
40 label_len: c_uint,
41 mech: CK_MECHANISM_TYPE,
42 key_size: c_uint,
43 secret: *mut *mut PK11SymKey,
44 ));
45
46 #[derive(Clone)]
47 pub enum HpKey {
48 /// An AES encryption context.
49 /// Note: as we need to clone this object, we clone the pointer and
50 /// track references using `Rc`. `PK11Context` can't be used with `PK11_CloneContext`
51 /// as that is not supported for these contexts.
52 Aes(Rc<RefCell<Context>>),
53 /// The `ChaCha20` mask has to invoke a new `PK11_Encrypt` every time as it needs to
54 /// change the counter and nonce on each invocation.
55 Chacha(SymKey),
56 }
57
58 impl Debug for HpKey {
59 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60 write!(f, "HpKey")
61 }
62 }
63
64 impl HpKey {
65 pub const SAMPLE_SIZE: usize = 16;
66
67 /// QUIC-specific API for extracting a header-protection key.
68 ///
69 /// # Errors
70 ///
71 /// Errors if HKDF fails or if the label is too long to fit in a `c_uint`.
72 ///
73 /// # Panics
74 ///
75 /// When `cipher` is not known to this code.
76 pub fn extract(version: Version, cipher: Cipher, prk: &SymKey, label: &str) -> Res<Self> {
77 const ZERO: &[u8] = &[0; 12];
78
79 let l = label.as_bytes();
80 let mut secret: *mut PK11SymKey = null_mut();
81
82 let (mech, key_size) = match cipher {
83 TLS_AES_128_GCM_SHA256 => (CK_MECHANISM_TYPE::from(CKM_AES_ECB), 16),
84 TLS_AES_256_GCM_SHA384 => (CK_MECHANISM_TYPE::from(CKM_AES_ECB), 32),
85 TLS_CHACHA20_POLY1305_SHA256 => (CK_MECHANISM_TYPE::from(CKM_CHACHA20), 32),
86 _ => unreachable!(),
87 };
88
89 // Note that this doesn't allow for passing null() for the handshake hash.
90 // A zero-length slice produces an identical result.
91 unsafe {
92 SSL_HkdfExpandLabelWithMech(
93 version,
94 cipher,
95 **prk,
96 null(),
97 0,
98 l.as_ptr().cast(),
99 c_uint::try_from(l.len())?,
100 mech,
101 key_size,
102 &mut secret,
103 )
104 }?;
105 let key = SymKey::from_ptr(secret).or(Err(Error::HkdfError))?;
106
107 let res = match cipher {
108 TLS_AES_128_GCM_SHA256 | TLS_AES_256_GCM_SHA384 => {
109 let context_ptr = unsafe {
110 PK11_CreateContextBySymKey(
111 mech,
112 CK_ATTRIBUTE_TYPE::from(CKA_ENCRYPT),
113 *key,
114 &Item::wrap(&ZERO[..0])?, // Borrow a zero-length slice of ZERO.
115 )
116 };
117 let context = Context::from_ptr(context_ptr).or(Err(Error::CipherInitFailure))?;
118 Self::Aes(Rc::new(RefCell::new(context)))
119 }
120 TLS_CHACHA20_POLY1305_SHA256 => Self::Chacha(key),
121 _ => unreachable!(),
122 };
123
124 debug_assert_eq!(
125 res.block_size(),
126 usize::try_from(unsafe { PK11_GetBlockSize(mech, null_mut()) })?
127 );
128 Ok(res)
129 }
130
131 const fn block_size(&self) -> usize {
132 match self {
133 Self::Aes(_) => 16,
134 Self::Chacha(_) => 64,
135 }
136 }
137
138 /// Generate a header protection mask for QUIC.
139 ///
140 /// # Errors
141 ///
142 /// An error is returned if the NSS functions fail; a sample of the
143 /// wrong size is the obvious cause.
144 ///
145 /// # Panics
146 ///
147 /// When the mechanism for our key is not supported.
148 /// Or when the sample provided is not at least `self.sample_size()` bytes.
149 pub fn mask(&self, sample: &[u8]) -> Res<[u8; Self::SAMPLE_SIZE]> {
150 let mut output = [0; Self::SAMPLE_SIZE];
151
152 match self {
153 Self::Aes(context) => {
154 let mut output_len: c_int = 0;
155 secstatus_to_res(unsafe {
156 PK11_CipherOp(
157 **context.borrow_mut(),
158 output.as_mut_ptr(),
159 &mut output_len,
160 c_int::try_from(output.len())?,
161 sample[..Self::SAMPLE_SIZE].as_ptr().cast(),
162 c_int::try_from(Self::SAMPLE_SIZE)?,
163 )
164 })?;
165 debug_assert_eq!(usize::try_from(output_len)?, output.len());
166 Ok(output)
167 }
168
169 Self::Chacha(key) => {
170 let params: CK_CHACHA20_PARAMS = CK_CHACHA20_PARAMS {
171 pBlockCounter: sample.as_ptr().cast_mut(),
172 blockCounterBits: 32,
173 pNonce: sample[4..Self::SAMPLE_SIZE].as_ptr().cast_mut(),
174 ulNonceBits: 96,
175 };
176 let mut output_len: c_uint = 0;
177 let mut param_item = Item::wrap_struct(&params)?;
178 secstatus_to_res(unsafe {
179 PK11_Encrypt(
180 **key,
181 CK_MECHANISM_TYPE::from(CKM_CHACHA20),
182 addr_of_mut!(param_item),
183 output[..].as_mut_ptr(),
184 &mut output_len,
185 c_uint::try_from(output.len())?,
186 [0; Self::SAMPLE_SIZE].as_ptr(),
187 c_uint::try_from(Self::SAMPLE_SIZE)?,
188 )
189 })?;
190 debug_assert_eq!(usize::try_from(output_len)?, output.len());
191 Ok(output)
192 }
193 }
194 }
195 }