1use crate::{
6 CertEncodeError, CertExt, Ed25519Cert, Ed25519CertConstructor, ExtType, SignedWithEd25519Ext,
7 UnrecognizedExt,
8};
9use std::time::{Duration, SystemTime};
10use tor_bytes::{EncodeResult, Writeable, Writer};
11use tor_llcrypto::pk::ed25519::{self, Ed25519PublicKey, Ed25519SigningKey};
12
13use derive_more::{AsRef, Deref, Into};
14
15#[derive(Clone, Debug, PartialEq, Into, AsRef, Deref)]
23#[cfg_attr(docsrs, doc(cfg(feature = "encode")))]
24pub struct EncodedEd25519Cert(Vec<u8>);
25
26impl Ed25519Cert {
27 pub fn constructor() -> Ed25519CertConstructor {
30 Default::default()
31 }
32}
33
34impl EncodedEd25519Cert {
35 #[cfg(feature = "experimental-api")]
46 pub fn dangerously_from_bytes(cert: &[u8]) -> Self {
47 Self(cert.into())
48 }
49}
50
51impl Writeable for CertExt {
52 fn write_onto<B: Writer + ?Sized>(&self, w: &mut B) -> EncodeResult<()> {
56 match self {
57 CertExt::SignedWithEd25519(pk) => pk.write_onto(w),
58 CertExt::Unrecognized(u) => u.write_onto(w),
59 }
60 }
61}
62
63impl Writeable for SignedWithEd25519Ext {
64 fn write_onto<B: Writer + ?Sized>(&self, w: &mut B) -> EncodeResult<()> {
66 w.write_u16(32);
68 w.write_u8(ExtType::SIGNED_WITH_ED25519_KEY.into());
70 w.write_u8(0);
72 w.write_all(self.pk.as_bytes());
74 Ok(())
75 }
76}
77
78impl Writeable for UnrecognizedExt {
79 fn write_onto<B: Writer + ?Sized>(&self, w: &mut B) -> EncodeResult<()> {
81 w.write_u16(
84 self.body
85 .len()
86 .try_into()
87 .map_err(|_| tor_bytes::EncodeError::BadLengthValue)?,
88 );
89 w.write_u8(self.ext_type.into());
90 let flags = u8::from(self.affects_validation);
91 w.write_u8(flags);
92 w.write_all(&self.body[..]);
93 Ok(())
94 }
95}
96
97impl Ed25519CertConstructor {
98 pub fn expiration(&mut self, expiration: SystemTime) -> &mut Self {
102 const SEC_PER_HOUR: u64 = 3600;
104 let duration = expiration
105 .duration_since(SystemTime::UNIX_EPOCH)
106 .unwrap_or(Duration::from_secs(0));
107 let exp_hours = duration.as_secs().saturating_add(SEC_PER_HOUR - 1) / SEC_PER_HOUR;
108 self.exp_hours = Some(exp_hours.try_into().unwrap_or(u32::MAX));
109 self
110 }
111
112 pub fn signing_key(&mut self, key: ed25519::Ed25519Identity) -> &mut Self {
118 self.clear_signing_key();
119 self.signed_with = Some(Some(key));
120 self.extensions
121 .get_or_insert_with(Vec::new)
122 .push(CertExt::SignedWithEd25519(SignedWithEd25519Ext { pk: key }));
123
124 self
125 }
126
127 pub fn clear_signing_key(&mut self) -> &mut Self {
129 self.signed_with = None;
130 self.extensions
131 .get_or_insert_with(Vec::new)
132 .retain(|ext| !matches!(ext, CertExt::SignedWithEd25519(_)));
133 self
134 }
135
136 pub fn encode_and_sign<S>(&self, skey: &S) -> Result<EncodedEd25519Cert, CertEncodeError>
143 where
144 S: Ed25519PublicKey + Ed25519SigningKey,
145 {
146 let Ed25519CertConstructor {
147 exp_hours,
148 cert_type,
149 cert_key,
150 extensions,
151 signed_with,
152 } = self;
153
154 if let Some(Some(signer)) = &signed_with {
156 if *signer != skey.public_key().into() {
157 return Err(CertEncodeError::KeyMismatch);
158 }
159 }
160
161 let mut w = Vec::new();
162 w.write_u8(1); w.write_u8(
164 cert_type
165 .ok_or(CertEncodeError::MissingField("cert_type"))?
166 .into(),
167 );
168 w.write_u32(exp_hours.ok_or(CertEncodeError::MissingField("expiration"))?);
169 let cert_key = cert_key
170 .clone()
171 .ok_or(CertEncodeError::MissingField("cert_key"))?;
172 w.write_u8(cert_key.key_type().into());
173 w.write_all(cert_key.as_bytes());
174 let extensions = extensions.as_ref().map(Vec::as_slice).unwrap_or(&[]);
175 w.write_u8(
176 extensions
177 .len()
178 .try_into()
179 .map_err(|_| CertEncodeError::TooManyExtensions)?,
180 );
181
182 for e in extensions.iter() {
183 e.write_onto(&mut w)?;
184 }
185
186 let signature = skey.sign(&w[..]);
187 w.write(&signature)?;
188 Ok(EncodedEd25519Cert(w))
189 }
190}
191
192#[cfg(test)]
193#[allow(clippy::unwrap_used)]
194mod test {
195 #![allow(clippy::bool_assert_comparison)]
197 #![allow(clippy::clone_on_copy)]
198 #![allow(clippy::dbg_macro)]
199 #![allow(clippy::mixed_attributes_style)]
200 #![allow(clippy::print_stderr)]
201 #![allow(clippy::print_stdout)]
202 #![allow(clippy::single_char_pattern)]
203 #![allow(clippy::unwrap_used)]
204 #![allow(clippy::unchecked_duration_subtraction)]
205 #![allow(clippy::useless_vec)]
206 #![allow(clippy::needless_pass_by_value)]
207 use super::*;
209 use crate::CertifiedKey;
210 use tor_checkable::{SelfSigned, Timebound};
211
212 #[test]
213 fn signed_cert_without_key() {
214 let mut rng = rand::rng();
215 let keypair = ed25519::Keypair::generate(&mut rng);
216 let now = SystemTime::now();
217 let day = Duration::from_secs(86400);
218 let encoded = Ed25519Cert::constructor()
219 .expiration(now + day * 30)
220 .cert_key(CertifiedKey::Ed25519(keypair.verifying_key().into()))
221 .cert_type(7.into())
222 .encode_and_sign(&keypair)
223 .unwrap();
224
225 let decoded = Ed25519Cert::decode(&encoded).unwrap(); let validated = decoded
227 .should_be_signed_with(&keypair.verifying_key().into())
228 .unwrap()
229 .check_signature()
230 .unwrap(); let cert = validated.check_valid_at(&(now + day * 20)).unwrap();
232 assert_eq!(cert.cert_type(), 7.into());
233 if let CertifiedKey::Ed25519(found) = cert.subject_key() {
234 assert_eq!(found, &keypair.verifying_key().into());
235 } else {
236 panic!("wrong key type");
237 }
238 assert!(cert.signing_key() == Some(&keypair.verifying_key().into()));
239 }
240
241 #[test]
242 fn unrecognized_ext() {
243 use hex_literal::hex;
244 use tor_bytes::Reader;
245
246 let mut reader = Reader::from_slice(&hex!("0001 2A 00 2A"));
247 let ext: CertExt = reader.extract().unwrap();
248
249 let mut encoded: Vec<u8> = Vec::new();
250 encoded.write(&ext).unwrap();
251
252 assert_eq!(encoded, hex!("0001 2A 00 2A"));
253 }
254}