1use base64::Engine as _;
5use rsa::BigUint;
6use rand::rngs::OsRng;
7use rcgen::{CertificateParams, DnType, IsCa, KeyPair as RcKeyPair, KeyUsagePurpose, ExtendedKeyUsagePurpose};
8use rsa::pkcs1::DecodeRsaPrivateKey;
9use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey};
10use rsa::traits::PublicKeyParts;
11use rsa::RsaPrivateKey;
12use sha2::{Digest, Sha256};
13use time::{Duration, OffsetDateTime};
14use x509_parser::certificate::X509Certificate;
15use x509_parser::prelude::FromDer;
16use x509_parser::public_key::PublicKey;
17
18use crate::clock::format_valid_to;
19use crate::error::{err, SamlError};
20
21pub struct KeyMaterial {
23 pub private_key_pem: String,
24 pub certificate_pem: String,
25 pub private_key: RsaPrivateKey,
26 pub certificate_der: Vec<u8>,
27}
28
29impl KeyMaterial {
30 pub fn fingerprint256(&self) -> String {
31 let sum = Sha256::digest(&self.certificate_der);
32 sum.iter().map(|b| format!("{b:02X}")).collect::<Vec<_>>().join(":")
33 }
34
35 pub fn valid_to(&self) -> String {
36 let Ok((_, cert)) = X509Certificate::from_der(&self.certificate_der) else {
37 return String::new();
38 };
39 format_valid_to(cert.validity().not_after.to_datetime())
40 }
41
42 pub fn public_key(&self) -> rsa::RsaPublicKey {
43 rsa::RsaPublicKey::from(&self.private_key)
44 }
45}
46
47pub fn create_self_signed_key_pair(common_name: &str, days: i64, bits: usize) -> Result<KeyMaterial, SamlError> {
49 let days = if days <= 0 { 1095 } else { days };
50 let bits = if bits == 0 { 3072 } else { bits };
51 let private_key = RsaPrivateKey::new(&mut OsRng, bits).map_err(|e| err("config", format!("the key could not be generated: {e}")))?;
52 let pkcs8 = private_key.to_pkcs8_der().map_err(|e| err("config", format!("the key could not be encoded: {e}")))?;
53 let rc_key = RcKeyPair::try_from(pkcs8.as_bytes()).map_err(|e| err("config", format!("the key could not be read for the certificate: {e}")))?;
54 let not_before = OffsetDateTime::now_utc() - Duration::seconds(60);
55 let not_after = not_before + Duration::days(days);
56 let mut params = CertificateParams::default();
57 params.not_before = not_before;
58 params.not_after = not_after;
59 params.distinguished_name = rcgen::DistinguishedName::new();
60 params.distinguished_name.push(DnType::CommonName, common_name);
61 params.is_ca = IsCa::NoCa;
62 params.key_usages = vec![KeyUsagePurpose::DigitalSignature, KeyUsagePurpose::KeyEncipherment];
63 params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth, ExtendedKeyUsagePurpose::ClientAuth];
64 let cert = params.self_signed(&rc_key).map_err(|e| err("config", format!("the certificate could not be signed: {e}")))?;
65 let der = cert.der().to_vec();
66 let certificate_pem = cert.pem();
67 let private_key_pem = private_key.to_pkcs8_pem(rsa::pkcs8::LineEnding::LF)
68 .map_err(|e| err("config", format!("the key could not be encoded: {e}")))?
69 .to_string();
70 Ok(KeyMaterial { private_key_pem, certificate_pem, private_key, certificate_der: der })
71}
72
73pub(crate) fn load_private_key(pem_text: &str) -> Result<RsaPrivateKey, SamlError> {
74 if let Ok(key) = RsaPrivateKey::from_pkcs8_pem(pem_text) {
75 return Ok(key);
76 }
77 if let Ok(key) = RsaPrivateKey::from_pkcs1_pem(pem_text) {
78 return Ok(key);
79 }
80 let kind = if pem_text.contains("EC PRIVATE KEY") {
81 "ec"
82 } else if pem_text.contains("OPENSSH") {
83 "openssh"
84 } else {
85 "unrecognized"
86 };
87 if pem_text.contains("BEGIN") && kind != "unrecognized" {
88 return Err(err("config", format!("the private key is {kind}; an RSA key is required")));
89 }
90 Err(err("config", format!("the private key or certificate cannot be read: unrecognized private key")))
91}
92
93pub(crate) fn load_certificate_der(pem_text: &str) -> Result<Vec<u8>, SamlError> {
94 pem_der(pem_text).map_err(|e| err("config", format!("the private key or certificate cannot be read: {e}")))
95}
96
97pub(crate) fn pem_der(pem_text: &str) -> Result<Vec<u8>, String> {
98 let mut body = String::new();
99 for line in pem_text.lines() {
100 let line = line.trim();
101 if line.is_empty() || line.starts_with("-----") {
102 continue;
103 }
104 body.push_str(line);
105 }
106 if body.is_empty() {
107 return Err("no PEM block".to_string());
108 }
109 base64::engine::general_purpose::STANDARD.decode(body).map_err(|e| e.to_string())
110}
111
112pub(crate) fn private_pem(key: &RsaPrivateKey) -> String {
113 key.to_pkcs8_pem(rsa::pkcs8::LineEnding::LF).map(|pem| pem.to_string()).unwrap_or_default()
114}
115
116pub(crate) fn certificate_pem(der: &[u8]) -> String {
117 let b64 = base64::engine::general_purpose::STANDARD.encode(der);
118 let mut lines = String::from("-----BEGIN CERTIFICATE-----\n");
119 for chunk in b64.as_bytes().chunks(64) {
120 lines.push_str(std::str::from_utf8(chunk).unwrap_or(""));
121 lines.push('\n');
122 }
123 lines.push_str("-----END CERTIFICATE-----\n");
124 lines
125}
126
127pub(crate) fn pem_body(pem_text: &str) -> String {
128 let mut body = String::new();
129 for line in pem_text.replace('\r', "\n").lines() {
130 let line = line.trim();
131 if line.is_empty() || line.starts_with("-----") {
132 continue;
133 }
134 body.push_str(line);
135 }
136 body
137}
138
139pub(crate) fn public_from_cert(der: &[u8]) -> Result<rsa::RsaPublicKey, SamlError> {
140 let (_, cert) = X509Certificate::from_der(der).map_err(|e| err("metadata", format!("a certificate cannot be read: {e}")))?;
141 let parsed = cert.public_key().parsed().map_err(|e| err("metadata", format!("a certificate cannot be read: {e}")))?;
142 match parsed {
143 PublicKey::RSA(key) => {
144 let n = BigUint::from_bytes_be(key.modulus);
145 let e = BigUint::from_bytes_be(key.exponent);
146 rsa::RsaPublicKey::new(n, e).map_err(|e| err("metadata", format!("a certificate cannot be read: {e}")))
147 }
148 _ => Err(err("metadata", "a certificate is not an RSA key")),
149 }
150}
151
152pub(crate) fn same_public(key: &RsaPrivateKey, der: &[u8]) -> bool {
153 let Ok(public) = public_from_cert(der) else { return false };
154 key.n() == public.n() && key.e() == public.e()
155}
156
157pub(crate) fn b64_standard(bytes: &[u8]) -> String {
158 base64::engine::general_purpose::STANDARD.encode(bytes)
159}
160
161pub(crate) fn b64_decode(value: &str) -> Result<Vec<u8>, base64::DecodeError> {
162 let compact: String = value.split_whitespace().collect();
163 base64::engine::general_purpose::STANDARD.decode(compact)
164}