Debian Codegraph @

src/trust/pgp.rs

raw
1 use std::{
2 collections::BTreeSet,
3 time::SystemTime,
4 sync::Arc,
5 };
6
7 use anyhow::Result;
8
9 use sequoia_openpgp as openpgp;
10 use openpgp::{
11 Fingerprint,
12 packet::UserID,
13 policy::Policy,
14 };
15 use sequoia_wot as wot;
16 use wot::store::{Backend, Store};
17
18 use sequoia_cert_store as cert_store;
19 use cert_store::LazyCert;
20
21 use crate::{
22 Config,
23 common::OwnerTrustLevel,
24 keydb::KeyDB,
25 trust::{
26 Query,
27 TrustModel,
28 Validity,
29 ValidityLevel,
30 },
31 };
32
33 pub use crate::common::Model;
34 pub use crate::common::ModelViewAt;
35
36 trace_module!(TRACE);
37
38 /// A flexible Web-of-Trust implementation.
39 ///
40 /// We support both Sequoia-style and the GnuPG-style Web-of-Trust
41 /// computations.
42 #[derive(Debug, Clone)]
43 pub struct WoT {
44 gnupg_roots: bool,
45 sequoia_roots: bool,
46 marginals_needed: u8,
47 completes_needed: u8,
48 }
49
50 impl WoT {
51 /// Configures the Web-of-Trust implementation.
52 ///
53 /// By default, only ultimately-trusted trust roots are used.
54 pub fn new() -> Self {
55 WoT {
56 gnupg_roots: false,
57 sequoia_roots: false,
58 marginals_needed: 0,
59 completes_needed: 0,
60 }
61 }
62
63 /// Enables Sequoia's trust roots.
64 ///
65 /// Currently, this is the `trust-root` in the cert-d.
66 pub fn with_sequoia_roots(mut self) -> Self {
67 self.sequoia_roots = true;
68 self
69 }
70
71 /// Enables GnuPG's non-ultimately trusted roots.
72 ///
73 /// For GnuPG to consider a non-ultimately trusted root as valid,
74 /// there must be a path from an ultimately trusted root to the
75 /// non-ultimately trusted root. If this is the case, add those
76 /// roots.
77 pub fn with_gnupg_roots(mut self,
78 marginals_needed: u8,
79 completes_needed: u8)
80 -> Self {
81 self.gnupg_roots = true;
82 self.marginals_needed = marginals_needed;
83 self.completes_needed = completes_needed;
84 self
85 }
86
87 /// Returns the trust model.
88 pub fn build(self) -> Result<Box<dyn Model>> {
89 Ok(Box::new(self))
90 }
91 }
92
93 impl Model for WoT {
94 fn with_policy_and_precompute<'a, 'store>(
95 &self, config: &'a Config<'store>,
96 at: Option<SystemTime>,
97 precompute: bool)
98 -> Result<Box<dyn ModelViewAt<'a, 'store> + 'a>>
99 where 'store: 'a
100 {
101 tracer!(TRACE, "WoT::with_policy_and_precompute");
102 use wot::Root;
103
104 let at = at.unwrap_or_else(SystemTime::now);
105
106 // Start with the roots from the trust database.
107 let mut trust_roots = Vec::<Root>::new();
108
109 // Now we add any roots from the configuration and command line.
110 config.trusted_keys.iter()
111 .for_each(|f| trust_roots.push(Root::new(f.clone(), wot::FULLY_TRUSTED)));
112 let mut ultimate_roots: BTreeSet<Fingerprint> =
113 config.trusted_keys.iter().cloned().collect();
114
115 if self.sequoia_roots {
116 // And the local trust root, if any.
117 if let Ok(overlay) = config.keydb.certd_overlay() {
118 if let Ok(trust_root) = overlay.trust_root() {
119 trust_roots.push(Root::new(trust_root.fingerprint(), wot::FULLY_TRUSTED));
120 }
121 }
122 }
123
124 let store = wot::store::CertStore::from_store(
125 &config.keydb, &config.policy, at);
126 if precompute {
127 store.precompute();
128 }
129 let roots = wot::Roots::new(trust_roots.clone());
130 let mut n = wot::Network::new(store, roots)?;
131
132 if self.gnupg_roots {
133 let mut possible_roots: Vec<Root> = Vec::new();
134
135 for (f, ownertrust) in config.trustdb.ownertrust().iter()
136 .map(|(f, ot)| (f, ot.level()))
137 {
138 /// Returns `ceil(x / y)`.
139 fn checked_div_ceil(x: usize, y: usize) -> Option<usize> {
140 if y == 0 {
141 None
142 } else if x == 0 {
143 Some(0)
144 } else {
145 Some(1 + (x - 1) / y)
146 }
147 }
148
149 match ownertrust {
150 OwnerTrustLevel::Ultimate => {
151 ultimate_roots.insert(f.clone());
152 trust_roots.push(
153 Root::new(f.clone(), wot::FULLY_TRUSTED));
154 },
155 OwnerTrustLevel::Fully =>
156 possible_roots.push(Root::new(
157 f.clone(),
158 checked_div_ceil(wot::FULLY_TRUSTED,
159 self.completes_needed as _)
160 .unwrap_or(wot::FULLY_TRUSTED))),
161 OwnerTrustLevel::Marginal =>
162 possible_roots.push(Root::new(
163 f.clone(),
164 checked_div_ceil(wot::FULLY_TRUSTED,
165 self.marginals_needed as _)
166 .unwrap_or(wot::FULLY_TRUSTED / 3))),
167 _ => (),
168 }
169 }
170
171 t!("trust_roots: {:?}", trust_roots);
172 t!("ultimate_roots: {:?}", ultimate_roots);
173 t!("possible_roots: {:?}", possible_roots);
174
175 let mut found_one = true;
176 while found_one && ! possible_roots.is_empty() {
177 // For GnuPG to consider a non-ultimately trusted root as
178 // valid, there must be a path from an ultimately trusted root
179 // to the non-ultimately trusted root. If this is the case,
180 // add those roots.
181
182 t!("Checking if any of {} are reachable from the current {} roots",
183 possible_roots.iter()
184 .fold(String::new(), |mut s, r| {
185 if ! s.is_empty() {
186 s.push_str(", ");
187 }
188 s.push_str(&r.fingerprint().to_hex());
189 s
190 }),
191 trust_roots.len());
192
193 found_one = false;
194 let pr = possible_roots;
195 possible_roots = Vec::new();
196
197 'root: for other_root in pr.into_iter() {
198 let cert = match n.lookup_synopsis_by_fpr(other_root.fingerprint()) {
199 Err(_err) => {
200 t!("Ignoring root {}: not in network.",
201 other_root.fingerprint());
202 continue;
203 }
204 Ok(cert) => cert,
205 };
206
207 for u in cert.userids() {
208 if u.revocation_status().in_effect(at) {
209 t!("Ignoring root {}'s User ID {:?}: revoked.",
210 other_root.fingerprint(),
211 String::from_utf8_lossy(u.value()));
212 continue;
213 }
214
215 let authenticated_amount
216 = n.authenticate(
217 u.userid(), other_root.fingerprint(),
218 wot::FULLY_TRUSTED)
219 .amount();
220
221 if authenticated_amount >= wot::FULLY_TRUSTED {
222 // Authenticated! We'll keep it.
223 t!("Non-ultimately trusted root <{}, {}> reachable, \
224 keeping at {}",
225 other_root.fingerprint(),
226 String::from_utf8_lossy(u.userid().value()),
227 other_root.amount());
228 found_one = true;
229
230 trust_roots.push(other_root);
231 let store = wot::store::CertStore::from_store(
232 &config.keydb, &config.policy, at);
233 let roots = wot::Roots::new(trust_roots.clone());
234 n = wot::Network::new(store, roots)?;
235
236 continue 'root;
237 } else {
238 t!("Non-ultimately trusted binding <{}, {}> \
239 NOT fully trusted (amount: {})",
240 other_root.fingerprint(),
241 String::from_utf8_lossy(u.userid().value()),
242 authenticated_amount);
243 }
244 }
245
246 t!("Non-ultimately trusted root {} NOT fully trusted. Ignoring.",
247 other_root.fingerprint());
248 possible_roots.push(other_root);
249 }
250 }
251 }
252
253 t!("computed trust_roots: {:?}", trust_roots);
254
255 Ok(Box::new(WoTViewAt {
256 wot: self.clone(),
257 config,
258 ultimate_roots,
259 network: n,
260 }))
261 }
262 }
263
264 struct WoTViewAt<'a, 'store> {
265 /// WoT configuration for reference.
266 wot: WoT,
267
268 config: &'a Config<'store>,
269
270 /// The set of keys for which we report `ValidityLevel::Ultimate`.
271 ultimate_roots: BTreeSet<Fingerprint>,
272
273 network: wot::Network<wot::store::CertStore<'store, 'a, &'a KeyDB<'store>>>,
274 }
275
276 impl<'a, 'store> ModelViewAt<'a, 'store> for WoTViewAt<'a, 'store> {
277 fn kind(&self) -> TrustModel {
278 match (self.wot.sequoia_roots, self.wot.gnupg_roots) {
279 (false, false) => TrustModel::PGP,
280 (false, true) => TrustModel::GnuPG,
281 (true, false) => TrustModel::Sequoia,
282 (true, true) => if crate::gnupg_interface::STRICT_OUTPUT {
283 TrustModel::PGP
284 } else {
285 TrustModel::SequoiaGnuPG
286 }
287 }
288 }
289
290 fn time(&self) -> SystemTime {
291 self.network.reference_time()
292 }
293 fn policy(&self) -> &dyn Policy {
294 self.network.policy()
295 }
296
297 fn validity(&self, userid: &UserID, fingerprint: &Fingerprint)
298 -> Result<Validity> {
299 tracer!(TRACE, "WoT::validity");
300
301 if self.ultimate_roots.contains(fingerprint) {
302 t!("{} is an ultimate root", fingerprint);
303 return Ok(ValidityLevel::Ultimate.into());
304 }
305
306 let paths = self.network.authenticate(
307 userid, fingerprint.clone(), wot::FULLY_TRUSTED);
308
309 let amount = paths.amount();
310 t!("authenticate({:?}, {}) => {}", userid, fingerprint, amount);
311 t!("paths: {:?}", paths);
312
313 if amount >= wot::FULLY_TRUSTED {
314 Ok(ValidityLevel::Fully.into())
315 } else if amount >= 60 { // XXX magic number
316 Ok(ValidityLevel::Marginal.into())
317 } else {
318 Ok(ValidityLevel::Unknown.into())
319 }
320 }
321
322 fn lookup(&self, query: &Query) -> Result<Vec<(Validity, Arc<LazyCert<'store>>)>> {
323 tracer!(TRACE, "WoT::lookup");
324 t!("query {:?}", query);
325
326 let certs = self.network.backend().store().lookup_candidates(self.config, &query)?;
327 Ok(certs.into_iter()
328 .map(|c| {
329 let validity = match query {
330 Query::Key(_) | Query::ExactKey(_) => {
331 // GnuPG computes the maximum validity of all user
332 // ids.
333 let fp = c.fingerprint();
334 c.userids()
335 .map(|uid| self.validity(&uid, &fp)
336 .unwrap_or(ValidityLevel::Unknown.into()))
337 .max()
338 .unwrap_or(ValidityLevel::Unknown.into())
339 },
340 Query::Email(_) | Query::UserIDFragment(_)
341 | Query::ExactUserID(_) =>
342 {
343 // GnuPG only matches on one userid, but a
344 // query could match more than one. Computes
345 // the maximum validity of all matching user
346 // ids.
347 let fp = c.fingerprint();
348 c.userids()
349 .filter(|uid| query.matches_userid(uid))
350 .map(|uid| self.validity(&uid, &fp)
351 .unwrap_or(ValidityLevel::Unknown.into()))
352 .max()
353 .unwrap_or(ValidityLevel::Unknown.into())
354 },
355 };
356 (validity, c)
357 })
358 .collect())
359 }
360 }