Debian Codegraph @

third_party/rust/nss-gk-api/src/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 #![allow(dead_code)]
8 #![allow(non_upper_case_globals)]
9 #![allow(non_camel_case_types)]
10 #![allow(non_snake_case)]
11
12 use crate::err::{secstatus_to_res, Error, Res};
13 use crate::util::SECItemMut;
14
15 use pkcs11_bindings::CKA_EC_POINT;
16 use pkcs11_bindings::CKA_VALUE;
17
18 use std::convert::TryFrom;
19 use std::os::raw::{c_int, c_uint};
20
21 #[must_use]
22 pub fn hex_with_len(buf: impl AsRef<[u8]>) -> String {
23 use std::fmt::Write;
24 let buf = buf.as_ref();
25 let mut ret = String::with_capacity(10 + buf.len() * 2);
26 write!(&mut ret, "[{}]: ", buf.len()).unwrap();
27 for b in buf {
28 write!(&mut ret, "{:02x}", b).unwrap();
29 }
30 ret
31 }
32
33 #[allow(clippy::upper_case_acronyms)]
34 #[allow(clippy::unreadable_literal)]
35 #[allow(unknown_lints, clippy::borrow_as_ptr)]
36 mod nss_p11 {
37 use crate::nss_prelude::*;
38 use crate::prtypes::*;
39 include!(concat!(env!("OUT_DIR"), "/nss_p11.rs"));
40 }
41
42 use crate::prtypes::*;
43 pub use nss_p11::*;
44
45 // Shadow these bindgen created values to correct their type.
46 pub const SHA256_LENGTH: usize = nss_p11::SHA256_LENGTH as usize;
47 pub const AES_BLOCK_SIZE: usize = nss_p11::AES_BLOCK_SIZE as usize;
48
49 scoped_ptr!(Certificate, CERTCertificate, CERT_DestroyCertificate);
50 scoped_ptr!(CertList, CERTCertList, CERT_DestroyCertList);
51
52 scoped_ptr!(
53 SubjectPublicKeyInfo,
54 CERTSubjectPublicKeyInfo,
55 SECKEY_DestroySubjectPublicKeyInfo
56 );
57
58 scoped_ptr!(PublicKey, SECKEYPublicKey, SECKEY_DestroyPublicKey);
59 impl_clone!(PublicKey, SECKEY_CopyPublicKey);
60
61 impl PublicKey {
62 /// Get the HPKE serialization of the public key.
63 ///
64 /// # Errors
65 /// When the key cannot be exported, which can be because the type is not supported.
66 /// # Panics
67 /// When keys are too large to fit in `c_uint/usize`. So only on programming error.
68 pub fn key_data(&self) -> Res<Vec<u8>> {
69 let mut buf = vec![0; 100];
70 let mut len: c_uint = 0;
71 secstatus_to_res(unsafe {
72 PK11_HPKE_Serialize(
73 **self,
74 buf.as_mut_ptr(),
75 &mut len,
76 c_uint::try_from(buf.len()).unwrap(),
77 )
78 })?;
79 buf.truncate(usize::try_from(len).unwrap());
80 Ok(buf)
81 }
82
83 pub fn key_data_alt(&self) -> Res<Vec<u8>> {
84 let mut key_item = SECItemMut::make_empty();
85 secstatus_to_res(unsafe {
86 PK11_ReadRawAttribute(
87 PK11ObjectType::PK11_TypePubKey,
88 (**self).cast(),
89 CKA_EC_POINT,
90 key_item.as_mut(),
91 )
92 })?;
93 Ok(key_item.as_slice().to_owned())
94 }
95 }
96
97 impl std::fmt::Debug for PublicKey {
98 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
99 if let Ok(b) = self.key_data() {
100 write!(f, "PublicKey {}", hex_with_len(b))
101 } else {
102 write!(f, "Opaque PublicKey")
103 }
104 }
105 }
106
107 scoped_ptr!(PrivateKey, SECKEYPrivateKey, SECKEY_DestroyPrivateKey);
108 impl_clone!(PrivateKey, SECKEY_CopyPrivateKey);
109
110 impl PrivateKey {
111 /// Get the bits of the private key.
112 ///
113 /// # Errors
114 /// When the key cannot be exported, which can be because the type is not supported
115 /// or because the key data cannot be extracted from the PKCS#11 module.
116 /// # Panics
117 /// When the values are too large to fit. So never.
118 pub fn key_data(&self) -> Res<Vec<u8>> {
119 let mut key_item = SECItemMut::make_empty();
120 secstatus_to_res(unsafe {
121 PK11_ReadRawAttribute(
122 PK11ObjectType::PK11_TypePrivKey,
123 (**self).cast(),
124 CKA_VALUE,
125 key_item.as_mut(),
126 )
127 })?;
128 Ok(key_item.as_slice().to_owned())
129 }
130 }
131
132 impl std::fmt::Debug for PrivateKey {
133 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
134 if let Ok(b) = self.key_data() {
135 write!(f, "PrivateKey {}", hex_with_len(b))
136 } else {
137 write!(f, "Opaque PrivateKey")
138 }
139 }
140 }
141
142 scoped_ptr!(Slot, PK11SlotInfo, PK11_FreeSlot);
143
144 impl Slot {
145 pub fn internal() -> Res<Self> {
146 unsafe { Slot::from_ptr(PK11_GetInternalSlot()) }
147 }
148 }
149
150 // Note: PK11SymKey is internally reference counted
151 scoped_ptr!(SymKey, PK11SymKey, PK11_FreeSymKey);
152 impl_clone!(SymKey, PK11_ReferenceSymKey);
153
154 impl SymKey {
155 /// You really don't want to use this.
156 ///
157 /// # Errors
158 /// Internal errors in case of failures in NSS.
159 pub fn key_data(&self) -> Res<&[u8]> {
160 secstatus_to_res(unsafe { PK11_ExtractKeyValue(**self) })?;
161
162 let key_item = unsafe { PK11_GetKeyData(**self) };
163 // This is accessing a value attached to the key, so we can treat this as a borrow.
164 match unsafe { key_item.as_mut() } {
165 None => Err(Error::InternalError),
166 Some(key) => Ok(unsafe { std::slice::from_raw_parts(key.data, key.len as usize) }),
167 }
168 }
169
170 pub fn as_bytes(&self) -> Res<&[u8]> {
171 self.key_data()
172 }
173 }
174
175 impl std::fmt::Debug for SymKey {
176 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
177 if let Ok(b) = self.key_data() {
178 write!(f, "SymKey {}", hex_with_len(b))
179 } else {
180 write!(f, "Opaque SymKey")
181 }
182 }
183 }
184
185 unsafe fn destroy_pk11_context(ctxt: *mut PK11Context) {
186 PK11_DestroyContext(ctxt, PRBool::from(true));
187 }
188 scoped_ptr!(Context, PK11Context, destroy_pk11_context);
189
190 /// Generate a randomized buffer.
191 /// # Panics
192 /// When `size` is too large or NSS fails.
193 #[must_use]
194 pub fn random(size: usize) -> Vec<u8> {
195 let mut buf = vec![0; size];
196 secstatus_to_res(unsafe {
197 PK11_GenerateRandom(buf.as_mut_ptr(), c_int::try_from(buf.len()).unwrap())
198 })
199 .unwrap();
200 buf
201 }
202
203 impl_into_result!(SECOidData);
204
205 #[cfg(test)]
206 mod test {
207 use super::random;
208 use test_fixture::fixture_init;
209
210 #[test]
211 fn randomness() {
212 fixture_init();
213 // If this ever fails, there is either a bug, or it's time to buy a lottery ticket.
214 assert_ne!(random(16), random(16));
215 }
216 }