Skip to main content

security/trust/
mod.rs

1use std::time::{Duration, SystemTime, UNIX_EPOCH};
2
3use crate::Value;
4
5use crate::bridge;
6use crate::certificate::{Certificate, PublicKey};
7use crate::error::{Result, SecurityError};
8pub use crate::policy::Policy;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[repr(transparent)]
12#[must_use]
13/// Mirrors `SecTrustOptionFlags`.
14pub struct TrustOptions(u32);
15
16impl TrustOptions {
17    /// Mirrors a `SecTrustOptionFlags` bit.
18    pub const ALLOW_EXPIRED: Self = Self(0x0000_0001);
19    /// Mirrors a `SecTrustOptionFlags` bit.
20    pub const LEAF_IS_CA: Self = Self(0x0000_0002);
21    /// Mirrors a `SecTrustOptionFlags` bit.
22    pub const FETCH_ISSUER_FROM_NET: Self = Self(0x0000_0004);
23    /// Mirrors a `SecTrustOptionFlags` bit.
24    pub const ALLOW_EXPIRED_ROOT: Self = Self(0x0000_0008);
25    /// Mirrors a `SecTrustOptionFlags` bit.
26    pub const REQUIRE_REVOCATION_PER_CERT: Self = Self(0x0000_0010);
27    /// Mirrors a `SecTrustOptionFlags` bit.
28    pub const USE_TRUST_SETTINGS: Self = Self(0x0000_0020);
29    /// Mirrors a `SecTrustOptionFlags` bit.
30    pub const IMPLICIT_ANCHORS: Self = Self(0x0000_0040);
31
32    pub const fn empty() -> Self {
33        Self(0)
34    }
35    pub const fn all() -> Self {
36        Self(0x7f)
37    }
38    pub const fn bits(self) -> u32 {
39        self.0
40    }
41    pub const fn from_bits(bits: u32) -> Option<Self> {
42        if bits & !Self::all().0 == 0 {
43            Some(Self(bits))
44        } else {
45            None
46        }
47    }
48    pub const fn from_bits_retain(bits: u32) -> Self {
49        Self(bits)
50    }
51    pub const fn from_bits_truncate(bits: u32) -> Self {
52        Self(bits & Self::all().0)
53    }
54    pub const fn is_empty(self) -> bool {
55        self.0 == 0
56    }
57    pub const fn is_all(self) -> bool {
58        self.0 & Self::all().0 == Self::all().0
59    }
60    pub const fn contains(self, other: Self) -> bool {
61        self.0 & other.0 == other.0
62    }
63    pub const fn intersects(self, other: Self) -> bool {
64        self.0 & other.0 != 0
65    }
66    pub const fn union(self, other: Self) -> Self {
67        Self(self.0 | other.0)
68    }
69    pub const fn intersection(self, other: Self) -> Self {
70        Self(self.0 & other.0)
71    }
72    pub const fn difference(self, other: Self) -> Self {
73        Self(self.0 & !other.0)
74    }
75    pub const fn symmetric_difference(self, other: Self) -> Self {
76        Self(self.0 ^ other.0)
77    }
78    pub const fn complement(self) -> Self {
79        Self(!self.0 & Self::all().0)
80    }
81    pub fn insert(&mut self, other: Self) {
82        self.0 |= other.0;
83    }
84    pub fn remove(&mut self, other: Self) {
85        self.0 &= !other.0;
86    }
87    pub fn toggle(&mut self, other: Self) {
88        self.0 ^= other.0;
89    }
90    pub fn set(&mut self, other: Self, value: bool) {
91        if value {
92            self.0 |= other.0;
93        } else {
94            self.0 &= !other.0;
95        }
96    }
97}
98
99impl std::ops::BitOr for TrustOptions {
100    type Output = Self;
101    fn bitor(self, rhs: Self) -> Self {
102        Self(self.0 | rhs.0)
103    }
104}
105impl std::ops::BitAnd for TrustOptions {
106    type Output = Self;
107    fn bitand(self, rhs: Self) -> Self {
108        Self(self.0 & rhs.0)
109    }
110}
111impl std::ops::BitXor for TrustOptions {
112    type Output = Self;
113    fn bitxor(self, rhs: Self) -> Self {
114        Self(self.0 ^ rhs.0)
115    }
116}
117impl std::ops::Sub for TrustOptions {
118    type Output = Self;
119    fn sub(self, rhs: Self) -> Self {
120        Self(self.0 & !rhs.0)
121    }
122}
123impl std::ops::Not for TrustOptions {
124    type Output = Self;
125    fn not(self) -> Self {
126        Self(!self.0 & Self::all().0)
127    }
128}
129impl std::ops::BitOrAssign for TrustOptions {
130    fn bitor_assign(&mut self, rhs: Self) {
131        self.0 |= rhs.0;
132    }
133}
134impl std::ops::BitAndAssign for TrustOptions {
135    fn bitand_assign(&mut self, rhs: Self) {
136        self.0 &= rhs.0;
137    }
138}
139impl std::ops::BitXorAssign for TrustOptions {
140    fn bitxor_assign(&mut self, rhs: Self) {
141        self.0 ^= rhs.0;
142    }
143}
144impl std::ops::SubAssign for TrustOptions {
145    fn sub_assign(&mut self, rhs: Self) {
146        self.0 &= !rhs.0;
147    }
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
151#[repr(u32)]
152/// Mirrors `SecTrustResultType`.
153pub enum TrustResultType {
154    /// Mirrors a `SecTrustResultType` constant.
155    Invalid = 0,
156    /// Mirrors a `SecTrustResultType` constant.
157    Proceed = 1,
158    /// Mirrors a `SecTrustResultType` constant.
159    Confirm = 2,
160    /// Mirrors a `SecTrustResultType` constant.
161    Deny = 3,
162    /// Mirrors a `SecTrustResultType` constant.
163    Unspecified = 4,
164    /// Mirrors a `SecTrustResultType` constant.
165    RecoverableTrustFailure = 5,
166    /// Mirrors a `SecTrustResultType` constant.
167    FatalTrustFailure = 6,
168    /// Mirrors a `SecTrustResultType` constant.
169    OtherError = 7,
170}
171
172impl TrustResultType {
173    fn from_raw(raw: u32) -> Result<Self> {
174        match raw {
175            0 => Ok(Self::Invalid),
176            1 => Ok(Self::Proceed),
177            2 => Ok(Self::Confirm),
178            3 => Ok(Self::Deny),
179            4 => Ok(Self::Unspecified),
180            5 => Ok(Self::RecoverableTrustFailure),
181            6 => Ok(Self::FatalTrustFailure),
182            7 => Ok(Self::OtherError),
183            _ => Err(SecurityError::InvalidArgument(format!(
184                "unexpected trust result type: {raw}"
185            ))),
186        }
187    }
188}
189
190#[derive(Debug)]
191/// Wraps `SecTrustRef`.
192pub struct Trust {
193    handle: bridge::Handle,
194}
195
196impl Trust {
197    #[cfg(feature = "async")]
198    pub(crate) fn as_ptr(&self) -> *mut std::ffi::c_void {
199        self.handle.as_ptr()
200    }
201
202    pub(crate) fn from_handle(handle: bridge::Handle) -> Self {
203        Self { handle }
204    }
205
206    /// Wraps the corresponding `SecTrustRef` operation.
207    pub fn type_id() -> usize {
208        unsafe { bridge::security_trust_get_type_id() }
209    }
210
211    /// Wraps the corresponding `SecTrustRef` operation.
212    pub fn new(certificate: &Certificate, policies: &[Policy]) -> Result<Self> {
213        Self::from_certificates(std::slice::from_ref(certificate), policies)
214    }
215
216    /// Wraps the corresponding `SecTrustRef` operation.
217    pub fn from_certificates(certificates: &[Certificate], policies: &[Policy]) -> Result<Self> {
218        let certificate_handles = certificates
219            .iter()
220            .map(Certificate::handle)
221            .collect::<Vec<_>>();
222        let policy_handles = policies.iter().map(Policy::handle).collect::<Vec<_>>();
223        let certificate_pointers = bridge::handle_pointer_array(&certificate_handles);
224        let policy_pointers = bridge::handle_pointer_array(&policy_handles);
225        let mut status = 0;
226        let mut error = std::ptr::null_mut();
227        let raw = unsafe {
228            bridge::security_trust_create(
229                certificate_pointers.as_ptr(),
230                bridge::len_to_isize(certificate_pointers.len())?,
231                policy_pointers.as_ptr(),
232                bridge::len_to_isize(policy_pointers.len())?,
233                &raw mut status,
234                &raw mut error,
235            )
236        };
237        bridge::required_handle("security_trust_create", raw, status, error)
238            .map(|handle| Self { handle })
239    }
240
241    /// Wraps the corresponding `SecTrustRef` operation.
242    pub fn set_policies(&mut self, policies: &[Policy]) -> Result<()> {
243        let policy_handles = policies.iter().map(Policy::handle).collect::<Vec<_>>();
244        let pointers = bridge::handle_pointer_array(&policy_handles);
245        let mut error = std::ptr::null_mut();
246        let status = unsafe {
247            bridge::security_trust_set_policies(
248                self.handle.as_ptr(),
249                pointers.as_ptr(),
250                bridge::len_to_isize(pointers.len())?,
251                &raw mut error,
252            )
253        };
254        bridge::status_result("security_trust_set_policies", status, error)
255    }
256
257    /// Wraps the corresponding `SecTrustRef` operation.
258    pub fn policies(&self) -> Result<Value> {
259        let mut status = 0;
260        let mut error = std::ptr::null_mut();
261        let raw = unsafe {
262            bridge::security_trust_copy_policies(
263                self.handle.as_ptr(),
264                &raw mut status,
265                &raw mut error,
266            )
267        };
268        bridge::required_value("security_trust_copy_policies", raw, status, error)
269    }
270
271    /// Wraps the corresponding `SecTrustRef` operation.
272    pub fn set_anchor_certificates(&mut self, certificates: &[Certificate]) -> Result<()> {
273        let certificate_handles = certificates
274            .iter()
275            .map(Certificate::handle)
276            .collect::<Vec<_>>();
277        let pointers = bridge::handle_pointer_array(&certificate_handles);
278        let mut error = std::ptr::null_mut();
279        let status = unsafe {
280            bridge::security_trust_set_anchor_certificates(
281                self.handle.as_ptr(),
282                pointers.as_ptr(),
283                bridge::len_to_isize(pointers.len())?,
284                &raw mut error,
285            )
286        };
287        bridge::status_result("security_trust_set_anchor_certificates", status, error)
288    }
289
290    /// Wraps the corresponding `SecTrustRef` operation.
291    pub fn custom_anchor_certificates(&self) -> Result<Value> {
292        let mut status = 0;
293        let mut error = std::ptr::null_mut();
294        let raw = unsafe {
295            bridge::security_trust_copy_custom_anchor_certificates(
296                self.handle.as_ptr(),
297                &raw mut status,
298                &raw mut error,
299            )
300        };
301        bridge::required_value(
302            "security_trust_copy_custom_anchor_certificates",
303            raw,
304            status,
305            error,
306        )
307    }
308
309    /// Wraps the corresponding `SecTrustRef` operation.
310    pub fn set_anchor_certificates_only(&mut self, only_anchor_certificates: bool) -> Result<()> {
311        let mut error = std::ptr::null_mut();
312        let status = unsafe {
313            bridge::security_trust_set_anchor_certificates_only(
314                self.handle.as_ptr(),
315                only_anchor_certificates,
316                &raw mut error,
317            )
318        };
319        bridge::status_result("security_trust_set_anchor_certificates_only", status, error)
320    }
321
322    /// Wraps the corresponding `SecTrustRef` operation.
323    pub fn set_network_fetch_allowed(&mut self, allowed: bool) -> Result<()> {
324        let mut error = std::ptr::null_mut();
325        let status = unsafe {
326            bridge::security_trust_set_network_fetch_allowed(
327                self.handle.as_ptr(),
328                allowed,
329                &raw mut error,
330            )
331        };
332        bridge::status_result("security_trust_set_network_fetch_allowed", status, error)
333    }
334
335    /// Wraps the corresponding `SecTrustRef` operation.
336    pub fn network_fetch_allowed(&self) -> Result<bool> {
337        let mut status = 0;
338        let mut error = std::ptr::null_mut();
339        let allowed = unsafe {
340            bridge::security_trust_get_network_fetch_allowed(
341                self.handle.as_ptr(),
342                &raw mut status,
343                &raw mut error,
344            )
345        };
346        if status != 0 {
347            return Err(bridge::status_error(
348                "security_trust_get_network_fetch_allowed",
349                status,
350                error,
351            )?);
352        }
353        Ok(allowed)
354    }
355
356    /// Wraps the corresponding `SecTrustRef` operation.
357    pub fn set_verify_date(&mut self, verify_date: SystemTime) -> Result<()> {
358        let mut error = std::ptr::null_mut();
359        let status = unsafe {
360            bridge::security_trust_set_verify_date(
361                self.handle.as_ptr(),
362                system_time_to_unix(verify_date),
363                &raw mut error,
364            )
365        };
366        bridge::status_result("security_trust_set_verify_date", status, error)
367    }
368
369    /// Wraps the corresponding `SecTrustRef` operation.
370    pub fn verify_time(&self) -> Result<Option<SystemTime>> {
371        let mut status = 0;
372        let mut error = std::ptr::null_mut();
373        let raw = unsafe {
374            bridge::security_trust_get_verify_time(
375                self.handle.as_ptr(),
376                &raw mut status,
377                &raw mut error,
378            )
379        };
380        if status != 0 {
381            return Err(bridge::status_error(
382                "security_trust_get_verify_time",
383                status,
384                error,
385            )?);
386        }
387        bridge::optional_value(raw)?.map_or(Ok(None), |value| decode_trust_date(value).map(Some))
388    }
389
390    /// Wraps the corresponding `SecTrustRef` operation.
391    pub fn evaluate(&self) -> Result<()> {
392        let mut error = std::ptr::null_mut();
393        let trusted =
394            unsafe { bridge::security_trust_evaluate(self.handle.as_ptr(), &raw mut error) };
395        if trusted {
396            Ok(())
397        } else {
398            let message = bridge::optional_string(error)?
399                .unwrap_or_else(|| "trust evaluation failed".to_owned());
400            Err(SecurityError::TrustEvaluationFailed(message))
401        }
402    }
403
404    /// Wraps the corresponding `SecTrustRef` operation.
405    pub fn evaluate_async(&self) -> Result<()> {
406        let mut status = 0;
407        let mut error = std::ptr::null_mut();
408        let trusted = unsafe {
409            bridge::security_trust_evaluate_async(
410                self.handle.as_ptr(),
411                &raw mut status,
412                &raw mut error,
413            )
414        };
415        if status != 0 {
416            return Err(bridge::status_error(
417                "security_trust_evaluate_async",
418                status,
419                error,
420            )?);
421        }
422        if trusted {
423            Ok(())
424        } else {
425            let message = bridge::optional_string(error)?
426                .unwrap_or_else(|| "trust evaluation failed".to_owned());
427            Err(SecurityError::TrustEvaluationFailed(message))
428        }
429    }
430
431    /// Wraps the corresponding `SecTrustRef` operation.
432    pub fn trust_result_type(&self) -> Result<TrustResultType> {
433        let mut status = 0;
434        let mut error = std::ptr::null_mut();
435        let raw = unsafe {
436            bridge::security_trust_get_trust_result(
437                self.handle.as_ptr(),
438                &raw mut status,
439                &raw mut error,
440            )
441        };
442        if status != 0 {
443            return Err(bridge::status_error(
444                "security_trust_get_trust_result",
445                status,
446                error,
447            )?);
448        }
449        TrustResultType::from_raw(raw)
450    }
451
452    /// Wraps the corresponding `SecTrustRef` operation.
453    pub fn result(&self) -> Result<Value> {
454        let mut status = 0;
455        let mut error = std::ptr::null_mut();
456        let raw = unsafe {
457            bridge::security_trust_copy_result(
458                self.handle.as_ptr(),
459                &raw mut status,
460                &raw mut error,
461            )
462        };
463        bridge::required_value("security_trust_copy_result", raw, status, error)
464    }
465
466    /// Wraps the corresponding `SecTrustRef` operation.
467    pub fn key(&self) -> Result<Option<PublicKey>> {
468        let mut status = 0;
469        let mut error = std::ptr::null_mut();
470        let raw = unsafe {
471            bridge::security_trust_copy_key(self.handle.as_ptr(), &raw mut status, &raw mut error)
472        };
473        if status != 0 {
474            return Err(bridge::status_error(
475                "security_trust_copy_key",
476                status,
477                error,
478            )?);
479        }
480        Ok(bridge::Handle::from_raw(raw).map(PublicKey::from_handle))
481    }
482
483    /// Wraps the corresponding `SecTrustRef` operation.
484    pub fn certificate_count(&self) -> usize {
485        usize::try_from(unsafe {
486            bridge::security_trust_get_certificate_count(self.handle.as_ptr())
487        })
488        .unwrap_or_default()
489    }
490
491    /// Wraps the corresponding `SecTrustRef` operation.
492    pub fn certificate_chain(&self) -> Result<Vec<Certificate>> {
493        let mut status = 0;
494        let mut error = std::ptr::null_mut();
495        let raw = unsafe {
496            bridge::security_trust_copy_certificate_chain(
497                self.handle.as_ptr(),
498                &raw mut status,
499                &raw mut error,
500            )
501        };
502        let array_handle =
503            bridge::required_handle("security_trust_copy_certificate_chain", raw, status, error)?;
504        Certificate::from_array_handle(&array_handle)
505    }
506
507    /// Wraps the corresponding `SecTrustRef` operation.
508    pub fn exceptions(&self) -> Result<Option<Vec<u8>>> {
509        let mut status = 0;
510        let mut error = std::ptr::null_mut();
511        let raw = unsafe {
512            bridge::security_trust_copy_exceptions(
513                self.handle.as_ptr(),
514                &raw mut status,
515                &raw mut error,
516            )
517        };
518        if status != 0 {
519            return Err(bridge::status_error(
520                "security_trust_copy_exceptions",
521                status,
522                error,
523            )?);
524        }
525        bridge::optional_data(raw)
526    }
527
528    /// Wraps the corresponding `SecTrustRef` operation.
529    pub fn set_exceptions(&mut self, exceptions: Option<&[u8]>) -> Result<bool> {
530        let mut error = std::ptr::null_mut();
531        let accepted = unsafe {
532            bridge::security_trust_set_exceptions(
533                self.handle.as_ptr(),
534                exceptions.map_or(std::ptr::null(), |value| value.as_ptr().cast()),
535                exceptions.map_or(Ok(0), |value| bridge::len_to_isize(value.len()))?,
536                &raw mut error,
537            )
538        };
539        if !error.is_null() {
540            return Err(bridge::status_error(
541                "security_trust_set_exceptions",
542                -1,
543                error,
544            )?);
545        }
546        Ok(accepted)
547    }
548
549    /// Wraps the corresponding `SecTrustRef` operation.
550    pub fn set_ocsp_responses(&mut self, responses: &[Vec<u8>]) -> Result<()> {
551        let responses = bridge::InputValue::data_array(responses)?;
552        let mut error = std::ptr::null_mut();
553        let status = unsafe {
554            bridge::security_trust_set_ocsp_response(
555                self.handle.as_ptr(),
556                responses.as_ptr(),
557                &raw mut error,
558            )
559        };
560        bridge::status_result("security_trust_set_ocsp_response", status, error)
561    }
562
563    /// Wraps the corresponding `SecTrustRef` operation.
564    pub fn set_signed_certificate_timestamps(&mut self, timestamps: &[Vec<u8>]) -> Result<()> {
565        let timestamps = bridge::InputValue::data_array(timestamps)?;
566        let mut error = std::ptr::null_mut();
567        let status = unsafe {
568            bridge::security_trust_set_signed_certificate_timestamps(
569                self.handle.as_ptr(),
570                timestamps.as_ptr(),
571                &raw mut error,
572            )
573        };
574        bridge::status_result(
575            "security_trust_set_signed_certificate_timestamps",
576            status,
577            error,
578        )
579    }
580
581    /// Wraps the corresponding `SecTrustRef` operation.
582    pub fn set_options(&mut self, options: TrustOptions) -> Result<()> {
583        let mut error = std::ptr::null_mut();
584        let status = unsafe {
585            bridge::security_trust_set_options(self.handle.as_ptr(), options.bits(), &raw mut error)
586        };
587        bridge::status_result("security_trust_set_options", status, error)
588    }
589
590    /// Wraps the corresponding `SecTrustRef` operation.
591    pub fn system_anchor_certificates() -> Result<Value> {
592        let mut status = 0;
593        let mut error = std::ptr::null_mut();
594        let raw = unsafe {
595            bridge::security_trust_copy_anchor_certificates(&raw mut status, &raw mut error)
596        };
597        bridge::required_value(
598            "security_trust_copy_anchor_certificates",
599            raw,
600            status,
601            error,
602        )
603    }
604}
605
606fn decode_trust_date(value: Value) -> Result<SystemTime> {
607    let unix = value
608        .as_date()
609        .ok_or_else(|| SecurityError::UnexpectedType {
610            operation: "security_trust_get_verify_time",
611            expected: "date",
612        })?;
613    let out_of_range =
614        || SecurityError::InvalidArgument("trust verify time is out of range".to_owned());
615    let duration = Duration::try_from_secs_f64(unix.abs()).map_err(|_| out_of_range())?;
616    if unix >= 0.0 {
617        UNIX_EPOCH.checked_add(duration).ok_or_else(out_of_range)
618    } else {
619        UNIX_EPOCH.checked_sub(duration).ok_or_else(out_of_range)
620    }
621}
622
623fn system_time_to_unix(time: SystemTime) -> f64 {
624    match time.duration_since(UNIX_EPOCH) {
625        Ok(duration) => duration.as_secs_f64(),
626        Err(error) => -error.duration().as_secs_f64(),
627    }
628}
629
630#[cfg(test)]
631mod tests {
632    use super::*;
633
634    #[test]
635    fn trust_result_type_from_raw_maps_known_values() {
636        assert_eq!(
637            TrustResultType::from_raw(0).unwrap(),
638            TrustResultType::Invalid
639        );
640        assert_eq!(
641            TrustResultType::from_raw(7).unwrap(),
642            TrustResultType::OtherError
643        );
644    }
645
646    #[test]
647    fn trust_result_type_from_raw_rejects_unknown_values() {
648        assert_eq!(
649            TrustResultType::from_raw(99).unwrap_err(),
650            SecurityError::InvalidArgument("unexpected trust result type: 99".to_owned())
651        );
652    }
653
654    #[test]
655    fn system_time_to_unix_preserves_times_after_epoch() {
656        let time = UNIX_EPOCH + Duration::from_secs_f64(42.5);
657
658        assert!((system_time_to_unix(time) - 42.5).abs() < f64::EPSILON);
659    }
660
661    #[test]
662    fn system_time_to_unix_preserves_times_before_epoch() {
663        let time = UNIX_EPOCH - Duration::from_secs_f64(12.5);
664
665        assert!((system_time_to_unix(time) + 12.5).abs() < f64::EPSILON);
666    }
667
668    #[test]
669    fn decode_trust_date_parses_positive_unix_seconds() {
670        let time = decode_trust_date(Value::Date(42.5)).unwrap();
671
672        assert_eq!(time, UNIX_EPOCH + Duration::from_secs_f64(42.5));
673    }
674
675    #[test]
676    fn decode_trust_date_parses_negative_unix_seconds() {
677        let time = decode_trust_date(Value::Date(-12.5)).unwrap();
678
679        assert_eq!(time, UNIX_EPOCH - Duration::from_secs_f64(12.5));
680    }
681
682    #[test]
683    fn decode_trust_date_requires_unix_field() {
684        assert!(matches!(
685            decode_trust_date(Value::Integer(1)).unwrap_err(),
686            SecurityError::UnexpectedType {
687                operation: "security_trust_get_verify_time",
688                expected: "date",
689            }
690        ));
691    }
692}