Debian Codegraph @

third_party/rust/neqo-crypto/src/lib.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 mod aead;
8 #[cfg(feature = "disable-encryption")]
9 pub mod aead_null;
10 pub mod agent;
11 mod agentio;
12 mod auth;
13 mod cert;
14 pub mod constants;
15 mod ech;
16 mod err;
17 #[macro_use]
18 mod exp;
19 pub mod ext;
20 pub mod hkdf;
21 pub mod hp;
22 #[macro_use]
23 mod p11;
24 mod prio;
25 mod replay;
26 mod secrets;
27 pub mod selfencrypt;
28 mod ssl;
29 mod time;
30
31 use std::{env, ffi::CString, path::PathBuf, ptr::null, sync::OnceLock};
32
33 #[cfg(not(feature = "disable-encryption"))]
34 pub use self::aead::RealAead as Aead;
35 #[cfg(feature = "disable-encryption")]
36 pub use self::aead::RealAead;
37 #[cfg(feature = "disable-encryption")]
38 pub use self::aead_null::AeadNull as Aead;
39 pub use self::{
40 agent::{
41 Agent, AllowZeroRtt, Client, HandshakeState, Record, RecordList, ResumptionToken,
42 SecretAgent, SecretAgentInfo, SecretAgentPreInfo, Server, ZeroRttCheckResult,
43 ZeroRttChecker,
44 },
45 auth::AuthenticationStatus,
46 constants::*,
47 ech::{
48 encode_config as encode_ech_config, generate_keys as generate_ech_keys, AeadId, KdfId,
49 KemId, SymmetricSuite,
50 },
51 err::{Error, PRErrorCode, Res},
52 ext::{ExtensionHandler, ExtensionHandlerResult, ExtensionWriterResult},
53 p11::{random, randomize, PrivateKey, PublicKey, SymKey},
54 replay::AntiReplay,
55 secrets::SecretDirection,
56 ssl::Opt,
57 };
58
59 mod min_version;
60 use min_version::MINIMUM_NSS_VERSION;
61 use neqo_common::qerror;
62
63 #[expect(non_upper_case_globals, reason = "Code is bindgen-generated.")]
64 mod nss {
65 include!(concat!(env!("OUT_DIR"), "/nss_init.rs"));
66 }
67
68 // Need to map the types through.
69 fn secstatus_to_res(code: nss::SECStatus) -> Res<()> {
70 err::secstatus_to_res(code)
71 }
72
73 enum NssLoaded {
74 External,
75 NoDb,
76 Db,
77 }
78
79 impl Drop for NssLoaded {
80 fn drop(&mut self) {
81 if !matches!(self, Self::External) {
82 unsafe {
83 secstatus_to_res(nss::NSS_Shutdown()).expect("NSS Shutdown failed");
84 }
85 }
86 }
87 }
88
89 static INITIALIZED: OnceLock<Res<NssLoaded>> = OnceLock::new();
90
91 fn version_check() -> Res<()> {
92 let min_ver = CString::new(MINIMUM_NSS_VERSION)?;
93 if unsafe { nss::NSS_VersionCheck(min_ver.as_ptr()) } == 0 {
94 qerror!("Minimum NSS version of {MINIMUM_NSS_VERSION} not supported");
95 return Err(Error::UnsupportedVersion);
96 }
97 Ok(())
98 }
99
100 /// This enables SSLTRACE by calling a simple, harmless function to trigger its
101 /// side effects. SSLTRACE is not enabled in NSS until a socket is made or
102 /// global options are accessed. Reading an option is the least impact approach.
103 /// This allows us to use SSLTRACE in all of our unit tests and programs.
104 #[cfg(debug_assertions)]
105 fn enable_ssl_trace() -> Res<()> {
106 let opt = Opt::Locking.as_int();
107 let mut v: ::std::os::raw::c_int = 0;
108 secstatus_to_res(unsafe { ssl::SSL_OptionGetDefault(opt, &mut v) })
109 }
110
111 fn init_once(db: Option<PathBuf>) -> Res<NssLoaded> {
112 // Set time zero.
113 time::init();
114 version_check()?;
115 if unsafe { nss::NSS_IsInitialized() != 0 } {
116 return Ok(NssLoaded::External);
117 }
118
119 let state = if let Some(path) = db {
120 if !path.is_dir() {
121 return Err(Error::InternalError);
122 }
123 let pathstr = path.to_str().ok_or(Error::InternalError)?;
124 let dircstr = CString::new(pathstr)?;
125 let empty = CString::new("")?;
126 secstatus_to_res(unsafe {
127 nss::NSS_Initialize(
128 dircstr.as_ptr(),
129 empty.as_ptr(),
130 empty.as_ptr(),
131 nss::SECMOD_DB.as_ptr().cast(),
132 nss::NSS_INIT_READONLY,
133 )
134 })?;
135
136 secstatus_to_res(unsafe {
137 ssl::SSL_ConfigServerSessionIDCache(1024, 0, 0, dircstr.as_ptr())
138 })?;
139 NssLoaded::Db
140 } else {
141 secstatus_to_res(unsafe { nss::NSS_NoDB_Init(null()) })?;
142 NssLoaded::NoDb
143 };
144
145 secstatus_to_res(unsafe { nss::NSS_SetDomesticPolicy() })?;
146
147 #[cfg(debug_assertions)]
148 enable_ssl_trace()?;
149
150 Ok(state)
151 }
152
153 /// Initialize NSS. This only executes the initialization routines once, so if there is any chance
154 /// that this is invoked twice, that's OK.
155 ///
156 /// # Errors
157 ///
158 /// When NSS initialization fails.
159 pub fn init() -> Res<()> {
160 let res = INITIALIZED.get_or_init(|| init_once(None));
161 res.as_ref().map(|_| ()).map_err(Clone::clone)
162 }
163
164 /// Initialize with a database.
165 ///
166 /// # Errors
167 ///
168 /// If NSS cannot be initialized.
169 pub fn init_db<P: Into<PathBuf>>(dir: P) -> Res<()> {
170 // Allow overriding the NSS database path with an environment variable.
171 let dir = env::var("NSS_DB_PATH")
172 .unwrap_or(dir.into().to_str().ok_or(Error::InternalError)?.to_string());
173 let res = INITIALIZED.get_or_init(|| init_once(Some(dir.into())));
174 res.as_ref().map(|_| ()).map_err(Clone::clone)
175 }
176
177 /// # Panics
178 ///
179 /// If NSS isn't initialized.
180 pub fn assert_initialized() {
181 INITIALIZED
182 .get()
183 .expect("NSS not initialized with init or init_db");
184 }
185
186 /// NSS tends to return empty "slices" with a null pointer, which will cause
187 /// `std::slice::from_raw_parts` to panic if passed directly. This wrapper avoids
188 /// that issue. It also performs conversion for lengths, as a convenience.
189 ///
190 /// # Panics
191 /// If the provided length doesn't fit into a `usize`.
192 ///
193 /// # Safety
194 /// The caller must adhere to the safety constraints of `std::slice::from_raw_parts`,
195 /// except that this will accept a null value for `data`.
196 unsafe fn null_safe_slice<'a, T, L>(data: *const T, len: L) -> &'a [T]
197 where
198 usize: TryFrom<L>,
199 {
200 let len = usize::try_from(len).unwrap_or_else(|_| panic!("null_safe_slice: size overflow"));
201 if data.is_null() || len == 0 {
202 &[]
203 } else {
204 #[expect(clippy::disallowed_methods, reason = "This is non-null.")]
205 std::slice::from_raw_parts(data, len)
206 }
207 }