Skip to main content

security/
policy.rs

1use crate::Value;
2
3use crate::bridge::{self, Handle};
4use crate::error::{Result, SecurityError};
5
6/// Mirrors `SecRevocationFlags`.
7pub type RevocationFlags = u32;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10/// Mirrors named `SecPolicyCreate*` policy selectors.
11pub enum PolicyIdentifier {
12    /// Mirrors a named `SecPolicyCreate*` selector.
13    AppleX509Basic,
14    /// Mirrors a named `SecPolicyCreate*` selector.
15    AppleSsl,
16    /// Mirrors a named `SecPolicyCreate*` selector.
17    AppleSmime,
18    /// Mirrors a named `SecPolicyCreate*` selector.
19    AppleEap,
20    /// Mirrors a named `SecPolicyCreate*` selector.
21    AppleIpsec,
22    /// Mirrors a named `SecPolicyCreate*` selector.
23    ApplePkinitClient,
24    /// Mirrors a named `SecPolicyCreate*` selector.
25    ApplePkinitServer,
26    /// Mirrors a named `SecPolicyCreate*` selector.
27    AppleCodeSigning,
28    /// Mirrors a named `SecPolicyCreate*` selector.
29    MacAppStoreReceipt,
30    /// Mirrors a named `SecPolicyCreate*` selector.
31    AppleIdValidation,
32    /// Mirrors a named `SecPolicyCreate*` selector.
33    AppleTimeStamping,
34    /// Mirrors a named `SecPolicyCreate*` selector.
35    AppleRevocation,
36    /// Mirrors a named `SecPolicyCreate*` selector.
37    ApplePassbookSigning,
38    /// Mirrors a named `SecPolicyCreate*` selector.
39    ApplePayIssuerEncryption,
40    /// Mirrors a named `SecPolicyCreate*` selector.
41    AppleSslServer,
42    /// Mirrors a named `SecPolicyCreate*` selector.
43    AppleSslClient,
44    /// Mirrors a named `SecPolicyCreate*` selector.
45    AppleEapServer,
46    /// Mirrors a named `SecPolicyCreate*` selector.
47    AppleEapClient,
48    /// Mirrors a named `SecPolicyCreate*` selector.
49    AppleIpsecServer,
50    /// Mirrors a named `SecPolicyCreate*` selector.
51    AppleIpsecClient,
52}
53
54impl PolicyIdentifier {
55    const fn as_bridge_name(self) -> &'static str {
56        match self {
57            Self::AppleX509Basic => "apple_x509_basic",
58            Self::AppleSsl => "apple_ssl",
59            Self::AppleSmime => "apple_smime",
60            Self::AppleEap => "apple_eap",
61            Self::AppleIpsec => "apple_ipsec",
62            Self::ApplePkinitClient => "apple_pkinit_client",
63            Self::ApplePkinitServer => "apple_pkinit_server",
64            Self::AppleCodeSigning => "apple_code_signing",
65            Self::MacAppStoreReceipt => "mac_app_store_receipt",
66            Self::AppleIdValidation => "apple_id_validation",
67            Self::AppleTimeStamping => "apple_time_stamping",
68            Self::AppleRevocation => "apple_revocation",
69            Self::ApplePassbookSigning => "apple_passbook_signing",
70            Self::ApplePayIssuerEncryption => "apple_pay_issuer_encryption",
71            Self::AppleSslServer => "apple_ssl_server",
72            Self::AppleSslClient => "apple_ssl_client",
73            Self::AppleEapServer => "apple_eap_server",
74            Self::AppleEapClient => "apple_eap_client",
75            Self::AppleIpsecServer => "apple_ipsec_server",
76            Self::AppleIpsecClient => "apple_ipsec_client",
77        }
78    }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
82/// Mirrors name inputs passed to `SecPolicyCreateWithProperties`.
83pub enum PolicyName {
84    /// Mirrors a name form accepted by `SecPolicyCreateWithProperties`.
85    Single(String),
86    /// Mirrors a name form accepted by `SecPolicyCreateWithProperties`.
87    Multiple(Vec<String>),
88}
89
90impl From<String> for PolicyName {
91    fn from(value: String) -> Self {
92        Self::Single(value)
93    }
94}
95
96impl From<&str> for PolicyName {
97    fn from(value: &str) -> Self {
98        Self::Single(value.to_owned())
99    }
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Default)]
103/// Mirrors the property dictionary passed to `SecPolicyCreateWithProperties`.
104pub struct PolicyProperties {
105    /// Mirrors a property accepted by `SecPolicyCreateWithProperties`.
106    pub name: Option<PolicyName>,
107    /// Mirrors a property accepted by `SecPolicyCreateWithProperties`.
108    pub client: Option<bool>,
109    /// Mirrors a property accepted by `SecPolicyCreateWithProperties`.
110    pub revocation_flags: Option<RevocationFlags>,
111    /// Mirrors a property accepted by `SecPolicyCreateWithProperties`.
112    pub team_identifier: Option<String>,
113}
114
115impl PolicyProperties {
116    const fn is_empty(&self) -> bool {
117        self.name.is_none()
118            && self.client.is_none()
119            && self.revocation_flags.is_none()
120            && self.team_identifier.is_none()
121    }
122}
123
124#[derive(Debug)]
125/// Wraps `SecPolicyRef`.
126pub struct Policy {
127    handle: Handle,
128}
129
130impl Policy {
131    /// Wraps the corresponding `SecPolicyRef` operation.
132    pub fn type_id() -> usize {
133        unsafe { bridge::security_policy_get_type_id() }
134    }
135
136    pub(crate) fn from_handle(handle: Handle) -> Self {
137        Self { handle }
138    }
139
140    pub(crate) fn handle(&self) -> &Handle {
141        &self.handle
142    }
143
144    /// Wraps the corresponding `SecPolicyRef` operation.
145    pub fn basic_x509() -> Result<Self> {
146        let mut status = 0;
147        let mut error = std::ptr::null_mut();
148        let raw =
149            unsafe { bridge::security_policy_create_basic_x509(&raw mut status, &raw mut error) };
150        bridge::required_handle("security_policy_create_basic_x509", raw, status, error)
151            .map(Self::from_handle)
152    }
153
154    /// Wraps `SecPolicyCreateSSL` and requires the leaf certificate to be valid for `hostname`.
155    pub fn ssl(server: bool, hostname: &str) -> Result<Self> {
156        if hostname.is_empty() {
157            return Err(SecurityError::InvalidArgument(
158                "an SSL policy needs a hostname; Policy::ssl_any_hostname skips the check"
159                    .to_owned(),
160            ));
161        }
162        let hostname = bridge::cstring(hostname)?;
163        let mut status = 0;
164        let mut error = std::ptr::null_mut();
165        let raw = unsafe {
166            bridge::security_policy_create_ssl(
167                server,
168                hostname.as_ptr(),
169                &raw mut status,
170                &raw mut error,
171            )
172        };
173        bridge::required_handle("security_policy_create_ssl", raw, status, error)
174            .map(Self::from_handle)
175    }
176
177    pub fn ssl_any_hostname(server: bool) -> Result<Self> {
178        let mut status = 0;
179        let mut error = std::ptr::null_mut();
180        let raw = unsafe {
181            bridge::security_policy_create_ssl(
182                server,
183                std::ptr::null(),
184                &raw mut status,
185                &raw mut error,
186            )
187        };
188        bridge::required_handle("security_policy_create_ssl", raw, status, error)
189            .map(Self::from_handle)
190    }
191
192    /// Wraps the corresponding `SecPolicyRef` operation.
193    pub fn revocation(flags: RevocationFlags) -> Result<Self> {
194        let mut status = 0;
195        let mut error = std::ptr::null_mut();
196        let raw = unsafe {
197            bridge::security_policy_create_revocation(flags, &raw mut status, &raw mut error)
198        };
199        bridge::required_handle("security_policy_create_revocation", raw, status, error)
200            .map(Self::from_handle)
201    }
202
203    /// Wraps the corresponding `SecPolicyRef` operation.
204    pub fn with_properties(
205        identifier: PolicyIdentifier,
206        properties: &PolicyProperties,
207    ) -> Result<Self> {
208        let identifier = bridge::cstring(identifier.as_bridge_name())?;
209        let properties = if properties.is_empty() {
210            None
211        } else {
212            let mut values = std::collections::BTreeMap::new();
213            if let Some(name) = &properties.name {
214                let name = match name {
215                    PolicyName::Single(value) => Value::String(value.clone()),
216                    PolicyName::Multiple(values) => {
217                        Value::Array(values.iter().cloned().map(Value::String).collect())
218                    }
219                };
220                values.insert("name".to_owned(), name);
221            }
222            if let Some(client) = properties.client {
223                values.insert("client".to_owned(), Value::Bool(client));
224            }
225            if let Some(flags) = properties.revocation_flags {
226                values.insert(
227                    "revocation_flags".to_owned(),
228                    Value::Unsigned(u64::from(flags)),
229                );
230            }
231            if let Some(identifier) = &properties.team_identifier {
232                values.insert(
233                    "team_identifier".to_owned(),
234                    Value::String(identifier.clone()),
235                );
236            }
237            Some(bridge::InputValue::new(&Value::Object(values))?)
238        };
239        let mut status = 0;
240        let mut error = std::ptr::null_mut();
241        let raw = unsafe {
242            bridge::security_policy_create_with_properties(
243                identifier.as_ptr(),
244                properties
245                    .as_ref()
246                    .map_or(std::ptr::null(), bridge::InputValue::as_ptr),
247                &raw mut status,
248                &raw mut error,
249            )
250        };
251        bridge::required_handle("security_policy_create_with_properties", raw, status, error)
252            .map(Self::from_handle)
253    }
254
255    /// Wraps the corresponding `SecPolicyRef` operation.
256    pub fn properties(&self) -> Result<Value> {
257        let mut status = 0;
258        let mut error = std::ptr::null_mut();
259        let raw = unsafe {
260            bridge::security_policy_copy_properties(
261                self.handle.as_ptr(),
262                &raw mut status,
263                &raw mut error,
264            )
265        };
266        bridge::required_value("security_policy_copy_properties", raw, status, error)
267    }
268}