quincy 2.0.2

QUIC-based VPN - Core library
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
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
use std::collections::HashSet;
use std::fmt::Debug;
use std::path::Path;
use std::{
    fs::File,
    io::{BufReader, Cursor},
};

use aws_lc_rs::digest;
use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, UnixTime};
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
use rustls::{DigitallySignedStruct, DistinguishedName, Error, SignatureScheme};

use crate::error::{CertificateError, Result};

/// Loads certificates from a file.
///
/// ### Arguments
/// - `path` - Path to the file containing the certificates.
///
/// ### Returns
/// - `Vec<CertificateDer>` - A list of loaded certificates.
pub fn load_certificates_from_file(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
    let file = File::open(path).map_err(|_| CertificateError::LoadFailed {
        path: path.to_path_buf(),
    })?;
    let mut reader = BufReader::new(file);

    let certs: std::result::Result<Vec<CertificateDer>, _> =
        rustls_pemfile::certs(&mut reader).collect();

    let certs = certs.map_err(|_| CertificateError::LoadFailed {
        path: path.to_path_buf(),
    })?;

    if certs.is_empty() {
        return Err(CertificateError::LoadFailed {
            path: path.to_path_buf(),
        }
        .into());
    }

    Ok(certs)
}

/// Loads certificates from a PEM string.
///
/// ### Arguments
/// - `pem_data` - PEM-encoded certificate data as a string.
///
/// ### Returns
/// - `Vec<CertificateDer>` - A list of loaded certificates.
pub fn load_certificates_from_pem(pem_data: &str) -> Result<Vec<CertificateDer<'static>>> {
    let mut reader = Cursor::new(pem_data.as_bytes());
    let certs: std::result::Result<Vec<CertificateDer>, _> =
        rustls_pemfile::certs(&mut reader).collect();

    let certs = certs.map_err(|_| CertificateError::UnsupportedFormat)?;

    if certs.is_empty() {
        return Err(CertificateError::UnsupportedFormat.into());
    }

    Ok(certs)
}

/// Loads a private key from a file.
///
/// Automatically detects and parses private keys in any supported format:
/// - PKCS8
/// - RSA PKCS1
/// - EC SEC1
///
/// ### Arguments
/// - `path` - Path to the file containing the private key.
///
/// ### Returns
/// - `PrivateKeyDer` - The loaded private key.
pub fn load_private_key_from_file(path: &Path) -> Result<PrivateKeyDer<'static>> {
    PrivateKeyDer::from_pem_file(path).map_err(|_| {
        CertificateError::PrivateKeyLoadFailed {
            path: path.to_path_buf(),
        }
        .into()
    })
}

/// Computes the SHA-256 fingerprint of a DER-encoded certificate.
///
/// Returns a string in the format `sha256:<lowercase-hex>`.
///
/// ### Arguments
/// - `cert` - the DER-encoded certificate
pub fn compute_cert_fingerprint(cert: &CertificateDer<'_>) -> String {
    let hash = digest::digest(&digest::SHA256, cert.as_ref());
    let hex: String = hash.as_ref().iter().map(|b| format!("{b:02x}")).collect();
    format!("sha256:{hex}")
}

/// Custom client certificate verifier for Quincy.
///
/// Validates client certificates by checking whether the leaf certificate's SHA-256
/// fingerprint is present in the allowed set. Client authentication is mandatory --
/// anonymous clients are rejected.
///
/// Fingerprint-based validation does not check certificate expiry. Expired certificates
/// remain valid until their fingerprint is removed from the users file.
pub struct QuincyCertVerifier {
    /// Set of allowed certificate fingerprints in `sha256:<hex>` format.
    allowed_fingerprints: HashSet<String>,
    /// Supported signature verification algorithms.
    supported_algs: WebPkiSupportedAlgorithms,
}

impl QuincyCertVerifier {
    /// Creates a new `QuincyCertVerifier`.
    ///
    /// ### Arguments
    /// - `allowed_fingerprints` - set of allowed certificate fingerprints
    /// - `crypto_provider` - the crypto provider for signature verification algorithms
    pub fn new(allowed_fingerprints: HashSet<String>, crypto_provider: &CryptoProvider) -> Self {
        Self {
            allowed_fingerprints,
            supported_algs: crypto_provider.signature_verification_algorithms,
        }
    }
}

impl Debug for QuincyCertVerifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("QuincyCertVerifier")
            .field(
                "allowed_fingerprints_count",
                &self.allowed_fingerprints.len(),
            )
            .finish()
    }
}

impl ClientCertVerifier for QuincyCertVerifier {
    fn offer_client_auth(&self) -> bool {
        true
    }

    fn client_auth_mandatory(&self) -> bool {
        true
    }

    fn root_hint_subjects(&self) -> &[DistinguishedName] {
        &[]
    }

    fn verify_client_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        _intermediates: &[CertificateDer<'_>],
        _now: UnixTime,
    ) -> std::result::Result<ClientCertVerified, Error> {
        let fingerprint = compute_cert_fingerprint(end_entity);
        if self.allowed_fingerprints.contains(&fingerprint) {
            return Ok(ClientCertVerified::assertion());
        }

        Err(Error::InvalidCertificate(
            rustls::CertificateError::ApplicationVerificationFailure,
        ))
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, Error> {
        rustls::crypto::verify_tls12_signature(message, cert, dss, &self.supported_algs)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, Error> {
        rustls::crypto::verify_tls13_signature(message, cert, dss, &self.supported_algs)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.supported_algs.supported_schemes()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    const VALID_CERT_PEM_PKCS8: &str =
        include_str!("../../quincy-tests/tests/static/server_cert_pkcs8.pem");
    const VALID_KEY_PEM_PKCS8: &str =
        include_str!("../../quincy-tests/tests/static/server_key_pkcs8.pem");
    const VALID_KEY_PEM_RSA_PKCS1: &str =
        include_str!("../../quincy-tests/tests/static/server_key_rsa_pkcs1.pem");
    const VALID_KEY_PEM_EC_SEC1: &str =
        include_str!("../../quincy-tests/tests/static/server_key_ec_sec1.pem");
    const CLIENT_CERT_PEM: &str = include_str!("../../quincy-tests/tests/static/client_cert.pem");
    const BAD_CLIENT_CERT_PEM: &str =
        include_str!("../../quincy-tests/tests/static/bad_client_cert.pem");
    // ========== compute_cert_fingerprint tests ==========

    #[test]
    fn compute_fingerprint_deterministic() {
        let certs = load_certificates_from_pem(VALID_CERT_PEM_PKCS8).unwrap();
        let fp1 = compute_cert_fingerprint(&certs[0]);
        let fp2 = compute_cert_fingerprint(&certs[0]);
        assert_eq!(fp1, fp2);
        assert!(fp1.starts_with("sha256:"));
        // SHA-256 produces 64 hex chars
        assert_eq!(fp1.len(), "sha256:".len() + 64);
    }

    #[test]
    fn compute_fingerprint_lowercase_hex() {
        let certs = load_certificates_from_pem(VALID_CERT_PEM_PKCS8).unwrap();
        let fp = compute_cert_fingerprint(&certs[0]);
        let hex_part = fp.strip_prefix("sha256:").unwrap();
        assert!(hex_part.chars().all(|c| c.is_ascii_hexdigit()));
        assert_eq!(hex_part, hex_part.to_lowercase());
    }

    // ========== load_certificates_from_pem tests ==========

    #[test]
    fn load_certificates_from_pem_valid() {
        let certs = load_certificates_from_pem(VALID_CERT_PEM_PKCS8).unwrap();
        assert_eq!(certs.len(), 1);
    }

    #[test]
    fn load_certificates_from_pem_empty_string() {
        let result = load_certificates_from_pem("");
        assert!(result.is_err());
    }

    #[test]
    fn load_certificates_from_pem_path_string() {
        let result = load_certificates_from_pem("/path/to/cert.pem");
        assert!(result.is_err());
    }

    #[test]
    fn load_certificates_from_pem_invalid_pem() {
        let result = load_certificates_from_pem("not a valid pem");
        assert!(result.is_err());
    }

    #[test]
    fn load_certificates_from_pem_wrong_pem_type() {
        // Private key PEM should not parse as certificate
        let result = load_certificates_from_pem(VALID_KEY_PEM_PKCS8);
        assert!(result.is_err());
    }

    // ========== load_certificates_from_file tests ==========

    #[test]
    fn load_certificates_from_file_valid() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(VALID_CERT_PEM_PKCS8.as_bytes()).unwrap();

        let certs = load_certificates_from_file(file.path()).unwrap();
        assert_eq!(certs.len(), 1);
    }

    #[test]
    fn load_certificates_from_file_nonexistent() {
        let result = load_certificates_from_file(Path::new("/nonexistent/path/cert.pem"));
        assert!(result.is_err());
    }

    #[test]
    fn load_certificates_from_file_empty() {
        let file = NamedTempFile::new().unwrap();

        let result = load_certificates_from_file(file.path());
        assert!(result.is_err());
    }

    #[test]
    fn load_certificates_from_file_invalid_content() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(b"not a valid certificate").unwrap();

        let result = load_certificates_from_file(file.path());
        assert!(result.is_err());
    }

    #[test]
    fn load_certificates_from_file_wrong_pem_type() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(VALID_KEY_PEM_PKCS8.as_bytes()).unwrap();

        let result = load_certificates_from_file(file.path());
        assert!(result.is_err());
    }

    // ========== load_private_key_from_file tests ==========

    #[test]
    fn load_private_key_from_file_valid_pkcs8() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(VALID_KEY_PEM_PKCS8.as_bytes()).unwrap();

        let result = load_private_key_from_file(file.path());
        assert!(result.is_ok());
        // Verify it's PKCS8 format
        if let Ok(PrivateKeyDer::Pkcs8(_)) = result {
            // Success
        } else {
            panic!("Expected PKCS8 key format");
        }
    }

    #[test]
    fn load_private_key_from_file_valid_rsa_pkcs1() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(VALID_KEY_PEM_RSA_PKCS1.as_bytes()).unwrap();

        let result = load_private_key_from_file(file.path());
        assert!(result.is_ok());
        // Verify it's PKCS1 (RSA) format
        if let Ok(PrivateKeyDer::Pkcs1(_)) = result {
            // Success
        } else {
            panic!("Expected PKCS1 (RSA) key format");
        }
    }

    #[test]
    fn load_private_key_from_file_valid_ec_sec1() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(VALID_KEY_PEM_EC_SEC1.as_bytes()).unwrap();

        let result = load_private_key_from_file(file.path());
        assert!(result.is_ok());
        // Verify it's SEC1 (EC) format
        if let Ok(PrivateKeyDer::Sec1(_)) = result {
            // Success
        } else {
            panic!("Expected SEC1 (EC) key format");
        }
    }

    #[test]
    fn load_private_key_from_file_nonexistent() {
        let result = load_private_key_from_file(Path::new("/nonexistent/path/key.pem"));
        assert!(result.is_err());
    }

    #[test]
    fn load_private_key_from_file_empty() {
        let file = NamedTempFile::new().unwrap();

        let result = load_private_key_from_file(file.path());
        assert!(result.is_err());
    }

    #[test]
    fn load_private_key_from_file_invalid_content() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(b"not a valid key").unwrap();

        let result = load_private_key_from_file(file.path());
        assert!(result.is_err());
    }

    #[test]
    fn load_private_key_from_file_wrong_pem_type() {
        let mut file = NamedTempFile::new().unwrap();
        file.write_all(VALID_CERT_PEM_PKCS8.as_bytes()).unwrap();

        let result = load_private_key_from_file(file.path());
        assert!(result.is_err());
    }

    // ========== QuincyCertVerifier tests ==========

    fn create_verifier(allowed_fingerprints: HashSet<String>) -> QuincyCertVerifier {
        let provider = CryptoProvider::get_default()
            .cloned()
            .unwrap_or_else(|| std::sync::Arc::new(rustls::crypto::aws_lc_rs::default_provider()));
        QuincyCertVerifier::new(allowed_fingerprints, &provider)
    }

    #[test]
    fn verify_client_cert_accepts_known_fingerprint() {
        let certs = load_certificates_from_pem(CLIENT_CERT_PEM).unwrap();
        let fingerprint = compute_cert_fingerprint(&certs[0]);
        let mut allowed = HashSet::new();
        allowed.insert(fingerprint);

        let verifier = create_verifier(allowed);

        let result = verifier.verify_client_cert(&certs[0], &[], UnixTime::now());
        assert!(result.is_ok());
    }

    #[test]
    fn verify_client_cert_rejects_unknown_fingerprint() {
        let certs = load_certificates_from_pem(BAD_CLIENT_CERT_PEM).unwrap();
        let client_certs = load_certificates_from_pem(CLIENT_CERT_PEM).unwrap();
        let fingerprint = compute_cert_fingerprint(&client_certs[0]);
        let mut allowed = HashSet::new();
        allowed.insert(fingerprint);

        let verifier = create_verifier(allowed);

        let result = verifier.verify_client_cert(&certs[0], &[], UnixTime::now());
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(
            err,
            Error::InvalidCertificate(rustls::CertificateError::ApplicationVerificationFailure)
        ));
    }

    #[test]
    fn verify_client_cert_rejects_empty_allowed_set() {
        let certs = load_certificates_from_pem(CLIENT_CERT_PEM).unwrap();
        let allowed: HashSet<String> = HashSet::new();

        let verifier = create_verifier(allowed);

        let result = verifier.verify_client_cert(&certs[0], &[], UnixTime::now());
        assert!(result.is_err());
    }

    #[test]
    fn verify_tls12_signature_delegates_to_rustls() {
        let verifier = create_verifier(HashSet::new());
        let schemes = verifier.supported_verify_schemes();
        assert!(schemes.contains(&SignatureScheme::ECDSA_NISTP256_SHA256));
    }

    #[test]
    fn verify_tls13_signature_delegates_to_rustls() {
        let verifier = create_verifier(HashSet::new());
        let schemes = verifier.supported_verify_schemes();
        assert!(schemes.contains(&SignatureScheme::ECDSA_NISTP256_SHA256));
    }

    #[test]
    fn verifier_supported_verify_schemes() {
        let verifier = create_verifier(HashSet::new());
        let schemes = verifier.supported_verify_schemes();
        assert!(!schemes.is_empty());
    }

    #[test]
    fn verifier_offer_client_auth() {
        let verifier = create_verifier(HashSet::new());
        assert!(verifier.offer_client_auth());
    }

    #[test]
    fn verifier_client_auth_mandatory() {
        let verifier = create_verifier(HashSet::new());
        assert!(verifier.client_auth_mandatory());
    }

    #[test]
    fn verifier_root_hint_subjects_empty() {
        let verifier = create_verifier(HashSet::new());
        assert!(verifier.root_hint_subjects().is_empty());
    }

    #[test]
    fn verifier_debug_impl() {
        let mut allowed = HashSet::new();
        allowed.insert("sha256:abc".to_string());
        let verifier = create_verifier(allowed);
        let debug_str = format!("{:?}", verifier);
        assert!(debug_str.contains("allowed_fingerprints_count"));
        assert!(debug_str.contains('1'));
    }
}