Skip to main content

rustflexstack/security/
validity.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! Certificate validity restrictions (IEEE Std 1609.2-2016, clauses
5//! 5.2.3.2.2, 6.4.8 and 6.4.17, as profiled by ETSI TS 103 097 V2.2.1).
6//!
7//! - time: the validityPeriod of a certificate (start + duration);
8//! - region: the circular, rectangular or polygonal region of a certificate;
9//!   a certificate without region inherits the region of its issuer;
10//! - permissions: the appPermissions entry (PSID and SSP) of a certificate.
11//!
12//! Identified regions (clauses 6.4.22 to 6.4.26) name countries (UN M.49
13//! codes; 65535 is the EU-27 in ETSI TS 103 097 clause 6), regions and
14//! subregions. The stack ships no border data: the application registers the
15//! geometry of the identifiers it recognises ([`register_identified_region`]),
16//! and the PICS conformance claim is the list of registered identifiers
17//! (TS 103 097 clause 5). An identifier without geometry cannot be evaluated
18//! (`None`).
19//!
20//! Mirrors `flexstack/security/validity.py`.
21
22use crate::security::certificate::Certificate;
23use crate::security::security_asn::ieee1609_dot2::ToBeSignedCertificate;
24use crate::security::security_asn::ieee1609_dot2_base_types::{
25    Duration, GeographicRegion, IdentifiedRegion, ServiceSpecificPermissions, TwoDLocation,
26};
27use std::collections::BTreeMap;
28use std::sync::RwLock;
29
30const EARTH_RADIUS_M: f64 = 6_371_000.0;
31const TENTH_MICRODEGREE: f64 = 1e-7;
32/// ETSI TS 103 097 clause 6: UnCountryId 65535 is the European Union
33/// "27 countries as of 31 January 2020".
34pub const EU27_COUNTRY_ID: u16 = 65535;
35
36/// An identified region: a country, a region of a country
37/// (CountryAndRegions) or a subregion of a region (RegionAndSubregions).
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct RegionKey {
40    pub country: u16,
41    pub region: Option<u8>,
42    pub subregion: Option<u16>,
43}
44
45impl RegionKey {
46    pub fn country(country: u16) -> Self {
47        Self {
48            country,
49            region: None,
50            subregion: None,
51        }
52    }
53    pub fn region(country: u16, region: u8) -> Self {
54        Self {
55            country,
56            region: Some(region),
57            subregion: None,
58        }
59    }
60    pub fn subregion(country: u16, region: u8, subregion: u16) -> Self {
61        Self {
62            country,
63            region: Some(region),
64            subregion: Some(subregion),
65        }
66    }
67    /// The enclosing identifiers, closest first (region, then country).
68    fn parents(&self) -> Vec<RegionKey> {
69        match (self.region, self.subregion) {
70            (Some(r), Some(_)) => vec![Self::region(self.country, r), Self::country(self.country)],
71            (Some(_), None) => vec![Self::country(self.country)],
72            _ => vec![],
73        }
74    }
75}
76
77/// Polygons of (latitude, longitude) vertices in degrees.
78type Polygons = Vec<Vec<(f64, f64)>>;
79
80static IDENTIFIED_REGIONS: RwLock<BTreeMap<RegionKey, Polygons>> = RwLock::new(BTreeMap::new());
81
82/// Register the borders of an identified region so that certificates
83/// restricted to it can be evaluated. `polygons` is a list of polygons
84/// (several for territories with islands), each a list of (latitude,
85/// longitude) vertices in 1/10 µdeg.
86pub fn register_identified_region(key: RegionKey, polygons: &[Vec<(i32, i32)>]) {
87    let geometry = polygons
88        .iter()
89        .map(|polygon| {
90            polygon
91                .iter()
92                .map(|(lat, lon)| {
93                    (
94                        *lat as f64 * TENTH_MICRODEGREE,
95                        *lon as f64 * TENTH_MICRODEGREE,
96                    )
97                })
98                .collect()
99        })
100        .collect();
101    IDENTIFIED_REGIONS
102        .write()
103        .unwrap_or_else(|e| e.into_inner())
104        .insert(key, geometry);
105}
106
107/// Forget the geometry of an identified region (no-op if unknown).
108pub fn unregister_identified_region(key: RegionKey) {
109    IDENTIFIED_REGIONS
110        .write()
111        .unwrap_or_else(|e| e.into_inner())
112        .remove(&key);
113}
114
115/// Identifiers the stack can evaluate (the PICS list of recognised values).
116pub fn recognized_identified_regions() -> Vec<RegionKey> {
117    IDENTIFIED_REGIONS
118        .read()
119        .unwrap_or_else(|e| e.into_inner())
120        .keys()
121        .copied()
122        .collect()
123}
124
125/// (start, end) of the validityPeriod in TAI microseconds since 2004.
126pub fn validity_window_us(tbs: &ToBeSignedCertificate) -> (u64, u64) {
127    let period = &tbs.validity_period;
128    let start_us = period.start.0 .0 as u64 * 1_000_000;
129    let duration_us: u64 = match &period.duration {
130        Duration::microseconds(v) => v.0 as u64,
131        Duration::milliseconds(v) => v.0 as u64 * 1_000,
132        Duration::seconds(v) => v.0 as u64 * 1_000_000,
133        Duration::minutes(v) => v.0 as u64 * 60_000_000,
134        Duration::hours(v) => v.0 as u64 * 3_600_000_000,
135        Duration::sixtyHours(v) => v.0 as u64 * 216_000_000_000,
136        Duration::years(v) => v.0 as u64 * 31_556_952_000_000,
137    };
138    (start_us, start_us + duration_us)
139}
140
141/// True when `time_us` (Time64, TAI µs since 2004) lies in the validity
142/// period of the certificate and of every issuer in its chain.
143pub fn valid_at(certificate: &Certificate, time_us: u64) -> bool {
144    let mut current = Some(certificate);
145    while let Some(cert) = current {
146        let (start, end) = validity_window_us(cert.tbs());
147        if time_us < start || time_us > end {
148            return false;
149        }
150        current = cert.issuer.as_deref();
151    }
152    true
153}
154
155/// Region of the certificate, or of the closest issuer that has one.
156pub fn effective_region(certificate: &Certificate) -> Option<&GeographicRegion> {
157    let mut current = Some(certificate);
158    while let Some(cert) = current {
159        if let Some(region) = &cert.tbs().region {
160            return Some(region);
161        }
162        current = cert.issuer.as_deref();
163    }
164    None
165}
166
167fn deg(location: &TwoDLocation) -> (f64, f64) {
168    (
169        location.latitude.0 .0 as f64 * TENTH_MICRODEGREE,
170        location.longitude.0 .0 as f64 * TENTH_MICRODEGREE,
171    )
172}
173
174/// Great-circle distance (haversine) in metres between two points in degrees.
175fn distance_m(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
176    let (p1, p2) = (lat1.to_radians(), lat2.to_radians());
177    let (dp, dl) = (p2 - p1, (lon2 - lon1).to_radians());
178    let a = (dp / 2.0).sin().powi(2) + p1.cos() * p2.cos() * (dl / 2.0).sin().powi(2);
179    2.0 * EARTH_RADIUS_M * a.sqrt().min(1.0).asin()
180}
181
182/// Ray casting in the (longitude, latitude) plane over (lat, lon) vertices in
183/// degrees; the border counts as inside.
184fn in_polygon(vertices: &[(f64, f64)], lat: f64, lon: f64) -> bool {
185    let mut inside = false;
186    for i in 0..vertices.len() {
187        let (lat_i, lon_i) = vertices[i];
188        let (lat_j, lon_j) = vertices[(i + vertices.len() - 1) % vertices.len()];
189        if (lat_i > lat) != (lat_j > lat) {
190            let cross = lon_i + (lat - lat_i) * (lon_j - lon_i) / (lat_j - lat_i);
191            if lon == cross {
192                return true;
193            }
194            if lon < cross {
195                inside = !inside;
196            }
197        } else if lat_i == lat && lat_j == lat && lon_i.min(lon_j) <= lon && lon <= lon_i.max(lon_j)
198        {
199            return true;
200        }
201    }
202    inside
203}
204
205/// Whether the position lies in a registered identifier. When the identifier
206/// itself is not registered, a registered enclosing one (the region of a
207/// subregion, the country of a region) can still show that the position is
208/// outside; otherwise `None`.
209fn key_contains(
210    regions: &BTreeMap<RegionKey, Polygons>,
211    key: &RegionKey,
212    lat: f64,
213    lon: f64,
214) -> Option<bool> {
215    let inside = |polygons: &Polygons| polygons.iter().any(|p| in_polygon(p, lat, lon));
216    if let Some(polygons) = regions.get(key) {
217        return Some(inside(polygons));
218    }
219    for parent in key.parents() {
220        if let Some(polygons) = regions.get(&parent) {
221            if !inside(polygons) {
222                return Some(false);
223            }
224        }
225    }
226    None
227}
228
229/// Identifiers named by one IdentifiedRegion (clauses 6.4.22 to 6.4.26);
230/// `None` for an empty list (not evaluable).
231fn identified_keys(entry: &IdentifiedRegion) -> Option<Vec<RegionKey>> {
232    let keys: Vec<RegionKey> = match entry {
233        IdentifiedRegion::countryOnly(c) => vec![RegionKey::country(c.0 .0)],
234        IdentifiedRegion::countryAndRegions(cr) => cr
235            .regions
236            .0
237            .iter()
238            .map(|r| RegionKey::region(cr.country_only.0 .0, r.0))
239            .collect(),
240        IdentifiedRegion::countryAndSubregions(cs) => cs
241            .region_and_subregions
242            .0
243            .iter()
244            .flat_map(|item| {
245                item.subregions.0.iter().map(move |sub| {
246                    RegionKey::subregion(cs.country_only.0 .0, item.region.0, sub.0)
247                })
248            })
249            .collect(),
250    };
251    (!keys.is_empty()).then_some(keys)
252}
253
254/// SequenceOfIdentifiedRegion: inside when any recognised identifier contains
255/// the position (IEEE 1609.2 allows unrecognised values when the recognised
256/// ones establish validity); outside when every identifier is recognised and
257/// none contains it; otherwise `None`.
258pub fn identified_region_contains(
259    entries: &[IdentifiedRegion],
260    lat: f64,
261    lon: f64,
262) -> Option<bool> {
263    let regions = IDENTIFIED_REGIONS.read().unwrap_or_else(|e| e.into_inner());
264    let mut unknown = false;
265    for entry in entries {
266        let Some(keys) = identified_keys(entry) else {
267            unknown = true;
268            continue;
269        };
270        for key in keys {
271            match key_contains(&regions, &key, lat, lon) {
272                Some(true) => return Some(true),
273                Some(false) => {}
274                None => unknown = true,
275            }
276        }
277    }
278    if unknown {
279        None
280    } else {
281        Some(false)
282    }
283}
284
285/// Whether a position (1/10 µdeg) lies inside a GeographicRegion. `Some(true)`
286/// for no region (no restriction); `None` when the region cannot be
287/// evaluated (identifiedRegion without registered geometry).
288pub fn region_contains(
289    region: Option<&GeographicRegion>,
290    latitude: i32,
291    longitude: i32,
292) -> Option<bool> {
293    let Some(region) = region else {
294        return Some(true);
295    };
296    let (lat, lon) = (
297        latitude as f64 * TENTH_MICRODEGREE,
298        longitude as f64 * TENTH_MICRODEGREE,
299    );
300    match region {
301        GeographicRegion::circularRegion(circle) => {
302            let (c_lat, c_lon) = deg(&circle.center);
303            Some(distance_m(c_lat, c_lon, lat, lon) <= circle.radius.0 as f64)
304        }
305        GeographicRegion::rectangularRegion(rects) => Some(rects.0.iter().any(|rect| {
306            let (north, west) = deg(&rect.north_west);
307            let (south, east) = deg(&rect.south_east);
308            south <= lat && lat <= north && west <= lon && lon <= east
309        })),
310        GeographicRegion::polygonalRegion(polygon) => {
311            let vertices: Vec<(f64, f64)> = polygon.0.iter().map(deg).collect();
312            Some(in_polygon(&vertices, lat, lon))
313        }
314        GeographicRegion::identifiedRegion(entries) => {
315            identified_region_contains(&entries.0, lat, lon)
316        }
317    }
318}
319
320/// Region consistency (IEEE 1609.2 clause 5.2.3.2.2): the position lies in
321/// the effective region of the certificate chain. A region that cannot be
322/// evaluated is not treated as a violation.
323pub fn location_permitted(certificate: &Certificate, latitude: i32, longitude: i32) -> bool {
324    region_contains(effective_region(certificate), latitude, longitude) != Some(false)
325}
326
327/// (permitted, SSP) for `psid` in the appPermissions of a certificate. The SSP
328/// is the BitmapSsp or opaque octets, or `None` when the entry has no SSP.
329pub fn app_permission(tbs: &ToBeSignedCertificate, psid: u64) -> (bool, Option<Vec<u8>>) {
330    let Some(permissions) = &tbs.app_permissions else {
331        return (false, None);
332    };
333    for entry in &permissions.0 {
334        if u64::try_from(&entry.psid.0).ok() == Some(psid) {
335            let ssp = entry.ssp.as_ref().map(|ssp| match ssp {
336                ServiceSpecificPermissions::opaque(o) => o.to_vec(),
337                ServiceSpecificPermissions::bitmapSsp(b) => b.0.to_vec(),
338            });
339            return (true, ssp);
340        }
341    }
342    (false, None)
343}
344
345/// True when the BitmapSsp of an AT grants every permission bit requested
346/// (octets after the SSP version octet). Without requested bits any SSP
347/// covers the request.
348pub fn ssp_covers(at_ssp: Option<&[u8]>, requested: &[u8]) -> bool {
349    let wanted = requested.get(1..).unwrap_or(&[]);
350    let have = at_ssp.and_then(|s| s.get(1..)).unwrap_or(&[]);
351    wanted
352        .iter()
353        .enumerate()
354        .all(|(i, bits)| *bits == 0 || (i < have.len() && bits & !have[i] == 0))
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360    use crate::security::security_asn::ieee1609_dot2_base_types::{
361        CircularRegion, CountryAndRegions, CountryAndSubregions, Latitude, Longitude,
362        NinetyDegreeInt, OneEightyDegreeInt, PolygonalRegion, RectangularRegion,
363        RegionAndSubregions, SequenceOfIdentifiedRegion, SequenceOfRectangularRegion,
364        SequenceOfRegionAndSubregions, SequenceOfUint16, SequenceOfUint8, Uint16, Uint8,
365        UnCountryId,
366    };
367
368    fn point(lat: i32, lon: i32) -> TwoDLocation {
369        TwoDLocation::new(
370            Latitude(NinetyDegreeInt(lat)),
371            Longitude(OneEightyDegreeInt(lon)),
372        )
373    }
374
375    #[test]
376    fn circular_region() {
377        let region = GeographicRegion::circularRegion(CircularRegion::new(
378            point(415520000, 21340000),
379            Uint16(5000),
380        ));
381        assert_eq!(
382            region_contains(Some(&region), 415520000, 21340000),
383            Some(true)
384        );
385        assert_eq!(
386            region_contains(Some(&region), 425520000, 21340000),
387            Some(false)
388        );
389        assert_eq!(region_contains(None, 0, 0), Some(true));
390    }
391
392    #[test]
393    fn rectangular_region() {
394        let rect = RectangularRegion::new(point(420000000, 20000000), point(410000000, 30000000));
395        let region = GeographicRegion::rectangularRegion(SequenceOfRectangularRegion(vec![rect]));
396        assert_eq!(
397            region_contains(Some(&region), 415000000, 25000000),
398            Some(true)
399        );
400        assert_eq!(
401            region_contains(Some(&region), 400000000, 25000000),
402            Some(false)
403        );
404    }
405
406    #[test]
407    fn polygonal_region_with_8_points() {
408        // Octagon around (41.5, 2.5) - IEEE 1609.2 clause 6.4.17: at least 8 points
409        let pts = [
410            (420000000, 24000000),
411            (420000000, 26000000),
412            (418000000, 28000000),
413            (412000000, 28000000),
414            (410000000, 26000000),
415            (410000000, 24000000),
416            (412000000, 22000000),
417            (418000000, 22000000),
418        ];
419        let region = GeographicRegion::polygonalRegion(PolygonalRegion(
420            pts.iter().map(|(a, b)| point(*a, *b)).collect(),
421        ));
422        assert_eq!(
423            region_contains(Some(&region), 415000000, 25000000),
424            Some(true)
425        );
426        assert_eq!(
427            region_contains(Some(&region), 419500000, 22100000),
428            Some(false)
429        );
430    }
431
432    fn boxed(south: i32, west: i32, north: i32, east: i32) -> Vec<(i32, i32)> {
433        vec![(south, west), (north, west), (north, east), (south, east)]
434    }
435
436    fn identified(entries: Vec<IdentifiedRegion>) -> GeographicRegion {
437        GeographicRegion::identifiedRegion(SequenceOfIdentifiedRegion(entries))
438    }
439
440    fn country(code: u16) -> IdentifiedRegion {
441        IdentifiedRegion::countryOnly(UnCountryId(Uint16(code)))
442    }
443
444    // Synthetic geometry and identifiers; each test uses its own country codes
445    // because the registry is shared by the tests running in parallel.
446
447    #[test]
448    fn identified_region_without_geometry_cannot_be_evaluated() {
449        let region = identified(vec![country(9000)]);
450        assert_eq!(region_contains(Some(&region), 0, 0), None);
451    }
452
453    #[test]
454    fn identified_region_country() {
455        let key = RegionKey::country(9001);
456        register_identified_region(key, &[boxed(410000000, 15000000, 420000000, 28000000)]);
457        assert!(recognized_identified_regions().contains(&key));
458        let region = identified(vec![country(9001)]);
459        assert_eq!(
460            region_contains(Some(&region), 415520000, 21340000),
461            Some(true)
462        );
463        assert_eq!(
464            region_contains(Some(&region), 425520000, 21340000),
465            Some(false)
466        );
467        unregister_identified_region(key);
468        assert_eq!(region_contains(Some(&region), 415520000, 21340000), None);
469    }
470
471    /// IEEE 1609.2 clause 6.4.17: identifiedRegion with 8 entries, one of
472    /// them containing the position.
473    #[test]
474    fn identified_region_with_8_entries() {
475        for i in 0..8u16 {
476            let lat = 340000000 + i as i32 * 15000000;
477            register_identified_region(
478                RegionKey::country(9100 + i),
479                &[boxed(lat, 0, lat + 10000000, 30000000)],
480            );
481        }
482        let region = identified((0..8).map(|i| country(9100 + i)).collect());
483        // Boxes 34.0-35.0 N, 35.5-36.5 N, ...: 41.55 N lies in the 6th (41.5-42.5 N)
484        assert_eq!(
485            region_contains(Some(&region), 415520000, 21340000),
486            Some(true)
487        );
488        assert_eq!(
489            region_contains(Some(&region), 412000000, 21340000),
490            Some(false)
491        );
492    }
493
494    #[test]
495    fn identified_regions_and_subregions() {
496        register_identified_region(
497            RegionKey::country(9200),
498            &[boxed(400000000, 0, 430000000, 40000000)],
499        );
500        register_identified_region(
501            RegionKey::region(9200, 3),
502            &[boxed(410000000, 15000000, 420000000, 28000000)],
503        );
504        let regions = identified(vec![IdentifiedRegion::countryAndRegions(
505            CountryAndRegions::new(UnCountryId(Uint16(9200)), SequenceOfUint8(vec![Uint8(3)])),
506        )]);
507        assert_eq!(
508            region_contains(Some(&regions), 415520000, 21340000),
509            Some(true)
510        );
511        assert_eq!(
512            region_contains(Some(&regions), 425520000, 21340000),
513            Some(false)
514        );
515        let subregions = identified(vec![IdentifiedRegion::countryAndSubregions(
516            CountryAndSubregions::new(
517                UnCountryId(Uint16(9200)),
518                SequenceOfRegionAndSubregions(vec![RegionAndSubregions::new(
519                    Uint8(3),
520                    SequenceOfUint16(vec![Uint16(7)]),
521                )]),
522            ),
523        )]);
524        // Subregion 7 has no geometry: inside region 3 it cannot be decided,
525        // outside region 3 (or the country) it is outside.
526        assert_eq!(
527            region_contains(Some(&subregions), 415520000, 21340000),
528            None
529        );
530        assert_eq!(
531            region_contains(Some(&subregions), 425520000, 21340000),
532            Some(false)
533        );
534        assert_eq!(
535            region_contains(Some(&subregions), 500000000, 21340000),
536            Some(false)
537        );
538        register_identified_region(
539            RegionKey::subregion(9200, 3, 7),
540            &[boxed(415000000, 21000000, 416000000, 22000000)],
541        );
542        assert_eq!(
543            region_contains(Some(&subregions), 415520000, 21340000),
544            Some(true)
545        );
546        assert_eq!(
547            region_contains(Some(&subregions), 418000000, 21340000),
548            Some(false)
549        );
550    }
551
552    /// IEEE 1609.2 clause 6.4.24: unrecognised values are allowed when the
553    /// recognised ones establish that the position is inside.
554    #[test]
555    fn identified_region_with_unrecognised_entries() {
556        register_identified_region(
557            RegionKey::country(9301),
558            &[boxed(410000000, 15000000, 420000000, 28000000)],
559        );
560        let region = identified(vec![country(9300), country(9301)]);
561        assert_eq!(
562            region_contains(Some(&region), 415520000, 21340000),
563            Some(true)
564        );
565        assert_eq!(region_contains(Some(&region), 425520000, 21340000), None);
566    }
567
568    #[test]
569    fn ssp_coverage() {
570        let at = [2u8, 0x02, 0x00];
571        assert!(ssp_covers(Some(&at), &[0, 0x02]));
572        assert!(!ssp_covers(Some(&at), &[0, 0x01]));
573        assert!(!ssp_covers(Some(&at), &[0, 0, 0, 0x80]));
574        assert!(ssp_covers(Some(&at), &[0]));
575        assert!(ssp_covers(None, &[]));
576        assert!(!ssp_covers(None, &[0, 0x01]));
577    }
578}