Skip to main content

structured_pkix/ocsp/
nonce.rs

1//! Request nonce binding; randomness and request transport belong to the caller.
2
3use super::{BasicResponse, end};
4use crate::error::{Error, ErrorCode, Located, Result};
5use crate::oid;
6use structured_asn1::memory::{MemoryError, Work};
7
8/// Caller-generated nonce for a new RFC9654 request. Construction validates
9/// size only; the caller must use a cryptographically strong random generator.
10#[derive(Debug, Clone, Copy)]
11pub struct RequestNonce<'a>(&'a [u8]);
12
13/// The actual sent nonce has a size outside the received wire schema.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct NonceSizeError {
16    /// Actual octet count; no input bytes are copied into diagnostics.
17    pub length: usize,
18}
19impl core::fmt::Display for NonceSizeError {
20    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
21        write!(formatter, "nonce length {} is outside 1..128", self.length)
22    }
23}
24#[cfg(feature = "std")]
25impl std::error::Error for NonceSizeError {}
26
27impl<'a> RequestNonce<'a> {
28    /// Retain an actual sent wire nonce for comparison, including legacy short
29    /// requests. RFC9654 §2.1 permits received sizes 1..128; generation of a
30    /// new compliant request must still use at least 32 strong random octets.
31    /// Invalid input is an error, not an absent request nonce.
32    /// <https://www.rfc-editor.org/rfc/rfc9654#section-2.1>
33    pub fn from_sent(bytes: &'a [u8]) -> core::result::Result<Self, NonceSizeError> {
34        if bytes.is_empty() || bytes.len() > 128 {
35            return Err(NonceSizeError {
36                length: bytes.len(),
37            });
38        }
39        Ok(Self(bytes))
40    }
41    /// Validate a newly generated request value. RFC9654 §2.1 requires new
42    /// requesters to use at least 32 octets; the
43    /// schema maximum is 128. This is not a check of the bytes' randomness.
44    /// <https://www.rfc-editor.org/rfc/rfc9654#section-2.1>
45    #[must_use]
46    pub fn new(bytes: &'a [u8]) -> Option<Self> {
47        if bytes.len() < 32 || bytes.len() > 128 {
48            return None;
49        }
50        Some(Self(bytes))
51    }
52
53    /// Original request bytes; no copy or encoding bridge.
54    #[must_use]
55    pub fn as_bytes(self) -> &'a [u8] {
56        self.0
57    }
58}
59
60/// Completed request-binding fact, not response authenticity or time validity.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum NonceBinding {
63    /// Neither request nor response carries a nonce.
64    NotRequested,
65    /// Responder supplied a nonce without a nonce-bearing request.
66    Unsolicited,
67    /// A nonce-bearing request received a response without one.
68    Missing,
69    /// The original request and response nonce bytes agree.
70    Matches,
71    /// The original request and response nonce bytes differ.
72    Differs,
73}
74
75pub(super) fn read<'a, W: Work>(
76    extension: &crate::Extension<'a>,
77    execution: &W,
78) -> Result<&'a [u8]> {
79    const FIELD: &str = "ocspResponse.nonce";
80    let mut reader = extension.reader_scoped(execution).field(FIELD)?;
81    let value = reader
82        .expect(structured_asn1::Tag::primitive(
83            structured_asn1::universal::OCTET_STRING,
84        ))
85        .field(FIELD)?;
86    end(&reader, FIELD)?;
87    let bytes = value.contents();
88    // RFC9654 §2.1: encoded inner OCTET STRING, not raw extnValue bytes.
89    // https://www.rfc-editor.org/rfc/rfc9654#section-2.1
90    if bytes.is_empty() || bytes.len() > 128 {
91        return Err(Error::new(
92            ErrorCode::MalformedValue,
93            FIELD,
94            extension.span().start,
95        ));
96    }
97    Ok(bytes)
98}
99
100pub(super) fn bind<W: Work>(
101    request: Option<RequestNonce<'_>>,
102    response: Option<&[u8]>,
103    execution: &W,
104    at: u64,
105) -> Result<NonceBinding> {
106    let (request, response) = match (request, response) {
107        (None, None) => return Ok(NonceBinding::NotRequested),
108        (None, Some(_)) => return Ok(NonceBinding::Unsolicited),
109        (Some(_), None) => return Ok(NonceBinding::Missing),
110        (Some(request), Some(response)) => (request.as_bytes(), response),
111    };
112    let work = u64::try_from(request.len().max(response.len()))
113        .ok()
114        .and_then(|n| n.checked_mul(2))
115        .and_then(|n| n.checked_add(1))
116        .ok_or_else(|| Error::resource(MemoryError::WorkExceeded, "ocspResponse.nonce", at))?;
117    execution
118        .charge_work(work)
119        .map_err(|reason| Error::resource(reason, "ocspResponse.nonce", at))?;
120    Ok(if request == response {
121        NonceBinding::Matches
122    } else {
123        NonceBinding::Differs
124    })
125}
126
127impl<'a> BasicResponse<'a> {
128    /// Decode a response nonce, retaining the producing parser's local work and
129    /// depth ceilings. Received nonce syntax accepts 1..128 octets, including
130    /// legacy short nonces; this does not relax new-request construction.
131    pub fn nonce<W: Work>(&self, execution: &W) -> Result<Option<&'a [u8]>> {
132        match self.extensions.get(oid::OCSP_NONCE, execution)? {
133            Some(extension) => read(extension, execution).map(Some),
134            None => Ok(None),
135        }
136    }
137
138    /// Compare the actual request nonce only after authenticating this response.
139    /// Missing/unsolicited values are preserved for the caller's replay policy;
140    /// they are never replaced by a generated or default nonce.
141    pub fn bind_nonce<W: Work>(
142        &self,
143        request: Option<RequestNonce<'_>>,
144        execution: &W,
145    ) -> Result<NonceBinding> {
146        bind(request, self.nonce(execution)?, execution, self.span.start)
147    }
148}