kryoptic-lib 1.5.1

A PKCS #11 software token written in Rust
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
// Copyright 2023 - 2024 Simo Sorce, Jakub Jelen
// See LICENSE.txt file for terms

//! This module implements ECDSA (Elliptic Curve Digital Signature Algorithm)
//! functionalities using the OpenSSL EVP interface, including key generation,
//! signing, verification, and signature format conversions.

use crate::attribute::Attribute;
use crate::ec::get_ec_point_from_obj;
use crate::error::Result;
use crate::kasn1::DerEncBigUint;
use crate::mechanism::*;
use crate::misc::zeromem;
use crate::object::Object;
use crate::ossl::common::*;
use crate::pkcs11::*;

use ossl::pkey::{EccData, EvpPkey, PkeyData};
use ossl::signature::{OsslSignature, SigAlg, SigOp};
use ossl::OsslSecret;

/// Converts a PKCS#11 EC key `Object` into an `EvpPkey`.
///
/// Extracts the curve type and relevant key components (public point or private
/// value) based on the object `class` and populates an `EccData` structure
/// suitable for creating an `EvpPkey`.
pub fn ecc_object_to_pkey(
    key: &Object,
    class: CK_OBJECT_CLASS,
) -> Result<EvpPkey> {
    let kclass = key.get_attr_as_ulong(CKA_CLASS)?;
    if kclass != class {
        return Err(CKR_KEY_TYPE_INCONSISTENT)?;
    }
    match kclass {
        CKO_PUBLIC_KEY => Ok(EvpPkey::import(
            osslctx(),
            get_evp_pkey_type_from_obj(key)?,
            PkeyData::Ecc(EccData {
                pubkey: Some(get_ec_point_from_obj(key)?),
                prikey: None,
            }),
        )?),
        CKO_PRIVATE_KEY => Ok(EvpPkey::import(
            osslctx(),
            get_evp_pkey_type_from_obj(key)?,
            PkeyData::Ecc(EccData {
                pubkey: None,
                prikey: Some(OsslSecret::from_vec(
                    key.get_attr_as_bytes(CKA_VALUE)?.clone(),
                )),
            }),
        )?),
        _ => Err(CKR_KEY_TYPE_INCONSISTENT)?,
    }
}

/// ASN.1 structure for an ECDSA signature value (SEQUENCE of two INTEGERs).
#[derive(asn1::Asn1Read, asn1::Asn1Write)]
struct EcdsaSignature<'a> {
    r: DerEncBigUint<'a>,
    s: DerEncBigUint<'a>,
}

/// Copies one half (r or s) of an ECDSA signature from an input slice `hin`
/// to an output slice `hout` of potentially different (but sufficient) length,
/// handling necessary padding or truncation of leading zeros.
fn slice_to_sig_half(hin: &[u8], hout: &mut [u8]) -> Result<()> {
    let mut len = hin.len();
    if len > hout.len() {
        /* check for leading zeros */
        for i in 0..hin.len() {
            if hin[i] != 0 {
                break;
            }
            len -= 1;
        }
        if len == 0 || len > hout.len() {
            return Err(CKR_GENERAL_ERROR)?;
        }
    }
    let ipad = hin.len() - len;
    let opad = hout.len() - len;
    if opad > 0 {
        hout[0..opad].fill(0);
    }
    hout[opad..].copy_from_slice(&hin[ipad..]);
    Ok(())
}

/// Convert OpenSSL ECDSA signature to PKCS #11 format
///
/// The OpenSSL ECDSA signature is DER encoded SEQUENCE of r and s values.
/// The PKCS #11 is representing the signature only using the two concatenated bignums
/// padded with zeroes to the fixed length.
/// This means we here parse the numbers from the DER encoding and construct fixed length
/// buffer with padding if needed.
/// Do not care if the first bit is 1 as in PKCS #11 we interpret the number always positive
fn ossl_to_pkcs11_signature(
    ossl_sign: &Vec<u8>,
    signature: &mut [u8],
) -> Result<()> {
    let sig = match asn1::parse_single::<EcdsaSignature>(ossl_sign.as_slice()) {
        Ok(a) => a,
        Err(_) => return Err(CKR_GENERAL_ERROR)?,
    };
    let bn_len = signature.len() / 2;
    slice_to_sig_half(sig.r.as_bytes(), &mut signature[..bn_len])?;
    slice_to_sig_half(sig.s.as_bytes(), &mut signature[bn_len..])
}

/// Convert PKCS #11 ECDSA signature to OpenSSL format
///
/// The PKCS #11 represents the ECDSA signature only as a two padded values of fixed length.
/// The OpenSSL expects the signature to be DER encoded SEQUENCE of two bignums so
/// we split here the provided buffer and wrap it with the DER encoding.
fn pkcs11_to_ossl_signature(signature: &[u8]) -> Result<Vec<u8>> {
    let bn_len = signature.len() / 2;
    let sig = EcdsaSignature {
        r: DerEncBigUint::new(&signature[..bn_len])?,
        s: DerEncBigUint::new(&signature[bn_len..])?,
    };
    let ossl_sign = match asn1::write_single(&sig) {
        Ok(b) => b,
        Err(_) => return Err(CKR_GENERAL_ERROR)?,
    };
    Ok(ossl_sign)
}

/// Helper function to convert PKCS#11 mechanism type to name
/// understood by the ossl package.
pub fn ecdsa_type_to_ossl_alg(mech: CK_MECHANISM_TYPE) -> Result<SigAlg> {
    Ok(match mech {
        CKM_ECDSA => SigAlg::Ecdsa,
        #[cfg(not(feature = "no_sha1"))]
        CKM_ECDSA_SHA1 => SigAlg::EcdsaSha1,
        CKM_ECDSA_SHA224 => SigAlg::EcdsaSha2_224,
        CKM_ECDSA_SHA256 => SigAlg::EcdsaSha2_256,
        CKM_ECDSA_SHA384 => SigAlg::EcdsaSha2_384,
        CKM_ECDSA_SHA512 => SigAlg::EcdsaSha2_512,
        CKM_ECDSA_SHA3_224 => SigAlg::EcdsaSha3_224,
        CKM_ECDSA_SHA3_256 => SigAlg::EcdsaSha3_256,
        CKM_ECDSA_SHA3_384 => SigAlg::EcdsaSha3_384,
        CKM_ECDSA_SHA3_512 => SigAlg::EcdsaSha3_512,
        _ => return Err(CKR_MECHANISM_INVALID)?,
    })
}

/// Represents an active ECDSA signing or verification operation.
#[derive(Debug)]
pub struct EcdsaOperation {
    /// The specific ECDSA mechanism type (e.g., CKM_ECDSA_SHA256).
    mech: CK_MECHANISM_TYPE,
    /// Expected output length of the signature in bytes (2 * field size).
    output_len: usize,
    /// Flag indicating if the operation has been finalized.
    finalized: bool,
    /// Flag indicating if the operation is in progress.
    in_use: bool,
    /// The OpenSSL Wrapper Signature Context
    sigctx: OsslSignature,
}

impl EcdsaOperation {
    /// Internal constructor to create a new `EcdsaOperation`.
    ///
    /// Sets up the internal state based on whether it's a signature or
    /// verification operation, imports the provided key, and calculates
    /// the expected signature length.
    fn new_op(
        flag: CK_FLAGS,
        mech: &CK_MECHANISM,
        key: &Object,
        signature: Option<Vec<u8>>,
    ) -> Result<EcdsaOperation> {
        let (op, mut pkey) = match flag {
            CKF_SIGN => (SigOp::Sign, privkey_from_object(key)?),
            CKF_VERIFY => (SigOp::Verify, pubkey_from_object(key)?),
            _ => return Err(CKR_GENERAL_ERROR)?,
        };
        let output_len = 2 * ((pkey.get_bits()? + 7) / 8);
        let mut sigctx = OsslSignature::new(
            osslctx(),
            op,
            ecdsa_type_to_ossl_alg(mech.mechanism)?,
            &mut pkey,
            None,
        )?;
        if let Some(s) = &signature {
            if s.len() != output_len {
                return Err(CKR_SIGNATURE_LEN_RANGE)?;
            }
            let mut sig = pkcs11_to_ossl_signature(s)?;
            sigctx.set_signature(sig.as_slice())?;
            zeromem(sig.as_mut_slice());
        }
        Ok(EcdsaOperation {
            mech: mech.mechanism,
            output_len: output_len,
            finalized: false,
            in_use: false,
            sigctx: sigctx,
        })
    }

    /// Creates a new `EcdsaOperation` for signing.
    pub fn sign_new(
        mech: &CK_MECHANISM,
        key: &Object,
        _: &CK_MECHANISM_INFO,
    ) -> Result<EcdsaOperation> {
        Self::new_op(CKF_SIGN, mech, key, None)
    }

    /// Creates a new `EcdsaOperation` for verification.
    pub fn verify_new(
        mech: &CK_MECHANISM,
        key: &Object,
        _: &CK_MECHANISM_INFO,
    ) -> Result<EcdsaOperation> {
        Self::new_op(CKF_VERIFY, mech, key, None)
    }

    /// Creates a new `EcdsaOperation` for verification with a pre-supplied
    /// signature.
    pub fn verify_signature_new(
        mech: &CK_MECHANISM,
        key: &Object,
        _: &CK_MECHANISM_INFO,
        signature: &[u8],
    ) -> Result<EcdsaOperation> {
        Self::new_op(CKF_VERIFY, mech, key, Some(signature.to_vec()))
    }

    /// Generates an EC key pair using OpenSSL.
    ///
    /// Takes mutable references to pre-created public and private key
    /// `Object`s (which contain the desired curve in CKA_EC_PARAMS),
    /// generates the key pair, and populates the CKA_EC_POINT and CKA_VALUE
    /// attributes.
    pub fn generate_keypair(
        pubkey: &mut Object,
        privkey: &mut Object,
    ) -> Result<()> {
        let pkey =
            EvpPkey::generate(osslctx(), get_evp_pkey_type_from_obj(pubkey)?)?;
        let mut ecc = match pkey.export()? {
            PkeyData::Ecc(e) => e,
            _ => return Err(CKR_GENERAL_ERROR)?,
        };

        /* Set Public Key */
        if let Some(key) = ecc.pubkey.take() {
            let point_encoded = match asn1::write_single(&key.as_slice()) {
                Ok(b) => b,
                Err(_) => return Err(CKR_GENERAL_ERROR)?,
            };
            pubkey
                .set_attr(Attribute::from_bytes(CKA_EC_POINT, point_encoded))?;
        } else {
            return Err(CKR_DEVICE_ERROR)?;
        }

        /* Set Private Key */
        if let Some(key) = ecc.prikey.take() {
            privkey.set_attr(Attribute::from_bytes(CKA_VALUE, key.to_vec()))?;
        } else {
            return Err(CKR_DEVICE_ERROR)?;
        }

        Ok(())
    }
}

impl MechOperation for EcdsaOperation {
    fn mechanism(&self) -> Result<CK_MECHANISM_TYPE> {
        Ok(self.mech)
    }

    fn finalized(&self) -> bool {
        self.finalized
    }
}

impl Sign for EcdsaOperation {
    fn sign(&mut self, data: &[u8], signature: &mut [u8]) -> Result<()> {
        if self.in_use {
            return Err(CKR_OPERATION_NOT_INITIALIZED)?;
        }
        if self.finalized {
            return Err(CKR_OPERATION_NOT_INITIALIZED)?;
        }
        if self.mech == CKM_ECDSA {
            self.finalized = true;
            if signature.len() != self.output_len {
                return Err(CKR_SIGNATURE_LEN_RANGE)?;
            }

            let mut sig = vec![0u8; self.sigctx.sign(data, None)?];
            let len = self.sigctx.sign(data, Some(sig.as_mut_slice()))?;
            sig.resize(len, 0);
            let ret = ossl_to_pkcs11_signature(&sig, signature);
            zeromem(sig.as_mut_slice());
            return ret;
        }
        self.sign_update(data)?;
        self.sign_final(signature)
    }

    fn sign_update(&mut self, data: &[u8]) -> Result<()> {
        if self.mech == CKM_ECDSA {
            self.finalized = true;
        }
        if self.finalized {
            return Err(CKR_OPERATION_NOT_INITIALIZED)?;
        }
        self.in_use = true;

        Ok(self.sigctx.update(data)?)
    }

    fn sign_final(&mut self, signature: &mut [u8]) -> Result<()> {
        if !self.in_use {
            return Err(CKR_OPERATION_NOT_INITIALIZED)?;
        }
        if self.finalized {
            return Err(CKR_OPERATION_NOT_INITIALIZED)?;
        }
        self.finalized = true;

        let mut sig = vec![0u8; signature.len() + 10];

        let len = self.sigctx.sign_final(sig.as_mut_slice())?;
        if len > sig.len() {
            return Err(CKR_DEVICE_ERROR)?;
        }

        /* can only shrink */
        sig.resize(len, 0);

        let ret = ossl_to_pkcs11_signature(&sig, signature);
        zeromem(sig.as_mut_slice());
        ret
    }

    fn signature_len(&self) -> Result<usize> {
        Ok(self.output_len)
    }
}

impl EcdsaOperation {
    /// Internal helper for performing one-shot or final verification step.
    fn verify_internal(
        &mut self,
        data: &[u8],
        signature: Option<&[u8]>,
    ) -> Result<()> {
        if self.in_use {
            return Err(CKR_OPERATION_NOT_INITIALIZED)?;
        }
        if self.finalized {
            return Err(CKR_OPERATION_NOT_INITIALIZED)?;
        }
        if self.mech == CKM_ECDSA {
            self.finalized = true;
            if let Some(s) = &signature {
                if s.len() != self.output_len {
                    return Err(CKR_SIGNATURE_LEN_RANGE)?;
                }
                let mut sig = pkcs11_to_ossl_signature(s)?;
                let ret = self.sigctx.verify(data, Some(sig.as_slice()));
                zeromem(sig.as_mut_slice());
                return Ok(ret?);
            } else {
                return Ok(self.sigctx.verify(data, None)?);
            }
        }
        self.verify_int_update(data)?;
        self.verify_int_final(signature)
    }

    /// Internal helper for updating a multi-part verification.
    fn verify_int_update(&mut self, data: &[u8]) -> Result<()> {
        if self.mech == CKM_ECDSA {
            self.finalized = true;
        }
        if self.finalized {
            return Err(CKR_OPERATION_NOT_INITIALIZED)?;
        }
        self.in_use = true;

        Ok(self.sigctx.update(data)?)
    }

    /// Internal helper for the final step of multi-part verification.
    fn verify_int_final(&mut self, signature: Option<&[u8]>) -> Result<()> {
        if !self.in_use {
            return Err(CKR_OPERATION_NOT_INITIALIZED)?;
        }
        if self.finalized {
            return Err(CKR_OPERATION_NOT_INITIALIZED)?;
        }
        self.finalized = true;

        // convert PKCS #11 signature to OpenSSL format
        if let Some(s) = &signature {
            if s.len() != self.output_len {
                return Err(CKR_SIGNATURE_LEN_RANGE)?;
            }
            let mut sig = pkcs11_to_ossl_signature(s)?;
            let ret = self.sigctx.verify_final(Some(sig.as_slice()));
            zeromem(sig.as_mut_slice());
            Ok(ret?)
        } else {
            Ok(self.sigctx.verify_final(None)?)
        }
    }
}

impl Verify for EcdsaOperation {
    fn verify(&mut self, data: &[u8], signature: &[u8]) -> Result<()> {
        self.verify_internal(data, Some(signature))
    }

    fn verify_update(&mut self, data: &[u8]) -> Result<()> {
        self.verify_int_update(data)
    }

    fn verify_final(&mut self, signature: &[u8]) -> Result<()> {
        self.verify_int_final(Some(signature))
    }

    fn signature_len(&self) -> Result<usize> {
        Ok(self.output_len)
    }
}

impl VerifySignature for EcdsaOperation {
    fn verify(&mut self, data: &[u8]) -> Result<()> {
        self.verify_internal(data, None)
    }

    fn verify_update(&mut self, data: &[u8]) -> Result<()> {
        self.verify_int_update(data)
    }

    fn verify_final(&mut self) -> Result<()> {
        self.verify_int_final(None)
    }
}