cosmian_kms_cli 5.20.0

Command Line Interface used to manage the KMS server If any assistance is needed, please either visit the Cosmian technical documentation at https://docs.cosmian.com or contact the Cosmian support team on Discord https://discord.com/invite/7kPMNtHpnz
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
use std::path::PathBuf;

use clap::Parser;
use cosmian_kmip::time_normalize;
use cosmian_kms_client::{
    KmsClient,
    cosmian_kmip::{
        kmip_0::kmip_types::CertificateType,
        kmip_2_1::{
            kmip_objects::Object,
            kmip_types::{KeyFormatType, LinkType, LinkedObjectIdentifier},
            requests::import_object_request,
        },
    },
    kmip_2_1::{self, kmip_attributes::Attributes, kmip_types::UniqueIdentifier},
    read_bytes_from_file, read_object_from_json_ttlv_file,
    reexport::cosmian_kms_client_utils::import_utils::{
        CertificateInputFormat, KeyUsage, build_private_key_from_der_bytes,
        build_usage_mask_from_key_usage,
    },
};
use cosmian_logger::{debug, trace};
use der::{Decode, DecodePem, Encode};
use x509_cert::Certificate;
use zeroize::Zeroizing;

use crate::{
    actions::kms::console,
    error::{KmsCliError, result::KmsCliResult},
};

const MOZILLA_CCADB: &str =
    "https://ccadb.my.salesforce-sites.com/mozilla/IncludedRootsPEMTxt?TrustBitsInclude=Websites";

/// Import one of the following:
/// - a certificate: formatted as a X509 PEM (pem), X509 DER (der) or JSON TTLV (json-ttlv)
/// - a certificate chain as a PEM-stack (chain)
/// - a PKCS12 file containing a certificate, a private key and possibly a chain (pkcs12)
/// - the Mozilla Common CA Database (CCADB - fetched by the CLI before import) (ccadb)
///
/// When no unique id is specified, a unique id based on the key material is generated.
///
/// Tags can later be used to retrieve the certificate. Tags are optional.
#[derive(Parser, Default, Debug)]
#[clap(verbatim_doc_comment)]
pub struct ImportCertificateAction {
    /// The input file in PEM, KMIP-JSON-TTLV or PKCS#12 format.
    #[clap(
        required_if_eq_any([
            ("input_format", "json-ttlv"),
            ("input_format", "pem"),
            ("input_format", "der"),
            ("input_format", "chain"),
            ("input_format", "pkcs12")
            ])
    )]
    pub(crate) certificate_file: Option<PathBuf>,

    /// The unique id of the leaf certificate; a unique id
    /// based on the key material is generated if not specified.
    /// When importing a PKCS12, the unique id will be that of the private key.
    #[clap(required = false, verbatim_doc_comment)]
    pub(crate) certificate_id: Option<String>,

    /// Import the certificate in the selected format.
    #[clap(
        required = true,
        long = "format",
        short = 'f',
        default_value = "json-ttlv"
    )]
    pub(crate) input_format: CertificateInputFormat,

    /// The corresponding private key id if any.
    /// Ignored for PKCS12 and CCADB formats.
    #[clap(long, short = 'k')]
    pub(crate) private_key_id: Option<String>,

    /// The corresponding public key id if any.
    /// Ignored for PKCS12 and CCADB formats.
    #[clap(long, short = 'q')]
    pub(crate) public_key_id: Option<String>,

    /// The issuer certificate id if any.
    /// Ignored for PKCS12 and CCADB formats.
    #[clap(long, short = 'i')]
    pub(crate) issuer_certificate_id: Option<String>,

    /// PKCS12 password: only available for PKCS12 format.
    #[clap(long = "pkcs12-password", short = 'p')]
    pub(crate) pkcs12_password: Option<String>,

    /// Replace an existing certificate under the same id.
    #[clap(
        required = false,
        long = "replace",
        short = 'r',
        default_value = "false"
    )]
    pub(crate) replace_existing: bool,

    /// The tag to associate with the certificate.
    /// To specify multiple tags, use the option multiple times.
    #[clap(long = "tag", short = 't', value_name = "TAG")]
    pub(crate) tags: Vec<String>,

    /// For what operations should the certificate be used.
    #[clap(long = "key-usage")]
    pub(crate) key_usage: Option<Vec<KeyUsage>>,
}

impl ImportCertificateAction {
    pub async fn run(&self, kms_rest_client: KmsClient) -> KmsCliResult<Option<String>> {
        trace!("{self:?}");

        // generate the leaf certificate attributes if links are specified
        let mut leaf_certificate_attributes = Some(Attributes {
            activation_date: Some(time_normalize()?),
            ..Default::default()
        });

        if let Some(issuer_certificate_id) = &self.issuer_certificate_id {
            let attributes = leaf_certificate_attributes.get_or_insert_with(Attributes::default);
            attributes.set_link(
                LinkType::CertificateLink,
                LinkedObjectIdentifier::TextString(issuer_certificate_id.clone()),
            );
        }
        if let Some(private_key_id) = &self.private_key_id {
            let attributes = leaf_certificate_attributes.get_or_insert_with(Attributes::default);
            attributes.set_link(
                LinkType::PrivateKeyLink,
                LinkedObjectIdentifier::TextString(private_key_id.clone()),
            );
        }
        if let Some(public_key_id) = &self.public_key_id {
            let attributes = leaf_certificate_attributes.get_or_insert_with(Attributes::default);
            attributes.set_link(
                LinkType::PublicKeyLink,
                LinkedObjectIdentifier::TextString(public_key_id.clone()),
            );
        }

        if let Some(ref attributes) = leaf_certificate_attributes {
            trace!("Leaf certificate attributes: {}", attributes);
        }
        let (stdout_message, returned_unique_identifier) = match self.input_format {
            CertificateInputFormat::JsonTtlv => {
                trace!("import certificate as TTLV JSON file");
                // read the certificate file
                let object = read_object_from_json_ttlv_file(self.get_certificate_file()?)?;
                let certificate_id = Box::pin(self.import_chain(
                    kms_rest_client,
                    vec![object],
                    self.replace_existing,
                    leaf_certificate_attributes,
                ))
                .await?;
                (
                    "The certificate in the JSON TTLV was successfully imported!".to_owned(),
                    Some(certificate_id),
                )
            }
            CertificateInputFormat::Pem => {
                trace!("import certificate as PEM file");
                let pem_value = read_bytes_from_file(&self.get_certificate_file()?)?;
                // convert the PEM to X509 to make sure it is correct
                let certificate = Certificate::from_pem(&pem_value).map_err(|e| {
                    KmsCliError::Conversion(format!(
                        "Cannot read PEM content to X509. Error: {e:?}"
                    ))
                })?;
                let object = Object::Certificate(kmip_2_1::kmip_objects::Certificate {
                    certificate_type: CertificateType::X509,
                    certificate_value: certificate.to_der()?,
                });
                let certificate_id = Box::pin(self.import_chain(
                    kms_rest_client,
                    vec![object],
                    self.replace_existing,
                    leaf_certificate_attributes,
                ))
                .await?;
                (
                    "The certificate in the PEM file was successfully imported!".to_owned(),
                    Some(certificate_id),
                )
            }
            CertificateInputFormat::Der => {
                debug!("import certificate as a DER file");
                let der_value = read_bytes_from_file(&self.get_certificate_file()?)?;
                // convert DER to X509 to make sure it is correct
                let certificate = Certificate::from_der(&der_value).map_err(|e| {
                    KmsCliError::Conversion(format!(
                        "Cannot read DER content to X509. Error: {e:?}"
                    ))
                })?;
                let object = Object::Certificate(kmip_2_1::kmip_objects::Certificate {
                    certificate_type: CertificateType::X509,
                    certificate_value: certificate.to_der()?,
                });
                let certificate_id = Box::pin(self.import_chain(
                    kms_rest_client,
                    vec![object],
                    self.replace_existing,
                    leaf_certificate_attributes,
                ))
                .await?;
                (
                    "The certificate in the DER file was successfully imported!".to_owned(),
                    Some(certificate_id),
                )
            }
            CertificateInputFormat::Pkcs12 => {
                debug!("import certificate as PKCS12 file");
                let private_key_id = self.import_pkcs12(kms_rest_client).await?;
                (
                    "The certificate(s), public key, and private key were successfully imported! \
                     The private key has id:"
                        .to_owned(),
                    Some(private_key_id),
                )
            }
            CertificateInputFormat::Chain => {
                debug!("import certificate chain as PEM file");
                let pem_stack = read_bytes_from_file(&self.get_certificate_file()?)?;
                let objects = build_chain_from_stack(&pem_stack)?;
                // import the full chain
                let leaf_certificate_id = Box::pin(self.import_chain(
                    kms_rest_client,
                    objects,
                    self.replace_existing,
                    leaf_certificate_attributes,
                ))
                .await?;
                (
                    "The certificate chain in the PEM file was successfully imported!".to_owned(),
                    Some(leaf_certificate_id),
                )
            }
            CertificateInputFormat::CCADB => {
                let ccadb_bytes = reqwest::get(MOZILLA_CCADB)
                    .await
                    .map_err(|e| {
                        KmsCliError::ItemNotFound(format!(
                            "Cannot fetch Mozilla CCADB ({MOZILLA_CCADB:?}. Error: {e:?})",
                        ))
                    })?
                    .bytes()
                    .await
                    .map_err(|e| {
                        KmsCliError::Conversion(format!(
                            "Cannot convert Mozilla CCADB content to bytes. Error: {e:?}"
                        ))
                    })?;
                // import the certificates
                let objects = build_chain_from_stack(&ccadb_bytes)?;
                Box::pin(self.import_chain(kms_rest_client, objects, self.replace_existing, None))
                    .await?;

                ("The list of Mozilla CCADB certificates".to_owned(), None)
            }
        };
        let mut stdout = console::Stdout::new(&stdout_message);
        stdout.set_tags(Some(&self.tags));
        if let Some(ref id) = returned_unique_identifier {
            let uid = UniqueIdentifier::TextString(id.clone());
            stdout.set_unique_identifier(&uid);
        }
        stdout.write()?;

        Ok(returned_unique_identifier)
    }

    /// Import the certificate, the chain and the associated private key
    async fn import_pkcs12(&self, kms_rest_client: KmsClient) -> KmsCliResult<String> {
        let cryptographic_usage_mask = self
            .key_usage
            .as_deref()
            .and_then(build_usage_mask_from_key_usage);
        let pkcs12_bytes = Zeroizing::from(read_bytes_from_file(&self.get_certificate_file()?)?);

        // Create a KMIP private key from the PKCS12 private key
        let private_key = build_private_key_from_der_bytes(KeyFormatType::PKCS12, pkcs12_bytes);

        let mut attributes = private_key.attributes().cloned().unwrap_or_default();
        attributes.set_cryptographic_usage_mask(cryptographic_usage_mask);

        if let Some(password) = &self.pkcs12_password {
            attributes.set_link(
                LinkType::PKCS12PasswordLink,
                LinkedObjectIdentifier::TextString(password.clone()),
            );
        }

        let import_object_request = import_object_request(
            kms_rest_client.config.vendor_id.as_str(),
            self.certificate_id.clone(),
            private_key,
            Some(attributes),
            false,
            self.replace_existing,
            &self.tags,
        )?;
        let private_key_id = kms_rest_client
            .import(import_object_request)
            .await?
            .unique_identifier
            .to_string();
        Ok(private_key_id)
    }

    fn get_certificate_file(&self) -> KmsCliResult<&PathBuf> {
        self.certificate_file.as_ref().ok_or_else(|| {
            KmsCliError::InvalidRequest(format!(
                "Certificate file parameter is MANDATORY for {:?} format",
                self.input_format
            ))
        })
    }

    /// Import the certificates in reverse order (from root to leaf)
    /// linking the child to the parent with `Link` of `LinkType::CertificateLink`
    async fn import_chain(
        &self,
        kms_rest_client: KmsClient,
        mut objects: Vec<Object>,
        replace_existing: bool,
        leaf_certificate_attributes: Option<Attributes>,
    ) -> KmsCliResult<String> {
        let mut previous_identifier: Option<String> = None;
        while let Some(object) = objects.pop() {
            let mut import_attributes = if objects.is_empty() {
                // this is the leaf certificate
                leaf_certificate_attributes.clone()
            } else {
                None
            };
            // add link to issuer/parent certificate if any
            if let Some(id) = previous_identifier {
                let attributes = import_attributes.get_or_insert_with(Attributes::default);
                attributes.set_link(
                    LinkType::CertificateLink,
                    LinkedObjectIdentifier::TextString(id.clone()),
                );
            }
            // Set activation_date to now if activate flag is set
            let attributes = import_attributes.get_or_insert_with(Attributes::default);
            attributes.activation_date = Some(time_normalize()?);
            // import the certificate
            let import_object_request = import_object_request(
                kms_rest_client.config.vendor_id.as_str(),
                self.certificate_id.clone(),
                object,
                import_attributes,
                false,
                replace_existing,
                &self.tags,
            )?;
            let unique_identifier = kms_rest_client
                .import(import_object_request)
                .await?
                .unique_identifier;

            previous_identifier = Some(unique_identifier.to_string());
        }
        // return the identifier of the leaf certificate
        previous_identifier.ok_or_else(|| {
            KmsCliError::Default(
                "The certificate chain does not contain any certificate".to_owned(),
            )
        })
    }
}

/// Build a chain of certificates from a PEM stack
fn build_chain_from_stack(pem_chain: &[u8]) -> KmsCliResult<Vec<Object>> {
    let pem_s = pem::parse_many(pem_chain)
        .map_err(|e| KmsCliError::Conversion(format!("Cannot parse PEM content. Error: {e:?}")))?; // check the PEM is valid (no error
    let mut objects = vec![];
    for pem_data in pem_s {
        // convert the PEM to X509 to make sure it is correct
        let certificate = Certificate::from_der(pem_data.contents()).map_err(|e| {
            KmsCliError::Conversion(format!("Cannot read DER content to X509. Error: {e:?}"))
        })?;
        let object = Object::Certificate(kmip_2_1::kmip_objects::Certificate {
            certificate_type: CertificateType::X509,
            certificate_value: certificate.to_der()?,
        });
        objects.push(object);
    }
    Ok(objects)
}

#[cfg(test)]
#[expect(clippy::unwrap_used)]
mod tests {
    use crate::actions::kms::certificates::import_certificate::build_chain_from_stack;

    #[test]
    fn test_chain_parse() {
        let chain_str =
            include_bytes!("../../../../../../test_data/certificates/mozilla_IncludedRootsPEM.txt");
        let objects = build_chain_from_stack(chain_str).unwrap();
        assert_eq!(objects.len(), 144);
    }
}