Struct openssl::ssl::SslRef

source ·
pub struct SslRef(_);
Expand description

Reference to an Ssl.

Implementations§

Configure as an outgoing stream from a client.

This corresponds to SSL_set_connect_state.

Configure as an incoming stream to a server.

This corresponds to SSL_set_accept_state.

Like SslContextBuilder::set_verify.

This corresponds to SSL_set_verify.

Returns the verify mode that was set using set_verify.

This corresponds to SSL_set_verify_mode.

Like SslContextBuilder::set_tmp_dh.

This corresponds to SSL_set_tmp_dh.

Like SslContextBuilder::set_alpn_protos.

Requires OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.

This corresponds to SSL_set_alpn_protos.

Returns the current cipher if the session is active.

This corresponds to SSL_get_current_cipher.

Returns a short string describing the state of the session.

This corresponds to SSL_state_string.

Returns a longer string describing the state of the session.

This corresponds to SSL_state_string_long.

Examples found in repository?
src/ssl/mod.rs (line 2258)
2256
2257
2258
2259
2260
2261
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("Ssl")
            .field("state", &self.state_string_long())
            .field("verify_result", &self.verify_result())
            .finish()
    }

Sets the host name to be sent to the server for Server Name Indication (SNI).

It has no effect for a server-side connection.

This corresponds to SSL_set_tlsext_host_name.

Examples found in repository?
src/ssl/connector.rs (line 183)
181
182
183
184
185
186
187
188
189
190
191
    pub fn into_ssl(mut self, domain: &str) -> Result<Ssl, ErrorStack> {
        if self.sni {
            self.ssl.set_hostname(domain)?;
        }

        if self.verify_hostname {
            setup_verify_hostname(&mut self.ssl, domain)?;
        }

        Ok(self.ssl)
    }

Returns the peer’s certificate, if present.

This corresponds to SSL_get_peer_certificate.

Returns the certificate chain of the peer, if present.

On the client side, the chain includes the leaf certificate, but on the server side it does not. Fun!

This corresponds to SSL_get_peer_cert_chain.

Returns the verified certificate chain of the peer, including the leaf certificate.

If verification was not successful (i.e. verify_result does not return X509VerifyResult::OK), this chain may be incomplete or invalid.

Requires OpenSSL 1.1.0 or newer.

This corresponds to SSL_get0_verified_chain.

Like [SslContext::certificate].

This corresponds to SSL_get_certificate.

Like SslContext::private_key.

This corresponds to SSL_get_privatekey.

This corresponds to SSL_get_certificate.

👎Deprecated since 0.10.5: renamed to version_str

Returns the protocol version of the session.

This corresponds to SSL_version.

Returns a string describing the protocol version of the session.

This corresponds to SSL_get_version.

Examples found in repository?
src/ssl/mod.rs (line 2523)
2522
2523
2524
    pub fn version(&self) -> &str {
        self.version_str()
    }

Returns the protocol selected via Application Layer Protocol Negotiation (ALPN).

The protocol’s name is returned is an opaque sequence of bytes. It is up to the client to interpret it.

Requires OpenSSL 1.0.2 or LibreSSL 2.6.1 or newer.

This corresponds to SSL_get0_alpn_selected.

Enables the DTLS extension “use_srtp” as defined in RFC5764.

This corresponds to SSL_set_tlsext_use_srtp.

This corresponds to SSL_set_tlsext_use_srtp.

Gets all SRTP profiles that are enabled for handshake via set_tlsext_use_srtp

DTLS extension “use_srtp” as defined in RFC5764 has to be enabled.

This corresponds to SSL_get_srtp_profiles.

This corresponds to SSL_get_srtp_profiles.

Gets the SRTP profile selected by handshake.

DTLS extension “use_srtp” as defined in RFC5764 has to be enabled.

This corresponds to SSL_get_selected_srtp_profile.

Returns the number of bytes remaining in the currently processed TLS record.

If this is greater than 0, the next call to read will not call down to the underlying stream.

This corresponds to SSL_pending.

Returns the servername sent by the client via Server Name Indication (SNI).

It is only useful on the server side.

Note

While the SNI specification requires that servernames be valid domain names (and therefore ASCII), OpenSSL does not enforce this restriction. If the servername provided by the client is not valid UTF-8, this function will return None. The servername_raw method returns the raw bytes and does not have this restriction.

This corresponds to SSL_get_servername.

Returns the servername sent by the client via Server Name Indication (SNI).

It is only useful on the server side.

Note

Unlike servername, this method does not require the name be valid UTF-8.

This corresponds to SSL_get_servername.

Examples found in repository?
src/ssl/mod.rs (line 2646)
2645
2646
2647
2648
    pub fn servername(&self, type_: NameType) -> Option<&str> {
        self.servername_raw(type_)
            .and_then(|b| str::from_utf8(b).ok())
    }

Changes the context corresponding to the current connection.

It is most commonly used in the Server Name Indication (SNI) callback.

This corresponds to SSL_set_SSL_CTX.

Returns the context corresponding to the current connection.

This corresponds to SSL_get_SSL_CTX.

Examples found in repository?
src/ssl/callbacks.rs (line 51)
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
pub extern "C" fn raw_verify<F>(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int
where
    F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,
{
    unsafe {
        let ctx = X509StoreContextRef::from_ptr_mut(x509_ctx);
        let ssl_idx = X509StoreContext::ssl_idx().expect("BUG: store context ssl index missing");
        let verify_idx = SslContext::cached_ex_index::<F>();

        // raw pointer shenanigans to break the borrow of ctx
        // the callback can't mess with its own ex_data slot so this is safe
        let verify = ctx
            .ex_data(ssl_idx)
            .expect("BUG: store context missing ssl")
            .ssl_context()
            .ex_data(verify_idx)
            .expect("BUG: verify callback missing") as *const F;

        (*verify)(preverify_ok != 0, ctx) as c_int
    }
}

#[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
pub extern "C" fn raw_client_psk<F>(
    ssl: *mut ffi::SSL,
    hint: *const c_char,
    identity: *mut c_char,
    max_identity_len: c_uint,
    psk: *mut c_uchar,
    max_psk_len: c_uint,
) -> c_uint
where
    F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result<usize, ErrorStack>
        + 'static
        + Sync
        + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback_idx = SslContext::cached_ex_index::<F>();

        let callback = ssl
            .ssl_context()
            .ex_data(callback_idx)
            .expect("BUG: psk callback missing") as *const F;
        let hint = if !hint.is_null() {
            Some(CStr::from_ptr(hint).to_bytes())
        } else {
            None
        };
        // Give the callback mutable slices into which it can write the identity and psk.
        let identity_sl = slice::from_raw_parts_mut(identity as *mut u8, max_identity_len as usize);
        let psk_sl = slice::from_raw_parts_mut(psk as *mut u8, max_psk_len as usize);
        match (*callback)(ssl, hint, identity_sl, psk_sl) {
            Ok(psk_len) => psk_len as u32,
            Err(e) => {
                e.put();
                0
            }
        }
    }
}

#[cfg(not(osslconf = "OPENSSL_NO_PSK"))]
pub extern "C" fn raw_server_psk<F>(
    ssl: *mut ffi::SSL,
    identity: *const c_char,
    psk: *mut c_uchar,
    max_psk_len: c_uint,
) -> c_uint
where
    F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8]) -> Result<usize, ErrorStack>
        + 'static
        + Sync
        + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback_idx = SslContext::cached_ex_index::<F>();

        let callback = ssl
            .ssl_context()
            .ex_data(callback_idx)
            .expect("BUG: psk callback missing") as *const F;
        let identity = if identity.is_null() {
            None
        } else {
            Some(CStr::from_ptr(identity).to_bytes())
        };
        // Give the callback mutable slices into which it can write the psk.
        let psk_sl = slice::from_raw_parts_mut(psk as *mut u8, max_psk_len as usize);
        match (*callback)(ssl, identity, psk_sl) {
            Ok(psk_len) => psk_len as u32,
            Err(e) => {
                e.put();
                0
            }
        }
    }
}

pub extern "C" fn ssl_raw_verify<F>(
    preverify_ok: c_int,
    x509_ctx: *mut ffi::X509_STORE_CTX,
) -> c_int
where
    F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,
{
    unsafe {
        let ctx = X509StoreContextRef::from_ptr_mut(x509_ctx);
        let ssl_idx = X509StoreContext::ssl_idx().expect("BUG: store context ssl index missing");
        let callback_idx = Ssl::cached_ex_index::<Arc<F>>();

        let callback = ctx
            .ex_data(ssl_idx)
            .expect("BUG: store context missing ssl")
            .ex_data(callback_idx)
            .expect("BUG: ssl verify callback missing")
            .clone();

        callback(preverify_ok != 0, ctx) as c_int
    }
}

pub extern "C" fn raw_sni<F>(ssl: *mut ffi::SSL, al: *mut c_int, arg: *mut c_void) -> c_int
where
    F: Fn(&mut SslRef, &mut SslAlert) -> Result<(), SniError> + 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback = arg as *const F;
        let mut alert = SslAlert(*al);

        let r = (*callback)(ssl, &mut alert);
        *al = alert.0;
        match r {
            Ok(()) => ffi::SSL_TLSEXT_ERR_OK,
            Err(e) => e.0,
        }
    }
}

#[cfg(any(ossl102, libressl261))]
pub extern "C" fn raw_alpn_select<F>(
    ssl: *mut ffi::SSL,
    out: *mut *const c_uchar,
    outlen: *mut c_uchar,
    inbuf: *const c_uchar,
    inlen: c_uint,
    _arg: *mut c_void,
) -> c_int
where
    F: for<'a> Fn(&mut SslRef, &'a [u8]) -> Result<&'a [u8], AlpnError> + 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback = ssl
            .ssl_context()
            .ex_data(SslContext::cached_ex_index::<F>())
            .expect("BUG: alpn callback missing") as *const F;
        let protos = slice::from_raw_parts(inbuf as *const u8, inlen as usize);

        match (*callback)(ssl, protos) {
            Ok(proto) => {
                *out = proto.as_ptr() as *const c_uchar;
                *outlen = proto.len() as c_uchar;
                ffi::SSL_TLSEXT_ERR_OK
            }
            Err(e) => e.0,
        }
    }
}

pub unsafe extern "C" fn raw_tmp_dh<F>(
    ssl: *mut ffi::SSL,
    is_export: c_int,
    keylength: c_int,
) -> *mut ffi::DH
where
    F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ssl_context()
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: tmp dh callback missing") as *const F;

    match (*callback)(ssl, is_export != 0, keylength as u32) {
        Ok(dh) => {
            let ptr = dh.as_ptr();
            mem::forget(dh);
            ptr
        }
        Err(e) => {
            e.put();
            ptr::null_mut()
        }
    }
}

#[cfg(all(ossl101, not(ossl110)))]
pub unsafe extern "C" fn raw_tmp_ecdh<F>(
    ssl: *mut ffi::SSL,
    is_export: c_int,
    keylength: c_int,
) -> *mut ffi::EC_KEY
where
    F: Fn(&mut SslRef, bool, u32) -> Result<EcKey<Params>, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ssl_context()
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: tmp ecdh callback missing") as *const F;

    match (*callback)(ssl, is_export != 0, keylength as u32) {
        Ok(ec_key) => {
            let ptr = ec_key.as_ptr();
            mem::forget(ec_key);
            ptr
        }
        Err(e) => {
            e.put();
            ptr::null_mut()
        }
    }
}

pub unsafe extern "C" fn raw_tmp_dh_ssl<F>(
    ssl: *mut ffi::SSL,
    is_export: c_int,
    keylength: c_int,
) -> *mut ffi::DH
where
    F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ex_data(Ssl::cached_ex_index::<Arc<F>>())
        .expect("BUG: ssl tmp dh callback missing")
        .clone();

    match callback(ssl, is_export != 0, keylength as u32) {
        Ok(dh) => {
            let ptr = dh.as_ptr();
            mem::forget(dh);
            ptr
        }
        Err(e) => {
            e.put();
            ptr::null_mut()
        }
    }
}

#[cfg(all(ossl101, not(ossl110)))]
pub unsafe extern "C" fn raw_tmp_ecdh_ssl<F>(
    ssl: *mut ffi::SSL,
    is_export: c_int,
    keylength: c_int,
) -> *mut ffi::EC_KEY
where
    F: Fn(&mut SslRef, bool, u32) -> Result<EcKey<Params>, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ex_data(Ssl::cached_ex_index::<Arc<F>>())
        .expect("BUG: ssl tmp ecdh callback missing")
        .clone();

    match callback(ssl, is_export != 0, keylength as u32) {
        Ok(ec_key) => {
            let ptr = ec_key.as_ptr();
            mem::forget(ec_key);
            ptr
        }
        Err(e) => {
            e.put();
            ptr::null_mut()
        }
    }
}

pub unsafe extern "C" fn raw_tlsext_status<F>(ssl: *mut ffi::SSL, _: *mut c_void) -> c_int
where
    F: Fn(&mut SslRef) -> Result<bool, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ssl_context()
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: ocsp callback missing") as *const F;
    let ret = (*callback)(ssl);

    if ssl.is_server() {
        match ret {
            Ok(true) => ffi::SSL_TLSEXT_ERR_OK,
            Ok(false) => ffi::SSL_TLSEXT_ERR_NOACK,
            Err(e) => {
                e.put();
                ffi::SSL_TLSEXT_ERR_ALERT_FATAL
            }
        }
    } else {
        match ret {
            Ok(true) => 1,
            Ok(false) => 0,
            Err(e) => {
                e.put();
                -1
            }
        }
    }
}

pub unsafe extern "C" fn raw_new_session<F>(
    ssl: *mut ffi::SSL,
    session: *mut ffi::SSL_SESSION,
) -> c_int
where
    F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send,
{
    let session_ctx_index =
        try_get_session_ctx_index().expect("BUG: session context index initialization failed");
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ex_data(*session_ctx_index)
        .expect("BUG: session context missing")
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: new session callback missing") as *const F;
    let session = SslSession::from_ptr(session);

    (*callback)(ssl, session);

    // the return code doesn't indicate error vs success, but whether or not we consumed the session
    1
}

pub unsafe extern "C" fn raw_remove_session<F>(
    ctx: *mut ffi::SSL_CTX,
    session: *mut ffi::SSL_SESSION,
) where
    F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send,
{
    let ctx = SslContextRef::from_ptr(ctx);
    let callback = ctx
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: remove session callback missing");
    let session = SslSessionRef::from_ptr(session);

    callback(ctx, session)
}

cfg_if! {
    if #[cfg(any(ossl110, libressl280, boringssl))] {
        type DataPtr = *const c_uchar;
    } else {
        type DataPtr = *mut c_uchar;
    }
}

pub unsafe extern "C" fn raw_get_session<F>(
    ssl: *mut ffi::SSL,
    data: DataPtr,
    len: c_int,
    copy: *mut c_int,
) -> *mut ffi::SSL_SESSION
where
    F: Fn(&mut SslRef, &[u8]) -> Option<SslSession> + 'static + Sync + Send,
{
    let session_ctx_index =
        try_get_session_ctx_index().expect("BUG: session context index initialization failed");
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ex_data(*session_ctx_index)
        .expect("BUG: session context missing")
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: get session callback missing") as *const F;
    let data = slice::from_raw_parts(data as *const u8, len as usize);

    match (*callback)(ssl, data) {
        Some(session) => {
            let p = session.as_ptr();
            mem::forget(session);
            *copy = 0;
            p
        }
        None => ptr::null_mut(),
    }
}

#[cfg(ossl111)]
pub unsafe extern "C" fn raw_keylog<F>(ssl: *const ffi::SSL, line: *const c_char)
where
    F: Fn(&SslRef, &str) + 'static + Sync + Send,
{
    let ssl = SslRef::from_const_ptr(ssl);
    let callback = ssl
        .ssl_context()
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: get session callback missing");
    let line = CStr::from_ptr(line).to_bytes();
    let line = str::from_utf8_unchecked(line);

    callback(ssl, line);
}

#[cfg(ossl111)]
pub unsafe extern "C" fn raw_stateless_cookie_generate<F>(
    ssl: *mut ffi::SSL,
    cookie: *mut c_uchar,
    cookie_len: *mut size_t,
) -> c_int
where
    F: Fn(&mut SslRef, &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ssl_context()
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: stateless cookie generate callback missing") as *const F;
    let slice = slice::from_raw_parts_mut(cookie as *mut u8, ffi::SSL_COOKIE_LENGTH as usize);
    match (*callback)(ssl, slice) {
        Ok(len) => {
            *cookie_len = len as size_t;
            1
        }
        Err(e) => {
            e.put();
            0
        }
    }
}

#[cfg(ossl111)]
pub unsafe extern "C" fn raw_stateless_cookie_verify<F>(
    ssl: *mut ffi::SSL,
    cookie: *const c_uchar,
    cookie_len: size_t,
) -> c_int
where
    F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ssl_context()
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: stateless cookie verify callback missing") as *const F;
    let slice = slice::from_raw_parts(cookie as *const c_uchar as *const u8, cookie_len);
    (*callback)(ssl, slice) as c_int
}

#[cfg(not(boringssl))]
pub extern "C" fn raw_cookie_generate<F>(
    ssl: *mut ffi::SSL,
    cookie: *mut c_uchar,
    cookie_len: *mut c_uint,
) -> c_int
where
    F: Fn(&mut SslRef, &mut [u8]) -> Result<usize, ErrorStack> + 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback = ssl
            .ssl_context()
            .ex_data(SslContext::cached_ex_index::<F>())
            .expect("BUG: cookie generate callback missing") as *const F;
        // We subtract 1 from DTLS1_COOKIE_LENGTH as the ostensible value, 256, is erroneous but retained for
        // compatibility. See comments in dtls1.h.
        let slice =
            slice::from_raw_parts_mut(cookie as *mut u8, ffi::DTLS1_COOKIE_LENGTH as usize - 1);
        match (*callback)(ssl, slice) {
            Ok(len) => {
                *cookie_len = len as c_uint;
                1
            }
            Err(e) => {
                e.put();
                0
            }
        }
    }
}

#[cfg(not(boringssl))]
cfg_if! {
    if #[cfg(any(ossl110, libressl280))] {
        type CookiePtr = *const c_uchar;
    } else {
        type CookiePtr = *mut c_uchar;
    }
}

#[cfg(not(boringssl))]
pub extern "C" fn raw_cookie_verify<F>(
    ssl: *mut ffi::SSL,
    cookie: CookiePtr,
    cookie_len: c_uint,
) -> c_int
where
    F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback = ssl
            .ssl_context()
            .ex_data(SslContext::cached_ex_index::<F>())
            .expect("BUG: cookie verify callback missing") as *const F;
        let slice =
            slice::from_raw_parts(cookie as *const c_uchar as *const u8, cookie_len as usize);
        (*callback)(ssl, slice) as c_int
    }
}

#[cfg(ossl111)]
pub struct CustomExtAddState<T>(Option<T>);

#[cfg(ossl111)]
pub extern "C" fn raw_custom_ext_add<F, T>(
    ssl: *mut ffi::SSL,
    _: c_uint,
    context: c_uint,
    out: *mut *const c_uchar,
    outlen: *mut size_t,
    x: *mut ffi::X509,
    chainidx: size_t,
    al: *mut c_int,
    _: *mut c_void,
) -> c_int
where
    F: Fn(&mut SslRef, ExtensionContext, Option<(usize, &X509Ref)>) -> Result<Option<T>, SslAlert>
        + 'static
        + Sync
        + Send,
    T: AsRef<[u8]> + 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback = ssl
            .ssl_context()
            .ex_data(SslContext::cached_ex_index::<F>())
            .expect("BUG: custom ext add callback missing") as *const F;
        let ectx = ExtensionContext::from_bits_truncate(context);
        let cert = if ectx.contains(ExtensionContext::TLS1_3_CERTIFICATE) {
            Some((chainidx, X509Ref::from_ptr(x)))
        } else {
            None
        };
        match (*callback)(ssl, ectx, cert) {
            Ok(None) => 0,
            Ok(Some(buf)) => {
                *outlen = buf.as_ref().len();
                *out = buf.as_ref().as_ptr();

                let idx = Ssl::cached_ex_index::<CustomExtAddState<T>>();
                let mut buf = Some(buf);
                let new = match ssl.ex_data_mut(idx) {
                    Some(state) => {
                        state.0 = buf.take();
                        false
                    }
                    None => true,
                };
                if new {
                    ssl.set_ex_data(idx, CustomExtAddState(buf));
                }
                1
            }
            Err(alert) => {
                *al = alert.0;
                -1
            }
        }
    }
}

#[cfg(ossl111)]
pub extern "C" fn raw_custom_ext_free<T>(
    ssl: *mut ffi::SSL,
    _: c_uint,
    _: c_uint,
    _: *const c_uchar,
    _: *mut c_void,
) where
    T: 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let idx = Ssl::cached_ex_index::<CustomExtAddState<T>>();
        if let Some(state) = ssl.ex_data_mut(idx) {
            state.0 = None;
        }
    }
}

#[cfg(ossl111)]
pub extern "C" fn raw_custom_ext_parse<F>(
    ssl: *mut ffi::SSL,
    _: c_uint,
    context: c_uint,
    input: *const c_uchar,
    inlen: size_t,
    x: *mut ffi::X509,
    chainidx: size_t,
    al: *mut c_int,
    _: *mut c_void,
) -> c_int
where
    F: Fn(&mut SslRef, ExtensionContext, &[u8], Option<(usize, &X509Ref)>) -> Result<(), SslAlert>
        + 'static
        + Sync
        + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback = ssl
            .ssl_context()
            .ex_data(SslContext::cached_ex_index::<F>())
            .expect("BUG: custom ext parse callback missing") as *const F;
        let ectx = ExtensionContext::from_bits_truncate(context);
        let slice = slice::from_raw_parts(input as *const u8, inlen);
        let cert = if ectx.contains(ExtensionContext::TLS1_3_CERTIFICATE) {
            Some((chainidx, X509Ref::from_ptr(x)))
        } else {
            None
        };
        match (*callback)(ssl, ectx, slice, cert) {
            Ok(()) => 1,
            Err(alert) => {
                *al = alert.0;
                0
            }
        }
    }
}

Returns a mutable reference to the X509 verification configuration.

Requires OpenSSL 1.0.2 or newer.

This corresponds to SSL_get0_param.

Examples found in repository?
src/ssl/connector.rs (line 395)
392
393
394
395
396
397
398
399
400
401
        fn setup_verify_hostname(ssl: &mut SslRef, domain: &str) -> Result<(), ErrorStack> {
            use crate::x509::verify::X509CheckFlags;

            let param = ssl.param_mut();
            param.set_hostflags(X509CheckFlags::NO_PARTIAL_WILDCARDS);
            match domain.parse() {
                Ok(ip) => param.set_ip(ip),
                Err(_) => param.set_host(domain),
            }
        }

Returns the certificate verification result.

This corresponds to SSL_get_verify_result.

Examples found in repository?
src/ssl/mod.rs (line 2259)
2256
2257
2258
2259
2260
2261
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("Ssl")
            .field("state", &self.state_string_long())
            .field("verify_result", &self.verify_result())
            .finish()
    }
More examples
Hide additional examples
src/ssl/error.rs (line 164)
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            HandshakeError::SetupFailure(ref e) => write!(f, "stream setup failed: {}", e)?,
            HandshakeError::Failure(ref s) => {
                write!(f, "the handshake failed: {}", s.error())?;
                let verify = s.ssl().verify_result();
                if verify != X509VerifyResult::OK {
                    write!(f, ": {}", verify)?;
                }
            }
            HandshakeError::WouldBlock(ref s) => {
                write!(f, "the handshake was interrupted: {}", s.error())?;
                let verify = s.ssl().verify_result();
                if verify != X509VerifyResult::OK {
                    write!(f, ": {}", verify)?;
                }
            }
        }
        Ok(())
    }

Returns a shared reference to the SSL session.

This corresponds to SSL_get_session.

Copies the client_random value sent by the client in the TLS handshake into a buffer.

Returns the number of bytes copied, or if the buffer is empty, the size of the client_random value.

Requires OpenSSL 1.1.0 or LibreSSL 2.7.0 or newer.

This corresponds to SSL_get_client_random.

Copies the server_random value sent by the server in the TLS handshake into a buffer.

Returns the number of bytes copied, or if the buffer is empty, the size of the server_random value.

Requires OpenSSL 1.1.0 or LibreSSL 2.7.0 or newer.

This corresponds to SSL_get_server_random.

Derives keying material for application use in accordance to RFC 5705.

This corresponds to SSL_export_keying_material.

Derives keying material for application use in accordance to RFC 5705.

This function is only usable with TLSv1.3, wherein there is no distinction between an empty context and no context. Therefore, unlike export_keying_material, context must always be supplied.

Requires OpenSSL 1.1.1 or newer.

This corresponds to SSL_export_keying_material_early.

Sets the session to be used.

This should be called before the handshake to attempt to reuse a previously established session. If the server is not willing to reuse the session, a new one will be transparently negotiated.

Safety

The caller of this method is responsible for ensuring that the session is associated with the same SslContext as this Ssl.

This corresponds to SSL_set_session.

Determines if the session provided to set_session was successfully reused.

This corresponds to SSL_session_reused.

Sets the status response a client wishes the server to reply with.

This corresponds to SSL_set_tlsext_status_type.

Determines if current session used Extended Master Secret

Returns None if the handshake is still in-progress.

This corresponds to SSL_get_extms_support.

Returns the server’s OCSP response, if present.

This corresponds to SSL_get_tlsext_status_ocsp_resp.

Sets the OCSP response to be returned to the client.

This corresponds to SSL_set_tlsext_status_oscp_resp.

Determines if this Ssl is configured for server-side or client-side use.

This corresponds to SSL_is_server.

Examples found in repository?
src/ssl/callbacks.rs (line 331)
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
pub unsafe extern "C" fn raw_tlsext_status<F>(ssl: *mut ffi::SSL, _: *mut c_void) -> c_int
where
    F: Fn(&mut SslRef) -> Result<bool, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ssl_context()
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: ocsp callback missing") as *const F;
    let ret = (*callback)(ssl);

    if ssl.is_server() {
        match ret {
            Ok(true) => ffi::SSL_TLSEXT_ERR_OK,
            Ok(false) => ffi::SSL_TLSEXT_ERR_NOACK,
            Err(e) => {
                e.put();
                ffi::SSL_TLSEXT_ERR_ALERT_FATAL
            }
        }
    } else {
        match ret {
            Ok(true) => 1,
            Ok(false) => 0,
            Err(e) => {
                e.put();
                -1
            }
        }
    }
}

Sets the extra data at the specified index.

This can be used to provide data to callbacks registered with the context. Use the Ssl::new_ex_index method to create an Index.

This corresponds to SSL_set_ex_data.

Examples found in repository?
src/ssl/mod.rs (line 2210)
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
    pub fn new(ctx: &SslContextRef) -> Result<Ssl, ErrorStack> {
        let session_ctx_index = try_get_session_ctx_index()?;
        unsafe {
            let ptr = cvt_p(ffi::SSL_new(ctx.as_ptr()))?;
            let mut ssl = Ssl::from_ptr(ptr);
            ssl.set_ex_data(*session_ctx_index, ctx.to_owned());

            Ok(ssl)
        }
    }

    /// Initiates a client-side TLS handshake.
    ///
    /// This corresponds to [`SSL_connect`].
    ///
    /// # Warning
    ///
    /// OpenSSL's default configuration is insecure. It is highly recommended to use
    /// `SslConnector` rather than `Ssl` directly, as it manages that configuration.
    ///
    /// [`SSL_connect`]: https://www.openssl.org/docs/manmaster/man3/SSL_connect.html
    #[corresponds(SSL_connect)]
    #[allow(deprecated)]
    pub fn connect<S>(self, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
    where
        S: Read + Write,
    {
        SslStreamBuilder::new(self, stream).connect()
    }

    /// Initiates a server-side TLS handshake.
    ///
    /// This corresponds to [`SSL_accept`].
    ///
    /// # Warning
    ///
    /// OpenSSL's default configuration is insecure. It is highly recommended to use
    /// `SslAcceptor` rather than `Ssl` directly, as it manages that configuration.
    ///
    /// [`SSL_accept`]: https://www.openssl.org/docs/manmaster/man3/SSL_accept.html
    #[corresponds(SSL_accept)]
    #[allow(deprecated)]
    pub fn accept<S>(self, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
    where
        S: Read + Write,
    {
        SslStreamBuilder::new(self, stream).accept()
    }
}

impl fmt::Debug for SslRef {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("Ssl")
            .field("state", &self.state_string_long())
            .field("verify_result", &self.verify_result())
            .finish()
    }
}

impl SslRef {
    fn get_raw_rbio(&self) -> *mut ffi::BIO {
        unsafe { ffi::SSL_get_rbio(self.as_ptr()) }
    }

    fn read(&mut self, buf: &mut [u8]) -> c_int {
        let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int;
        unsafe { ffi::SSL_read(self.as_ptr(), buf.as_ptr() as *mut c_void, len) }
    }

    fn peek(&mut self, buf: &mut [u8]) -> c_int {
        let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int;
        unsafe { ffi::SSL_peek(self.as_ptr(), buf.as_ptr() as *mut c_void, len) }
    }

    fn write(&mut self, buf: &[u8]) -> c_int {
        let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int;
        unsafe { ffi::SSL_write(self.as_ptr(), buf.as_ptr() as *const c_void, len) }
    }

    fn get_error(&self, ret: c_int) -> ErrorCode {
        unsafe { ErrorCode::from_raw(ffi::SSL_get_error(self.as_ptr(), ret)) }
    }

    /// Configure as an outgoing stream from a client.
    #[corresponds(SSL_set_connect_state)]
    pub fn set_connect_state(&mut self) {
        unsafe { ffi::SSL_set_connect_state(self.as_ptr()) }
    }

    /// Configure as an incoming stream to a server.
    #[corresponds(SSL_set_accept_state)]
    pub fn set_accept_state(&mut self) {
        unsafe { ffi::SSL_set_accept_state(self.as_ptr()) }
    }

    /// Like [`SslContextBuilder::set_verify`].
    ///
    /// [`SslContextBuilder::set_verify`]: struct.SslContextBuilder.html#method.set_verify
    #[corresponds(SSL_set_verify)]
    pub fn set_verify(&mut self, mode: SslVerifyMode) {
        unsafe { ffi::SSL_set_verify(self.as_ptr(), mode.bits as c_int, None) }
    }

    /// Returns the verify mode that was set using `set_verify`.
    #[corresponds(SSL_set_verify_mode)]
    pub fn verify_mode(&self) -> SslVerifyMode {
        let mode = unsafe { ffi::SSL_get_verify_mode(self.as_ptr()) };
        SslVerifyMode::from_bits(mode).expect("SSL_get_verify_mode returned invalid mode")
    }

    /// Like [`SslContextBuilder::set_verify_callback`].
    ///
    /// [`SslContextBuilder::set_verify_callback`]: struct.SslContextBuilder.html#method.set_verify_callback
    #[corresponds(SSL_set_verify)]
    pub fn set_verify_callback<F>(&mut self, mode: SslVerifyMode, verify: F)
    where
        F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,
    {
        unsafe {
            // this needs to be in an Arc since the callback can register a new callback!
            self.set_ex_data(Ssl::cached_ex_index(), Arc::new(verify));
            ffi::SSL_set_verify(self.as_ptr(), mode.bits as c_int, Some(ssl_raw_verify::<F>));
        }
    }

    /// Like [`SslContextBuilder::set_tmp_dh`].
    ///
    /// [`SslContextBuilder::set_tmp_dh`]: struct.SslContextBuilder.html#method.set_tmp_dh
    #[corresponds(SSL_set_tmp_dh)]
    pub fn set_tmp_dh(&mut self, dh: &DhRef<Params>) -> Result<(), ErrorStack> {
        unsafe { cvt(ffi::SSL_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) }
    }

    /// Like [`SslContextBuilder::set_tmp_dh_callback`].
    ///
    /// [`SslContextBuilder::set_tmp_dh_callback`]: struct.SslContextBuilder.html#method.set_tmp_dh_callback
    #[corresponds(SSL_set_tmp_dh_callback)]
    pub fn set_tmp_dh_callback<F>(&mut self, callback: F)
    where
        F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
    {
        unsafe {
            // this needs to be in an Arc since the callback can register a new callback!
            self.set_ex_data(Ssl::cached_ex_index(), Arc::new(callback));
            #[cfg(boringssl)]
            ffi::SSL_set_tmp_dh_callback(self.as_ptr(), Some(raw_tmp_dh_ssl::<F>));
            #[cfg(not(boringssl))]
            ffi::SSL_set_tmp_dh_callback__fixed_rust(self.as_ptr(), Some(raw_tmp_dh_ssl::<F>));
        }
    }
More examples
Hide additional examples
src/ssl/callbacks.rs (line 601)
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
pub extern "C" fn raw_custom_ext_add<F, T>(
    ssl: *mut ffi::SSL,
    _: c_uint,
    context: c_uint,
    out: *mut *const c_uchar,
    outlen: *mut size_t,
    x: *mut ffi::X509,
    chainidx: size_t,
    al: *mut c_int,
    _: *mut c_void,
) -> c_int
where
    F: Fn(&mut SslRef, ExtensionContext, Option<(usize, &X509Ref)>) -> Result<Option<T>, SslAlert>
        + 'static
        + Sync
        + Send,
    T: AsRef<[u8]> + 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback = ssl
            .ssl_context()
            .ex_data(SslContext::cached_ex_index::<F>())
            .expect("BUG: custom ext add callback missing") as *const F;
        let ectx = ExtensionContext::from_bits_truncate(context);
        let cert = if ectx.contains(ExtensionContext::TLS1_3_CERTIFICATE) {
            Some((chainidx, X509Ref::from_ptr(x)))
        } else {
            None
        };
        match (*callback)(ssl, ectx, cert) {
            Ok(None) => 0,
            Ok(Some(buf)) => {
                *outlen = buf.as_ref().len();
                *out = buf.as_ref().as_ptr();

                let idx = Ssl::cached_ex_index::<CustomExtAddState<T>>();
                let mut buf = Some(buf);
                let new = match ssl.ex_data_mut(idx) {
                    Some(state) => {
                        state.0 = buf.take();
                        false
                    }
                    None => true,
                };
                if new {
                    ssl.set_ex_data(idx, CustomExtAddState(buf));
                }
                1
            }
            Err(alert) => {
                *al = alert.0;
                -1
            }
        }
    }
}

Returns a reference to the extra data at the specified index.

This corresponds to SSL_get_ex_data.

Examples found in repository?
src/ssl/callbacks.rs (line 153)
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
pub extern "C" fn ssl_raw_verify<F>(
    preverify_ok: c_int,
    x509_ctx: *mut ffi::X509_STORE_CTX,
) -> c_int
where
    F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send,
{
    unsafe {
        let ctx = X509StoreContextRef::from_ptr_mut(x509_ctx);
        let ssl_idx = X509StoreContext::ssl_idx().expect("BUG: store context ssl index missing");
        let callback_idx = Ssl::cached_ex_index::<Arc<F>>();

        let callback = ctx
            .ex_data(ssl_idx)
            .expect("BUG: store context missing ssl")
            .ex_data(callback_idx)
            .expect("BUG: ssl verify callback missing")
            .clone();

        callback(preverify_ok != 0, ctx) as c_int
    }
}

pub extern "C" fn raw_sni<F>(ssl: *mut ffi::SSL, al: *mut c_int, arg: *mut c_void) -> c_int
where
    F: Fn(&mut SslRef, &mut SslAlert) -> Result<(), SniError> + 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback = arg as *const F;
        let mut alert = SslAlert(*al);

        let r = (*callback)(ssl, &mut alert);
        *al = alert.0;
        match r {
            Ok(()) => ffi::SSL_TLSEXT_ERR_OK,
            Err(e) => e.0,
        }
    }
}

#[cfg(any(ossl102, libressl261))]
pub extern "C" fn raw_alpn_select<F>(
    ssl: *mut ffi::SSL,
    out: *mut *const c_uchar,
    outlen: *mut c_uchar,
    inbuf: *const c_uchar,
    inlen: c_uint,
    _arg: *mut c_void,
) -> c_int
where
    F: for<'a> Fn(&mut SslRef, &'a [u8]) -> Result<&'a [u8], AlpnError> + 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback = ssl
            .ssl_context()
            .ex_data(SslContext::cached_ex_index::<F>())
            .expect("BUG: alpn callback missing") as *const F;
        let protos = slice::from_raw_parts(inbuf as *const u8, inlen as usize);

        match (*callback)(ssl, protos) {
            Ok(proto) => {
                *out = proto.as_ptr() as *const c_uchar;
                *outlen = proto.len() as c_uchar;
                ffi::SSL_TLSEXT_ERR_OK
            }
            Err(e) => e.0,
        }
    }
}

pub unsafe extern "C" fn raw_tmp_dh<F>(
    ssl: *mut ffi::SSL,
    is_export: c_int,
    keylength: c_int,
) -> *mut ffi::DH
where
    F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ssl_context()
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: tmp dh callback missing") as *const F;

    match (*callback)(ssl, is_export != 0, keylength as u32) {
        Ok(dh) => {
            let ptr = dh.as_ptr();
            mem::forget(dh);
            ptr
        }
        Err(e) => {
            e.put();
            ptr::null_mut()
        }
    }
}

#[cfg(all(ossl101, not(ossl110)))]
pub unsafe extern "C" fn raw_tmp_ecdh<F>(
    ssl: *mut ffi::SSL,
    is_export: c_int,
    keylength: c_int,
) -> *mut ffi::EC_KEY
where
    F: Fn(&mut SslRef, bool, u32) -> Result<EcKey<Params>, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ssl_context()
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: tmp ecdh callback missing") as *const F;

    match (*callback)(ssl, is_export != 0, keylength as u32) {
        Ok(ec_key) => {
            let ptr = ec_key.as_ptr();
            mem::forget(ec_key);
            ptr
        }
        Err(e) => {
            e.put();
            ptr::null_mut()
        }
    }
}

pub unsafe extern "C" fn raw_tmp_dh_ssl<F>(
    ssl: *mut ffi::SSL,
    is_export: c_int,
    keylength: c_int,
) -> *mut ffi::DH
where
    F: Fn(&mut SslRef, bool, u32) -> Result<Dh<Params>, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ex_data(Ssl::cached_ex_index::<Arc<F>>())
        .expect("BUG: ssl tmp dh callback missing")
        .clone();

    match callback(ssl, is_export != 0, keylength as u32) {
        Ok(dh) => {
            let ptr = dh.as_ptr();
            mem::forget(dh);
            ptr
        }
        Err(e) => {
            e.put();
            ptr::null_mut()
        }
    }
}

#[cfg(all(ossl101, not(ossl110)))]
pub unsafe extern "C" fn raw_tmp_ecdh_ssl<F>(
    ssl: *mut ffi::SSL,
    is_export: c_int,
    keylength: c_int,
) -> *mut ffi::EC_KEY
where
    F: Fn(&mut SslRef, bool, u32) -> Result<EcKey<Params>, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ex_data(Ssl::cached_ex_index::<Arc<F>>())
        .expect("BUG: ssl tmp ecdh callback missing")
        .clone();

    match callback(ssl, is_export != 0, keylength as u32) {
        Ok(ec_key) => {
            let ptr = ec_key.as_ptr();
            mem::forget(ec_key);
            ptr
        }
        Err(e) => {
            e.put();
            ptr::null_mut()
        }
    }
}

pub unsafe extern "C" fn raw_tlsext_status<F>(ssl: *mut ffi::SSL, _: *mut c_void) -> c_int
where
    F: Fn(&mut SslRef) -> Result<bool, ErrorStack> + 'static + Sync + Send,
{
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ssl_context()
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: ocsp callback missing") as *const F;
    let ret = (*callback)(ssl);

    if ssl.is_server() {
        match ret {
            Ok(true) => ffi::SSL_TLSEXT_ERR_OK,
            Ok(false) => ffi::SSL_TLSEXT_ERR_NOACK,
            Err(e) => {
                e.put();
                ffi::SSL_TLSEXT_ERR_ALERT_FATAL
            }
        }
    } else {
        match ret {
            Ok(true) => 1,
            Ok(false) => 0,
            Err(e) => {
                e.put();
                -1
            }
        }
    }
}

pub unsafe extern "C" fn raw_new_session<F>(
    ssl: *mut ffi::SSL,
    session: *mut ffi::SSL_SESSION,
) -> c_int
where
    F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send,
{
    let session_ctx_index =
        try_get_session_ctx_index().expect("BUG: session context index initialization failed");
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ex_data(*session_ctx_index)
        .expect("BUG: session context missing")
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: new session callback missing") as *const F;
    let session = SslSession::from_ptr(session);

    (*callback)(ssl, session);

    // the return code doesn't indicate error vs success, but whether or not we consumed the session
    1
}

pub unsafe extern "C" fn raw_remove_session<F>(
    ctx: *mut ffi::SSL_CTX,
    session: *mut ffi::SSL_SESSION,
) where
    F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send,
{
    let ctx = SslContextRef::from_ptr(ctx);
    let callback = ctx
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: remove session callback missing");
    let session = SslSessionRef::from_ptr(session);

    callback(ctx, session)
}

cfg_if! {
    if #[cfg(any(ossl110, libressl280, boringssl))] {
        type DataPtr = *const c_uchar;
    } else {
        type DataPtr = *mut c_uchar;
    }
}

pub unsafe extern "C" fn raw_get_session<F>(
    ssl: *mut ffi::SSL,
    data: DataPtr,
    len: c_int,
    copy: *mut c_int,
) -> *mut ffi::SSL_SESSION
where
    F: Fn(&mut SslRef, &[u8]) -> Option<SslSession> + 'static + Sync + Send,
{
    let session_ctx_index =
        try_get_session_ctx_index().expect("BUG: session context index initialization failed");
    let ssl = SslRef::from_ptr_mut(ssl);
    let callback = ssl
        .ex_data(*session_ctx_index)
        .expect("BUG: session context missing")
        .ex_data(SslContext::cached_ex_index::<F>())
        .expect("BUG: get session callback missing") as *const F;
    let data = slice::from_raw_parts(data as *const u8, len as usize);

    match (*callback)(ssl, data) {
        Some(session) => {
            let p = session.as_ptr();
            mem::forget(session);
            *copy = 0;
            p
        }
        None => ptr::null_mut(),
    }
}

Returns a mutable reference to the extra data at the specified index.

This corresponds to SSL_get_ex_data.

Examples found in repository?
src/ssl/callbacks.rs (line 593)
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
pub extern "C" fn raw_custom_ext_add<F, T>(
    ssl: *mut ffi::SSL,
    _: c_uint,
    context: c_uint,
    out: *mut *const c_uchar,
    outlen: *mut size_t,
    x: *mut ffi::X509,
    chainidx: size_t,
    al: *mut c_int,
    _: *mut c_void,
) -> c_int
where
    F: Fn(&mut SslRef, ExtensionContext, Option<(usize, &X509Ref)>) -> Result<Option<T>, SslAlert>
        + 'static
        + Sync
        + Send,
    T: AsRef<[u8]> + 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let callback = ssl
            .ssl_context()
            .ex_data(SslContext::cached_ex_index::<F>())
            .expect("BUG: custom ext add callback missing") as *const F;
        let ectx = ExtensionContext::from_bits_truncate(context);
        let cert = if ectx.contains(ExtensionContext::TLS1_3_CERTIFICATE) {
            Some((chainidx, X509Ref::from_ptr(x)))
        } else {
            None
        };
        match (*callback)(ssl, ectx, cert) {
            Ok(None) => 0,
            Ok(Some(buf)) => {
                *outlen = buf.as_ref().len();
                *out = buf.as_ref().as_ptr();

                let idx = Ssl::cached_ex_index::<CustomExtAddState<T>>();
                let mut buf = Some(buf);
                let new = match ssl.ex_data_mut(idx) {
                    Some(state) => {
                        state.0 = buf.take();
                        false
                    }
                    None => true,
                };
                if new {
                    ssl.set_ex_data(idx, CustomExtAddState(buf));
                }
                1
            }
            Err(alert) => {
                *al = alert.0;
                -1
            }
        }
    }
}

#[cfg(ossl111)]
pub extern "C" fn raw_custom_ext_free<T>(
    ssl: *mut ffi::SSL,
    _: c_uint,
    _: c_uint,
    _: *const c_uchar,
    _: *mut c_void,
) where
    T: 'static + Sync + Send,
{
    unsafe {
        let ssl = SslRef::from_ptr_mut(ssl);
        let idx = Ssl::cached_ex_index::<CustomExtAddState<T>>();
        if let Some(state) = ssl.ex_data_mut(idx) {
            state.0 = None;
        }
    }
}

Sets the maximum amount of early data that will be accepted on this connection.

Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.

This corresponds to SSL_set_max_early_data.

Gets the maximum amount of early data that can be sent on this connection.

Requires OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer.

This corresponds to SSL_get_max_early_data.

Copies the contents of the last Finished message sent to the peer into the provided buffer.

The total size of the message is returned, so this can be used to determine the size of the buffer required.

This corresponds to SSL_get_finished.

Copies the contents of the last Finished message received from the peer into the provided buffer.

The total size of the message is returned, so this can be used to determine the size of the buffer required.

This corresponds to SSL_get_peer_finished.

Determines if the initial handshake has been completed.

This corresponds to SSL_is_init_finished.

Determines if the client’s hello message is in the SSLv2 format.

This can only be used inside of the client hello callback. Otherwise, false is returned.

Requires OpenSSL 1.1.1 or newer.

This corresponds to SSL_client_hello_isv2.

Returns the legacy version field of the client’s hello message.

This can only be used inside of the client hello callback. Otherwise, None is returned.

Requires OpenSSL 1.1.1 or newer.

This corresponds to SSL_client_hello_get0_legacy_version.

Returns the random field of the client’s hello message.

This can only be used inside of the client hello callback. Otherwise, None is returned.

Requires OpenSSL 1.1.1 or newer.

This corresponds to SSL_client_hello_get0_random.

Returns the session ID field of the client’s hello message.

This can only be used inside of the client hello callback. Otherwise, None is returned.

Requires OpenSSL 1.1.1 or newer.

This corresponds to SSL_client_hello_get0_session_id.

Returns the ciphers field of the client’s hello message.

This can only be used inside of the client hello callback. Otherwise, None is returned.

Requires OpenSSL 1.1.1 or newer.

This corresponds to SSL_client_hello_get0_ciphers.

Returns the compression methods field of the client’s hello message.

This can only be used inside of the client hello callback. Otherwise, None is returned.

Requires OpenSSL 1.1.1 or newer.

This corresponds to SSL_client_hello_get0_compression_methods.

Sets the MTU used for DTLS connections.

This corresponds to SSL_set_mtu.

Returns the PSK identity hint used during connection setup.

May return None if no PSK identity hint was used during the connection setup.

This corresponds to SSL_get_psk_identity_hint.

Returns the PSK identity used during connection setup.

This corresponds to SSL_get_psk_identity.

This corresponds to SSL_add0_chain_cert.

Trait Implementations§

Converts this type into a shared reference of the (usually inferred) input type.
Immutably borrows from an owned value. Read more
Formats the value using the given formatter. Read more
The raw C type.
Constructs a shared instance of this type from its raw type.
Constructs a mutable reference of this type from its raw type.
Returns a raw pointer to the wrapped value.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.