| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
use crate::{ |
| 5 |
callbacks::*, |
| 6 |
connection::Connection, |
| 7 |
enums::{HashAlgorithm, Mode, SignatureAlgorithm}, |
| 8 |
error::{Error, Fallible}, |
| 9 |
ffi::*, |
| 10 |
}; |
| 11 |
use std::{pin::Pin, ptr::NonNull}; |
| 12 |
|
| 13 |
#[non_exhaustive] |
| 14 |
#[derive(Debug)] |
| 15 |
pub enum OperationType { |
| 16 |
Decrypt, |
| 17 |
Sign(SignatureAlgorithm, HashAlgorithm), |
| 18 |
} |
| 19 |
|
| 20 |
|
| 21 |
pub struct PrivateKeyOperation { |
| 22 |
raw: NonNull<s2n_async_pkey_op>, |
| 23 |
kind: OperationType, |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
unsafe impl Send for PrivateKeyOperation {} |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
unsafe impl Sync for PrivateKeyOperation {} |
| 36 |
|
| 37 |
impl PrivateKeyOperation { |
| 38 |
pub(crate) fn try_from_cb( |
| 39 |
conn: &Connection, |
| 40 |
op_ptr: *mut s2n_async_pkey_op, |
| 41 |
) -> Result<Self, Error> { |
| 42 |
let mut raw_kind = 0; |
| 43 |
unsafe { s2n_async_pkey_op_get_op_type(op_ptr, &mut raw_kind) }.into_result()?; |
| 44 |
|
| 45 |
let kind = match raw_kind { |
| 46 |
s2n_async_pkey_op_type::SIGN => { |
| 47 |
let sig_alg = match conn.mode() { |
| 48 |
Mode::Client => conn |
| 49 |
.selected_client_signature_algorithm()? |
| 50 |
.ok_or(Error::INVALID_INPUT)?, |
| 51 |
Mode::Server => conn.selected_signature_algorithm()?, |
| 52 |
}; |
| 53 |
let hash_alg = match conn.mode() { |
| 54 |
Mode::Client => conn |
| 55 |
.selected_client_hash_algorithm()? |
| 56 |
.ok_or(Error::INVALID_INPUT)?, |
| 57 |
Mode::Server => conn.selected_hash_algorithm()?, |
| 58 |
}; |
| 59 |
OperationType::Sign(sig_alg, hash_alg) |
| 60 |
} |
| 61 |
s2n_async_pkey_op_type::DECRYPT => OperationType::Decrypt, |
| 62 |
_ => return Err(Error::INVALID_INPUT), |
| 63 |
}; |
| 64 |
|
| 65 |
let raw = NonNull::new(op_ptr).ok_or(Error::INVALID_INPUT)?; |
| 66 |
Ok(PrivateKeyOperation { raw, kind }) |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
pub fn kind(&self) -> Result<&OperationType, Error> { |
| 73 |
Ok(&self.kind) |
| 74 |
} |
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
pub fn input_size(&self) -> Result<usize, Error> { |
| 80 |
let mut size = 0; |
| 81 |
unsafe { s2n_async_pkey_op_get_input_size(self.as_ptr(), &mut size) }.into_result()?; |
| 82 |
size.try_into().map_err(|_| Error::INVALID_INPUT) |
| 83 |
} |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
pub fn input(&self, buf: &mut [u8]) -> Result<(), Error> { |
| 92 |
let buf_len: u32 = buf.len().try_into().map_err(|_| Error::INVALID_INPUT)?; |
| 93 |
let buf_ptr = buf.as_ptr() as *mut u8; |
| 94 |
unsafe { s2n_async_pkey_op_get_input(self.as_ptr(), buf_ptr, buf_len) }.into_result()?; |
| 95 |
Ok(()) |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
pub fn set_output(self, conn: &mut Connection, buf: &[u8]) -> Result<(), Error> { |
| 103 |
let buf_len: u32 = buf.len().try_into().map_err(|_| Error::INVALID_INPUT)?; |
| 104 |
let buf_ptr = buf.as_ptr(); |
| 105 |
unsafe { |
| 106 |
s2n_async_pkey_op_set_output(self.as_ptr(), buf_ptr, buf_len).into_result()?; |
| 107 |
s2n_async_pkey_op_apply(self.as_ptr(), conn.as_ptr()).into_result()?; |
| 108 |
} |
| 109 |
Ok(()) |
| 110 |
} |
| 111 |
|
| 112 |
pub(crate) fn as_ptr(&self) -> *mut s2n_async_pkey_op { |
| 113 |
self.raw.as_ptr() |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
impl Drop for PrivateKeyOperation { |
| 118 |
|
| 119 |
fn drop(&mut self) { |
| 120 |
unsafe { |
| 121 |
let _ = s2n_async_pkey_op_free(self.raw.as_ptr()); |
| 122 |
} |
| 123 |
} |
| 124 |
} |
| 125 |
|
| 126 |
pub trait PrivateKeyCallback: 'static + Send + Sync { |
| 127 |
fn handle_operation( |
| 128 |
&self, |
| 129 |
connection: &mut Connection, |
| 130 |
operation: PrivateKeyOperation, |
| 131 |
) -> Result<Option<Pin<Box<dyn ConnectionFuture>>>, Error>; |
| 132 |
} |
| 133 |
|
| 134 |
#[cfg(test)] |
| 135 |
mod tests { |
| 136 |
use super::*; |
| 137 |
use crate::{ |
| 138 |
config, connection, error, security, |
| 139 |
testing::{self, *}, |
| 140 |
}; |
| 141 |
use core::task::{Poll, Waker}; |
| 142 |
use futures_test::task::{new_count_waker, noop_waker}; |
| 143 |
use openssl::{ec::EcKey, ecdsa::EcdsaSig}; |
| 144 |
|
| 145 |
type Error = Box<dyn std::error::Error>; |
| 146 |
|
| 147 |
const KEY: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../certs/key.pem")); |
| 148 |
const CERT: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../certs/cert.pem")); |
| 149 |
|
| 150 |
fn new_pair<T>(callback: T, waker: Waker) -> Result<TestPair, Error> |
| 151 |
where |
| 152 |
T: 'static + PrivateKeyCallback, |
| 153 |
{ |
| 154 |
let config = { |
| 155 |
let mut config = config::Builder::new(); |
| 156 |
config.set_security_policy(&security::DEFAULT_TLS13)?; |
| 157 |
config.load_public_pem(CERT)?; |
| 158 |
config.set_private_key_callback(callback)?; |
| 159 |
|
| 160 |
|
| 161 |
unsafe { config.disable_x509_verification() }?; |
| 162 |
config.build()? |
| 163 |
}; |
| 164 |
|
| 165 |
let mut pair = TestPair::from_config(&config); |
| 166 |
pair.server.set_waker(Some(&waker))?; |
| 167 |
|
| 168 |
Ok(pair) |
| 169 |
} |
| 170 |
|
| 171 |
fn ecdsa_sign( |
| 172 |
op: PrivateKeyOperation, |
| 173 |
conn: &mut connection::Connection, |
| 174 |
key: &[u8], |
| 175 |
) -> Result<(), error::Error> { |
| 176 |
match op.kind()? { |
| 177 |
OperationType::Sign(SignatureAlgorithm::ECDSA, _) => { |
| 178 |
let in_buf_size = op.input_size()?; |
| 179 |
let mut in_buf = vec![0; in_buf_size]; |
| 180 |
op.input(&mut in_buf)?; |
| 181 |
|
| 182 |
let key = |
| 183 |
EcKey::private_key_from_pem(key).expect("Failed to create EcKey from pem"); |
| 184 |
let sig = EcdsaSig::sign(&in_buf, &key).expect("Failed to sign input"); |
| 185 |
let out = sig.to_der().expect("Failed to convert signature to der"); |
| 186 |
|
| 187 |
op.set_output(conn, &out)?; |
| 188 |
} |
| 189 |
_ => panic!("Unexpected pkey operation"), |
| 190 |
} |
| 191 |
Ok(()) |
| 192 |
} |
| 193 |
|
| 194 |
#[test] |
| 195 |
fn sync_offload_success() -> Result<(), Error> { |
| 196 |
struct TestPkeyCallback(Counter); |
| 197 |
impl PrivateKeyCallback for TestPkeyCallback { |
| 198 |
fn handle_operation( |
| 199 |
&self, |
| 200 |
conn: &mut connection::Connection, |
| 201 |
op: PrivateKeyOperation, |
| 202 |
) -> Result<Option<Pin<Box<dyn ConnectionFuture>>>, error::Error> { |
| 203 |
self.0.increment(); |
| 204 |
ecdsa_sign(op, conn, KEY)?; |
| 205 |
Ok(None) |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
let (waker, wake_count) = new_count_waker(); |
| 210 |
let counter = testing::Counter::default(); |
| 211 |
let callback = TestPkeyCallback(counter.clone()); |
| 212 |
let mut pair = new_pair(callback, waker)?; |
| 213 |
|
| 214 |
assert_eq!(counter.count(), 0); |
| 215 |
assert_eq!(wake_count, 0); |
| 216 |
pair.handshake()?; |
| 217 |
assert_eq!(counter.count(), 1); |
| 218 |
assert_eq!(wake_count, 0); |
| 219 |
|
| 220 |
Ok(()) |
| 221 |
} |
| 222 |
|
| 223 |
#[test] |
| 224 |
fn async_offload_success() -> Result<(), Error> { |
| 225 |
const POLL_COUNT: usize = 10; |
| 226 |
|
| 227 |
struct TestPkeyFuture { |
| 228 |
counter: usize, |
| 229 |
op: Option<PrivateKeyOperation>, |
| 230 |
} |
| 231 |
impl ConnectionFuture for TestPkeyFuture { |
| 232 |
fn poll( |
| 233 |
mut self: Pin<&mut Self>, |
| 234 |
conn: &mut connection::Connection, |
| 235 |
ctx: &mut core::task::Context, |
| 236 |
) -> Poll<Result<(), error::Error>> { |
| 237 |
ctx.waker().wake_by_ref(); |
| 238 |
self.counter += 1; |
| 239 |
if self.counter < POLL_COUNT { |
| 240 |
Poll::Pending |
| 241 |
} else if let Some(op) = self.op.take() { |
| 242 |
Poll::Ready(ecdsa_sign(op, conn, KEY)) |
| 243 |
} else { |
| 244 |
Poll::Ready(Err(error::Error::application( |
| 245 |
"missing pkey operation".into(), |
| 246 |
))) |
| 247 |
} |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
struct TestPkeyCallback(Counter); |
| 252 |
impl PrivateKeyCallback for TestPkeyCallback { |
| 253 |
fn handle_operation( |
| 254 |
&self, |
| 255 |
_conn: &mut connection::Connection, |
| 256 |
op: PrivateKeyOperation, |
| 257 |
) -> Result<Option<Pin<Box<dyn ConnectionFuture>>>, error::Error> { |
| 258 |
self.0.increment(); |
| 259 |
let future = TestPkeyFuture { |
| 260 |
counter: 0, |
| 261 |
op: Some(op), |
| 262 |
}; |
| 263 |
Ok(Some(Box::pin(future))) |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
let (waker, wake_count) = new_count_waker(); |
| 268 |
let counter = testing::Counter::default(); |
| 269 |
let callback = TestPkeyCallback(counter.clone()); |
| 270 |
let mut pair = new_pair(callback, waker)?; |
| 271 |
|
| 272 |
assert_eq!(counter.count(), 0); |
| 273 |
assert_eq!(wake_count, 0); |
| 274 |
pair.handshake()?; |
| 275 |
assert_eq!(counter.count(), 1); |
| 276 |
assert_eq!(wake_count, POLL_COUNT); |
| 277 |
|
| 278 |
Ok(()) |
| 279 |
} |
| 280 |
|
| 281 |
#[test] |
| 282 |
fn sync_failure() -> Result<(), Error> { |
| 283 |
const ERROR: &str = "sync_failure error"; |
| 284 |
|
| 285 |
struct TestPkeyCallback(Counter); |
| 286 |
impl PrivateKeyCallback for TestPkeyCallback { |
| 287 |
fn handle_operation( |
| 288 |
&self, |
| 289 |
_conn: &mut connection::Connection, |
| 290 |
_op: PrivateKeyOperation, |
| 291 |
) -> Result<Option<Pin<Box<dyn ConnectionFuture>>>, error::Error> { |
| 292 |
self.0.increment(); |
| 293 |
Err(testing::test_error(ERROR)) |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
let (waker, wake_count) = new_count_waker(); |
| 298 |
let counter = testing::Counter::default(); |
| 299 |
let callback = TestPkeyCallback(counter.clone()); |
| 300 |
let mut pair = new_pair(callback, waker)?; |
| 301 |
|
| 302 |
assert_eq!(counter.count(), 0); |
| 303 |
assert_eq!(wake_count, 0); |
| 304 |
let err = pair.handshake().unwrap_err(); |
| 305 |
assert_eq!(counter.count(), 1); |
| 306 |
assert_eq!(wake_count, 0); |
| 307 |
|
| 308 |
assert_test_error(err, ERROR); |
| 309 |
Ok(()) |
| 310 |
} |
| 311 |
|
| 312 |
#[test] |
| 313 |
fn async_failure() -> Result<(), Error> { |
| 314 |
const POLL_COUNT: usize = 10; |
| 315 |
const ERROR: &str = "async_failure error"; |
| 316 |
|
| 317 |
struct TestPkeyFuture { |
| 318 |
counter: usize, |
| 319 |
_op: PrivateKeyOperation, |
| 320 |
} |
| 321 |
impl ConnectionFuture for TestPkeyFuture { |
| 322 |
fn poll( |
| 323 |
mut self: Pin<&mut Self>, |
| 324 |
_conn: &mut connection::Connection, |
| 325 |
ctx: &mut core::task::Context, |
| 326 |
) -> Poll<Result<(), error::Error>> { |
| 327 |
ctx.waker().wake_by_ref(); |
| 328 |
self.counter += 1; |
| 329 |
if self.counter < POLL_COUNT { |
| 330 |
Poll::Pending |
| 331 |
} else { |
| 332 |
Poll::Ready(Err(testing::test_error(ERROR))) |
| 333 |
} |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
struct TestPkeyCallback(Counter); |
| 338 |
impl PrivateKeyCallback for TestPkeyCallback { |
| 339 |
fn handle_operation( |
| 340 |
&self, |
| 341 |
_conn: &mut connection::Connection, |
| 342 |
_op: PrivateKeyOperation, |
| 343 |
) -> Result<Option<Pin<Box<dyn ConnectionFuture>>>, error::Error> { |
| 344 |
self.0.increment(); |
| 345 |
let future = TestPkeyFuture { counter: 0, _op }; |
| 346 |
Ok(Some(Box::pin(future))) |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
let (waker, wake_count) = new_count_waker(); |
| 351 |
let counter = testing::Counter::default(); |
| 352 |
let callback = TestPkeyCallback(counter.clone()); |
| 353 |
let mut pair = new_pair(callback, waker)?; |
| 354 |
|
| 355 |
assert_eq!(counter.count(), 0); |
| 356 |
assert_eq!(wake_count, 0); |
| 357 |
let err = pair.handshake().unwrap_err(); |
| 358 |
assert_eq!(counter.count(), 1); |
| 359 |
assert_eq!(wake_count, POLL_COUNT); |
| 360 |
|
| 361 |
assert_test_error(err, ERROR); |
| 362 |
Ok(()) |
| 363 |
} |
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
#[test] |
| 368 |
fn app_owned_public_cert() -> Result<(), Error> { |
| 369 |
struct TestPkeyCallback; |
| 370 |
impl PrivateKeyCallback for TestPkeyCallback { |
| 371 |
fn handle_operation( |
| 372 |
&self, |
| 373 |
conn: &mut connection::Connection, |
| 374 |
op: PrivateKeyOperation, |
| 375 |
) -> Result<Option<Pin<Box<dyn ConnectionFuture>>>, error::Error> { |
| 376 |
ecdsa_sign(op, conn, KEY)?; |
| 377 |
Ok(None) |
| 378 |
} |
| 379 |
} |
| 380 |
|
| 381 |
let public_chain = { |
| 382 |
let mut chain = crate::cert_chain::Builder::new()?; |
| 383 |
chain.load_public_pem(CERT)?; |
| 384 |
chain.build()? |
| 385 |
}; |
| 386 |
|
| 387 |
let server_config = { |
| 388 |
let mut config = config::Builder::new(); |
| 389 |
config |
| 390 |
.set_security_policy(&security::DEFAULT_TLS13)? |
| 391 |
.load_chain(public_chain)? |
| 392 |
.set_private_key_callback(TestPkeyCallback)?; |
| 393 |
config.build()? |
| 394 |
}; |
| 395 |
|
| 396 |
let client_config = { |
| 397 |
let mut config = config::Builder::new(); |
| 398 |
config |
| 399 |
.set_security_policy(&security::DEFAULT_TLS13)? |
| 400 |
.set_verify_host_callback(InsecureAcceptAllCertificatesHandler {})? |
| 401 |
.trust_pem(CERT)?; |
| 402 |
config.build()? |
| 403 |
}; |
| 404 |
|
| 405 |
let mut pair = TestPair::from_configs(&client_config, &server_config); |
| 406 |
pair.server.set_waker(Some(&noop_waker()))?; |
| 407 |
|
| 408 |
assert!(pair.handshake().is_ok()); |
| 409 |
|
| 410 |
Ok(()) |
| 411 |
} |
| 412 |
} |