Debian Codegraph @

third_party/rust/neqo-crypto/src/agent.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 #![expect(
12 clippy::unwrap_used,
13 reason = "Let's assume the use of `unwrap` was checked when the use of `unsafe` was reviewed."
14 )]
15
16 use std::{
17 cell::RefCell,
18 ffi::{CStr, CString},
19 fmt::{self, Debug, Display, Formatter},
20 mem::MaybeUninit,
21 ops::{Deref, DerefMut},
22 os::raw::{c_uint, c_void},
23 pin::Pin,
24 ptr::{null, null_mut},
25 rc::Rc,
26 time::Instant,
27 };
28
29 use neqo_common::{hex_snip_middle, hex_with_len, qdebug, qtrace, qwarn};
30
31 pub use crate::{
32 agentio::{as_c_void, Record, RecordList},
33 cert::CertificateInfo,
34 };
35 use crate::{
36 agentio::{AgentIo, METHODS},
37 assert_initialized,
38 auth::AuthenticationStatus,
39 constants::{
40 Alert, Cipher, Epoch, Extension, Group, SignatureScheme, Version, TLS_VERSION_1_3,
41 },
42 ech,
43 err::{is_blocked, secstatus_to_res, Error, PRErrorCode, Res},
44 ext::{ExtensionHandler, ExtensionTracker},
45 null_safe_slice,
46 p11::{self, PrivateKey, PublicKey},
47 prio,
48 replay::AntiReplay,
49 secrets::SecretHolder,
50 ssl::{self, PRBool},
51 time::{Time, TimeHolder},
52 };
53
54 /// The maximum number of tickets to remember for a given connection.
55 const MAX_TICKETS: usize = 4;
56
57 #[derive(Clone, Debug, PartialEq, Eq)]
58 pub enum HandshakeState {
59 New,
60 InProgress,
61 AuthenticationPending,
62 /// When encrypted client hello is enabled, the server might engage a fallback.
63 /// This is the status that is returned. The included value is the public
64 /// name of the server, which should be used to validated the certificate.
65 EchFallbackAuthenticationPending(String),
66 Authenticated(PRErrorCode),
67 Complete(SecretAgentInfo),
68 Failed(Error),
69 }
70
71 impl HandshakeState {
72 #[must_use]
73 pub const fn is_connected(&self) -> bool {
74 matches!(self, Self::Complete(_))
75 }
76
77 #[must_use]
78 pub const fn is_final(&self) -> bool {
79 matches!(self, Self::Complete(_) | Self::Failed(_))
80 }
81
82 #[must_use]
83 pub const fn authentication_needed(&self) -> bool {
84 matches!(
85 self,
86 Self::AuthenticationPending | Self::EchFallbackAuthenticationPending(_)
87 )
88 }
89 }
90
91 fn get_alpn(fd: *mut ssl::PRFileDesc, pre: bool) -> Res<Option<String>> {
92 let mut alpn_state = ssl::SSLNextProtoState::SSL_NEXT_PROTO_NO_SUPPORT;
93 let mut chosen = vec![0_u8; 255];
94 let mut chosen_len: c_uint = 0;
95 secstatus_to_res(unsafe {
96 ssl::SSL_GetNextProto(
97 fd,
98 &mut alpn_state,
99 chosen.as_mut_ptr(),
100 &mut chosen_len,
101 c_uint::try_from(chosen.len())?,
102 )
103 })?;
104
105 let alpn = match (pre, alpn_state) {
106 (true, ssl::SSLNextProtoState::SSL_NEXT_PROTO_EARLY_VALUE)
107 | (
108 false,
109 ssl::SSLNextProtoState::SSL_NEXT_PROTO_NEGOTIATED
110 | ssl::SSLNextProtoState::SSL_NEXT_PROTO_SELECTED,
111 ) => {
112 chosen.truncate(usize::try_from(chosen_len)?);
113 Some(match String::from_utf8(chosen) {
114 Ok(a) => a,
115 Err(_) => return Err(Error::InternalError),
116 })
117 }
118 _ => None,
119 };
120 qtrace!("[{fd:p}] got ALPN {alpn:?}");
121 Ok(alpn)
122 }
123
124 pub struct SecretAgentPreInfo {
125 info: ssl::SSLPreliminaryChannelInfo,
126 alpn: Option<String>,
127 }
128
129 macro_rules! preinfo_arg {
130 ($v:ident, $m:ident, $f:ident: $t:ty $(,)?) => {
131 #[must_use]
132 pub fn $v(&self) -> Option<$t> {
133 match self.info.valuesSet & ssl::$m {
134 0 => None,
135 _ => Some(
136 <$t>::try_from(self.info.$f)
137 .inspect_err(|e| qdebug!("Invalid value in preinfo: {e:?}"))
138 .ok()?,
139 ),
140 }
141 }
142 };
143 }
144
145 impl SecretAgentPreInfo {
146 fn new(fd: *mut ssl::PRFileDesc) -> Res<Self> {
147 let mut info: MaybeUninit<ssl::SSLPreliminaryChannelInfo> = MaybeUninit::uninit();
148 secstatus_to_res(unsafe {
149 ssl::SSL_GetPreliminaryChannelInfo(
150 fd,
151 info.as_mut_ptr(),
152 c_uint::try_from(size_of::<ssl::SSLPreliminaryChannelInfo>())?,
153 )
154 })?;
155
156 Ok(Self {
157 info: unsafe { info.assume_init() },
158 alpn: get_alpn(fd, true)?,
159 })
160 }
161
162 preinfo_arg!(version, ssl_preinfo_version, protocolVersion: Version);
163 preinfo_arg!(cipher_suite, ssl_preinfo_cipher_suite, cipherSuite: Cipher);
164 preinfo_arg!(
165 early_data_cipher,
166 ssl_preinfo_0rtt_cipher_suite,
167 zeroRttCipherSuite: Cipher,
168 );
169
170 #[must_use]
171 pub const fn early_data(&self) -> bool {
172 self.info.canSendEarlyData != 0
173 }
174
175 /// # Errors
176 ///
177 /// If `usize` is less than 32 bits and the value is too large.
178 pub fn max_early_data(&self) -> Res<usize> {
179 Ok(usize::try_from(self.info.maxEarlyDataSize)?)
180 }
181
182 /// Was ECH accepted.
183 #[must_use]
184 pub const fn ech_accepted(&self) -> Option<bool> {
185 if self.info.valuesSet & ssl::ssl_preinfo_ech == 0 {
186 None
187 } else {
188 Some(self.info.echAccepted != 0)
189 }
190 }
191
192 /// Get the ECH public name that was used. This will only be available
193 /// (that is, not `None`) if `ech_accepted()` returns `false`.
194 /// In this case, certificate validation needs to use this name rather
195 /// than the original name to validate the certificate. If
196 /// that validation passes (that is, `SecretAgent::authenticated` is called
197 /// with `AuthenticationStatus::Ok`), then the handshake will still fail.
198 /// After the failed handshake, the state will be `Error::EchRetry`,
199 /// which contains a valid ECH configuration.
200 ///
201 /// # Errors
202 ///
203 /// When the public name is not valid UTF-8. (Note: names should be ASCII.)
204 pub fn ech_public_name(&self) -> Res<Option<&str>> {
205 if self.info.valuesSet & ssl::ssl_preinfo_ech == 0 || self.info.echPublicName.is_null() {
206 Ok(None)
207 } else {
208 let n = unsafe { CStr::from_ptr(self.info.echPublicName) };
209 Ok(Some(n.to_str()?))
210 }
211 }
212
213 #[must_use]
214 pub const fn alpn(&self) -> Option<&String> {
215 self.alpn.as_ref()
216 }
217 }
218
219 #[derive(Clone, Debug, Default, PartialEq, Eq)]
220 pub struct SecretAgentInfo {
221 version: Version,
222 cipher: Cipher,
223 group: Group,
224 resumed: bool,
225 early_data: bool,
226 ech_accepted: bool,
227 alpn: Option<String>,
228 signature_scheme: SignatureScheme,
229 }
230
231 impl SecretAgentInfo {
232 fn new(fd: *mut ssl::PRFileDesc) -> Res<Self> {
233 let mut info: MaybeUninit<ssl::SSLChannelInfo> = MaybeUninit::uninit();
234 secstatus_to_res(unsafe {
235 ssl::SSL_GetChannelInfo(
236 fd,
237 info.as_mut_ptr(),
238 c_uint::try_from(size_of::<ssl::SSLChannelInfo>())?,
239 )
240 })?;
241 let info = unsafe { info.assume_init() };
242 Ok(Self {
243 version: info.protocolVersion,
244 cipher: info.cipherSuite,
245 group: Group::try_from(info.keaGroup)?,
246 resumed: info.resumed != 0,
247 early_data: info.earlyDataAccepted != 0,
248 ech_accepted: info.echAccepted != 0,
249 alpn: get_alpn(fd, false)?,
250 signature_scheme: SignatureScheme::try_from(info.signatureScheme)?,
251 })
252 }
253 #[must_use]
254 pub const fn version(&self) -> Version {
255 self.version
256 }
257 #[must_use]
258 pub const fn cipher_suite(&self) -> Cipher {
259 self.cipher
260 }
261 #[must_use]
262 pub const fn key_exchange(&self) -> Group {
263 self.group
264 }
265 #[must_use]
266 pub const fn resumed(&self) -> bool {
267 self.resumed
268 }
269 #[must_use]
270 pub const fn early_data_accepted(&self) -> bool {
271 self.early_data
272 }
273 #[must_use]
274 pub const fn ech_accepted(&self) -> bool {
275 self.ech_accepted
276 }
277 #[must_use]
278 pub const fn alpn(&self) -> Option<&String> {
279 self.alpn.as_ref()
280 }
281 #[must_use]
282 pub const fn signature_scheme(&self) -> SignatureScheme {
283 self.signature_scheme
284 }
285 }
286
287 /// `SecretAgent` holds the common parts of client and server.
288 #[derive(Debug)]
289 pub struct SecretAgent {
290 fd: *mut ssl::PRFileDesc,
291 secrets: SecretHolder,
292 raw: Option<bool>,
293 io: Pin<Box<AgentIo>>,
294 state: HandshakeState,
295
296 /// Records whether authentication of certificates is required.
297 auth_required: Pin<Box<bool>>,
298 /// Records any fatal alert that is sent by the stack.
299 alert: Pin<Box<Option<Alert>>>,
300 /// The current time.
301 now: TimeHolder,
302
303 extension_handlers: Vec<ExtensionTracker>,
304
305 /// The encrypted client hello (ECH) configuration that is in use.
306 /// Empty if ECH is not enabled.
307 ech_config: Vec<u8>,
308 }
309
310 impl SecretAgent {
311 fn new() -> Res<Self> {
312 let mut io = Box::pin(AgentIo::new());
313 let fd = Self::create_fd(&mut io)?;
314 Ok(Self {
315 fd,
316 secrets: SecretHolder::default(),
317 raw: None,
318 io,
319 state: HandshakeState::New,
320
321 auth_required: Box::pin(false),
322 alert: Box::pin(None),
323 now: TimeHolder::default(),
324
325 extension_handlers: Vec::new(),
326
327 ech_config: Vec::new(),
328 })
329 }
330
331 // Create a new SSL file descriptor.
332 //
333 // Note that we create separate bindings for PRFileDesc as both
334 // ssl::PRFileDesc and prio::PRFileDesc. This keeps the bindings
335 // minimal, but it means that the two forms need casts to translate
336 // between them. ssl::PRFileDesc is left as an opaque type, as the
337 // ssl::SSL_* APIs only need an opaque type.
338 fn create_fd(io: &mut Pin<Box<AgentIo>>) -> Res<*mut ssl::PRFileDesc> {
339 assert_initialized();
340 let label = CString::new("sslwrapper")?;
341 let id = unsafe { prio::PR_GetUniqueIdentity(label.as_ptr()) };
342
343 let base_fd = unsafe { prio::PR_CreateIOLayerStub(id, METHODS) };
344 if base_fd.is_null() {
345 return Err(Error::CreateSslSocket);
346 }
347 let fd = unsafe {
348 (*base_fd).secret = as_c_void(io).cast();
349 ssl::SSL_ImportFD(null_mut(), base_fd.cast())
350 };
351 if fd.is_null() {
352 unsafe {
353 prio::PR_Close(base_fd);
354 }
355 return Err(Error::CreateSslSocket);
356 }
357 Ok(fd)
358 }
359
360 unsafe extern "C" fn auth_complete_hook(
361 arg: *mut c_void,
362 _fd: *mut ssl::PRFileDesc,
363 _check_sig: PRBool,
364 _is_server: PRBool,
365 ) -> ssl::SECStatus {
366 let auth_required_ptr = arg.cast::<bool>();
367 *auth_required_ptr = true;
368 // NSS insists on getting SECWouldBlock here rather than accepting
369 // the usual combination of PR_WOULD_BLOCK_ERROR and SECFailure.
370 ssl::_SECStatus_SECWouldBlock
371 }
372
373 unsafe extern "C" fn alert_sent_cb(
374 fd: *const ssl::PRFileDesc,
375 arg: *mut c_void,
376 alert: *const ssl::SSLAlert,
377 ) {
378 let alert = alert.as_ref().unwrap();
379 if alert.level == 2 {
380 // Fatal alerts demand attention.
381 let st = arg.cast::<Option<Alert>>().as_mut().unwrap();
382 if st.is_none() {
383 *st = Some(alert.description);
384 } else {
385 qwarn!("[{fd:p}] duplicate alert {}", alert.description);
386 }
387 }
388 }
389
390 // Ready this for connecting.
391 fn ready(&mut self, is_server: bool, grease: bool) -> Res<()> {
392 secstatus_to_res(unsafe {
393 ssl::SSL_AuthCertificateHook(
394 self.fd,
395 Some(Self::auth_complete_hook),
396 as_c_void(&mut self.auth_required),
397 )
398 })?;
399
400 secstatus_to_res(unsafe {
401 ssl::SSL_AlertSentCallback(
402 self.fd,
403 Some(Self::alert_sent_cb),
404 as_c_void(&mut self.alert),
405 )
406 })?;
407
408 self.now.bind(self.fd)?;
409 self.configure(grease)?;
410 secstatus_to_res(unsafe { ssl::SSL_ResetHandshake(self.fd, PRBool::from(is_server)) })
411 }
412
413 /// Default configuration.
414 ///
415 /// # Errors
416 ///
417 /// If `set_version_range` fails.
418 fn configure(&mut self, grease: bool) -> Res<()> {
419 self.set_version_range(TLS_VERSION_1_3, TLS_VERSION_1_3)?;
420 self.set_option(ssl::Opt::Locking, false)?;
421 self.set_option(ssl::Opt::Tickets, false)?;
422 self.set_option(ssl::Opt::OcspStapling, true)?;
423 self.set_option(ssl::Opt::Grease, grease)?;
424 self.set_option(ssl::Opt::EnableChExtensionPermutation, true)?;
425 Ok(())
426 }
427
428 /// Set the versions that are supported.
429 ///
430 /// # Errors
431 ///
432 /// If the range of versions isn't supported.
433 pub fn set_version_range(&mut self, min: Version, max: Version) -> Res<()> {
434 let range = ssl::SSLVersionRange { min, max };
435 secstatus_to_res(unsafe { ssl::SSL_VersionRangeSet(self.fd, &range) })
436 }
437
438 /// Enable a set of ciphers. Note that the order of these is not respected.
439 ///
440 /// # Errors
441 ///
442 /// If NSS can't enable or disable ciphers.
443 pub fn set_ciphers(&mut self, ciphers: &[Cipher]) -> Res<()> {
444 if self.state != HandshakeState::New {
445 qwarn!("[{self}] Cannot enable ciphers in state {:?}", self.state);
446 return Err(Error::InternalError);
447 }
448
449 let all_ciphers = unsafe { ssl::SSL_GetImplementedCiphers() };
450 let cipher_count = usize::from(unsafe { ssl::SSL_GetNumImplementedCiphers() });
451 for i in 0..cipher_count {
452 let p = all_ciphers.wrapping_add(i);
453 secstatus_to_res(unsafe {
454 ssl::SSL_CipherPrefSet(self.fd, i32::from(*p), PRBool::from(false))
455 })?;
456 }
457
458 for c in ciphers {
459 secstatus_to_res(unsafe {
460 ssl::SSL_CipherPrefSet(self.fd, i32::from(*c), PRBool::from(true))
461 })?;
462 }
463 Ok(())
464 }
465
466 /// Set key exchange groups.
467 ///
468 /// # Errors
469 ///
470 /// If the underlying API fails (which shouldn't happen).
471 pub fn set_groups(&mut self, groups: &[Group]) -> Res<()> {
472 // SSLNamedGroup is a different size to Group, so copy one by one.
473 let group_vec: Vec<_> = groups
474 .iter()
475 .map(|&g| ssl::SSLNamedGroup::Type::from(g))
476 .collect();
477
478 let ptr = group_vec.as_slice().as_ptr();
479 secstatus_to_res(unsafe {
480 ssl::SSL_NamedGroupConfig(self.fd, ptr, c_uint::try_from(group_vec.len())?)
481 })
482 }
483
484 /// Set the number of additional key shares that will be sent in the client hello
485 ///
486 /// # Errors
487 ///
488 /// If the underlying API fails (which shouldn't happen).
489 pub fn send_additional_key_shares(&mut self, count: usize) -> Res<()> {
490 secstatus_to_res(unsafe {
491 ssl::SSL_SendAdditionalKeyShares(self.fd, c_uint::try_from(count)?)
492 })
493 }
494
495 /// Set TLS options.
496 ///
497 /// # Errors
498 ///
499 /// Returns an error if the option or option value is invalid; i.e., never.
500 pub fn set_option(&self, opt: ssl::Opt, value: bool) -> Res<()> {
501 opt.set(self.fd, value)
502 }
503
504 /// Enable 0-RTT.
505 ///
506 /// # Errors
507 ///
508 /// See `set_option`.
509 pub fn enable_0rtt(&self) -> Res<()> {
510 self.set_option(ssl::Opt::EarlyData, true)
511 }
512
513 /// Disable the `EndOfEarlyData` message.
514 ///
515 /// # Errors
516 ///
517 /// See `set_option`.
518 pub fn disable_end_of_early_data(&self) -> Res<()> {
519 self.set_option(ssl::Opt::SuppressEndOfEarlyData, true)
520 }
521
522 /// `set_alpn` sets a list of preferred protocols, starting with the most preferred.
523 /// Though ALPN [RFC7301] permits octet sequences, this only allows for UTF-8-encoded
524 /// strings.
525 ///
526 /// This asserts if no items are provided, or if any individual item is longer than
527 /// 255 octets in length.
528 ///
529 /// # Errors
530 ///
531 /// This should always panic rather than return an error.
532 ///
533 /// # Panics
534 ///
535 /// If any of the provided `protocols` are more than 255 bytes long.
536 ///
537 /// [RFC7301]: https://datatracker.ietf.org/doc/html/rfc7301
538 pub fn set_alpn(&mut self, protocols: &[impl AsRef<str>]) -> Res<()> {
539 // Validate and set length.
540 let mut encoded_len = protocols.len();
541 for v in protocols {
542 assert!(v.as_ref().len() < 256);
543 assert!(!v.as_ref().is_empty());
544 encoded_len += v.as_ref().len();
545 }
546
547 // Prepare to encode.
548 let mut encoded = Vec::with_capacity(encoded_len);
549 let mut add = |v: &str| {
550 if let Ok(s) = u8::try_from(v.len()) {
551 encoded.push(s);
552 encoded.extend_from_slice(v.as_bytes());
553 }
554 };
555
556 // NSS inherited an idiosyncratic API as a result of having implemented NPN
557 // before ALPN. For that reason, we need to put the "best" option last.
558 let (first, rest) = protocols.split_first().ok_or(Error::InternalError)?;
559 for v in rest {
560 add(v.as_ref());
561 }
562 add(first.as_ref());
563 assert_eq!(encoded_len, encoded.len());
564
565 // Now give the result to NSS.
566 secstatus_to_res(unsafe {
567 ssl::SSL_SetNextProtoNego(
568 self.fd,
569 encoded.as_slice().as_ptr(),
570 c_uint::try_from(encoded.len())?,
571 )
572 })
573 }
574
575 /// Install an extension handler.
576 ///
577 /// This can be called multiple times with different values for `ext`. The handler is provided
578 /// as `Rc<RefCell<dyn T>>` so that the caller is able to hold a reference to the handler
579 /// and later access any state that it accumulates.
580 ///
581 /// # Errors
582 ///
583 /// When the extension handler can't be successfully installed.
584 pub fn extension_handler(
585 &mut self,
586 ext: Extension,
587 handler: Rc<RefCell<dyn ExtensionHandler>>,
588 ) -> Res<()> {
589 let tracker = unsafe { ExtensionTracker::new(self.fd, ext, handler) }?;
590 self.extension_handlers.push(tracker);
591 Ok(())
592 }
593
594 // This function tracks whether handshake() or handshake_raw() was used
595 // and prevents the other from being used.
596 fn set_raw(&mut self, r: bool) -> Res<()> {
597 if let Some(raw) = self.raw {
598 if raw == r {
599 Ok(())
600 } else {
601 Err(Error::MixedHandshakeMethod)
602 }
603 } else {
604 self.secrets.register(self.fd)?;
605 self.raw = Some(r);
606 Ok(())
607 }
608 }
609
610 /// Get information about the connection.
611 /// This includes the version, ciphersuite, and ALPN.
612 ///
613 /// Calling this function returns None until the connection is complete.
614 #[must_use]
615 pub const fn info(&self) -> Option<&SecretAgentInfo> {
616 match &self.state {
617 HandshakeState::Complete(info) => Some(info),
618 _ => None,
619 }
620 }
621
622 /// Get any preliminary information about the status of the connection.
623 ///
624 /// This includes whether 0-RTT was accepted and any information related to that.
625 /// Calling this function collects all the relevant information.
626 ///
627 /// # Errors
628 ///
629 /// When the underlying socket functions fail.
630 pub fn preinfo(&self) -> Res<SecretAgentPreInfo> {
631 SecretAgentPreInfo::new(self.fd)
632 }
633
634 /// Get the peer's certificate chain.
635 #[must_use]
636 pub fn peer_certificate(&self) -> Option<CertificateInfo> {
637 CertificateInfo::new(self.fd)
638 }
639
640 /// Return any fatal alert that the TLS stack might have sent.
641 #[must_use]
642 pub fn alert(&self) -> Option<&Alert> {
643 (*self.alert).as_ref()
644 }
645
646 /// Call this function to mark the peer as authenticated.
647 ///
648 /// # Panics
649 ///
650 /// If the handshake doesn't need to be authenticated.
651 pub fn authenticated(&mut self, status: AuthenticationStatus) {
652 assert!(self.state.authentication_needed());
653 *self.auth_required = false;
654 self.state = HandshakeState::Authenticated(status.into());
655 }
656
657 fn capture_error<T>(&mut self, res: Res<T>) -> Res<T> {
658 if let Err(e) = res {
659 let e = ech::convert_ech_error(self.fd, e);
660 qwarn!("[{self}] error: {e:?}");
661 self.state = HandshakeState::Failed(e.clone());
662 Err(e)
663 } else {
664 res
665 }
666 }
667
668 fn update_state(&mut self, res: Res<()>) -> Res<()> {
669 self.state = if is_blocked(&res) {
670 if *self.auth_required {
671 self.preinfo()?.ech_public_name()?.map_or(
672 HandshakeState::AuthenticationPending,
673 |public_name| {
674 HandshakeState::EchFallbackAuthenticationPending(public_name.to_owned())
675 },
676 )
677 } else {
678 HandshakeState::InProgress
679 }
680 } else {
681 self.capture_error(res)?;
682 let info = self.capture_error(SecretAgentInfo::new(self.fd))?;
683 HandshakeState::Complete(info)
684 };
685 qdebug!("[{self}] state -> {:?}", self.state);
686 Ok(())
687 }
688
689 /// Drive the TLS handshake, taking bytes from `input` and putting
690 /// any bytes necessary into `output`.
691 /// This takes the current time as `now`.
692 /// On success a tuple of a `HandshakeState` and usize indicate whether the handshake
693 /// is complete and how many bytes were written to `output`, respectively.
694 /// If the state is `HandshakeState::AuthenticationPending`, then ONLY call this
695 /// function if you want to proceed, because this will mark the certificate as OK.
696 ///
697 /// # Errors
698 ///
699 /// When the handshake fails this returns an error.
700 pub fn handshake(&mut self, now: Instant, input: &[u8]) -> Res<Vec<u8>> {
701 self.now.set(now)?;
702 self.set_raw(false)?;
703
704 let rv = {
705 // Within this scope, _h maintains a mutable reference to self.io.
706 let _h = self.io.wrap(input);
707 match self.state {
708 HandshakeState::Authenticated(err) => unsafe {
709 ssl::SSL_AuthCertificateComplete(self.fd, err)
710 },
711 _ => unsafe { ssl::SSL_ForceHandshake(self.fd) },
712 }
713 };
714 // Take before updating state so that we leave the output buffer empty
715 // even if there is an error.
716 let output = self.io.take_output();
717 self.update_state(secstatus_to_res(rv))?;
718 Ok(output)
719 }
720
721 /// Setup to receive records for raw handshake functions.
722 fn setup_raw(&mut self) -> Res<Pin<Box<RecordList>>> {
723 self.set_raw(true)?;
724 self.capture_error(RecordList::setup(self.fd))
725 }
726
727 /// Drive the TLS handshake, but get the raw content of records, not
728 /// protected records as bytes. This function is incompatible with
729 /// `handshake()`; use either this or `handshake()` exclusively.
730 ///
731 /// Ideally, this only includes records from the current epoch.
732 /// If you send data from multiple epochs, you might end up being sad.
733 ///
734 /// # Errors
735 ///
736 /// When the handshake fails this returns an error.
737 pub fn handshake_raw(&mut self, now: Instant, input: Option<Record>) -> Res<RecordList> {
738 self.now.set(now)?;
739 let records = self.setup_raw()?;
740
741 // Fire off any authentication we might need to complete.
742 if let HandshakeState::Authenticated(err) = self.state {
743 let result =
744 secstatus_to_res(unsafe { ssl::SSL_AuthCertificateComplete(self.fd, err) });
745 qdebug!("[{self}] SSL_AuthCertificateComplete: {result:?}");
746 // This should return SECSuccess, so don't use update_state().
747 self.capture_error(result)?;
748 }
749
750 // Feed in any records.
751 if let Some(rec) = input {
752 self.capture_error(rec.write(self.fd))?;
753 }
754
755 // Drive the handshake once more.
756 let rv = secstatus_to_res(unsafe { ssl::SSL_ForceHandshake(self.fd) });
757 self.update_state(rv)?;
758
759 Ok(*Pin::into_inner(records))
760 }
761
762 /// # Panics
763 ///
764 /// If setup fails.
765 pub fn close(&mut self) {
766 // It should be safe to close multiple times.
767 if self.fd.is_null() {
768 return;
769 }
770 #[expect(
771 clippy::branches_sharing_code,
772 reason = "Moving the PR_Close call after the conditional crashes things?!"
773 )]
774 if self.raw == Some(true) {
775 // Need to hold the record list in scope until the close is done.
776 let _records = self.setup_raw().expect("Can only close");
777 unsafe {
778 prio::PR_Close(self.fd.cast());
779 }
780 } else {
781 // Need to hold the IO wrapper in scope until the close is done.
782 let _io = self.io.wrap(&[]);
783 unsafe {
784 prio::PR_Close(self.fd.cast());
785 }
786 }
787 let _output = self.io.take_output();
788 self.fd = null_mut();
789 }
790
791 /// State returns the status of the handshake.
792 #[must_use]
793 pub const fn state(&self) -> &HandshakeState {
794 &self.state
795 }
796
797 /// Take a read secret. This will only return a non-`None` value once.
798 #[must_use]
799 pub fn read_secret(&mut self, epoch: Epoch) -> Option<p11::SymKey> {
800 self.secrets.take_read(epoch)
801 }
802
803 /// Take a write secret.
804 #[must_use]
805 pub fn write_secret(&mut self, epoch: Epoch) -> Option<p11::SymKey> {
806 self.secrets.take_write(epoch)
807 }
808
809 /// Get the active ECH configuration, which is empty if ECH is disabled.
810 #[must_use]
811 pub fn ech_config(&self) -> &[u8] {
812 &self.ech_config
813 }
814 }
815
816 impl Drop for SecretAgent {
817 fn drop(&mut self) {
818 self.close();
819 }
820 }
821
822 impl Display for SecretAgent {
823 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
824 write!(f, "Agent {:p}", self.fd)
825 }
826 }
827
828 #[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone)]
829 pub struct ResumptionToken {
830 token: Vec<u8>,
831 expiration_time: Instant,
832 }
833
834 impl AsRef<[u8]> for ResumptionToken {
835 fn as_ref(&self) -> &[u8] {
836 &self.token
837 }
838 }
839
840 impl ResumptionToken {
841 #[must_use]
842 pub const fn new(token: Vec<u8>, expiration_time: Instant) -> Self {
843 Self {
844 token,
845 expiration_time,
846 }
847 }
848
849 #[must_use]
850 pub const fn expiration_time(&self) -> Instant {
851 self.expiration_time
852 }
853 }
854
855 /// A TLS Client.
856 #[derive(Debug)]
857 pub struct Client {
858 agent: SecretAgent,
859
860 /// The name of the server we're attempting a connection to.
861 server_name: String,
862 /// Records the resumption tokens we've received.
863 #[expect(clippy::box_collection, reason = "We need the Box.")]
864 resumption: Pin<Box<Vec<ResumptionToken>>>,
865 }
866
867 impl Client {
868 /// Create a new client agent.
869 ///
870 /// # Errors
871 ///
872 /// Errors returned if the socket can't be created or configured.
873 pub fn new(server_name: impl Into<String>, grease: bool) -> Res<Self> {
874 let server_name = server_name.into();
875 let mut agent = SecretAgent::new()?;
876 let url = CString::new(server_name.as_bytes())?;
877 secstatus_to_res(unsafe { ssl::SSL_SetURL(agent.fd, url.as_ptr()) })?;
878 agent.ready(false, grease)?;
879 let mut client = Self {
880 agent,
881 server_name,
882 resumption: Box::pin(Vec::new()),
883 };
884 client.ready()?;
885 Ok(client)
886 }
887
888 unsafe extern "C" fn resumption_token_cb(
889 fd: *mut ssl::PRFileDesc,
890 token: *const u8,
891 len: c_uint,
892 arg: *mut c_void,
893 ) -> ssl::SECStatus {
894 let mut info: MaybeUninit<ssl::SSLResumptionTokenInfo> = MaybeUninit::uninit();
895 let Ok(info_len) = c_uint::try_from(size_of::<ssl::SSLResumptionTokenInfo>()) else {
896 return ssl::SECFailure;
897 };
898 let info_res = &ssl::SSL_GetResumptionTokenInfo(token, len, info.as_mut_ptr(), info_len);
899 if info_res.is_err() {
900 // Ignore the token.
901 return ssl::SECSuccess;
902 }
903 let expiration_time = info.assume_init().expirationTime;
904 if ssl::SSL_DestroyResumptionTokenInfo(info.as_mut_ptr()).is_err() {
905 // Ignore the token.
906 return ssl::SECSuccess;
907 }
908 let Some(resumption) = arg.cast::<Vec<ResumptionToken>>().as_mut() else {
909 return ssl::SECFailure;
910 };
911 let Ok(len) = usize::try_from(len) else {
912 return ssl::SECFailure;
913 };
914 let mut v = Vec::with_capacity(len);
915 v.extend_from_slice(null_safe_slice(token, len));
916 qdebug!("[{fd:p}] Got resumption token {}", hex_snip_middle(&v));
917
918 if resumption.len() >= MAX_TICKETS {
919 resumption.remove(0);
920 }
921 if let Ok(t) = Time::try_from(expiration_time) {
922 resumption.push(ResumptionToken::new(v, *t));
923 }
924 ssl::SECSuccess
925 }
926
927 #[must_use]
928 pub fn server_name(&self) -> &str {
929 &self.server_name
930 }
931
932 fn ready(&mut self) -> Res<()> {
933 let fd = self.fd;
934 unsafe {
935 ssl::SSL_SetResumptionTokenCallback(
936 fd,
937 Some(Self::resumption_token_cb),
938 as_c_void(&mut self.resumption),
939 )
940 }
941 }
942
943 /// Take a resumption token.
944 #[must_use]
945 pub fn resumption_token(&mut self) -> Option<ResumptionToken> {
946 (*self.resumption).pop()
947 }
948
949 /// Check if there are more resumption tokens.
950 #[must_use]
951 pub fn has_resumption_token(&self) -> bool {
952 !(*self.resumption).is_empty()
953 }
954
955 /// Enable resumption, using a token previously provided.
956 ///
957 /// # Errors
958 ///
959 /// Error returned when the resumption token is invalid or
960 /// the socket is not able to use the value.
961 pub fn enable_resumption(&mut self, token: impl AsRef<[u8]>) -> Res<()> {
962 unsafe {
963 ssl::SSL_SetResumptionToken(
964 self.agent.fd,
965 token.as_ref().as_ptr(),
966 c_uint::try_from(token.as_ref().len())?,
967 )
968 }
969 }
970
971 /// Enable encrypted client hello (ECH), using the encoded `ECHConfigList`.
972 ///
973 /// When ECH is enabled, a client needs to look for `Error::EchRetry` as a
974 /// failure code. If `Error::EchRetry` is received when connecting, the
975 /// connection attempt should be retried and the included value provided
976 /// to this function (instead of what is received from DNS).
977 ///
978 /// Calling this function with an empty value for `ech_config_list` enables
979 /// ECH greasing. When that is done, there is no need to look for `EchRetry`
980 ///
981 /// # Errors
982 ///
983 /// Error returned when the configuration is invalid.
984 pub fn enable_ech(&mut self, ech_config_list: impl AsRef<[u8]>) -> Res<()> {
985 let config = ech_config_list.as_ref();
986 qdebug!("[{self}] Enable ECH for a server: {}", hex_with_len(config));
987 self.ech_config = Vec::from(config);
988 if config.is_empty() {
989 unsafe { ech::SSL_EnableTls13GreaseEch(self.agent.fd, PRBool::from(true)) }
990 } else {
991 unsafe {
992 ech::SSL_SetClientEchConfigs(
993 self.agent.fd,
994 config.as_ptr(),
995 c_uint::try_from(config.len())?,
996 )
997 }
998 }
999 }
1000 }
1001
1002 impl Deref for Client {
1003 type Target = SecretAgent;
1004 fn deref(&self) -> &SecretAgent {
1005 &self.agent
1006 }
1007 }
1008
1009 impl DerefMut for Client {
1010 fn deref_mut(&mut self) -> &mut SecretAgent {
1011 &mut self.agent
1012 }
1013 }
1014
1015 impl Display for Client {
1016 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1017 write!(f, "Client {:p}", self.agent.fd)
1018 }
1019 }
1020
1021 /// `ZeroRttCheckResult` encapsulates the options for handling a `ClientHello`.
1022 #[derive(Clone, Debug, PartialEq, Eq)]
1023 pub enum ZeroRttCheckResult {
1024 /// Accept 0-RTT.
1025 Accept,
1026 /// Reject 0-RTT, but continue the handshake normally.
1027 Reject,
1028 /// Send `HelloRetryRequest` (probably not needed for QUIC).
1029 HelloRetryRequest(Vec<u8>),
1030 /// Fail the handshake.
1031 Fail,
1032 }
1033
1034 /// A `ZeroRttChecker` is used by the agent to validate the application token (as provided by
1035 /// `send_ticket`)
1036 pub trait ZeroRttChecker: Debug + Unpin {
1037 fn check(&self, token: &[u8]) -> ZeroRttCheckResult;
1038 }
1039
1040 /// Using `AllowZeroRtt` for the implementation of `ZeroRttChecker` means
1041 /// accepting 0-RTT always. This generally isn't a great idea, so this
1042 /// generates a strong warning when it is used.
1043 #[derive(Debug)]
1044 pub struct AllowZeroRtt {}
1045 impl ZeroRttChecker for AllowZeroRtt {
1046 fn check(&self, _token: &[u8]) -> ZeroRttCheckResult {
1047 qwarn!("AllowZeroRtt accepting 0-RTT");
1048 ZeroRttCheckResult::Accept
1049 }
1050 }
1051
1052 #[derive(Debug)]
1053 struct ZeroRttCheckState {
1054 checker: Pin<Box<dyn ZeroRttChecker>>,
1055 }
1056
1057 impl ZeroRttCheckState {
1058 pub fn new(checker: Box<dyn ZeroRttChecker>) -> Self {
1059 Self {
1060 checker: Pin::new(checker),
1061 }
1062 }
1063 }
1064
1065 #[derive(Debug)]
1066 pub struct Server {
1067 agent: SecretAgent,
1068 /// This holds the HRR callback context.
1069 zero_rtt_check: Option<Pin<Box<ZeroRttCheckState>>>,
1070 }
1071
1072 impl Server {
1073 /// Create a new server agent.
1074 ///
1075 /// # Errors
1076 ///
1077 /// Errors returned when NSS fails.
1078 pub fn new(certificates: &[impl AsRef<str>]) -> Res<Self> {
1079 let mut agent = SecretAgent::new()?;
1080
1081 for n in certificates {
1082 let c = CString::new(n.as_ref())?;
1083 let cert_ptr = unsafe { p11::PK11_FindCertFromNickname(c.as_ptr(), null_mut()) };
1084 let Ok(cert) = p11::Certificate::from_ptr(cert_ptr) else {
1085 return Err(Error::CertificateLoading);
1086 };
1087 let key_ptr = unsafe { p11::PK11_FindKeyByAnyCert(*cert, null_mut()) };
1088 let Ok(key) = PrivateKey::from_ptr(key_ptr) else {
1089 return Err(Error::CertificateLoading);
1090 };
1091 secstatus_to_res(unsafe {
1092 ssl::SSL_ConfigServerCert(agent.fd, *cert, *key, null(), 0)
1093 })?;
1094 }
1095
1096 agent.ready(true, true)?;
1097 Ok(Self {
1098 agent,
1099 zero_rtt_check: None,
1100 })
1101 }
1102
1103 unsafe extern "C" fn hello_retry_cb(
1104 first_hello: PRBool,
1105 client_token: *const u8,
1106 client_token_len: c_uint,
1107 retry_token: *mut u8,
1108 retry_token_len: *mut c_uint,
1109 retry_token_max: c_uint,
1110 arg: *mut c_void,
1111 ) -> ssl::SSLHelloRetryRequestAction::Type {
1112 if first_hello == 0 {
1113 // On the second ClientHello after HelloRetryRequest, skip checks.
1114 return ssl::SSLHelloRetryRequestAction::ssl_hello_retry_accept;
1115 }
1116
1117 let check_state = arg.cast::<ZeroRttCheckState>().as_mut().unwrap();
1118 let token = null_safe_slice(client_token, usize::try_from(client_token_len).unwrap());
1119 match check_state.checker.check(token) {
1120 ZeroRttCheckResult::Accept => ssl::SSLHelloRetryRequestAction::ssl_hello_retry_accept,
1121 ZeroRttCheckResult::Fail => ssl::SSLHelloRetryRequestAction::ssl_hello_retry_fail,
1122 ZeroRttCheckResult::Reject => {
1123 ssl::SSLHelloRetryRequestAction::ssl_hello_retry_reject_0rtt
1124 }
1125 ZeroRttCheckResult::HelloRetryRequest(tok) => {
1126 // Don't bother propagating errors from this, because it should be caught in
1127 // testing.
1128 assert!(tok.len() <= usize::try_from(retry_token_max).unwrap());
1129 let slc = std::slice::from_raw_parts_mut(retry_token, tok.len());
1130 slc.copy_from_slice(&tok);
1131 *retry_token_len = c_uint::try_from(tok.len()).unwrap();
1132 ssl::SSLHelloRetryRequestAction::ssl_hello_retry_request
1133 }
1134 }
1135 }
1136
1137 /// Enable 0-RTT. This shadows the function of the same name that can be accessed
1138 /// via the Deref implementation on Server.
1139 ///
1140 /// # Errors
1141 ///
1142 /// Returns an error if the underlying NSS functions fail.
1143 pub fn enable_0rtt(
1144 &mut self,
1145 anti_replay: &AntiReplay,
1146 max_early_data: u32,
1147 checker: Box<dyn ZeroRttChecker>,
1148 ) -> Res<()> {
1149 let mut check_state = Box::pin(ZeroRttCheckState::new(checker));
1150 unsafe {
1151 ssl::SSL_HelloRetryRequestCallback(
1152 self.agent.fd,
1153 Some(Self::hello_retry_cb),
1154 as_c_void(&mut check_state),
1155 )
1156 }?;
1157 unsafe { ssl::SSL_SetMaxEarlyDataSize(self.agent.fd, max_early_data) }?;
1158 self.zero_rtt_check = Some(check_state);
1159 self.agent.enable_0rtt()?;
1160 anti_replay.config_socket(self.fd)?;
1161 Ok(())
1162 }
1163
1164 /// Send a session ticket to the client.
1165 /// This adds |extra| application-specific content into that ticket.
1166 /// The records that are sent are captured and returned.
1167 ///
1168 /// # Errors
1169 ///
1170 /// If NSS is unable to send a ticket, or if this agent is incorrectly configured.
1171 pub fn send_ticket(&mut self, now: Instant, extra: &[u8]) -> Res<RecordList> {
1172 self.agent.now.set(now)?;
1173 let records = self.setup_raw()?;
1174
1175 unsafe {
1176 ssl::SSL_SendSessionTicket(self.fd, extra.as_ptr(), c_uint::try_from(extra.len())?)
1177 }?;
1178
1179 Ok(*Pin::into_inner(records))
1180 }
1181
1182 /// Enable encrypted client hello (ECH).
1183 ///
1184 /// # Errors
1185 ///
1186 /// Fails when NSS cannot create a key pair.
1187 pub fn enable_ech(
1188 &mut self,
1189 config: u8,
1190 public_name: &str,
1191 sk: &PrivateKey,
1192 pk: &PublicKey,
1193 ) -> Res<()> {
1194 let cfg = ech::encode_config(config, public_name, pk)?;
1195 qdebug!("[{self}] Enable ECH for a server: {}", hex_with_len(&cfg));
1196 unsafe {
1197 ech::SSL_SetServerEchConfigs(
1198 self.agent.fd,
1199 **pk,
1200 **sk,
1201 cfg.as_ptr(),
1202 c_uint::try_from(cfg.len())?,
1203 )?;
1204 };
1205 self.ech_config = cfg;
1206 Ok(())
1207 }
1208 }
1209
1210 impl Deref for Server {
1211 type Target = SecretAgent;
1212 fn deref(&self) -> &SecretAgent {
1213 &self.agent
1214 }
1215 }
1216
1217 impl DerefMut for Server {
1218 fn deref_mut(&mut self) -> &mut SecretAgent {
1219 &mut self.agent
1220 }
1221 }
1222
1223 impl Display for Server {
1224 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1225 write!(f, "Server {:p}", self.agent.fd)
1226 }
1227 }
1228
1229 /// A generic container for Client or Server.
1230 #[derive(Debug)]
1231 pub enum Agent {
1232 Client(Client),
1233 Server(Server),
1234 }
1235
1236 impl Deref for Agent {
1237 type Target = SecretAgent;
1238 fn deref(&self) -> &SecretAgent {
1239 match self {
1240 Self::Client(c) => c,
1241 Self::Server(s) => s,
1242 }
1243 }
1244 }
1245
1246 impl DerefMut for Agent {
1247 fn deref_mut(&mut self) -> &mut SecretAgent {
1248 match self {
1249 Self::Client(c) => c,
1250 Self::Server(s) => s,
1251 }
1252 }
1253 }
1254
1255 impl From<Client> for Agent {
1256 fn from(c: Client) -> Self {
1257 Self::Client(c)
1258 }
1259 }
1260
1261 impl From<Server> for Agent {
1262 fn from(s: Server) -> Self {
1263 Self::Server(s)
1264 }
1265 }