siguldry 0.8.0

A signing server and client.
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
// SPDX-License-Identifier: MIT
// Copyright (c) Microsoft Corporation.

//! Functions for signing content.
//!
//! This includes functions for signing using PGP, or using various key algorithms (RSA PKCS #1
//! v1.5, ECDSA, etc).

use anyhow::Context;
use cryptoki::{mechanism::Mechanism, session::Session};
use openssl::{pkey::PKey, pkey_ctx::PkeyCtx};

use crate::{
    protocol::{self, DigestAlgorithm, KeyAlgorithm, SignaturePayload},
    server::db,
};

/// Sign a set of digests with a key stored in the database protected by a password.
pub fn sign_with_softkey(
    key: &db::Key,
    pkey: &PKey<openssl::pkey::Private>,
    digests: Vec<(DigestAlgorithm, String)>,
) -> anyhow::Result<Vec<protocol::Signature>> {
    let mut signatures = Vec::with_capacity(digests.len());
    for (algorithm, hex_hash) in digests {
        let hash = hex::decode(&hex_hash).context("The digest provided was not valid hex")?;
        if hash.len() != algorithm.size() {
            return Err(anyhow::anyhow!(
                "The specified digest algorithm is {} bytes; payload was {}",
                algorithm.size(),
                hash.len()
            ));
        }

        let mut ctx = PkeyCtx::new(pkey)?;
        ctx.sign_init()?;
        ctx.set_signature_md(algorithm.into())?;
        if key.key_algorithm == KeyAlgorithm::Rsa4K {
            // PKCS #1 should be the default, but lets be explicit about it.
            ctx.set_rsa_padding(openssl::rsa::Padding::PKCS1)?;
        }
        let mut signature = vec![];
        ctx.sign_to_vec(&hash, &mut signature)?;
        let signature = match key.key_algorithm {
            KeyAlgorithm::Rsa2K | KeyAlgorithm::Rsa4K => protocol::SignaturePayload::RSA(signature),
            KeyAlgorithm::P256 => protocol::SignaturePayload::P256(signature),
        };

        tracing::info!(digest_algorithm=%algorithm, digest=hex_hash, "Signature issued");
        signatures.push(protocol::Signature {
            signature,
            digest: algorithm,
            hash: hex_hash,
        });
    }

    Ok(signatures)
}

/// Sign a set of digests with a PKCS#11-backed key
pub fn sign_with_pkcs11(
    key: &db::Key,
    session: &Session,
    digests: Vec<(DigestAlgorithm, String)>,
) -> anyhow::Result<Vec<protocol::Signature>> {
    let private_key = key.get_pkcs11_private_key(session)?;

    let mut signatures = Vec::with_capacity(digests.len());
    for (algorithm, hex_hash) in digests {
        let hash = hex::decode(&hex_hash).context("The digest provided was not valid hex")?;
        if hash.len() != algorithm.size() {
            return Err(anyhow::anyhow!(
                "The specified digest algorithm is {} bytes; payload was {}",
                algorithm.size(),
                hash.len()
            ));
        }

        // Select the appropriate PKCS#11 mechanism and data format based on key type;
        // the input/output from PKCS#11 signing mechanisms don't match OpenSSL, so we
        // need to handle the differences here
        let (mechanism, data_to_sign) = match key.key_algorithm {
            KeyAlgorithm::Rsa4K | KeyAlgorithm::Rsa2K => {
                // For RSA PKCS#1 v1.5 with CKM_RSA_PKCS, we need to provide DigestInfo
                // structure (DER-encoded hash algorithm OID + hash value)
                let digest_info = crate::der::encode_digest_info(algorithm, &hash)?;
                (Mechanism::RsaPkcs, digest_info)
            }
            KeyAlgorithm::P256 => {
                // ECDSA mechanism expects raw hash bytes
                (Mechanism::Ecdsa, hash)
            }
        };

        let signature = session
            .sign(&mechanism, private_key, &data_to_sign)
            .context("PKCS#11 signing operation failed")?;

        let signature = match key.key_algorithm {
            KeyAlgorithm::Rsa4K | KeyAlgorithm::Rsa2K => SignaturePayload::RSA(signature),
            KeyAlgorithm::P256 => {
                // Softkey signatures use OpenSSL, which return a DER-encoded signature, while PKCS #11
                // returns the raw r and s values (refer to https://www.ietf.org/rfc/rfc6979.html#appendix-A.1.3).
                // In order to be consistent, we'll always return the DER-encoded signature.
                let r = signature
                    .get(..32)
                    .map(openssl::bn::BigNum::from_slice)
                    .expect("A P256 signature should be 64 bytes")?;
                let s = signature
                    .get(32..)
                    .map(openssl::bn::BigNum::from_slice)
                    .expect("A P256 signature should be 64 bytes")?;
                let ecdsa_sig = openssl::ecdsa::EcdsaSig::from_private_components(r, s)?;
                SignaturePayload::P256(ecdsa_sig.to_der()?)
            }
        };

        tracing::info!(digest_algorithm=%algorithm, digest=hex_hash, "Signature issued");
        signatures.push(protocol::Signature {
            signature,
            digest: algorithm,
            hash: hex_hash,
        });
    }

    Ok(signatures)
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroU32;
    use std::path::PathBuf;
    use std::process::Command;

    use anyhow::Result;
    use sequoia_openpgp::crypto::Password;
    use tempfile::TempDir;
    use zerocopy::IntoBytes;

    use super::*;
    use crate::der::{decode_digest_info, encode_digest_info};
    use crate::protocol::DigestAlgorithm;
    use crate::server::crypto;
    use crate::server::crypto::binding::decrypt_private_key;
    use crate::server::crypto::test_utils::setup_hsm;
    use crate::server::crypto::token::import_pkcs11_token;

    #[test]
    fn encode_decode_digest_info() -> Result<()> {
        let algorithm = DigestAlgorithm::Sha256;
        let hash = openssl::hash::hash(algorithm.into(), b"data")?;
        let encoded = encode_digest_info(algorithm, &hash)?;
        let (decoded_algorithm, decoded_hash) = decode_digest_info(&encoded)?;

        assert_eq!(
            algorithm, decoded_algorithm,
            "Digest algorithm should match"
        );
        assert_eq!(hash.as_bytes(), &decoded_hash, "Digest should match");

        Ok(())
    }

    #[tokio::test]
    async fn sign_with_pkcs11_rsa_key() -> Result<()> {
        let hsm = setup_hsm()?;
        let db_pool = db::pool("sqlite::memory:", false).await?;
        db::migrate(&db_pool).await?;
        let mut conn = db_pool.begin().await?;

        let token = import_pkcs11_token(
            &mut conn,
            PathBuf::from("/usr/lib64/pkcs11/libkryoptic_pkcs11.so"),
            None,
            hsm.user_pin.clone(),
        )
        .await?;
        let pkcs11 = token.intialize()?;
        let slot = token.slot(&pkcs11)?;
        let session = pkcs11.open_ro_session(slot)?;
        session.login(cryptoki::session::UserType::User, Some(&hsm.user_pin))?;

        let keys = db::Key::list(&mut conn).await?;
        let rsa_key = keys
            .iter()
            .find(|k| k.key_algorithm == KeyAlgorithm::Rsa4K)
            .expect("Should have an RSA key");

        let data = b"test data";
        let digest = openssl::hash::hash(openssl::hash::MessageDigest::sha256(), data)?;
        let hex_hash = hex::encode(digest);
        let signatures = super::sign_with_pkcs11(
            rsa_key,
            &session,
            vec![(DigestAlgorithm::Sha256, hex_hash.clone())],
        )?;
        pkcs11.finalize()?;
        assert_eq!(signatures.len(), 1);
        assert_eq!(signatures.first().unwrap().digest, DigestAlgorithm::Sha256);
        assert_eq!(signatures.first().unwrap().hash, hex_hash);
        assert!(!signatures.first().unwrap().signature.is_empty());

        // Verify the signature using the public key via OpenSSL Rust bindings
        let public_key = openssl::pkey::PKey::public_key_from_pem(rsa_key.public_key.as_bytes())?;
        let mut ctx = openssl::pkey_ctx::PkeyCtx::new(&public_key)?;
        ctx.verify_init()?;
        ctx.set_signature_md(openssl::md::Md::sha256())?;
        ctx.set_rsa_padding(openssl::rsa::Padding::PKCS1)?;
        let signature = signatures.first().unwrap().signature.as_ref();
        let result = ctx.verify(&digest, signature)?;
        assert!(result, "Signature should be valid (OpenSSL bindings)");

        // Also verify using the OpenSSL CLI in case I'm using the bindings wrong
        let data_path = hsm.directory.path().join("unsigned_data");
        let signature_path = hsm.directory.path().join("signature.bin");
        let pubkey_path = hsm.directory.path().join("pubkey.pem");
        std::fs::write(&data_path, data)?;
        std::fs::write(&signature_path, signature)?;
        std::fs::write(&pubkey_path, rsa_key.public_key.as_bytes())?;
        let output = Command::new("openssl")
            .args(["dgst", "-sha256", "-verify"])
            .arg(&pubkey_path)
            .arg("-signature")
            .arg(&signature_path)
            .arg(&data_path)
            .output()?;

        assert!(
            output.status.success(),
            "OpenSSL CLI verification failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        Ok(())
    }

    #[tokio::test]
    async fn sign_with_pkcs11_ecc_key() -> Result<()> {
        let hsm = setup_hsm()?;
        let db_pool = db::pool("sqlite::memory:", false).await?;
        db::migrate(&db_pool).await?;
        let mut conn = db_pool.begin().await?;

        let token = import_pkcs11_token(
            &mut conn,
            PathBuf::from("/usr/lib64/pkcs11/libkryoptic_pkcs11.so"),
            None,
            hsm.user_pin.clone(),
        )
        .await?;
        let pkcs11 = token.intialize()?;
        let slot = token.slot(&pkcs11)?;
        let session = pkcs11.open_ro_session(slot)?;
        session.login(cryptoki::session::UserType::User, Some(&hsm.user_pin))?;

        let keys = db::Key::list(&mut conn).await?;
        let ecc_key = keys
            .iter()
            .find(|k| k.key_algorithm == KeyAlgorithm::P256)
            .expect("Should have an ECC key");

        let data = b"test data";
        let digest = openssl::hash::hash(openssl::hash::MessageDigest::sha256(), data)?;
        let hex_hash = hex::encode(digest);

        let signatures = super::sign_with_pkcs11(
            ecc_key,
            &session,
            vec![(DigestAlgorithm::Sha256, hex_hash.clone())],
        )?;
        pkcs11.finalize()?;

        assert_eq!(signatures.len(), 1);
        assert_eq!(signatures.first().unwrap().digest, DigestAlgorithm::Sha256);
        assert_eq!(signatures.first().unwrap().hash, hex_hash);
        assert!(!signatures.first().unwrap().signature.is_empty());

        let public_key = openssl::pkey::PKey::public_key_from_pem(ecc_key.public_key.as_bytes())?;
        let ec_key = public_key.ec_key()?;
        let signature = signatures.first().unwrap().signature.as_ref();
        let ecdsa_sig = openssl::ecdsa::EcdsaSig::from_der(signature)?;
        assert!(
            ecdsa_sig.verify(&digest, &ec_key)?,
            "ECDSA signature should be valid (OpenSSL bindings)"
        );

        // Also verify using the OpenSSL CLI in case I'm using the bindings wrong
        let data_path = hsm.directory.path().join("unsigned_data");
        let signature_path = hsm.directory.path().join("signature.bin");
        let pubkey_path = hsm.directory.path().join("pubkey.pem");
        std::fs::write(&data_path, data)?;
        std::fs::write(&signature_path, signature)?;
        std::fs::write(&pubkey_path, ecc_key.public_key.as_bytes())?;
        let output = Command::new("openssl")
            .args(["dgst", "-sha256", "-verify"])
            .arg(&pubkey_path)
            .arg("-signature")
            .arg(&signature_path)
            .arg(&data_path)
            .output()?;

        assert!(
            output.status.success(),
            "OpenSSL CLI verification failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        Ok(())
    }

    #[tokio::test]
    async fn sign_with_softkey_rsa() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let user_password = Password::from("test-key-password");

        let key_algorithm = KeyAlgorithm::Rsa4K;
        let encrypted_key = crypto::create_encrypted_key(
            &crate::server::Config::default(),
            user_password.clone(),
            key_algorithm,
            sequoia_openpgp::Profile::RFC4880,
            crypto::KeyUsage::CodeSigning,
            "test-key".to_string(),
            NonZeroU32::new(100).unwrap(),
            None,
        )?;
        let key = db::Key {
            id: 1,
            hybrid_pair_id: None,
            name: "test-rsa-softkey".to_string(),
            key_algorithm,
            handle: encrypted_key.handle,
            key_material: Some(encrypted_key.key_material),
            public_key: encrypted_key.public_key_pem,
            pkcs11_token_id: None,
            pkcs11_key_id: None,
        };

        let data = b"test data";
        let digest = openssl::hash::hash(openssl::hash::MessageDigest::sha256(), data)?;
        let hex_hash = hex::encode(digest);

        let pkey = decrypt_private_key(&key, &encrypted_key.encrypted_password, &[], user_password)
            .await?;
        let signatures = super::sign_with_softkey(
            &key,
            &pkey,
            vec![(DigestAlgorithm::Sha256, hex_hash.clone())],
        )?;

        assert_eq!(signatures.len(), 1);
        assert_eq!(signatures.first().unwrap().digest, DigestAlgorithm::Sha256);
        assert_eq!(signatures.first().unwrap().hash, hex_hash);
        assert!(!signatures.first().unwrap().signature.is_empty());

        // Verify the signature using OpenSSL Rust bindings
        let public_key = openssl::pkey::PKey::public_key_from_pem(key.public_key.as_bytes())?;
        let mut ctx = openssl::pkey_ctx::PkeyCtx::new(&public_key)?;
        ctx.verify_init()?;
        ctx.set_signature_md(openssl::md::Md::sha256())?;
        ctx.set_rsa_padding(openssl::rsa::Padding::PKCS1)?;
        let signature = signatures.first().unwrap().signature.as_ref();
        let result = ctx.verify(&digest, signature)?;
        assert!(result, "Signature should be valid (OpenSSL bindings)");

        // Also verify using the OpenSSL CLI in case I'm using the bindings wrong
        let data_path = temp_dir.path().join("unsigned_data");
        let signature_path = temp_dir.path().join("signature.bin");
        let pubkey_path = temp_dir.path().join("pubkey.pem");
        std::fs::write(&data_path, data)?;
        std::fs::write(&signature_path, signature)?;
        std::fs::write(&pubkey_path, key.public_key.as_bytes())?;
        let output = Command::new("openssl")
            .args(["dgst", "-sha256", "-verify"])
            .arg(&pubkey_path)
            .arg("-signature")
            .arg(&signature_path)
            .arg(&data_path)
            .output()?;

        assert!(
            output.status.success(),
            "OpenSSL CLI verification failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        Ok(())
    }

    #[tokio::test]
    async fn sign_with_softkey_ecc() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let user_password = Password::from("test-key-password");

        let key_algorithm = KeyAlgorithm::P256;
        let encrypted_key = crypto::create_encrypted_key(
            &crate::server::Config::default(),
            user_password.clone(),
            key_algorithm,
            sequoia_openpgp::Profile::RFC4880,
            crypto::KeyUsage::CodeSigning,
            "test-key".to_string(),
            NonZeroU32::new(100).unwrap(),
            None,
        )?;
        let key = db::Key {
            id: 1,
            hybrid_pair_id: None,
            name: "test-ecc-softkey".to_string(),
            key_algorithm,
            handle: encrypted_key.handle,
            key_material: Some(encrypted_key.key_material),
            public_key: encrypted_key.public_key_pem,
            pkcs11_token_id: None,
            pkcs11_key_id: None,
        };

        let data = b"test data for ECC softkey signing";
        let digest = openssl::hash::hash(openssl::hash::MessageDigest::sha256(), data)?;
        let hex_hash = hex::encode(digest);

        let pkey = decrypt_private_key(&key, &encrypted_key.encrypted_password, &[], user_password)
            .await?;
        let signatures = super::sign_with_softkey(
            &key,
            &pkey,
            vec![(DigestAlgorithm::Sha256, hex_hash.clone())],
        )?;

        assert_eq!(signatures.len(), 1);
        assert_eq!(signatures.first().unwrap().digest, DigestAlgorithm::Sha256);
        assert_eq!(signatures.first().unwrap().hash, hex_hash);
        assert!(!signatures.first().unwrap().signature.is_empty());

        let public_key = openssl::pkey::PKey::public_key_from_pem(key.public_key.as_bytes())?;
        let ec_key = public_key.ec_key()?;
        let signature = signatures.first().unwrap().signature.as_ref();
        let ecdsa_sig = openssl::ecdsa::EcdsaSig::from_der(signature)?;
        assert!(
            ecdsa_sig.verify(&digest, &ec_key)?,
            "ECDSA signature should be valid (OpenSSL bindings)"
        );

        // Also verify using the OpenSSL CLI in case I'm using the bindings wrong
        let data_path = temp_dir.path().join("unsigned_data");
        let signature_path = temp_dir.path().join("signature.bin");
        let pubkey_path = temp_dir.path().join("pubkey.pem");
        std::fs::write(&data_path, data)?;
        std::fs::write(&signature_path, signature)?;
        std::fs::write(&pubkey_path, key.public_key.as_bytes())?;
        let output = Command::new("openssl")
            .args(["dgst", "-sha256", "-verify"])
            .arg(&pubkey_path)
            .arg("-signature")
            .arg(&signature_path)
            .arg(&data_path)
            .output()?;

        assert!(
            output.status.success(),
            "OpenSSL CLI verification failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        Ok(())
    }
}