Repository navigation
Expand file tree
/
Copy pathpki.rs
More file actions
497 lines (455 loc) · 17.5 KB
/
Copy pathpki.rs
File metadata and controls
497 lines (455 loc) · 17.5 KB
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
use std::{
cmp::Ordering,
time::{SystemTime, UNIX_EPOCH},
};
use openssl::{asn1::Asn1Time, x509::X509};
use serde_json::{Value, json};
use crate::{common::errors::MegaError, contract::vault::integration::vault_core::VaultCore};
// FIXME: A more official and robust ROLE name
const ROLE: &str = "test-role";
#[allow(unused)]
impl VaultCore {
/// Initialize the Vault CA
async fn init_ca(&self) -> Result<(), MegaError> {
// err = not found
if self.read_api("pki/ca/tls/pem").await.is_err() {
self.config_ca().await?;
self.generate_root(false).await?;
self.config_role(json!({
"ttl": "60d",
"max_ttl": "365d",
"key_type": "rsa",
"key_bits": 4096,
"country": "CN",
"province": "Beijing",
"locality": "Beijing",
"organization": "OpenAtom-Mega",
"no_store": false,
}))
.await?;
}
Ok(())
}
async fn config_ca(&self) -> Result<(), MegaError> {
// mount pki backend to path: pki/
let mount_data = json!({
"type": "pki",
})
.as_object()
.ok_or_else(|| MegaError::Other("PKI mount data must be a JSON object".to_string()))?
.clone();
self.write_api("sys/mounts/pki/", Some(mount_data)).await?;
Ok(())
}
/// generate root cert, so that you can read from `pki/ca/tls/pem`
/// - if `exported` is true, then the response will contain `private key`
async fn generate_root(&self, exported: bool) -> Result<(), MegaError> {
let key_type = "rsa";
let key_bits = 4096;
let common_name = "mega-ca";
let req_data = json!({
"common_name": common_name,
"ttl": "365d",
"country": "cn",
"key_type": key_type,
"key_bits": key_bits,
})
.as_object()
.ok_or_else(|| MegaError::Other("PKI root request must be a JSON object".to_string()))?
.clone();
self.write_api(
format!(
"pki/root/tls/generate/{}",
if exported { "exported" } else { "internal" }
)
.as_str(),
Some(req_data),
)
.await?;
Ok(())
}
/// - `data`: see `libvault::modules::pki::path_roles`'s `RoleEntry`
/// - This function configures a role for issuing certificates.
/// - The `ROLE` constant is used as the role name.
///
/// # Arguments
/// - `data`: A JSON object containing the role configuration data.
///
/// # Example
/// ```json
/// {
/// "ttl": "60d",
/// "max_ttl": "365d",
/// "key_type": "rsa",
/// "key_bits": 4096,
/// "country": "CN",
/// "province": "Beijing",
/// "locality": "Beijing",
/// "organization": "Open Atom-Mega",
/// "no_store": false
/// }
/// ```
pub async fn config_role(&self, data: Value) -> Result<(), MegaError> {
let role_data = data
.as_object()
.ok_or_else(|| MegaError::Other("PKI role data must be a JSON object".to_string()))?
.clone();
// config role
self.write_api(format!("pki/roles/tls/{ROLE}"), Some(role_data))
.await?;
Ok(())
}
/// issue certificate
/// - `data`: see `libvault::modules::pki::path_issue`
/// - return: `(cert_pem, private_key)`
pub async fn issue_cert(&self, data: Value) -> Result<(String, String), MegaError> {
// let dns_sans = ["test.com", "a.test.com", "b.test.com"];
let issue_data = data
.as_object()
.ok_or_else(|| MegaError::Other("PKI issue data must be a JSON object".to_string()))?
.clone();
// issue cert
let resp_body = self
.write_api(format!("pki/issue/tls/{ROLE}"), Some(issue_data))
.await?;
let cert_data = resp_body
.and_then(|response| response.data)
.ok_or_else(|| MegaError::Other("PKI issue response is missing data".to_string()))?;
let certificate = cert_data
.get("certificate")
.and_then(|value| value.as_str())
.ok_or_else(|| {
MegaError::Other("PKI issue response is missing certificate".to_string())
})?
.to_owned();
let private_key = cert_data
.get("private_key")
.and_then(|value| value.as_str())
.ok_or_else(|| {
MegaError::Other("PKI issue response is missing private_key".to_string())
})?
.to_owned();
Ok((certificate, private_key))
}
/// Verify certificate: time & signature
/// # Arguments
/// - `cert_pem`: The PEM-encoded certificate to verify.
///
/// # Returns
/// - `true` if the certificate is valid, `false` otherwise.
pub async fn verify_cert(&self, cert_pem: &[u8]) -> Result<bool, MegaError> {
let root_cert = self.get_root_cert().await?;
let ca_cert = X509::from_pem(root_cert.as_bytes())
.map_err(|e| MegaError::Other(format!("failed to parse PKI root certificate: {e}")))?;
let cert = X509::from_pem(cert_pem)
.map_err(|e| MegaError::Other(format!("failed to parse certificate: {e}")))?;
// verify time
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| MegaError::Other(format!("system time before UNIX epoch: {e}")))?
.as_secs() as i64;
let now = Asn1Time::from_unix(now)
.map_err(|e| MegaError::Other(format!("failed to construct ASN.1 time: {e}")))?;
let not_before = cert.not_before();
let not_after = cert.not_after();
match now.compare(not_before) {
Ok(Ordering::Less) | Err(_) => return Ok(false),
_ => {}
}
match now.compare(not_after) {
Ok(Ordering::Greater) | Err(_) => return Ok(false),
_ => {}
}
// verify signature
let public_key = ca_cert
.public_key()
.map_err(|e| MegaError::Other(format!("failed to read PKI root public key: {e}")))?;
cert.verify(&public_key)
.map_err(|e| MegaError::Other(format!("failed to verify certificate: {e}")))
}
/// Get root certificate of CA
pub async fn get_root_cert(&self) -> Result<String, MegaError> {
let resp_ca_pem = self.read_api("pki/ca/tls/pem").await?.ok_or_else(|| {
MegaError::Other("PKI root certificate response is empty".to_string())
})?;
let ca_data = resp_ca_pem.data.ok_or_else(|| {
MegaError::Other("PKI root certificate response is missing data".to_string())
})?;
ca_data
.get("certificate")
.and_then(|value| value.as_str())
.map(str::to_owned)
.ok_or_else(|| {
MegaError::Other("PKI root certificate response is missing certificate".to_string())
})
}
}
#[allow(clippy::await_holding_lock)]
#[cfg(test)]
mod tests_raw {
use std::{
fs,
io::Write,
time::{SystemTime, UNIX_EPOCH},
};
use libvault::logical::Response;
use openssl::{asn1::Asn1Time, ec::EcKey, nid::Nid, pkey::PKey, rsa::Rsa, x509::X509};
use serde_json::{Map, Value, json};
use crate::{
common::errors::VaultResult, contract::vault::integration::vault_core::VaultCore,
jupiter::tests::test_storage,
};
async fn test_read_api(
core: &VaultCore,
path: &str,
is_ok: bool,
) -> VaultResult<Option<Response>> {
let resp = core.read_api(path).await;
assert_eq!(resp.is_ok(), is_ok);
resp
}
async fn test_write_api(
core: &VaultCore,
path: &str,
is_ok: bool,
data: Option<Map<String, Value>>,
) -> VaultResult<Option<Response>> {
let resp = core.write_api(path, data).await;
assert_eq!(resp.is_ok(), is_ok, "{path}: {resp:?}");
resp
}
async fn test_pki_config_ca(core: &VaultCore) {
let mount_data = json!({
"type": "pki",
})
.as_object()
.unwrap()
.clone();
let resp = test_write_api(core, "sys/mounts/pki/", true, Some(mount_data)).await;
assert!(resp.is_ok());
}
async fn test_pki_config_role(core: &VaultCore) {
let role_data = json!({
"ttl": "60d",
"max_ttl": "365d",
"key_type": "rsa",
"key_bits": 4096,
"country": "CN",
"province": "Beijing",
"locality": "Beijing",
"organization": "OpenAtom",
"no_store": false,
})
.as_object()
.unwrap()
.clone();
// config role
assert!(
test_write_api(core, "pki/roles/tls/test", true, Some(role_data))
.await
.is_ok()
);
let resp = test_read_api(core, "pki/roles/tls/test", true).await;
assert!(resp.as_ref().unwrap().is_some());
let resp = resp.unwrap();
assert!(resp.is_some());
let data = resp.unwrap().data;
assert!(data.is_some());
let role_data = data.unwrap();
println!("role_data: {role_data:?}");
assert_eq!(role_data["ttl"].as_u64().unwrap(), 60 * 24 * 60 * 60);
assert_eq!(role_data["max_ttl"].as_u64().unwrap(), 365 * 24 * 60 * 60);
assert_eq!(role_data["not_before_duration"].as_u64().unwrap(), 30);
assert_eq!(role_data["key_type"].as_str().unwrap(), "rsa");
assert_eq!(role_data["key_bits"].as_u64().unwrap(), 4096);
assert_eq!(role_data["country"].as_str().unwrap(), "CN");
assert_eq!(role_data["province"].as_str().unwrap(), "Beijing");
assert_eq!(role_data["locality"].as_str().unwrap(), "Beijing");
assert_eq!(role_data["organization"].as_str().unwrap(), "OpenAtom");
assert!(!role_data["no_store"].as_bool().unwrap());
}
async fn test_pki_generate_root(core: &VaultCore, exported: bool, is_ok: bool) {
let key_type = "rsa";
let key_bits = 4096;
let common_name = "test-ca";
let req_data = json!({
"common_name": common_name,
"ttl": "365d",
"country": "cn",
"key_type": key_type,
"key_bits": key_bits,
})
.as_object()
.unwrap()
.clone();
// println!("generate root req_data: {:?}, is_ok: {}", req_data, is_ok);
let resp = test_write_api(
core,
format!(
"pki/root/tls/generate/{}",
if exported { "exported" } else { "internal" }
)
.as_str(),
is_ok,
Some(req_data),
)
.await;
if !is_ok {
return;
}
let resp_body = resp.unwrap();
assert!(resp_body.is_some());
let data = resp_body.unwrap().data;
assert!(data.is_some());
let key_data = data.unwrap();
let resp_ca_pem = test_read_api(core, "pki/ca/tls/pem", true).await;
let resp_ca_pem_cert_data = resp_ca_pem.unwrap().unwrap().data.unwrap();
let ca_cert = X509::from_pem(
resp_ca_pem_cert_data["certificate"]
.as_str()
.unwrap()
.as_bytes(),
)
.unwrap();
let subject = ca_cert.subject_name();
let cn = subject.entries_by_nid(Nid::COMMONNAME).next().unwrap();
assert_eq!(cn.data().as_slice(), common_name.as_bytes());
let not_after = Asn1Time::days_from_now(365).unwrap();
let ttl_diff = ca_cert.not_after().diff(¬_after);
assert!(ttl_diff.is_ok());
let ttl_diff = ttl_diff.unwrap();
assert_eq!(ttl_diff.days, 0);
if exported {
assert!(key_data["private_key_type"].as_str().is_some());
assert_eq!(key_data["private_key_type"].as_str().unwrap(), key_type);
assert!(key_data["private_key"].as_str().is_some());
let private_key_pem = key_data["private_key"].as_str().unwrap();
match key_type {
"rsa" => {
let rsa_key = Rsa::private_key_from_pem(private_key_pem.as_bytes());
assert!(rsa_key.is_ok());
assert_eq!(rsa_key.unwrap().size() * 8, key_bits);
}
"ec" => {
let ec_key = EcKey::private_key_from_pem(private_key_pem.as_bytes());
assert!(ec_key.is_ok());
assert_eq!(ec_key.unwrap().group().degree(), key_bits);
}
_ => {}
}
} else {
assert!(key_data.get("private_key").is_none());
}
}
async fn test_pki_issue_cert_by_generate_root(core: &VaultCore) {
let dns_sans = ["test.com", "a.test.com", "b.test.com"];
let issue_data = json!({
"ttl": "10d",
"common_name": "test.com",
"alt_names": "a.test.com,b.test.com",
})
.as_object()
.unwrap()
.clone();
let issuance_started = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
// issue cert
let resp = test_write_api(core, "pki/issue/tls/test", true, Some(issue_data)).await;
let issuance_completed = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
assert!(resp.is_ok());
let resp_body = resp.unwrap();
assert!(resp_body.is_some());
let data = resp_body.unwrap().data;
assert!(data.is_some());
let cert_data = data.unwrap();
println!("issue cert result: {:?}", cert_data["certificate"]);
let mut file = fs::File::create("/tmp/cert.crt").unwrap();
file.write_all(cert_data["certificate"].as_str().unwrap().as_ref())
.unwrap();
let cert = X509::from_pem(cert_data["certificate"].as_str().unwrap().as_bytes()).unwrap();
let alt_names = cert.subject_alt_names();
assert!(alt_names.is_some());
let alt_names = alt_names.unwrap();
assert_eq!(alt_names.len(), dns_sans.len());
for alt_name in alt_names {
assert!(dns_sans.contains(&alt_name.dnsname().unwrap()));
}
assert_eq!(cert_data["private_key_type"].as_str().unwrap(), "rsa");
let priv_key =
PKey::private_key_from_pem(cert_data["private_key"].as_str().unwrap().as_bytes())
.unwrap();
assert_eq!(priv_key.bits(), 4096);
assert!(priv_key.public_eq(&cert.public_key().unwrap()));
let serial_number = cert.serial_number().to_bn().unwrap();
let serial_number_hex = serial_number.to_hex_str().unwrap();
assert_eq!(
cert_data["serial_number"]
.as_str()
.unwrap()
.replace(':', "")
.to_lowercase()
.as_str(),
serial_number_hex.to_lowercase().as_str()
);
let expiration_time =
Asn1Time::from_unix(cert_data["expiration"].as_i64().unwrap()).unwrap();
let ttl_compare = cert.not_after().compare(&expiration_time);
assert!(ttl_compare.is_ok());
assert_eq!(ttl_compare.unwrap(), std::cmp::Ordering::Equal);
let expiration_ttl = cert_data["expiration"].as_u64().unwrap();
let expect_ttl = 10 * 24 * 60 * 60;
assert!(expiration_ttl >= issuance_started + expect_ttl);
assert!(expiration_ttl <= issuance_completed + expect_ttl);
let authority_key_id = cert.authority_key_id();
assert!(authority_key_id.is_some());
println!(
"authority_key_id: {}",
hex::encode(authority_key_id.unwrap().as_slice())
);
let resp_ca_pem = test_read_api(core, "pki/ca/tls/pem", true).await;
let resp_ca_pem_cert_data = resp_ca_pem.unwrap().unwrap().data.unwrap();
let ca_cert = X509::from_pem(
resp_ca_pem_cert_data["certificate"]
.as_str()
.unwrap()
.as_bytes(),
)
.unwrap();
let subject = ca_cert.subject_name();
let cn = subject.entries_by_nid(Nid::COMMONNAME).next().unwrap();
assert_eq!(cn.data().as_slice(), "test-ca".as_bytes());
println!(
"ca subject_key_id: {}",
hex::encode(ca_cert.subject_key_id().unwrap().as_slice())
);
assert_eq!(
ca_cert.subject_key_id().unwrap().as_slice(),
authority_key_id.unwrap().as_slice()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_pki_module() {
let temp_dir = tempfile::tempdir().expect("Failed to create temporary directory");
let key_path = temp_dir.path().join("key.json");
let storage = test_storage(temp_dir.path()).await;
let vault_core = VaultCore::config(storage.vault_storage(), key_path)
.await
.expect("vault core should initialize");
{
println!("Initializing Vault CA...");
test_pki_config_ca(&vault_core).await;
println!("Vault CA initialized.");
test_pki_generate_root(&vault_core, false, true).await;
println!("Root CA generated.");
test_pki_config_role(&vault_core).await;
println!("Role configured.");
test_pki_issue_cert_by_generate_root(&vault_core).await;
println!("Certificate issued.");
}
}
}