1use foreign_types::ForeignType;
2use foreign_types::ForeignTypeRef;
3#[cfg(any(ossl111, not(osslconf = "OPENSSL_NO_PSK")))]
4use libc::c_char;
5#[cfg(ossl111)]
6use libc::size_t;
7use libc::{c_int, c_uchar, c_uint, c_void};
8#[cfg(any(ossl111, not(osslconf = "OPENSSL_NO_PSK")))]
9use std::ffi::CStr;
10use std::mem;
11use std::ptr;
12#[cfg(any(ossl111, boringssl, awslc))]
13use std::str;
14use std::sync::Arc;
15
16use crate::dh::Dh;
17use crate::error::ErrorStack;
18use crate::pkey::Params;
19use crate::ssl::AlpnError;
20use crate::ssl::{
21 try_get_session_ctx_index, SniError, Ssl, SslAlert, SslContext, SslContextRef, SslRef,
22 SslSession, SslSessionRef,
23};
24#[cfg(ossl111)]
25use crate::ssl::{ClientHelloResponse, ExtensionContext};
26use crate::util;
27#[cfg(any(ossl111, boringssl, awslc))]
28use crate::util::ForeignTypeRefExt;
29#[cfg(ossl111)]
30use crate::x509::X509Ref;
31use crate::x509::{X509StoreContext, X509StoreContextRef};
32
33pub extern "C" fn raw_verify<F>(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int
34where
35 F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,
36{
37 unsafe {
38 let ctx = X509StoreContextRef::from_ptr_mut(x509_ctx);
39 let ssl_idx = X509StoreContext::ssl_idx().expect("BUG: store context ssl index missing");
40 let verify_idx = SslContext::cached_ex_index::<F>();
41
42 let verify = ctx
45 .ex_data(ssl_idx)
46 .expect("BUG: store context missing ssl")
47 .ssl_context()
48 .ex_data(verify_idx)
49 .expect("BUG: verify callback missing") as *const F;
50
51 (*verify)(preverify_ok != 0, ctx) as c_int
52 }
53}
54
55#[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
56pub extern "C" fn raw_client_psk<F>(
57 ssl: *mut ffi::SSL,
58 hint: *const c_char,
59 identity: *mut c_char,
60 max_identity_len: c_uint,
61 psk: *mut c_uchar,
62 max_psk_len: c_uint,
63) -> c_uint
64where
65 F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result<usize, ErrorStack>
66 + 'static
67 + Sync
68 + Send,
69{
70 unsafe {
71 let ssl = SslRef::from_ptr_mut(ssl);
72 let callback_idx = SslContext::cached_ex_index::<F>();
73
74 let callback = ssl
75 .ssl_context()
76 .ex_data(callback_idx)
77 .expect("BUG: psk callback missing") as *const F;
78 let hint = if !hint.is_null() {
79 Some(CStr::from_ptr(hint).to_bytes())
80 } else {
81 None
82 };
83 let identity_sl = util::from_raw_parts_mut(identity as *mut u8, max_identity_len as usize);
85 #[allow(clippy::unnecessary_cast)]
86 let psk_sl = util::from_raw_parts_mut(psk as *mut u8, max_psk_len as usize);
87 let psk_cap = psk_sl.len();
88 match (*callback)(ssl, hint, identity_sl, psk_sl) {
89 Ok(psk_len) if psk_len <= psk_cap => psk_len as u32,
90 Ok(_) => 0,
91 Err(e) => {
92 e.put();
93 0
94 }
95 }
96 }
97}
98
99#[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
100pub extern "C" fn raw_server_psk<F>(
101 ssl: *mut ffi::SSL,
102 identity: *const c_char,
103 psk: *mut c_uchar,
104 max_psk_len: c_uint,
105) -> c_uint
106where
107 F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8]) -> Result<usize, ErrorStack>
108 + 'static
109 + Sync
110 + Send,
111{
112 unsafe {
113 let ssl = SslRef::from_ptr_mut(ssl);
114 let callback_idx = SslContext::cached_ex_index::<F>();
115
116 let callback = ssl
117 .ssl_context()
118 .ex_data(callback_idx)
119 .expect("BUG: psk callback missing") as *const F;
120 let identity = if identity.is_null() {
121 None
122 } else {
123 Some(CStr::from_ptr(identity).to_bytes())
124 };
125 #[allow(clippy::unnecessary_cast)]
127 let psk_sl = util::from_raw_parts_mut(psk as *mut u8, max_psk_len as usize);
128 let psk_cap = psk_sl.len();
129 match (*callback)(ssl, identity, psk_sl) {
130 Ok(psk_len) if psk_len <= psk_cap => psk_len as u32,
131 Ok(_) => 0,
132 Err(e) => {
133 e.put();
134 0
135 }
136 }
137 }
138}
139
140pub extern "C" fn ssl_raw_verify<F>(
141 preverify_ok: c_int,
142 x509_ctx: *mut ffi::X509_STORE_CTX,
143) -> c_int
144where
145 F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,
146{
147 unsafe {
148 let ctx = X509StoreContextRef::from_ptr_mut(x509_ctx);
149 let ssl_idx = X509StoreContext::ssl_idx().expect("BUG: store context ssl index missing");
150 let callback_idx = Ssl::cached_ex_index::<Arc<F>>();
151
152 let callback = ctx
153 .ex_data(ssl_idx)
154 .expect("BUG: store context missing ssl")
155 .ex_data(callback_idx)
156 .expect("BUG: ssl verify callback missing")
157 .clone();
158
159 callback(preverify_ok != 0, ctx) as c_int
160 }
161}
162
163pub extern "C" fn raw_sni<F>(ssl: *mut ffi::SSL, al: *mut c_int, arg: *mut c_void) -> c_int
164where
165 F: Fn(&mut SslRef, &mut SslAlert) -> Result<(), SniError> + 'static + Sync + Send,
166{
167 unsafe {
168 let ssl = SslRef::from_ptr_mut(ssl);
169 let callback = arg as *const F;
170 let mut alert = SslAlert(*al);
171
172 let r = (*callback)(ssl, &mut alert);
173 *al = alert.0;
174 match r {
175 Ok(()) => ffi::SSL_TLSEXT_ERR_OK,
176 Err(e) => e.0,
177 }
178 }
179}
180
181pub extern "C" fn raw_alpn_select<F>(
182 ssl: *mut ffi::SSL,
183 out: *mut *const c_uchar,
184 outlen: *mut c_uchar,
185 inbuf: *const c_uchar,
186 inlen: c_uint,
187 _arg: *mut c_void,
188) -> c_int
189where
190 F: for<'a> Fn(&mut SslRef, &'a [u8]) -> Result<&'a [u8], AlpnError> + 'static + Sync + Send,
191{
192 unsafe {
193 let ssl = SslRef::from_ptr_mut(ssl);
194 let callback = ssl
195 .ssl_context()
196 .ex_data(SslContext::cached_ex_index::<F>())
197 .expect("BUG: alpn callback missing") as *const F;
198 #[allow(clippy::unnecessary_cast)]
199 let protos = util::from_raw_parts(inbuf as *const u8, inlen as usize);
200
201 match (*callback)(ssl, protos) {
202 Ok(proto) => {
203 *out = proto.as_ptr() as *const c_uchar;
204 *outlen = proto.len() as c_uchar;
205 ffi::SSL_TLSEXT_ERR_OK
206 }
207 Err(e) => e.0,
208 }
209 }
210}
211
212pub unsafe extern "C" fn raw_tmp_dh<F>(
213 ssl: *mut ffi::SSL,
214 is_export: c_int,
215 keylength: c_int,
216) -> *mut ffi::DH
217where
218 F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
219{
220 let ssl = SslRef::from_ptr_mut(ssl);
221 let callback = ssl
222 .ssl_context()
223 .ex_data(SslContext::cached_ex_index::<F>())
224 .expect("BUG: tmp dh callback missing") as *const F;
225
226 match (*callback)(ssl, is_export != 0, keylength as u32) {
227 Ok(dh) => {
228 let ptr = dh.as_ptr();
229 mem::forget(dh);
230 ptr
231 }
232 Err(e) => {
233 e.put();
234 ptr::null_mut()
235 }
236 }
237}
238
239pub unsafe extern "C" fn raw_tmp_dh_ssl<F>(
240 ssl: *mut ffi::SSL,
241 is_export: c_int,
242 keylength: c_int,
243) -> *mut ffi::DH
244where
245 F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
246{
247 let ssl = SslRef::from_ptr_mut(ssl);
248 let callback = ssl
249 .ex_data(Ssl::cached_ex_index::<Arc<F>>())
250 .expect("BUG: ssl tmp dh callback missing")
251 .clone();
252
253 match callback(ssl, is_export != 0, keylength as u32) {
254 Ok(dh) => {
255 let ptr = dh.as_ptr();
256 mem::forget(dh);
257 ptr
258 }
259 Err(e) => {
260 e.put();
261 ptr::null_mut()
262 }
263 }
264}
265
266pub unsafe extern "C" fn raw_tlsext_status<F>(ssl: *mut ffi::SSL, _: *mut c_void) -> c_int
267where
268 F: Fn(&mut SslRef) -> Result<bool, ErrorStack> + 'static + Sync + Send,
269{
270 let ssl = SslRef::from_ptr_mut(ssl);
271 let callback = ssl
272 .ssl_context()
273 .ex_data(SslContext::cached_ex_index::<F>())
274 .expect("BUG: ocsp callback missing") as *const F;
275 let ret = (*callback)(ssl);
276
277 if ssl.is_server() {
278 match ret {
279 Ok(true) => ffi::SSL_TLSEXT_ERR_OK,
280 Ok(false) => ffi::SSL_TLSEXT_ERR_NOACK,
281 Err(e) => {
282 e.put();
283 ffi::SSL_TLSEXT_ERR_ALERT_FATAL
284 }
285 }
286 } else {
287 match ret {
288 Ok(true) => 1,
289 Ok(false) => 0,
290 Err(e) => {
291 e.put();
292 -1
293 }
294 }
295 }
296}
297
298pub unsafe extern "C" fn raw_new_session<F>(
299 ssl: *mut ffi::SSL,
300 session: *mut ffi::SSL_SESSION,
301) -> c_int
302where
303 F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send,
304{
305 let session_ctx_index =
306 try_get_session_ctx_index().expect("BUG: session context index initialization failed");
307 let ssl = SslRef::from_ptr_mut(ssl);
308 let callback = ssl
309 .ex_data(*session_ctx_index)
310 .expect("BUG: session context missing")
311 .ex_data(SslContext::cached_ex_index::<F>())
312 .expect("BUG: new session callback missing") as *const F;
313 let session = SslSession::from_ptr(session);
314
315 (*callback)(ssl, session);
316
317 1
319}
320
321pub unsafe extern "C" fn raw_remove_session<F>(
322 ctx: *mut ffi::SSL_CTX,
323 session: *mut ffi::SSL_SESSION,
324) where
325 F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send,
326{
327 let ctx = SslContextRef::from_ptr(ctx);
328 let callback = ctx
329 .ex_data(SslContext::cached_ex_index::<F>())
330 .expect("BUG: remove session callback missing");
331 let session = SslSessionRef::from_ptr(session);
332
333 callback(ctx, session)
334}
335
336pub unsafe extern "C" fn raw_get_session<F>(
337 ssl: *mut ffi::SSL,
338 data: *const c_uchar,
339 len: c_int,
340 copy: *mut c_int,
341) -> *mut ffi::SSL_SESSION
342where
343 F: Fn(&mut SslRef, &[u8]) -> Option<SslSession> + 'static + Sync + Send,
344{
345 let session_ctx_index =
346 try_get_session_ctx_index().expect("BUG: session context index initialization failed");
347 let ssl = SslRef::from_ptr_mut(ssl);
348 let callback = ssl
349 .ex_data(*session_ctx_index)
350 .expect("BUG: session context missing")
351 .ex_data(SslContext::cached_ex_index::<F>())
352 .expect("BUG: get session callback missing") as *const F;
353 #[allow(clippy::unnecessary_cast)]
354 let data = util::from_raw_parts(data as *const u8, len as usize);
355
356 match (*callback)(ssl, data) {
357 Some(session) => {
358 let p = session.as_ptr();
359 mem::forget(session);
360 *copy = 0;
361 p
362 }
363 None => ptr::null_mut(),
364 }
365}
366
367#[cfg(any(ossl111, boringssl, awslc))]
368pub unsafe extern "C" fn raw_keylog<F>(ssl: *const ffi::SSL, line: *const c_char)
369where
370 F: Fn(&SslRef, &str) + 'static + Sync + Send,
371{
372 let ssl = SslRef::from_const_ptr(ssl);
373 let callback = ssl
374 .ssl_context()
375 .ex_data(SslContext::cached_ex_index::<F>())
376 .expect("BUG: get session callback missing");
377 let line = CStr::from_ptr(line).to_bytes();
378 let line = str::from_utf8_unchecked(line);
379
380 callback(ssl, line);
381}
382
383#[cfg(ossl111)]
384pub unsafe extern "C" fn raw_stateless_cookie_generate<F>(
385 ssl: *mut ffi::SSL,
386 cookie: *mut c_uchar,
387 cookie_len: *mut size_t,
388) -> c_int
389where
390 F: Fn(&mut SslRef, &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,
391{
392 let ssl = SslRef::from_ptr_mut(ssl);
393 let callback = ssl
394 .ssl_context()
395 .ex_data(SslContext::cached_ex_index::<F>())
396 .expect("BUG: stateless cookie generate callback missing") as *const F;
397 #[allow(clippy::unnecessary_cast)]
398 let slice = util::from_raw_parts_mut(cookie as *mut u8, ffi::SSL_COOKIE_LENGTH as usize);
399 let cap = slice.len();
400 match (*callback)(ssl, slice) {
401 Ok(len) if len <= cap => {
402 *cookie_len = len as size_t;
403 1
404 }
405 Ok(_) => 0,
406 Err(e) => {
407 e.put();
408 0
409 }
410 }
411}
412
413#[cfg(ossl111)]
414pub unsafe extern "C" fn raw_stateless_cookie_verify<F>(
415 ssl: *mut ffi::SSL,
416 cookie: *const c_uchar,
417 cookie_len: size_t,
418) -> c_int
419where
420 F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send,
421{
422 let ssl = SslRef::from_ptr_mut(ssl);
423 let callback = ssl
424 .ssl_context()
425 .ex_data(SslContext::cached_ex_index::<F>())
426 .expect("BUG: stateless cookie verify callback missing") as *const F;
427 #[allow(clippy::unnecessary_cast)]
428 let slice = util::from_raw_parts(cookie as *const c_uchar as *const u8, cookie_len);
429 (*callback)(ssl, slice) as c_int
430}
431
432#[cfg(not(any(boringssl, awslc)))]
433pub extern "C" fn raw_cookie_generate<F>(
434 ssl: *mut ffi::SSL,
435 cookie: *mut c_uchar,
436 cookie_len: *mut c_uint,
437) -> c_int
438where
439 F: Fn(&mut SslRef, &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,
440{
441 unsafe {
442 let ssl = SslRef::from_ptr_mut(ssl);
443 let callback = ssl
444 .ssl_context()
445 .ex_data(SslContext::cached_ex_index::<F>())
446 .expect("BUG: cookie generate callback missing") as *const F;
447 #[allow(clippy::unnecessary_cast)]
450 let slice =
451 util::from_raw_parts_mut(cookie as *mut u8, ffi::DTLS1_COOKIE_LENGTH as usize - 1);
452 let cap = slice.len();
453 match (*callback)(ssl, slice) {
454 Ok(len) if len <= cap => {
455 *cookie_len = len as c_uint;
456 1
457 }
458 Ok(_) => 0,
459 Err(e) => {
460 e.put();
461 0
462 }
463 }
464 }
465}
466
467#[cfg(not(any(boringssl, awslc)))]
468pub extern "C" fn raw_cookie_verify<F>(
469 ssl: *mut ffi::SSL,
470 cookie: *const c_uchar,
471 cookie_len: c_uint,
472) -> c_int
473where
474 F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send,
475{
476 unsafe {
477 let ssl = SslRef::from_ptr_mut(ssl);
478 let callback = ssl
479 .ssl_context()
480 .ex_data(SslContext::cached_ex_index::<F>())
481 .expect("BUG: cookie verify callback missing") as *const F;
482 #[allow(clippy::unnecessary_cast)]
483 let slice =
484 util::from_raw_parts(cookie as *const c_uchar as *const u8, cookie_len as usize);
485 (*callback)(ssl, slice) as c_int
486 }
487}
488
489#[cfg(ossl111)]
490pub struct CustomExtAddState<T>(Option<T>);
491
492#[cfg(ossl111)]
493pub extern "C" fn raw_custom_ext_add<F, T>(
494 ssl: *mut ffi::SSL,
495 _: c_uint,
496 context: c_uint,
497 out: *mut *const c_uchar,
498 outlen: *mut size_t,
499 x: *mut ffi::X509,
500 chainidx: size_t,
501 al: *mut c_int,
502 _: *mut c_void,
503) -> c_int
504where
505 F: Fn(&mut SslRef, ExtensionContext, Option<(usize, &X509Ref)>) -> Result<Option<T>, SslAlert>
506 + 'static
507 + Sync
508 + Send,
509 T: AsRef<[u8]> + 'static + Sync + Send,
510{
511 unsafe {
512 let ssl = SslRef::from_ptr_mut(ssl);
513 let callback = ssl
514 .ssl_context()
515 .ex_data(SslContext::cached_ex_index::<F>())
516 .expect("BUG: custom ext add callback missing") as *const F;
517 let ectx = ExtensionContext::from_bits_truncate(context);
518 let cert = if ectx.contains(ExtensionContext::TLS1_3_CERTIFICATE) {
519 Some((chainidx, X509Ref::from_ptr(x)))
520 } else {
521 None
522 };
523 match (*callback)(ssl, ectx, cert) {
524 Ok(None) => 0,
525 Ok(Some(buf)) => {
526 let idx = Ssl::cached_ex_index::<CustomExtAddState<T>>();
527 let mut buf = Some(buf);
528 let new = match ssl.ex_data_mut(idx) {
529 Some(state) => {
530 state.0 = buf.take();
531 false
532 }
533 None => true,
534 };
535 if new {
536 ssl.set_ex_data(idx, CustomExtAddState(buf));
537 }
538
539 let stored = ssl.ex_data(idx).unwrap();
542 let data = stored.0.as_ref().unwrap().as_ref();
543 *outlen = data.len();
544 *out = data.as_ptr();
545
546 1
547 }
548 Err(alert) => {
549 *al = alert.0;
550 -1
551 }
552 }
553 }
554}
555
556#[cfg(ossl111)]
557pub extern "C" fn raw_custom_ext_free<T>(
558 ssl: *mut ffi::SSL,
559 _: c_uint,
560 _: c_uint,
561 _: *const c_uchar,
562 _: *mut c_void,
563) where
564 T: 'static + Sync + Send,
565{
566 unsafe {
567 let ssl = SslRef::from_ptr_mut(ssl);
568 let idx = Ssl::cached_ex_index::<CustomExtAddState<T>>();
569 if let Some(state) = ssl.ex_data_mut(idx) {
570 state.0 = None;
571 }
572 }
573}
574
575#[cfg(ossl111)]
576pub extern "C" fn raw_custom_ext_parse<F>(
577 ssl: *mut ffi::SSL,
578 _: c_uint,
579 context: c_uint,
580 input: *const c_uchar,
581 inlen: size_t,
582 x: *mut ffi::X509,
583 chainidx: size_t,
584 al: *mut c_int,
585 _: *mut c_void,
586) -> c_int
587where
588 F: Fn(&mut SslRef, ExtensionContext, &[u8], Option<(usize, &X509Ref)>) -> Result<(), SslAlert>
589 + 'static
590 + Sync
591 + Send,
592{
593 unsafe {
594 let ssl = SslRef::from_ptr_mut(ssl);
595 let callback = ssl
596 .ssl_context()
597 .ex_data(SslContext::cached_ex_index::<F>())
598 .expect("BUG: custom ext parse callback missing") as *const F;
599 let ectx = ExtensionContext::from_bits_truncate(context);
600 #[allow(clippy::unnecessary_cast)]
601 let slice = util::from_raw_parts(input as *const u8, inlen);
602 let cert = if ectx.contains(ExtensionContext::TLS1_3_CERTIFICATE) {
603 Some((chainidx, X509Ref::from_ptr(x)))
604 } else {
605 None
606 };
607 match (*callback)(ssl, ectx, slice, cert) {
608 Ok(()) => 1,
609 Err(alert) => {
610 *al = alert.0;
611 0
612 }
613 }
614 }
615}
616
617#[cfg(ossl111)]
618pub unsafe extern "C" fn raw_client_hello<F>(
619 ssl: *mut ffi::SSL,
620 al: *mut c_int,
621 arg: *mut c_void,
622) -> c_int
623where
624 F: Fn(&mut SslRef, &mut SslAlert) -> Result<ClientHelloResponse, ErrorStack>
625 + 'static
626 + Sync
627 + Send,
628{
629 let ssl = SslRef::from_ptr_mut(ssl);
630 let callback = arg as *const F;
631 let mut alert = SslAlert(*al);
632
633 let r = (*callback)(ssl, &mut alert);
634 *al = alert.0;
635 match r {
636 Ok(c) => c.0,
637 Err(e) => {
638 e.put();
639 ffi::SSL_CLIENT_HELLO_ERROR
640 }
641 }
642}