Debian Codegraph @

third_party/rust/ohttp/src/nss/p11.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 super::err::{secstatus_to_res, Error};
8 use crate::err::Res;
9 use std::{
10 convert::TryFrom,
11 marker::PhantomData,
12 mem,
13 os::raw::{c_int, c_uint},
14 ptr::null_mut,
15 };
16
17 #[allow(
18 clippy::pedantic,
19 clippy::upper_case_acronyms,
20 dead_code,
21 deref_nullptr,
22 non_camel_case_types,
23 non_snake_case,
24 non_upper_case_globals
25 )]
26 pub mod sys {
27 include!(concat!(env!("OUT_DIR"), "/nss_p11.rs"));
28 }
29
30 use sys::{
31 PK11ObjectType, PK11SlotInfo, PK11SymKey, PK11_ExtractKeyValue, PK11_FreeSlot, PK11_FreeSymKey,
32 PK11_GenerateRandom, PK11_GetInternalSlot, PK11_GetKeyData, PK11_ReadRawAttribute,
33 PK11_ReferenceSymKey, PRBool, SECITEM_FreeItem, SECItem, SECItemType, SECKEYPrivateKey,
34 SECKEYPublicKey, SECKEY_DestroyPrivateKey, SECKEY_DestroyPublicKey, CKA_VALUE,
35 CK_ATTRIBUTE_TYPE,
36 };
37
38 macro_rules! scoped_ptr {
39 ($scoped:ident, $target:ty, $dtor:path) => {
40 pub struct $scoped {
41 ptr: *mut $target,
42 }
43
44 impl $scoped {
45 pub fn from_ptr(ptr: *mut $target) -> Result<Self, crate::err::Error> {
46 if ptr.is_null() {
47 Err(crate::nss::err::Error::last())
48 } else {
49 Ok(Self { ptr })
50 }
51 }
52 }
53
54 impl std::ops::Deref for $scoped {
55 type Target = *mut $target;
56 #[must_use]
57 fn deref(&self) -> &*mut $target {
58 &self.ptr
59 }
60 }
61
62 impl std::ops::DerefMut for $scoped {
63 fn deref_mut(&mut self) -> &mut *mut $target {
64 &mut self.ptr
65 }
66 }
67
68 impl Drop for $scoped {
69 fn drop(&mut self) {
70 unsafe { $dtor(self.ptr) };
71 }
72 }
73 };
74 }
75
76 scoped_ptr!(PrivateKey, SECKEYPrivateKey, SECKEY_DestroyPrivateKey);
77
78 impl PrivateKey {
79 pub fn key_data(&self) -> Res<Vec<u8>> {
80 let mut key_item = SECItem {
81 type_: SECItemType::siBuffer,
82 data: null_mut(),
83 len: 0,
84 };
85 secstatus_to_res(unsafe {
86 PK11_ReadRawAttribute(
87 PK11ObjectType::PK11_TypePrivKey,
88 (**self).cast(),
89 CK_ATTRIBUTE_TYPE::from(CKA_VALUE),
90 &mut key_item,
91 )
92 })?;
93 let slc = unsafe {
94 std::slice::from_raw_parts(key_item.data, usize::try_from(key_item.len).unwrap())
95 };
96 let key = Vec::from(slc);
97 // The data that `key_item` refers to needs to be freed, but we can't
98 // use the scoped `Item` implementation. This is OK as long as nothing
99 // panics between `PK11_ReadRawAttribute` succeeding and here.
100 unsafe {
101 SECITEM_FreeItem(&mut key_item, PRBool::from(false));
102 }
103 Ok(key)
104 }
105 }
106 unsafe impl Send for PrivateKey {}
107
108 impl Clone for PrivateKey {
109 #[must_use]
110 fn clone(&self) -> Self {
111 let ptr = unsafe { sys::SECKEY_CopyPrivateKey(self.ptr) };
112 assert!(!ptr.is_null());
113 Self { ptr }
114 }
115 }
116
117 impl std::fmt::Debug for PrivateKey {
118 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
119 if let Ok(b) = self.key_data() {
120 write!(f, "PrivateKey {}", hex::encode(b))
121 } else {
122 write!(f, "Opaque PrivateKey")
123 }
124 }
125 }
126
127 scoped_ptr!(PublicKey, SECKEYPublicKey, SECKEY_DestroyPublicKey);
128
129 impl PublicKey {
130 /// Get the HPKE serialization of the public key.
131 pub fn key_data(&self) -> Res<Vec<u8>> {
132 let mut buf = vec![0; 100];
133 let mut len: c_uint = 0;
134 secstatus_to_res(unsafe {
135 sys::PK11_HPKE_Serialize(
136 **self,
137 buf.as_mut_ptr(),
138 &mut len,
139 c_uint::try_from(buf.len()).unwrap(),
140 )
141 })?;
142 buf.truncate(usize::try_from(len).unwrap());
143 Ok(buf)
144 }
145 }
146
147 unsafe impl Send for PublicKey {}
148
149 impl Clone for PublicKey {
150 #[must_use]
151 fn clone(&self) -> Self {
152 let ptr = unsafe { sys::SECKEY_CopyPublicKey(self.ptr) };
153 assert!(!ptr.is_null());
154 Self { ptr }
155 }
156 }
157
158 impl std::fmt::Debug for PublicKey {
159 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
160 if let Ok(b) = self.key_data() {
161 write!(f, "PublicKey {}", hex::encode(b))
162 } else {
163 write!(f, "Opaque PublicKey")
164 }
165 }
166 }
167
168 scoped_ptr!(Slot, PK11SlotInfo, PK11_FreeSlot);
169
170 impl Slot {
171 pub(crate) fn internal() -> Res<Self> {
172 let p = unsafe { PK11_GetInternalSlot() };
173 Slot::from_ptr(p)
174 }
175 }
176
177 scoped_ptr!(SymKey, PK11SymKey, PK11_FreeSymKey);
178
179 impl SymKey {
180 /// You really don't want to use this.
181 ///
182 /// # Errors
183 /// Some keys cannot be inspected in this way.
184 /// Also, internal errors in case of failures in NSS.
185 pub fn key_data(&self) -> Res<&[u8]> {
186 secstatus_to_res(unsafe { PK11_ExtractKeyValue(self.ptr) })?;
187
188 let key_item = unsafe { PK11_GetKeyData(self.ptr) };
189 // This is accessing a value attached to the key, so we can treat this as a borrow.
190 match unsafe { key_item.as_mut() } {
191 None => Err(Error::last()),
192 Some(key) => Ok(unsafe { std::slice::from_raw_parts(key.data, key.len as usize) }),
193 }
194 }
195 }
196
197 impl Clone for SymKey {
198 #[must_use]
199 fn clone(&self) -> Self {
200 let ptr = unsafe { PK11_ReferenceSymKey(self.ptr) };
201 assert!(!ptr.is_null());
202 Self { ptr }
203 }
204 }
205
206 impl std::fmt::Debug for SymKey {
207 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
208 if let Ok(b) = self.key_data() {
209 write!(f, "SymKey {}", hex::encode(b))
210 } else {
211 write!(f, "Opaque SymKey")
212 }
213 }
214 }
215
216 unsafe impl Send for SymKey {}
217
218 /// Generate a randomized buffer.
219 #[must_use]
220 pub fn random(size: usize) -> Vec<u8> {
221 let mut buf = vec![0; size];
222 secstatus_to_res(unsafe {
223 PK11_GenerateRandom(buf.as_mut_ptr(), c_int::try_from(buf.len()).unwrap())
224 })
225 .unwrap();
226 buf
227 }
228
229 pub(crate) struct ParamItem<'a, T: 'a> {
230 item: SECItem,
231 marker: PhantomData<&'a T>,
232 }
233
234 impl<'a, T: Sized + 'a> ParamItem<'a, T> {
235 pub fn new(v: &'a mut T) -> Self {
236 let item = SECItem {
237 type_: SECItemType::siBuffer,
238 data: (v as *mut T).cast::<u8>(),
239 len: c_uint::try_from(mem::size_of::<T>()).unwrap(),
240 };
241 Self {
242 item,
243 marker: PhantomData,
244 }
245 }
246
247 pub fn ptr(&mut self) -> *mut SECItem {
248 std::ptr::addr_of_mut!(self.item)
249 }
250 }
251
252 unsafe fn destroy_secitem(item: *mut SECItem) {
253 SECITEM_FreeItem(item, PRBool::from(true));
254 }
255 scoped_ptr!(Item, SECItem, destroy_secitem);
256
257 impl Item {
258 /// Create a wrapper for a slice of this object.
259 /// Creating this object is technically safe, but using it is extremely dangerous.
260 /// Minimally, it can only be passed as a `const SECItem*` argument to functions.
261 pub(crate) fn wrap(buf: &[u8]) -> SECItem {
262 SECItem {
263 type_: SECItemType::siBuffer,
264 data: buf.as_ptr() as *mut u8,
265 len: c_uint::try_from(buf.len()).unwrap(),
266 }
267 }
268
269 /// This dereferences the pointer held by the item and makes a copy of the
270 /// content that is referenced there.
271 ///
272 /// # Safety
273 /// This dereferences two pointers. It doesn't get much less safe.
274 pub(crate) unsafe fn into_vec(self) -> Vec<u8> {
275 let b = self.ptr.as_ref().unwrap();
276 // Sanity check the type, as some types don't count bytes in `Item::len`.
277 assert_eq!(b.type_, SECItemType::siBuffer);
278 let slc = std::slice::from_raw_parts(b.data, usize::try_from(b.len).unwrap());
279 Vec::from(slc)
280 }
281 }
282
283 #[cfg(test)]
284 mod test {
285 use super::random;
286 use crate::init;
287
288 #[test]
289 fn randomness() {
290 init();
291 // If this ever fails, there is either a bug, or it's time to buy a lottery ticket.
292 assert_ne!(random(16), random(16));
293 }
294 }