rustls-openssl 0.3.0

Rustls crypto provider for OpenSSL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
//! Integration tests
use crate::server::start_server;
use openssl::bn::BigNumContext;
use openssl::ec::{EcGroup, EcKey, PointConversionForm};
use openssl::nid::Nid;
#[cfg(not(feature = "fips"))]
use openssl::pkey::PKey;
use openssl::rsa::Rsa;
use rstest::rstest;
use rustls::crypto::{CryptoProvider, SupportedKxGroup};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::{CipherSuite, SignatureScheme, SupportedCipherSuite};
use rustls_openssl::{custom_provider, default_provider};
use std::io::{Read, Write};
use std::net::TcpStream;
use std::sync::Arc;

pub mod server;

fn test_with_provider(
    provider: CryptoProvider,
    port: u16,
    root_ca_certs: Vec<CertificateDer<'static>>,
) -> CipherSuite {
    #[cfg(feature = "fips")]
    {
        rustls_openssl::fips::enable();
    }

    // Add default webpki roots to the root store
    let mut root_store = rustls::RootCertStore {
        roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
    };

    root_store.add_parsable_certificates(root_ca_certs);

    #[allow(unused_mut)]
    let mut config = rustls::ClientConfig::builder_with_provider(Arc::new(provider))
        .with_safe_default_protocol_versions()
        .unwrap()
        .with_root_certificates(root_store)
        .with_no_client_auth();

    #[cfg(feature = "fips")]
    {
        config.require_ems = true;
        assert!(config.fips());
    }

    let server_name = "localhost".try_into().unwrap();

    let mut sock = TcpStream::connect(format!("localhost:{port}")).unwrap();

    let mut conn = rustls::ClientConnection::new(Arc::new(config), server_name).unwrap();
    let mut tls = rustls::Stream::new(&mut conn, &mut sock);
    tls.write_all(
        concat!(
            "GET / HTTP/1.1\r\n",
            "Host: localhost\r\n",
            "Connection: close\r\n",
            "Accept-Encoding: identity\r\n",
            "\r\n"
        )
        .as_bytes(),
    )
    .unwrap();

    let ciphersuite = tls.conn.negotiated_cipher_suite().unwrap();

    let mut exit_buffer: [u8; 1] = [0]; // Size 1 because "q" is a single byte command
    exit_buffer[0] = b'q'; // Assign the ASCII value of "q" to the buffer

    // Write the "q" command to the TLS connection stream
    tls.write_all(&exit_buffer).unwrap();
    ciphersuite.suite()
}

#[rstest]
#[case::tls13_aes_128_gcm_sha256(
    rustls_openssl::cipher_suite::TLS13_AES_128_GCM_SHA256,
    rustls_openssl::kx_group::SECP384R1,
    server::Alg::PKCS_ECDSA_P256_SHA256,
    CipherSuite::TLS13_AES_128_GCM_SHA256
)]
#[case::tls13_aes_256_gcm_sha384(
    rustls_openssl::cipher_suite::TLS13_AES_256_GCM_SHA384,
    rustls_openssl::kx_group::SECP256R1,
    server::Alg::PKCS_ECDSA_P256_SHA256,
    CipherSuite::TLS13_AES_256_GCM_SHA384
)]
#[cfg_attr(
    all(chacha, not(feature = "fips")),
    case::tls13_chacha20_poly1305_sha256(
        rustls_openssl::cipher_suite::TLS13_CHACHA20_POLY1305_SHA256,
        rustls_openssl::kx_group::SECP256R1,
        server::Alg::PKCS_ECDSA_P256_SHA256,
        CipherSuite::TLS13_CHACHA20_POLY1305_SHA256
    )
)]
#[cfg_attr(
    feature = "tls12",
    case::tls_ecdhe_rsa_with_aes_256_gcm_sha384(
        rustls_openssl::cipher_suite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
        rustls_openssl::kx_group::SECP256R1,
        server::Alg::PKCS_RSA_SHA384,
        CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
    )
)]
#[cfg_attr(
    feature = "tls12",
    case::tls_ecdhe_rsa_with_aes_128_gcm_sha256(
        rustls_openssl::cipher_suite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
        rustls_openssl::kx_group::SECP256R1,
        server::Alg::PKCS_RSA_SHA384,
        CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
    )
)]
#[cfg_attr(
    not(feature = "fips"),
    case::tls13_aes_256_gcm_sha384_x25519(
        rustls_openssl::cipher_suite::TLS13_AES_256_GCM_SHA384,
        rustls_openssl::kx_group::X25519,
        server::Alg::PKCS_ECDSA_P256_SHA256,
        CipherSuite::TLS13_AES_256_GCM_SHA384
    )
)]
#[case::tls13_aes_256_gcm_sha384_secp384r1(
    rustls_openssl::cipher_suite::TLS13_AES_256_GCM_SHA384,
    rustls_openssl::kx_group::SECP384R1,
    server::Alg::PKCS_ECDSA_P256_SHA256,
    CipherSuite::TLS13_AES_256_GCM_SHA384
)]
#[cfg_attr(
    all(feature = "tls12", chacha, not(feature = "fips")),
    case::tls_ecdhe_rsa_with_chacha20_poly1305_sha256(
        rustls_openssl::cipher_suite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
        rustls_openssl::kx_group::SECP256R1,
        server::Alg::PKCS_RSA_SHA384,
        CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
    )
)]
#[cfg_attr(
    feature = "tls12",
    case::tls_ecdhe_ecdsa_with_aes_128_gcm_sha256(
        rustls_openssl::cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
        rustls_openssl::kx_group::SECP256R1,
        server::Alg::PKCS_ECDSA_P256_SHA256,
        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
    )
)]
#[cfg_attr(
    all(feature = "tls12", not(feature = "fips")),
    case::ed25519_tls12(
        rustls_openssl::cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
        rustls_openssl::kx_group::SECP256R1,
        server::Alg::PKCS_ED25519,
        CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
    )
)]
#[cfg_attr(
    all(feature = "tls12", not(feature = "fips")),
    case::tls_ecdhe_rsa_with_aes_256_gcm_sha384(
        rustls_openssl::cipher_suite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
        rustls_openssl::kx_group::X25519,
        server::Alg::PKCS_RSA_SHA384,
        CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
    )
)]
#[case::tls13_aes_256_gcm_sha384_secp384r1(
    rustls_openssl::cipher_suite::TLS13_AES_256_GCM_SHA384,
    rustls_openssl::kx_group::SECP384R1,
    server::Alg::PKCS_RSA_SHA512,
    CipherSuite::TLS13_AES_256_GCM_SHA384
)]
fn test_client_and_server(
    #[case] suite: SupportedCipherSuite,
    #[case] group: &'static dyn SupportedKxGroup,
    #[case] alg: server::Alg,
    #[case] expected: CipherSuite,
) {
    // Run against a server using our default provider
    let (port, certificate) = start_server(alg, None);
    let provider = custom_provider(vec![suite], vec![group]);
    let actual_suite = test_with_provider(provider, port, vec![certificate]);
    assert_eq!(actual_suite, expected);
}

#[cfg(ossl350)]
#[test]
fn test_classical_completion() {
    // Run against a server that only supports the classical component
    let provider = custom_provider(
        rustls_openssl::ALL_CIPHER_SUITES.to_vec(),
        vec![rustls_openssl::kx_group::X25519],
    );

    let (port, certificate) = start_server(server::Alg::PKCS_ECDSA_P256_SHA256, Some(provider));
    let provider = custom_provider(
        vec![rustls_openssl::cipher_suite::TLS13_AES_256_GCM_SHA384],
        // specifying both, with the hybrid first, causes rustls to reuse the classical component from the hybrid
        vec![
            rustls_openssl::kx_group::X25519MLKEM768,
            rustls_openssl::kx_group::X25519,
        ],
    );
    let actual_suite = test_with_provider(provider, port, vec![certificate]);
    assert_eq!(actual_suite, CipherSuite::TLS13_AES_256_GCM_SHA384);
}

#[rstest]
#[cfg_attr(
    all(feature = "tls12", chacha, not(feature = "fips")),
    case(
        rustls_openssl::cipher_suite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
        rustls_openssl::kx_group::SECP384R1,
        CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
    )
)]
#[case::tls13_aes_256_gcm_sha384(
    rustls_openssl::cipher_suite::TLS13_AES_256_GCM_SHA384,
    rustls_openssl::kx_group::SECP384R1,
    CipherSuite::TLS13_AES_256_GCM_SHA384
)]
fn test_to_internet(
    #[case] suite: SupportedCipherSuite,
    #[case] group: &'static dyn SupportedKxGroup,
    #[case] expected: CipherSuite,
) {
    #[cfg(feature = "fips")]
    {
        rustls_openssl::fips::enable();
    }

    let cipher_suites = vec![suite];
    let kx_group = vec![group];

    // Add default webpki roots to the root store
    let root_store = rustls::RootCertStore {
        roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
    };

    #[allow(unused_mut)]
    let mut config = rustls::ClientConfig::builder_with_provider(Arc::new(custom_provider(
        cipher_suites,
        kx_group,
    )))
    .with_safe_default_protocol_versions()
    .unwrap()
    .with_root_certificates(root_store)
    .with_no_client_auth();

    #[cfg(feature = "fips")]
    {
        config.require_ems = true;
        assert!(config.fips());
    }

    let server_name = "index.crates.io".try_into().unwrap();
    let mut sock = TcpStream::connect("index.crates.io:443").unwrap();

    let mut conn = rustls::ClientConnection::new(Arc::new(config), server_name).unwrap();
    let mut tls = rustls::Stream::new(&mut conn, &mut sock);

    tls.write_all(
        concat!(
            "GET /config.json HTTP/1.1\r\n",
            "Host: index.crates.io\r\n",
            "Connection: close\r\n",
            "Accept-Encoding: identity\r\n",
            "\r\n"
        )
        .as_bytes(),
    )
    .unwrap();

    let mut buf = Vec::new();
    tls.read_to_end(&mut buf).unwrap();
    assert!(String::from_utf8_lossy(&buf).contains("https://static.crates.io/crates"));

    let ciphersuite = tls.conn.negotiated_cipher_suite().unwrap();

    let mut exit_buffer: [u8; 1] = [0]; // Size 1 because "Q" is a single byte command
    exit_buffer[0] = b'q'; // Assign the ASCII value of "Q" to the buffer

    // Write the "Q" command to the TLS connection stream
    tls.write_all(&exit_buffer).unwrap();
    assert_eq!(ciphersuite.suite(), expected);
}

/// Test that the default provider returns the highest priority cipher suite
#[test]
fn test_default_client() {
    let (port, certificate) = start_server(server::Alg::PKCS_RSA_SHA512, None);
    let actual_suite = test_with_provider(default_provider(), port, vec![certificate]);
    assert_eq!(actual_suite, CipherSuite::TLS13_AES_256_GCM_SHA384);
}

static RSA_SIGNING_SCHEMES: &[SignatureScheme] = &[
    SignatureScheme::RSA_PKCS1_SHA256,
    SignatureScheme::RSA_PKCS1_SHA384,
    SignatureScheme::RSA_PKCS1_SHA512,
    SignatureScheme::RSA_PSS_SHA256,
    SignatureScheme::RSA_PSS_SHA384,
    SignatureScheme::RSA_PSS_SHA512,
];

#[test]
fn test_rsa_sign_and_verify() {
    #[cfg(feature = "fips")]
    {
        rustls_openssl::fips::enable();
    }
    let ours = rustls_openssl::default_provider();
    let theirs = rustls::crypto::aws_lc_rs::default_provider();

    let private_key = Rsa::generate(2048).unwrap();
    let rustls_private_key =
        PrivateKeyDer::from_pem_slice(&private_key.private_key_to_pem().unwrap()).unwrap();
    let pub_key = private_key.public_key_to_der_pkcs1().unwrap();

    for scheme in RSA_SIGNING_SCHEMES {
        eprintln!("Testing scheme {scheme:?}");

        sign_and_verify(
            &ours,
            &theirs,
            *scheme,
            rustls_private_key.clone_key(),
            &pub_key,
        );
        sign_and_verify(
            &theirs,
            &ours,
            *scheme,
            rustls_private_key.clone_key(),
            &pub_key,
        );
    }
}

#[rstest]
#[case::ecdsa_nistp256_sha256(SignatureScheme::ECDSA_NISTP256_SHA256, Nid::X9_62_PRIME256V1)]
#[case::ecdsa_nistp384_sha384(SignatureScheme::ECDSA_NISTP384_SHA384, Nid::SECP384R1)]
#[case::ecdsa_nistp521_sha512(SignatureScheme::ECDSA_NISTP521_SHA512, Nid::SECP521R1)]

fn test_ec_sign_and_verify(#[case] scheme: SignatureScheme, #[case] curve: Nid) {
    #[cfg(feature = "fips")]
    {
        rustls_openssl::fips::enable();
    }
    let ours = rustls_openssl::default_provider();
    let theirs = rustls::crypto::aws_lc_rs::default_provider();

    let group = EcGroup::from_curve_name(curve).unwrap();

    let private_key = EcKey::generate(&group).unwrap();
    let rustls_private_key =
        PrivateKeyDer::from_pem_slice(&private_key.private_key_to_pem().unwrap()).unwrap();

    eprintln!("private_key: {rustls_private_key:?}");

    let mut ctx = BigNumContext::new().unwrap();
    let pub_key = private_key
        .public_key()
        // ring doesn't work if PointConversionForm::Compression, aws_lc_rs does
        .to_bytes(&group, PointConversionForm::UNCOMPRESSED, &mut ctx)
        .unwrap();

    eprintln!("verifying using theirs");
    sign_and_verify(
        &ours,
        &theirs,
        scheme,
        rustls_private_key.clone_key(),
        &pub_key,
    );
    eprintln!("verifying using ours");
    sign_and_verify(
        &theirs,
        &ours,
        scheme,
        rustls_private_key.clone_key(),
        &pub_key,
    );
}

#[cfg(not(feature = "fips"))]
#[test]
fn test_ed25119_sign_and_verify() {
    let ours = rustls_openssl::default_provider();
    let theirs = rustls::crypto::aws_lc_rs::default_provider();
    let scheme = SignatureScheme::ED25519;

    let private_key = PKey::generate_ed25519().unwrap();
    let pub_key = private_key.raw_public_key().unwrap();
    let rustls_private_key =
        PrivateKeyDer::from_pem_slice(&private_key.private_key_to_pem_pkcs8().unwrap()).unwrap();
    eprintln!("verifying using theirs");
    sign_and_verify(
        &ours,
        &theirs,
        scheme,
        rustls_private_key.clone_key(),
        &pub_key,
    );
    eprintln!("verifying using ours");
    sign_and_verify(
        &theirs,
        &ours,
        scheme,
        rustls_private_key.clone_key(),
        &pub_key,
    );
}

fn sign_and_verify(
    signing_provider: &rustls::crypto::CryptoProvider,
    verifying_provider: &rustls::crypto::CryptoProvider,
    scheme: SignatureScheme,
    rustls_private_key: PrivateKeyDer<'static>,
    pub_key: &[u8],
) {
    let data = b"hello, world!";

    // sign
    let signing_key = signing_provider
        .key_provider
        .load_private_key(rustls_private_key)
        .unwrap();
    let signer = signing_key
        .choose_scheme(&[scheme])
        .expect("signing provider supports this scheme");
    let signature = signer.sign(data).unwrap();

    // verify
    let algs = verifying_provider
        .signature_verification_algorithms
        .mapping
        .iter()
        .find(|(k, _v)| *k == scheme)
        .map(|(_k, v)| *v)
        .expect("verifying provider supports this scheme");
    assert!(!algs.is_empty());
    assert!(
        algs.iter()
            .any(|alg| { alg.verify_signature(pub_key, data, &signature).is_ok() })
    );
}

#[cfg(feature = "fips")]
#[test]
fn provider_is_fips() {
    rustls_openssl::fips::enable();
    let provider = rustls_openssl::default_provider();
    assert!(provider.fips());
}