use std::collections::HashMap;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use rtci::peer_connection::certificate::CertificateParams;
use rtci::peer_connection::certificate::RTCCertificate;
use crate::args::CertificateInfo;
use crate::args::FingerprintInfo;
use crate::args::KeygenArg;
use crate::error::Error;
use crate::error::ErrorKind;
fn op_err(e: impl std::fmt::Display) -> Error {
Error::new(ErrorKind::Operation, e.to_string())
}
#[derive(Default)]
pub struct CertificateStore {
next: u32,
certs: HashMap<u32, RTCCertificate>,
}
impl CertificateStore {
pub fn get(&self, id: u32) -> Result<RTCCertificate, Error> {
self.certs.get(&id).cloned().ok_or_else(|| {
Error::new(ErrorKind::InvalidAccess, "Unknown RTCCertificate")
})
}
pub fn remove(&mut self, id: u32) {
self.certs.remove(&id);
}
pub fn insert(
&mut self,
cert: RTCCertificate,
) -> Result<CertificateInfo, Error> {
let fingerprints = certificate_fingerprints(&cert)?;
let expires = expires_ms(&cert);
self.next += 1;
let id = self.next;
self.certs.insert(id, cert);
Ok(CertificateInfo {
id,
expires,
fingerprints,
})
}
}
pub fn certificate_fingerprints(
cert: &RTCCertificate,
) -> Result<Vec<FingerprintInfo>, Error> {
let provider = rtci::crypto::default_provider().map_err(op_err)?;
Ok(
cert
.get_fingerprints(provider.crypto())
.map_err(op_err)?
.into_iter()
.map(|f| FingerprintInfo {
algorithm: f.algorithm,
value: f.value,
})
.collect(),
)
}
pub fn expires_ms(cert: &RTCCertificate) -> f64 {
cert
.expires
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as f64)
.unwrap_or(0.0)
}
pub fn generate_certificate(
alg: &KeygenArg,
expires_at_ms: f64,
) -> Result<RTCCertificate, Error> {
use rtci::crypto::SignatureScheme;
let provider = rtci::crypto::default_provider().map_err(op_err)?;
let not_supported = |m: String| Error::new(ErrorKind::NotSupported, m);
let name = alg.name.to_ascii_uppercase();
let (scheme, signing_key) = match name.as_str() {
"ECDSA" => {
if alg.named_curve.as_deref() != Some("P-256") {
return Err(not_supported(format!(
"ECDSA curve {:?} is not supported (P-256 is)",
alg.named_curve.as_deref().unwrap_or("")
)));
}
let key = provider
.crypto()
.generate_signing_key(SignatureScheme::EcdsaP256Sha256)
.map_err(op_err)?;
(SignatureScheme::EcdsaP256Sha256, key)
}
"RSASSA-PKCS1-V1_5" => {
let hash = alg
.hash
.as_deref()
.unwrap_or("SHA-256")
.to_ascii_uppercase();
if hash != "SHA-256" {
return Err(not_supported(format!(
"RSASSA-PKCS1-v1_5 with {hash} is not supported (SHA-256 is)"
)));
}
let exponent = alg.public_exponent.as_deref().unwrap_or(&[1, 0, 1]);
let trimmed: Vec<u8> =
exponent.iter().copied().skip_while(|b| *b == 0).collect();
if trimmed != [1, 0, 1] {
return Err(not_supported(
"Only the RSA public exponent 65537 is supported".to_string(),
));
}
let size = match alg.modulus_length.unwrap_or(2048) {
2048 => aws_lc_rs::rsa::KeySize::Rsa2048,
3072 => aws_lc_rs::rsa::KeySize::Rsa3072,
4096 => aws_lc_rs::rsa::KeySize::Rsa4096,
other => {
return Err(not_supported(format!(
"An RSA modulus of {other} bits is not supported (2048, 3072 or 4096 are)"
)));
}
};
let pair = aws_lc_rs::rsa::KeyPair::generate(size).map_err(op_err)?;
let der = aws_lc_rs::encoding::AsDer::<
aws_lc_rs::encoding::Pkcs8V1Der<'static>,
>::as_der(&pair)
.map_err(op_err)?;
let key = provider
.crypto()
.import_signing_key(SignatureScheme::RsaPkcs1Sha256, der.as_ref())
.map_err(op_err)?;
(SignatureScheme::RsaPkcs1Sha256, key)
}
_ => {
return Err(not_supported(format!(
"'{}' is not a supported certificate algorithm",
alg.name
)));
}
};
let params =
CertificateParams::new(vec!["WebRTC".to_owned()]).map_err(op_err)?;
let mut cert =
RTCCertificate::generate_from_signing_key(params, scheme, signing_key)
.map_err(op_err)?;
let max_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as f64)
.unwrap_or(0.0)
+ 365.0 * 24.0 * 3600.0 * 1000.0;
let expires_at_ms = expires_at_ms.clamp(0.0, max_ms);
cert.expires = UNIX_EPOCH + Duration::from_millis(expires_at_ms as u64);
Ok(cert)
}
pub fn certificate_to_pem(cert: &RTCCertificate) -> Result<String, Error> {
cert.serialize_pem().map_err(op_err)
}
pub fn certificate_from_pem(pem: &str) -> Result<RTCCertificate, Error> {
let provider = rtci::crypto::default_provider().map_err(op_err)?;
RTCCertificate::from_pem(pem, provider.crypto()).map_err(|e| {
Error::new(
ErrorKind::Syntax,
format!("Not an exported RTCCertificate: {e}"),
)
})
}