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
use crate::{
CertEncodeError, CertExt, Ed25519Cert, Ed25519CertConstructor, ExtType, SignedWithEd25519Ext,
UnrecognizedExt,
};
use std::time::{Duration, SystemTime};
use tor_bytes::{EncodeResult, Writeable, Writer};
use tor_llcrypto::pk::ed25519;
impl Ed25519Cert {
pub fn constructor() -> Ed25519CertConstructor {
Default::default()
}
}
impl Writeable for CertExt {
fn write_onto<B: Writer + ?Sized>(&self, w: &mut B) -> EncodeResult<()> {
match self {
CertExt::SignedWithEd25519(pk) => pk.write_onto(w),
CertExt::Unrecognized(u) => u.write_onto(w),
}
}
}
impl Writeable for SignedWithEd25519Ext {
fn write_onto<B: Writer + ?Sized>(&self, w: &mut B) -> EncodeResult<()> {
w.write_u16(32);
w.write_u8(ExtType::SIGNED_WITH_ED25519_KEY.into());
w.write_u8(0);
w.write_all(self.pk.as_bytes());
Ok(())
}
}
impl Writeable for UnrecognizedExt {
fn write_onto<B: Writer + ?Sized>(&self, w: &mut B) -> EncodeResult<()> {
w.write_u16(
self.body
.len()
.try_into()
.map_err(|_| tor_bytes::EncodeError::BadLengthValue)?,
);
w.write_u8(self.ext_type.into());
let flags = u8::from(self.affects_validation);
w.write_u8(flags);
w.write_all(&self.body[..]);
Ok(())
}
}
impl Ed25519CertConstructor {
pub fn expiration(&mut self, expiration: SystemTime) -> &mut Self {
const SEC_PER_HOUR: u64 = 3600;
let duration = expiration
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or(Duration::from_secs(0));
let exp_hours = duration.as_secs().saturating_add(SEC_PER_HOUR - 1) / SEC_PER_HOUR;
self.exp_hours = Some(exp_hours.try_into().unwrap_or(u32::MAX));
self
}
pub fn signing_key(&mut self, key: ed25519::Ed25519Identity) -> &mut Self {
self.clear_signing_key();
self.signed_with = Some(Some(key));
self.extensions
.get_or_insert_with(Vec::new)
.push(CertExt::SignedWithEd25519(SignedWithEd25519Ext { pk: key }));
self
}
pub fn clear_signing_key(&mut self) -> &mut Self {
self.signed_with = None;
self.extensions
.get_or_insert_with(Vec::new)
.retain(|ext| !matches!(ext, CertExt::SignedWithEd25519(_)));
self
}
pub fn encode_and_sign(&self, skey: &ed25519::Keypair) -> Result<Vec<u8>, CertEncodeError> {
use ed25519::Signer;
let Ed25519CertConstructor {
exp_hours,
cert_type,
cert_key,
extensions,
signed_with,
} = self;
if let Some(Some(signer)) = &signed_with {
if *signer != skey.public.into() {
return Err(CertEncodeError::KeyMismatch);
}
}
let mut w = Vec::new();
w.write_u8(1); w.write_u8(
cert_type
.ok_or(CertEncodeError::MissingField("cert_type"))?
.into(),
);
w.write_u32(exp_hours.ok_or(CertEncodeError::MissingField("expiration"))?);
let cert_key = cert_key
.clone()
.ok_or(CertEncodeError::MissingField("cert_key"))?;
w.write_u8(cert_key.key_type().into());
w.write_all(cert_key.as_bytes());
let extensions = extensions.as_ref().map(Vec::as_slice).unwrap_or(&[]);
w.write_u8(
extensions
.len()
.try_into()
.map_err(|_| CertEncodeError::TooManyExtensions)?,
);
for e in extensions.iter() {
e.write_onto(&mut w)?;
}
let signature = skey.sign(&w[..]);
w.write(&signature)?;
Ok(w)
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_duration_subtraction)]
use super::*;
use crate::CertifiedKey;
use tor_checkable::{SelfSigned, Timebound};
use tor_llcrypto::util::rand_compat::RngCompatExt;
#[test]
fn signed_cert_without_key() {
let mut rng = rand::thread_rng().rng_compat();
let keypair = ed25519::Keypair::generate(&mut rng);
let now = SystemTime::now();
let day = Duration::from_secs(86400);
let encoded = Ed25519Cert::constructor()
.expiration(now + day * 30)
.cert_key(CertifiedKey::Ed25519(keypair.public.into()))
.cert_type(7.into())
.encode_and_sign(&keypair)
.unwrap();
let decoded = Ed25519Cert::decode(&encoded).unwrap(); let validated = decoded
.check_key(Some(&keypair.public.into()))
.unwrap()
.check_signature()
.unwrap(); let cert = validated.check_valid_at(&(now + day * 20)).unwrap();
assert_eq!(cert.cert_type(), 7.into());
if let CertifiedKey::Ed25519(found) = cert.subject_key() {
assert_eq!(found, &keypair.public.into());
} else {
panic!("wrong key type");
}
assert!(cert.signing_key() == Some(&keypair.public.into()));
}
}