forked from oxidecomputer/offline-keystore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathca.rs
619 lines (532 loc) · 19.6 KB
/
ca.rs
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use anyhow::Result;
use fs_extra::dir::CopyOptions;
use log::{debug, error, info, warn};
use std::{
env,
fs::{self, OpenOptions, Permissions},
io,
os::unix::fs::PermissionsExt,
path::Path,
process::{Child, Command, Stdio},
str::FromStr,
thread,
time::Duration,
};
use tempfile::{NamedTempFile, TempDir};
use thiserror::Error;
use zeroize::Zeroizing;
use crate::config::{
self, CsrSpec, KeySpec, Purpose, Transport, ENV_PASSWORD, KEYSPEC_EXT,
};
/// Name of file in root of a CA directory with key spec used to generate key
/// in HSM.
const CA_KEY_SPEC: &str = "key.spec";
const CSRSPEC_EXT: &str = ".csrspec.json";
#[derive(Error, Debug)]
pub enum CaError {
#[error("Invalid path to CsrSpec file")]
BadCsrSpecPath,
#[error("Invalid purpose for root CA key")]
BadPurpose,
#[error("path not a directory")]
BadSpecDirectory,
#[error("failed to generate certificate")]
CertGenFail,
#[error("failed to create self signed cert for key")]
SelfCertGenFail,
}
// NOTE: before using the pkcs11 engine the connector must be running:
// sudo systemctl start yubihsm-connector
macro_rules! openssl_cnf_fmt {
() => {
r#"
openssl_conf = default_modules
[default_modules]
engines = engine_section
oid_section = OIDs
[engine_section]
pkcs11 = pkcs11_section
[pkcs11_section]
engine_id = pkcs11
MODULE_PATH = {pkcs11_path}
# add 'debug' to INIT_ARGS
INIT_ARGS = connector=http://127.0.0.1:12345
init = 0
[ ca ]
default_ca = CA_default
[ CA_default ]
dir = ./
crl_dir = $dir/crl
database = $dir/index.txt
new_certs_dir = $dir/newcerts
certificate = $dir/ca.cert.pem
serial = $dir/serial
# key format: <slot>:<key id>
private_key = 0:{key:04x}
name_opt = ca_default
cert_opt = ca_default
# certs may be retired, but they won't expire
default_enddate = 99991231235959Z
default_crl_days = 30
default_md = {hash:?}
preserve = no
policy = policy_match
email_in_dn = no
# Setting rand_serial to _any_ value, including "no", enables that option
#rand_serial = yes
unique_subject = no
[ policy_match ]
countryName = supplied
stateOrProvinceName = optional
organizationName = supplied
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ req ]
default_md = {hash:?}
string_mask = utf8only
[ v3_rot_release_root ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical,CA:true
keyUsage = critical, keyCertSign, cRLSign
extendedKeyUsage = nxpLpc55DebugAuthCredentialSigning
certificatePolicies = rotCodeSigningReleasePolicy
[ v3_code_signing_rel ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical,CA:false
keyUsage = critical, digitalSignature
extendedKeyUsage = codeSigning
certificatePolicies = rotCodeSigningReleasePolicy
[ v3_rot_development_root ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical,CA:true
keyUsage = critical, keyCertSign, cRLSign
extendedKeyUsage = nxpLpc55DebugAuthCredentialSigning
certificatePolicies = rotCodeSigningDevelopmentPolicy
[ v3_code_signing_dev ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical,CA:false
keyUsage = critical, digitalSignature
extendedKeyUsage = codeSigning
certificatePolicies = rotCodeSigningDevelopmentPolicy
[ v3_identity ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical,CA:true
keyUsage = critical, keyCertSign, cRLSign
certificatePolicies = critical, deviceIdentityPolicy, tcg-dice-kp-identityInit, tcg-dice-kp-attestInit, tcg-dice-kp-eca
[ OIDs ]
# https://github.com/oxidecomputer/oana#asn1-object-identifiers
rotCodeSigningReleasePolicy = 1.3.6.1.4.1.57551.1.1
rotCodeSigningDevelopmentPolicy = 1.3.6.1.4.1.57551.1.2
deviceIdentityPolicy = 1.3.6.1.4.1.57551.1.3
nxpLpc55DebugAuthCredentialSigning = 1.3.6.1.4.1.57551.2.1
tcg-dice-kp-identityInit = 2.23.133.5.4.100.6
tcg-dice-kp-attestInit = 2.23.133.5.4.100.8
tcg-dice-kp-eca = 2.23.133.5.4.100.12
"#
};
}
/// Get password for pkcs11 operations to keep the user from having to enter
/// the password multiple times (once for signing the CSR, one for signing
/// the cert). We also prefix the password with '0002' so the YubiHSM
/// PKCS#11 module knows which key to use
fn passwd_to_env(env_str: &str) -> Result<()> {
let mut password = Zeroizing::new("0002".to_string());
let passwd = Zeroizing::new(match env::var(ENV_PASSWORD).ok() {
Some(p) => p,
None => rpassword::prompt_password("Enter YubiHSM Password: ")?,
});
password.push_str(&passwd);
std::env::set_var(env_str, password);
Ok(())
}
/// Start the yubihsm-connector process.
/// NOTE: The connector dumps ~10 lines of text for each command.
/// We can increase verbosity with the `-debug` flag, but the only way
/// we can dial this down is by sending stderr to /dev/null.
fn start_connector() -> Result<Child> {
debug!("starting connector");
let child = Command::new("yubihsm-connector")
.stderr(Stdio::null())
.stdout(Stdio::null())
.spawn()?;
// Sleep for a second to allow the connector to start before we start
// sending commands to it.
std::thread::sleep(std::time::Duration::from_millis(1000));
Ok(child)
}
/// Initialize an openssl CA directory & self signed cert for the provided
/// KeySpec.
/// NOTE: The YubiHSM supports 16 sessions and stale sessions are recycled
/// after 30 seconds of inactivity. Depending on however many KeySpecs we're
/// processing tests shows that we run out of sessions pretty quickly. This
/// is likely caused by the pkcs11 module not cleaning up after itself. To
/// account for this we sleep between invocations of the openssl tools to give
/// the stale sessions time to be reclaimed by the HSM.
pub fn initialize(
key_spec: &Path,
pkcs11_path: &Path,
ca_state: &Path,
out: &Path,
transport: Transport,
) -> Result<()> {
let key_spec = fs::canonicalize(key_spec)?;
debug!("canonical KeySpec path: {}", key_spec.display());
let paths = if key_spec.is_file() {
vec![key_spec.clone()]
} else {
config::files_with_ext(&key_spec, KEYSPEC_EXT)?
};
if paths.is_empty() {
return Err(anyhow::anyhow!(
"no files with extension \"{}\" found in dir: {}",
KEYSPEC_EXT,
&key_spec.display()
));
}
let connector = match transport {
// The yubihsm pkcs#11 module relies on the yubihsm-connector. If
// we've been using the Usb connector up to this point we assume the
// daemon is not running and that we must start it.
Transport::Usb => Some(start_connector()?),
_ => None,
};
passwd_to_env("OKM_HSM_PKCS11_AUTH")?;
let tmp_dir = TempDir::new()?;
let tmp_ca_state = tmp_dir.path().join("ca-state");
fs::create_dir_all(&tmp_ca_state)?;
let tmp_out = tmp_dir.path().join("public");
fs::create_dir_all(&tmp_out)?;
for path in paths {
info!("Initializing CA from KeySpec: {:?}", path);
// sleep to let sessions cycle
thread::sleep(Duration::from_millis(1500));
if let Err(e) =
initialize_keyspec(&path, pkcs11_path, &tmp_ca_state, &tmp_out)
{
// Ignore possible error from killing connector because we already
// have an error to report and it'll be more interesting.
if let Some(mut c) = connector {
let _ = c.kill();
}
return Err(e);
}
}
if connector.is_some() {
connector.unwrap().kill()?;
}
// copy contents of temp directory to out
debug!("tmpdir: {:?}", tmp_dir);
let paths = fs::read_dir(&tmp_ca_state)?
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, io::Error>>()?;
let opts = CopyOptions::default().overwrite(true);
fs_extra::move_items(&paths, ca_state, &opts)?;
let paths = fs::read_dir(&tmp_out)?
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, io::Error>>()?;
let opts = CopyOptions::default().overwrite(true);
fs_extra::move_items(&paths, out, &opts)?;
Ok(())
}
fn initialize_keyspec(
key_spec: &Path,
pkcs11_path: &Path,
ca_state: &Path,
out: &Path,
) -> Result<()> {
let json = fs::read_to_string(key_spec)?;
debug!("spec as json: {}", json);
let spec = KeySpec::from_str(&json)?;
debug!("KeySpec from {}: {:#?}", key_spec.display(), spec);
// sanity check: no signing keys at CA init
// this makes me think we need different types for this:
// one for the CA keys, one for the children we sign
match spec.purpose {
Purpose::RoTReleaseRoot
| Purpose::RoTDevelopmentRoot
| Purpose::Identity => (),
_ => return Err(CaError::BadPurpose.into()),
}
let pwd = std::env::current_dir()?;
debug!("got current directory: {:?}", pwd);
// setup CA directory structure
let label = spec.label.to_string();
let ca_dir = ca_state.join(&label);
fs::create_dir_all(&ca_dir)?;
info!("Bootstrapping CA files for key with label: {}", &label);
debug!("setting current directory: {}", ca_dir.display());
std::env::set_current_dir(&ca_dir)?;
// copy the key spec file to the ca state dir
fs::write("key.spec", json)?;
bootstrap_ca(&spec, pkcs11_path)?;
// We don't have a use-case for this artifact once the root cert is
// generated so it's purely a temp file.
let csr = NamedTempFile::new()?;
// sleep to let sessions cycle
thread::sleep(Duration::from_millis(1500));
let mut cmd = Command::new("openssl");
let output = cmd
.arg("req")
.arg("-config")
.arg("openssl.cnf")
.arg("-new")
.arg("-subj")
.arg(format!(
"/C=US/O=Oxide Computer Company/CN={}/",
spec.common_name
))
.arg("-engine")
.arg("pkcs11")
.arg("-keyform")
.arg("engine")
.arg("-key")
.arg(format!("0:{:04x}", spec.id))
.arg("-passin")
.arg("env:OKM_HSM_PKCS11_AUTH")
.arg("-out")
.arg(csr.path())
.output()?;
debug!("executing command: \"{:#?}\"", cmd);
if !output.status.success() {
warn!("command failed with status: {}", output.status);
warn!("stderr: \"{}\"", String::from_utf8_lossy(&output.stderr));
return Err(CaError::SelfCertGenFail.into());
}
if spec.self_signed {
// sleep to let sessions cycle
thread::sleep(Duration::from_millis(1500));
// generate cert for CA root
info!("Generating self-signed cert for CA root");
let mut cmd = Command::new("openssl");
let output = cmd
.arg("ca")
.arg("-batch")
.arg("-selfsign")
.arg("-notext")
.arg("-config")
.arg("openssl.cnf")
.arg("-engine")
.arg("pkcs11")
.arg("-keyform")
.arg("engine")
.arg("-keyfile")
.arg(format!("0:{:04x}", spec.id))
.arg("-extensions")
.arg(spec.purpose.to_string())
.arg("-passin")
.arg("env:OKM_HSM_PKCS11_AUTH")
.arg("-in")
.arg(csr.path())
.arg("-out")
.arg("ca.cert.pem")
.output()?;
debug!("executing command: \"{:#?}\"", cmd);
if !output.status.success() {
warn!("command failed with status: {}", output.status);
warn!("stderr: \"{}\"", String::from_utf8_lossy(&output.stderr));
return Err(CaError::SelfCertGenFail.into());
}
let cert = out.join(format!("{}.cert.pem", label));
fs::copy("ca.cert.pem", cert)?;
} else {
// when we're not generating a self signed cert we copy the csr
// to the output directory so it can be certified through an
// external process
fs::copy(csr, out.join(format!("{}.csr.pem", label)))?;
}
env::set_current_dir(pwd)?;
Ok(())
}
pub fn sign(
csr_spec: &Path,
state: &Path,
publish: &Path,
transport: Transport,
) -> Result<()> {
let csr_spec = fs::canonicalize(csr_spec)?;
debug!("canonical CsrSpec path: {}", &csr_spec.display());
let paths = if csr_spec.is_file() {
vec![csr_spec.clone()]
} else {
config::files_with_ext(&csr_spec, CSRSPEC_EXT)?
};
if paths.is_empty() {
return Err(anyhow::anyhow!(
"no files with extension \"{}\" found in dir: {}",
CSRSPEC_EXT,
&csr_spec.display()
));
}
let connector = match transport {
// The yubihsm pkcs#11 module relies on the yubihsm-connector. If
// we've been using the Usb connector up to this point we assume the
// daemon is not running and that we must start it.
Transport::Usb => Some(start_connector()?),
_ => None,
};
passwd_to_env("OKM_HSM_PKCS11_AUTH")?;
let tmp_dir = TempDir::new()?;
for path in paths {
// process csr spec
info!("Signing CSR from CsrSpec: {:?}", path);
if let Err(e) = sign_csrspec(&path, &tmp_dir, state, publish) {
// Ignore possible error from killing connector because we already
// have an error to report and it'll be more interesting.
if let Some(mut c) = connector {
let _ = c.kill();
}
return Err(e);
}
}
// kill connector
if connector.is_some() {
connector.unwrap().kill()?;
}
Ok(())
}
pub fn sign_csrspec(
csr_spec_path: &Path,
tmp_dir: &TempDir,
state: &Path,
publish: &Path,
) -> Result<()> {
// deserialize the csrspec
debug!("Getting CSR spec from: {}", csr_spec_path.display());
let json = fs::read_to_string(csr_spec_path)?;
debug!("spec as json: {}", json);
let csr_spec = CsrSpec::from_str(&json)?;
debug!("CsrSpec: {:#?}", csr_spec);
// get the label
// use label to reconstruct path to CA root dir for key w/ label
let key_spec = state.join(csr_spec.label.to_string()).join(CA_KEY_SPEC);
debug!("Getting KeySpec from: {}", key_spec.display());
let json = fs::read_to_string(key_spec)?;
debug!("spec as json: {}", json);
let key_spec = KeySpec::from_str(&json)?;
debug!("KeySpec: {:#?}", key_spec);
// sanity check: no signing keys at CA init
// this makes me think we need different types for this:
// one for the CA keys, one for the children we sign
// map purpose of CA key to key associated with CSR
let purpose = match key_spec.purpose {
Purpose::RoTReleaseRoot => Purpose::RoTReleaseCodeSigning,
Purpose::RoTDevelopmentRoot => Purpose::RoTDevelopmentCodeSigning,
Purpose::Identity => Purpose::Identity,
_ => return Err(CaError::BadPurpose.into()),
};
let publish = fs::canonicalize(publish)?;
debug!("canonical publish: {}", publish.display());
// pushd into ca dir based on spec file
let pwd = std::env::current_dir()?;
debug!("got current directory: {:?}", pwd);
let ca_dir = state.join(key_spec.label.to_string());
std::env::set_current_dir(&ca_dir)?;
debug!("setting current directory: {}", ca_dir.display());
// Get prefix from CsrSpec file. We us this to generate file names for the
// temp CSR file and the output cert file.
let csr_filename = match csr_spec_path
.file_name()
.ok_or(CaError::BadCsrSpecPath)?
.to_os_string()
.into_string()
{
Ok(s) => s,
Err(_) => return Err(CaError::BadCsrSpecPath.into()),
};
let csr_prefix = match csr_filename.find('.') {
Some(i) => csr_filename[..i].to_string(),
None => csr_filename,
};
// create a tempdir & write CSR there for openssl: AFAIK the `ca` command
// won't take the CSR over stdin
let tmp_csr = tmp_dir.path().join(format!("{}.csr.pem", csr_prefix));
debug!("writing CSR to: {}", tmp_csr.display());
fs::write(&tmp_csr, &csr_spec.csr)?;
let cert = publish.join(format!("{}.cert.pem", csr_prefix));
debug!("writing cert to: {}", cert.display());
// sleep to let sessions cycle
thread::sleep(Duration::from_millis(2500));
// execute CA command
info!(
"Generating cert from CSR & signing with key: {}",
key_spec.label.to_string()
);
let mut cmd = Command::new("openssl");
cmd.arg("ca")
.arg("-batch")
.arg("-notext")
.arg("-config")
.arg("openssl.cnf")
.arg("-engine")
.arg("pkcs11")
.arg("-keyform")
.arg("engine")
.arg("-keyfile")
.arg(format!("0:{:04x}", key_spec.id))
.arg("-extensions")
.arg(purpose.to_string())
.arg("-passin")
.arg("env:OKM_HSM_PKCS11_AUTH")
.arg("-in")
.arg(&tmp_csr)
.arg("-out")
.arg(&cert);
debug!("executing command: \"{:#?}\"", cmd);
let output = cmd.output()?;
if !output.status.success() {
warn!("command failed with status: {}", output.status);
warn!("stderr: \"{}\"", String::from_utf8_lossy(&output.stderr));
return Err(CaError::CertGenFail.into());
}
std::env::set_current_dir(pwd)?;
Ok(())
}
/// Create the directory structure and initial files expected by the `openssl ca` tool.
fn bootstrap_ca(key_spec: &KeySpec, pkcs11_path: &Path) -> Result<()> {
// create directories expected by `openssl ca`: crl, newcerts
for dir in ["crl", "newcerts", "csr"] {
debug!("creating directory: {}?", dir);
fs::create_dir(dir)?;
}
// the 'private' directory is a special case w/ restricted permissions
let priv_dir = "private";
debug!("creating directory: {}?", priv_dir);
fs::create_dir(priv_dir)?;
let perms = Permissions::from_mode(0o700);
debug!(
"setting permissions on directory {} to {:#?}",
priv_dir, perms
);
fs::set_permissions(priv_dir, perms)?;
// touch 'index.txt' file
let index = "index.txt";
debug!("touching file {}", index);
OpenOptions::new().create(true).write(true).open(index)?;
// write initial serial number to 'serial' (echo 1000 > serial)
let serial = "serial";
let init_serial_hex = format!("{:020x}", key_spec.initial_serial_number);
debug!(
"setting initial serial number to \"{init_serial_hex}\" in file \"{serial}\""
);
fs::write(serial, init_serial_hex)?;
// create & write out an openssl.cnf
fs::write(
"openssl.cnf",
format!(
openssl_cnf_fmt!(),
key = key_spec.id,
hash = key_spec.hash,
pkcs11_path = pkcs11_path.display()
),
)?;
Ok(())
}