| 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 std::{ |
| 8 |
ops::{Deref, DerefMut}, |
| 9 |
os::raw::c_uint, |
| 10 |
ptr::null_mut, |
| 11 |
time::{Duration, Instant}, |
| 12 |
}; |
| 13 |
|
| 14 |
use crate::{ |
| 15 |
err::Res, |
| 16 |
ssl::PRFileDesc, |
| 17 |
time::{Interval, PRTime, Time}, |
| 18 |
}; |
| 19 |
|
| 20 |
// This is an opaque struct in NSS. |
| 21 |
pub enum SSLAntiReplayContext {} |
| 22 |
|
| 23 |
experimental_api!(SSL_CreateAntiReplayContext( |
| 24 |
now: PRTime, |
| 25 |
window: PRTime, |
| 26 |
k: c_uint, |
| 27 |
bits: c_uint, |
| 28 |
ctx: *mut *mut SSLAntiReplayContext, |
| 29 |
)); |
| 30 |
experimental_api!(SSL_ReleaseAntiReplayContext(ctx: *mut SSLAntiReplayContext)); |
| 31 |
experimental_api!(SSL_SetAntiReplayContext( |
| 32 |
fd: *mut PRFileDesc, |
| 33 |
ctx: *mut SSLAntiReplayContext, |
| 34 |
)); |
| 35 |
|
| 36 |
scoped_ptr!( |
| 37 |
AntiReplayContext, |
| 38 |
SSLAntiReplayContext, |
| 39 |
SSL_ReleaseAntiReplayContext |
| 40 |
); |
| 41 |
|
| 42 |
/// `AntiReplay` is used by servers when processing 0-RTT handshakes. |
| 43 |
/// |
| 44 |
/// It limits the exposure of servers to replay attack by rejecting 0-RTT |
| 45 |
/// if it appears to be a replay. There is a false-positive rate that can be |
| 46 |
/// managed by tuning the parameters used to create the context. |
| 47 |
pub struct AntiReplay { |
| 48 |
ctx: AntiReplayContext, |
| 49 |
} |
| 50 |
|
| 51 |
impl AntiReplay { |
| 52 |
/// Make a new anti-replay context. |
| 53 |
/// See the documentation in NSS for advice on how to set these values. |
| 54 |
/// |
| 55 |
/// # Errors |
| 56 |
/// |
| 57 |
/// Returns an error if `now` is in the past relative to our baseline or |
| 58 |
/// NSS is unable to generate an anti-replay context. |
| 59 |
pub fn new(now: Instant, window: Duration, k: usize, bits: usize) -> Res<Self> { |
| 60 |
let mut ctx: *mut SSLAntiReplayContext = null_mut(); |
| 61 |
unsafe { |
| 62 |
SSL_CreateAntiReplayContext( |
| 63 |
Time::from(now).try_into()?, |
| 64 |
Interval::from(window).try_into()?, |
| 65 |
c_uint::try_from(k)?, |
| 66 |
c_uint::try_from(bits)?, |
| 67 |
&mut ctx, |
| 68 |
) |
| 69 |
}?; |
| 70 |
|
| 71 |
Ok(Self { |
| 72 |
ctx: AntiReplayContext::from_ptr(ctx)?, |
| 73 |
}) |
| 74 |
} |
| 75 |
|
| 76 |
/// Configure the provided socket with this anti-replay context. |
| 77 |
pub(crate) fn config_socket(&self, fd: *mut PRFileDesc) -> Res<()> { |
| 78 |
unsafe { SSL_SetAntiReplayContext(fd, *self.ctx) } |
| 79 |
} |
| 80 |
} |