1use crate::Value;
2use std::collections::BTreeMap;
3use std::ffi::c_void;
4use std::path::{Path, PathBuf};
5
6use crate::bridge;
7use crate::error::{Result, SecurityError};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10#[repr(transparent)]
11#[must_use]
12pub struct CodeSigningFlags(u32);
14
15impl CodeSigningFlags {
16 pub const CHECK_ALL_ARCHITECTURES: Self = Self(1 << 0);
18 pub const DO_NOT_VALIDATE_EXECUTABLE: Self = Self(1 << 1);
20 pub const DO_NOT_VALIDATE_RESOURCES: Self = Self(1 << 2);
22 pub const BASIC_VALIDATE_ONLY: Self =
24 Self(Self::DO_NOT_VALIDATE_EXECUTABLE.0 | Self::DO_NOT_VALIDATE_RESOURCES.0);
25 pub const CHECK_NESTED_CODE: Self = Self(1 << 3);
27 pub const STRICT_VALIDATE: Self = Self(1 << 4);
29 pub const FULL_REPORT: Self = Self(1 << 5);
31 pub const CHECK_GATEKEEPER_ARCHITECTURES: Self =
33 Self((1 << 6) | Self::CHECK_ALL_ARCHITECTURES.0);
34 pub const RESTRICT_SYMLINKS: Self = Self(1 << 7);
36 pub const RESTRICT_TO_APP_LIKE: Self = Self(1 << 8);
38 pub const RESTRICT_SIDEBAND_DATA: Self = Self(1 << 9);
40 pub const USE_SOFTWARE_SIGNING_CERT: Self = Self(1 << 10);
42 pub const VALIDATE_PEH: Self = Self(1 << 11);
44 pub const SINGLE_THREADED: Self = Self(1 << 12);
46 pub const ALLOW_NETWORK_ACCESS: Self = Self(1 << 16);
48 pub const FAST_EXECUTABLE_VALIDATION: Self = Self(1 << 17);
50 pub const CHECK_TRUSTED_ANCHORS: Self = Self(1 << 27);
51 pub const NO_NETWORK_ACCESS: Self = Self(1 << 29);
52 pub const ENFORCE_REVOCATION_CHECKS: Self = Self(1 << 30);
53 pub const CONSIDER_EXPIRATION: Self = Self(1 << 31);
54
55 pub const fn empty() -> Self {
56 Self(0)
57 }
58 pub const fn all() -> Self {
59 Self(0xe803_1fff)
60 }
61 pub const fn bits(self) -> u32 {
62 self.0
63 }
64 pub const fn from_bits(bits: u32) -> Option<Self> {
65 if bits & !Self::all().0 == 0 {
66 Some(Self(bits))
67 } else {
68 None
69 }
70 }
71 pub const fn from_bits_retain(bits: u32) -> Self {
72 Self(bits)
73 }
74 pub const fn from_bits_truncate(bits: u32) -> Self {
75 Self(bits & Self::all().0)
76 }
77 pub const fn is_empty(self) -> bool {
78 self.0 == 0
79 }
80 pub const fn is_all(self) -> bool {
81 self.0 & Self::all().0 == Self::all().0
82 }
83 pub const fn contains(self, other: Self) -> bool {
84 self.0 & other.0 == other.0
85 }
86 pub const fn intersects(self, other: Self) -> bool {
87 self.0 & other.0 != 0
88 }
89 pub const fn union(self, other: Self) -> Self {
90 Self(self.0 | other.0)
91 }
92 pub const fn intersection(self, other: Self) -> Self {
93 Self(self.0 & other.0)
94 }
95 pub const fn difference(self, other: Self) -> Self {
96 Self(self.0 & !other.0)
97 }
98 pub const fn symmetric_difference(self, other: Self) -> Self {
99 Self(self.0 ^ other.0)
100 }
101 pub const fn complement(self) -> Self {
102 Self(!self.0 & Self::all().0)
103 }
104 pub fn insert(&mut self, other: Self) {
105 self.0 |= other.0;
106 }
107 pub fn remove(&mut self, other: Self) {
108 self.0 &= !other.0;
109 }
110 pub fn toggle(&mut self, other: Self) {
111 self.0 ^= other.0;
112 }
113 pub fn set(&mut self, other: Self, value: bool) {
114 if value {
115 self.0 |= other.0;
116 } else {
117 self.0 &= !other.0;
118 }
119 }
120}
121
122impl std::ops::BitOr for CodeSigningFlags {
123 type Output = Self;
124 fn bitor(self, rhs: Self) -> Self {
125 Self(self.0 | rhs.0)
126 }
127}
128impl std::ops::BitAnd for CodeSigningFlags {
129 type Output = Self;
130 fn bitand(self, rhs: Self) -> Self {
131 Self(self.0 & rhs.0)
132 }
133}
134impl std::ops::BitXor for CodeSigningFlags {
135 type Output = Self;
136 fn bitxor(self, rhs: Self) -> Self {
137 Self(self.0 ^ rhs.0)
138 }
139}
140impl std::ops::Sub for CodeSigningFlags {
141 type Output = Self;
142 fn sub(self, rhs: Self) -> Self {
143 Self(self.0 & !rhs.0)
144 }
145}
146impl std::ops::Not for CodeSigningFlags {
147 type Output = Self;
148 fn not(self) -> Self {
149 Self(!self.0 & Self::all().0)
150 }
151}
152impl std::ops::BitOrAssign for CodeSigningFlags {
153 fn bitor_assign(&mut self, rhs: Self) {
154 self.0 |= rhs.0;
155 }
156}
157impl std::ops::BitAndAssign for CodeSigningFlags {
158 fn bitand_assign(&mut self, rhs: Self) {
159 self.0 &= rhs.0;
160 }
161}
162impl std::ops::BitXorAssign for CodeSigningFlags {
163 fn bitxor_assign(&mut self, rhs: Self) {
164 self.0 ^= rhs.0;
165 }
166}
167impl std::ops::SubAssign for CodeSigningFlags {
168 fn sub_assign(&mut self, rhs: Self) {
169 self.0 &= !rhs.0;
170 }
171}
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
174#[repr(transparent)]
175#[must_use]
176pub struct CodeStatus(u32);
177
178impl CodeStatus {
179 pub const VALID: Self = Self(0x0000_0001);
180 pub const HARD: Self = Self(0x0000_0100);
181 pub const KILL: Self = Self(0x0000_0200);
182 pub const PLATFORM: Self = Self(0x0400_0000);
183 pub const DEBUGGED: Self = Self(0x1000_0000);
184
185 pub const fn empty() -> Self {
186 Self(0)
187 }
188 pub const fn all() -> Self {
189 Self(0x1400_0301)
190 }
191 pub const fn bits(self) -> u32 {
192 self.0
193 }
194 pub const fn from_bits(bits: u32) -> Option<Self> {
195 if bits & !Self::all().0 == 0 {
196 Some(Self(bits))
197 } else {
198 None
199 }
200 }
201 pub const fn from_bits_retain(bits: u32) -> Self {
202 Self(bits)
203 }
204 pub const fn from_bits_truncate(bits: u32) -> Self {
205 Self(bits & Self::all().0)
206 }
207 pub const fn is_empty(self) -> bool {
208 self.0 == 0
209 }
210 pub const fn is_all(self) -> bool {
211 self.0 & Self::all().0 == Self::all().0
212 }
213 pub const fn contains(self, other: Self) -> bool {
214 self.0 & other.0 == other.0
215 }
216 pub const fn intersects(self, other: Self) -> bool {
217 self.0 & other.0 != 0
218 }
219 pub const fn union(self, other: Self) -> Self {
220 Self(self.0 | other.0)
221 }
222 pub const fn intersection(self, other: Self) -> Self {
223 Self(self.0 & other.0)
224 }
225 pub const fn difference(self, other: Self) -> Self {
226 Self(self.0 & !other.0)
227 }
228 pub const fn symmetric_difference(self, other: Self) -> Self {
229 Self(self.0 ^ other.0)
230 }
231 pub const fn complement(self) -> Self {
232 Self(!self.0 & Self::all().0)
233 }
234 pub fn insert(&mut self, other: Self) {
235 self.0 |= other.0;
236 }
237 pub fn remove(&mut self, other: Self) {
238 self.0 &= !other.0;
239 }
240 pub fn toggle(&mut self, other: Self) {
241 self.0 ^= other.0;
242 }
243 pub fn set(&mut self, other: Self, value: bool) {
244 if value {
245 self.0 |= other.0;
246 } else {
247 self.0 &= !other.0;
248 }
249 }
250}
251
252impl std::ops::BitOr for CodeStatus {
253 type Output = Self;
254 fn bitor(self, rhs: Self) -> Self {
255 Self(self.0 | rhs.0)
256 }
257}
258impl std::ops::BitAnd for CodeStatus {
259 type Output = Self;
260 fn bitand(self, rhs: Self) -> Self {
261 Self(self.0 & rhs.0)
262 }
263}
264impl std::ops::BitXor for CodeStatus {
265 type Output = Self;
266 fn bitxor(self, rhs: Self) -> Self {
267 Self(self.0 ^ rhs.0)
268 }
269}
270impl std::ops::Sub for CodeStatus {
271 type Output = Self;
272 fn sub(self, rhs: Self) -> Self {
273 Self(self.0 & !rhs.0)
274 }
275}
276impl std::ops::Not for CodeStatus {
277 type Output = Self;
278 fn not(self) -> Self {
279 Self(!self.0 & Self::all().0)
280 }
281}
282impl std::ops::BitOrAssign for CodeStatus {
283 fn bitor_assign(&mut self, rhs: Self) {
284 self.0 |= rhs.0;
285 }
286}
287impl std::ops::BitAndAssign for CodeStatus {
288 fn bitand_assign(&mut self, rhs: Self) {
289 self.0 &= rhs.0;
290 }
291}
292impl std::ops::BitXorAssign for CodeStatus {
293 fn bitxor_assign(&mut self, rhs: Self) {
294 self.0 ^= rhs.0;
295 }
296}
297impl std::ops::SubAssign for CodeStatus {
298 fn sub_assign(&mut self, rhs: Self) {
299 self.0 &= !rhs.0;
300 }
301}
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
304pub struct AuditToken([u32; 8]);
305
306impl AuditToken {
307 pub const LEN: usize = 32;
308
309 pub const fn from_raw(values: [u32; 8]) -> Self {
310 Self(values)
311 }
312
313 pub const fn to_raw(self) -> [u32; 8] {
314 self.0
315 }
316
317 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
318 if bytes.len() != Self::LEN {
319 return Err(SecurityError::InvalidArgument(format!(
320 "an audit token is {} bytes, got {}",
321 Self::LEN,
322 bytes.len()
323 )));
324 }
325 let mut values = [0_u32; 8];
326 for (value, chunk) in values.iter_mut().zip(bytes.chunks_exact(4)) {
327 *value = u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
328 }
329 Ok(Self(values))
330 }
331
332 pub fn to_bytes(self) -> [u8; 32] {
333 let mut bytes = [0_u8; 32];
334 for (chunk, value) in bytes.chunks_exact_mut(4).zip(self.0) {
335 chunk.copy_from_slice(&value.to_ne_bytes());
336 }
337 bytes
338 }
339
340 pub fn current() -> Result<Self> {
341 let mut values = [0_u32; 8];
342 if unsafe { bridge::security_audit_token_copy_current(values.as_mut_ptr()) } {
343 Ok(Self(values))
344 } else {
345 Err(SecurityError::InvalidArgument(
346 "task_info(TASK_AUDIT_TOKEN) failed for the current task".to_owned(),
347 ))
348 }
349 }
350}
351
352#[derive(Debug, Clone, PartialEq, Eq)]
353#[non_exhaustive]
354pub enum SigningValue {
356 Boolean(bool),
358 Integer(i64),
360 String(String),
362 Data(Vec<u8>),
364 Array(Vec<Self>),
366 Dictionary(BTreeMap<String, Self>),
368 Unknown(String),
370}
371
372#[derive(Debug, Clone, PartialEq, Eq)]
373pub struct SigningInformation {
375 pub identifier: Option<String>,
377 pub team_identifier: Option<String>,
379 pub entitlements: BTreeMap<String, SigningValue>,
381 pub sandboxed: bool,
383 pub status: Option<u32>,
385}
386
387impl SigningInformation {
388 pub const fn is_signed(&self) -> bool {
390 self.identifier.is_some()
391 }
392
393 pub fn code_status(&self) -> Option<CodeStatus> {
394 self.status.map(CodeStatus::from_bits_retain)
395 }
396
397 fn from_value(value: &Value) -> Self {
398 let entitlements = find_object(
399 value,
400 &[
401 "entitlements-dict",
402 "EntitlementsDict",
403 "entitlements",
404 "Entitlements",
405 ],
406 );
407 Self {
408 identifier: find_string(value, &["identifier", "Identifier"]),
409 team_identifier: find_string(value, &["teamid", "TeamIdentifier", "teamIdentifier"]),
410 entitlements: entitlements.map(signing_dictionary).unwrap_or_default(),
411 sandboxed: matches!(
412 entitlements.and_then(|value| value.get("com.apple.security.app-sandbox")),
413 Some(Value::Bool(true))
414 ),
415 status: find_integer(value, &["status", "Status"])
416 .and_then(|value| u32::try_from(value).ok()),
417 }
418 }
419}
420
421#[derive(Debug)]
422pub struct Code {
424 handle: bridge::Handle,
425}
426
427impl Code {
428 pub fn type_id() -> usize {
430 unsafe { bridge::security_code_get_type_id() }
431 }
432
433 pub fn current() -> Result<Self> {
435 let mut status = 0;
436 let mut error = std::ptr::null_mut();
437 let raw = unsafe { bridge::security_code_copy_self(&raw mut status, &raw mut error) };
438 bridge::required_handle("security_code_copy_self", raw, status, error)
439 .map(|handle| Self { handle })
440 }
441
442 pub fn host(&self) -> Result<Self> {
444 let mut status = 0;
445 let mut error = std::ptr::null_mut();
446 let raw = unsafe {
447 bridge::security_code_copy_host(self.handle.as_ptr(), &raw mut status, &raw mut error)
448 };
449 bridge::required_handle("security_code_copy_host", raw, status, error)
450 .map(|handle| Self { handle })
451 }
452
453 pub fn guest_with_attributes(
455 host: Option<&Self>,
456 attributes: Option<&Value>,
457 flags: CodeSigningFlags,
458 ) -> Result<Self> {
459 let attributes = attributes.map(bridge::InputValue::new).transpose()?;
460 let mut status = 0;
461 let mut error = std::ptr::null_mut();
462 let raw = unsafe {
463 bridge::security_code_copy_guest_with_attributes(
464 host.map_or(std::ptr::null_mut(), |value| value.handle.as_ptr()),
465 attributes
466 .as_ref()
467 .map_or(std::ptr::null(), bridge::InputValue::as_ptr),
468 flags.bits(),
469 &raw mut status,
470 &raw mut error,
471 )
472 };
473 bridge::required_handle(
474 "security_code_copy_guest_with_attributes",
475 raw,
476 status,
477 error,
478 )
479 .map(|handle| Self { handle })
480 }
481
482 pub fn static_code(&self) -> Result<StaticCode> {
484 let mut status = 0;
485 let mut error = std::ptr::null_mut();
486 let raw = unsafe {
487 bridge::security_code_copy_static_code(
488 self.handle.as_ptr(),
489 &raw mut status,
490 &raw mut error,
491 )
492 };
493 bridge::required_handle("security_code_copy_static_code", raw, status, error)
494 .map(StaticCode::from_handle)
495 }
496
497 pub fn guest_with_audit_token(audit_token: &AuditToken) -> Result<Self> {
498 let values = audit_token.to_raw();
499 let mut status = 0;
500 let mut error = std::ptr::null_mut();
501 let raw = unsafe {
502 bridge::security_code_copy_guest_with_audit_token(
503 values.as_ptr(),
504 &raw mut status,
505 &raw mut error,
506 )
507 };
508 bridge::required_handle(
509 "security_code_copy_guest_with_audit_token",
510 raw,
511 status,
512 error,
513 )
514 .map(|handle| Self { handle })
515 }
516
517 #[allow(clippy::missing_safety_doc)]
518 pub unsafe fn from_xpc_message(message: *mut c_void) -> Result<Self> {
519 if message.is_null() {
520 return Err(SecurityError::InvalidArgument(
521 "an XPC message object is required".to_owned(),
522 ));
523 }
524 let mut status = 0;
525 let mut error = std::ptr::null_mut();
526 let raw = unsafe {
527 bridge::security_code_create_with_xpc_message(message, &raw mut status, &raw mut error)
528 };
529 bridge::required_handle("security_code_create_with_xpc_message", raw, status, error)
530 .map(|handle| Self { handle })
531 }
532
533 pub fn audit_token(&self) -> Option<AuditToken> {
534 let mut values = [0_u32; 8];
535 unsafe { bridge::security_code_copy_audit_token(self.handle.as_ptr(), values.as_mut_ptr()) }
536 .then_some(AuditToken(values))
537 }
538
539 pub fn check_validity(
540 &self,
541 flags: CodeSigningFlags,
542 requirement: Option<&Requirement>,
543 ) -> Result<()> {
544 let mut error = std::ptr::null_mut();
545 let status = unsafe {
546 bridge::security_code_check_validity(
547 self.handle.as_ptr(),
548 flags.bits(),
549 requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
550 &raw mut error,
551 )
552 };
553 bridge::status_result("security_code_check_validity", status, error)
554 }
555
556 pub fn signing_information(&self) -> Result<SigningInformation> {
558 let mut status = 0;
559 let mut error = std::ptr::null_mut();
560 let raw = unsafe {
561 bridge::security_code_copy_signing_information(
562 self.handle.as_ptr(),
563 &raw mut status,
564 &raw mut error,
565 )
566 };
567 let value: Value =
568 bridge::required_value("security_code_copy_signing_information", raw, status, error)?;
569 Ok(SigningInformation::from_value(&value))
570 }
571
572 pub fn task(&self) -> Result<Task> {
574 let audit_token = self.audit_token().ok_or_else(|| {
575 SecurityError::Unsupported(
576 "this code object was not looked up by audit token, so its task cannot be \
577 identified without a PID race; use Code::guest_with_audit_token"
578 .to_owned(),
579 )
580 })?;
581 Task::from_audit_token(&audit_token)
582 }
583}
584
585#[derive(Debug)]
586pub struct Requirement {
588 handle: bridge::Handle,
589}
590
591impl Requirement {
592 fn from_handle(handle: bridge::Handle) -> Self {
593 Self { handle }
594 }
595
596 fn handle(&self) -> &bridge::Handle {
597 &self.handle
598 }
599
600 pub fn type_id() -> usize {
602 unsafe { bridge::security_requirement_get_type_id() }
603 }
604
605 pub fn from_data(data: &[u8]) -> Result<Self> {
607 let mut status = 0;
608 let mut error = std::ptr::null_mut();
609 let raw = unsafe {
610 bridge::security_requirement_create_with_data(
611 data.as_ptr().cast(),
612 bridge::len_to_isize(data.len())?,
613 &raw mut status,
614 &raw mut error,
615 )
616 };
617 bridge::required_handle("security_requirement_create_with_data", raw, status, error)
618 .map(Self::from_handle)
619 }
620
621 pub fn from_string(text: &str) -> Result<Self> {
623 let text = bridge::cstring(text)?;
624 let mut status = 0;
625 let mut error = std::ptr::null_mut();
626 let raw = unsafe {
627 bridge::security_requirement_create_with_string(
628 text.as_ptr(),
629 &raw mut status,
630 &raw mut error,
631 )
632 };
633 bridge::required_handle(
634 "security_requirement_create_with_string",
635 raw,
636 status,
637 error,
638 )
639 .map(Self::from_handle)
640 }
641
642 pub fn from_string_with_errors(text: &str) -> Result<Self> {
644 let text = bridge::cstring(text)?;
645 let mut status = 0;
646 let mut error = std::ptr::null_mut();
647 let raw = unsafe {
648 bridge::security_requirement_create_with_string_and_errors(
649 text.as_ptr(),
650 &raw mut status,
651 &raw mut error,
652 )
653 };
654 bridge::required_handle(
655 "security_requirement_create_with_string_and_errors",
656 raw,
657 status,
658 error,
659 )
660 .map(Self::from_handle)
661 }
662
663 pub fn data(&self) -> Result<Vec<u8>> {
665 let mut status = 0;
666 let mut error = std::ptr::null_mut();
667 let raw = unsafe {
668 bridge::security_requirement_copy_data(
669 self.handle.as_ptr(),
670 &raw mut status,
671 &raw mut error,
672 )
673 };
674 bridge::required_data("security_requirement_copy_data", raw, status, error)
675 }
676
677 pub fn string(&self) -> Result<String> {
679 let mut status = 0;
680 let mut error = std::ptr::null_mut();
681 let raw = unsafe {
682 bridge::security_requirement_copy_string(
683 self.handle.as_ptr(),
684 &raw mut status,
685 &raw mut error,
686 )
687 };
688 bridge::required_string("security_requirement_copy_string", raw, status, error)
689 }
690}
691
692#[derive(Debug)]
693pub struct StaticCode {
695 handle: bridge::Handle,
696}
697
698impl StaticCode {
699 fn from_handle(handle: bridge::Handle) -> Self {
700 Self { handle }
701 }
702
703 pub fn type_id() -> usize {
705 unsafe { bridge::security_static_code_get_type_id() }
706 }
707
708 pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
710 let path = bridge::cstring(&path.as_ref().to_string_lossy())?;
711 let mut status = 0;
712 let mut error = std::ptr::null_mut();
713 let raw = unsafe {
714 bridge::security_static_code_create_with_path(
715 path.as_ptr(),
716 &raw mut status,
717 &raw mut error,
718 )
719 };
720 bridge::required_handle("security_static_code_create_with_path", raw, status, error)
721 .map(Self::from_handle)
722 }
723
724 pub fn from_path_with_attributes(path: impl AsRef<Path>, attributes: &Value) -> Result<Self> {
726 let path = bridge::cstring(&path.as_ref().to_string_lossy())?;
727 let attributes = bridge::InputValue::new(attributes)?;
728 let mut status = 0;
729 let mut error = std::ptr::null_mut();
730 let raw = unsafe {
731 bridge::security_static_code_create_with_path_and_attributes(
732 path.as_ptr(),
733 attributes.as_ptr(),
734 &raw mut status,
735 &raw mut error,
736 )
737 };
738 bridge::required_handle(
739 "security_static_code_create_with_path_and_attributes",
740 raw,
741 status,
742 error,
743 )
744 .map(Self::from_handle)
745 }
746
747 pub fn check_validity(&self) -> Result<()> {
749 let mut error = std::ptr::null_mut();
750 let status = unsafe {
751 bridge::security_static_code_check_static_validity_with_errors(
752 self.handle.as_ptr(),
753 CodeSigningFlags::empty().bits(),
754 std::ptr::null_mut(),
755 &raw mut error,
756 )
757 };
758 bridge::status_result(
759 "security_static_code_check_static_validity_with_errors",
760 status,
761 error,
762 )
763 }
764
765 pub fn check_validity_with_errors(
767 &self,
768 flags: CodeSigningFlags,
769 requirement: Option<&Requirement>,
770 ) -> Result<()> {
771 let mut error = std::ptr::null_mut();
772 let status = unsafe {
773 bridge::security_static_code_check_static_validity_with_errors(
774 self.handle.as_ptr(),
775 flags.bits(),
776 requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
777 &raw mut error,
778 )
779 };
780 bridge::status_result(
781 "security_static_code_check_static_validity_with_errors",
782 status,
783 error,
784 )
785 }
786
787 pub fn check_static_validity(
789 &self,
790 flags: CodeSigningFlags,
791 requirement: Option<&Requirement>,
792 ) -> Result<()> {
793 let mut error = std::ptr::null_mut();
794 let status = unsafe {
795 bridge::security_static_code_check_static_validity(
796 self.handle.as_ptr(),
797 flags.bits(),
798 requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
799 &raw mut error,
800 )
801 };
802 bridge::status_result("security_static_code_check_static_validity", status, error)
803 }
804
805 pub fn check_static_validity_with_errors(
807 &self,
808 flags: CodeSigningFlags,
809 requirement: Option<&Requirement>,
810 ) -> Result<()> {
811 let mut error = std::ptr::null_mut();
812 let status = unsafe {
813 bridge::security_static_code_check_static_validity_with_errors(
814 self.handle.as_ptr(),
815 flags.bits(),
816 requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
817 &raw mut error,
818 )
819 };
820 bridge::status_result(
821 "security_static_code_check_static_validity_with_errors",
822 status,
823 error,
824 )
825 }
826
827 pub fn path(&self) -> Result<PathBuf> {
829 let mut status = 0;
830 let mut error = std::ptr::null_mut();
831 let raw = unsafe {
832 bridge::security_static_code_copy_path(
833 self.handle.as_ptr(),
834 &raw mut status,
835 &raw mut error,
836 )
837 };
838 bridge::required_string("security_static_code_copy_path", raw, status, error)
839 .map(PathBuf::from)
840 }
841
842 pub fn designated_requirement(&self) -> Result<String> {
844 let mut status = 0;
845 let mut error = std::ptr::null_mut();
846 let raw = unsafe {
847 bridge::security_static_code_copy_designated_requirement(
848 self.handle.as_ptr(),
849 &raw mut status,
850 &raw mut error,
851 )
852 };
853 bridge::required_string(
854 "security_static_code_copy_designated_requirement",
855 raw,
856 status,
857 error,
858 )
859 }
860
861 pub fn signing_information(&self) -> Result<SigningInformation> {
863 let mut status = 0;
864 let mut error = std::ptr::null_mut();
865 let raw = unsafe {
866 bridge::security_static_code_copy_signing_information(
867 self.handle.as_ptr(),
868 &raw mut status,
869 &raw mut error,
870 )
871 };
872 let value: Value = bridge::required_value(
873 "security_static_code_copy_signing_information",
874 raw,
875 status,
876 error,
877 )?;
878 Ok(SigningInformation::from_value(&value))
879 }
880
881 pub fn validate_file_resource(
883 &self,
884 relative_path: &str,
885 data: &[u8],
886 flags: CodeSigningFlags,
887 ) -> Result<()> {
888 let relative_path = bridge::cstring(relative_path)?;
889 let mut error = std::ptr::null_mut();
890 let status = unsafe {
891 bridge::security_static_code_validate_file_resource(
892 self.handle.as_ptr(),
893 relative_path.as_ptr(),
894 data.as_ptr().cast(),
895 bridge::len_to_isize(data.len())?,
896 flags.bits(),
897 &raw mut error,
898 )
899 };
900 bridge::status_result("security_static_code_validate_file_resource", status, error)
901 }
902
903 pub fn map_memory(&self, flags: CodeSigningFlags) -> Result<()> {
905 let mut error = std::ptr::null_mut();
906 let status = unsafe {
907 bridge::security_static_code_map_memory(
908 self.handle.as_ptr(),
909 flags.bits(),
910 &raw mut error,
911 )
912 };
913 bridge::status_result("security_static_code_map_memory", status, error)
914 }
915}
916
917#[derive(Debug)]
918pub struct Task {
920 handle: bridge::Handle,
921}
922
923impl Task {
924 pub fn type_id() -> usize {
926 unsafe { bridge::security_task_get_type_id() }
927 }
928
929 pub fn current() -> Result<Self> {
931 let mut status = 0;
932 let mut error = std::ptr::null_mut();
933 let raw =
934 unsafe { bridge::security_task_create_from_self(&raw mut status, &raw mut error) };
935 bridge::required_handle("security_task_create_from_self", raw, status, error)
936 .map(|handle| Self { handle })
937 }
938
939 pub fn from_audit_token(audit_token: &AuditToken) -> Result<Self> {
940 let values = audit_token.to_raw();
941 let mut status = 0;
942 let mut error = std::ptr::null_mut();
943 let raw = unsafe {
944 bridge::security_task_create_with_audit_token(
945 values.as_ptr(),
946 &raw mut status,
947 &raw mut error,
948 )
949 };
950 bridge::required_handle("security_task_create_with_audit_token", raw, status, error)
951 .map(|handle| Self { handle })
952 }
953
954 pub fn current_with_audit_token() -> Result<Self> {
956 let mut status = 0;
957 let mut error = std::ptr::null_mut();
958 let raw = unsafe {
959 bridge::security_task_create_from_current_audit_token(&raw mut status, &raw mut error)
960 };
961 bridge::required_handle(
962 "security_task_create_from_current_audit_token",
963 raw,
964 status,
965 error,
966 )
967 .map(|handle| Self { handle })
968 }
969
970 pub fn signing_identifier(&self) -> Result<Option<String>> {
972 let mut status = 0;
973 let mut error = std::ptr::null_mut();
974 let raw = unsafe {
975 bridge::security_task_copy_signing_identifier(
976 self.handle.as_ptr(),
977 &raw mut status,
978 &raw mut error,
979 )
980 };
981 if raw.is_null() && status == 0 {
982 Ok(None)
983 } else {
984 bridge::required_string("security_task_copy_signing_identifier", raw, status, error)
985 .map(Some)
986 }
987 }
988
989 pub fn entitlement(&self, entitlement: &str) -> Result<Option<Value>> {
991 let entitlement = bridge::cstring(entitlement)?;
992 let mut status = 0;
993 let mut error = std::ptr::null_mut();
994 let raw = unsafe {
995 bridge::security_task_copy_value_for_entitlement(
996 self.handle.as_ptr(),
997 entitlement.as_ptr(),
998 &raw mut status,
999 &raw mut error,
1000 )
1001 };
1002 if raw.is_null() && status == 0 {
1003 return Ok(None);
1004 }
1005 let value: Value = bridge::required_value(
1006 "security_task_copy_value_for_entitlement",
1007 raw,
1008 status,
1009 error,
1010 )?;
1011 Ok(Some(value))
1012 }
1013
1014 pub fn entitlements(&self, entitlements: &[&str]) -> Result<Value> {
1016 let entitlements = bridge::InputValue::strings(entitlements)?;
1017 let mut status = 0;
1018 let mut error = std::ptr::null_mut();
1019 let raw = unsafe {
1020 bridge::security_task_copy_values_for_entitlements(
1021 self.handle.as_ptr(),
1022 entitlements.as_ptr(),
1023 &raw mut status,
1024 &raw mut error,
1025 )
1026 };
1027 bridge::required_value(
1028 "security_task_copy_values_for_entitlements",
1029 raw,
1030 status,
1031 error,
1032 )
1033 }
1034}
1035
1036fn find_object<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a BTreeMap<String, Value>> {
1037 keys.iter()
1038 .find_map(|key| value.get(key))
1039 .and_then(Value::as_object)
1040}
1041
1042fn find_string(value: &Value, keys: &[&str]) -> Option<String> {
1043 keys.iter()
1044 .find_map(|key| value.get(key))
1045 .and_then(Value::as_str)
1046 .map(ToOwned::to_owned)
1047}
1048
1049fn find_integer(value: &Value, keys: &[&str]) -> Option<i64> {
1050 keys.iter()
1051 .find_map(|key| value.get(key))
1052 .and_then(Value::as_i64)
1053}
1054
1055fn signing_dictionary(object: &BTreeMap<String, Value>) -> BTreeMap<String, SigningValue> {
1056 object
1057 .iter()
1058 .map(|(key, value)| (key.clone(), signing_value(value)))
1059 .collect()
1060}
1061
1062#[allow(
1063 clippy::cast_possible_truncation,
1064 clippy::cast_precision_loss,
1065 clippy::float_cmp
1066)]
1067fn signing_value(value: &Value) -> SigningValue {
1068 match value {
1069 Value::Bool(value) => SigningValue::Boolean(*value),
1070 Value::Integer(value) => SigningValue::Integer(*value),
1071 Value::Unsigned(value) => i64::try_from(*value).map_or_else(
1072 |_| SigningValue::Unknown(value.to_string()),
1073 SigningValue::Integer,
1074 ),
1075 Value::Real(value) => {
1076 let integer = *value as i64;
1077 if *value < 9_223_372_036_854_775_808.0 && integer as f64 == *value {
1078 SigningValue::Integer(integer)
1079 } else {
1080 SigningValue::Unknown(value.to_string())
1081 }
1082 }
1083 Value::Date(value) => SigningValue::Dictionary(BTreeMap::from([
1084 ("_type".to_owned(), SigningValue::String("date".to_owned())),
1085 ("unix".to_owned(), signing_value(&Value::Real(*value))),
1086 ])),
1087 Value::String(value) => SigningValue::String(value.clone()),
1088 Value::Url(value) => SigningValue::Dictionary(BTreeMap::from([
1089 ("_type".to_owned(), SigningValue::String("url".to_owned())),
1090 ("value".to_owned(), SigningValue::String(value.clone())),
1091 ])),
1092 Value::Data(value) => SigningValue::Data(value.clone()),
1093 Value::Array(values) => SigningValue::Array(values.iter().map(signing_value).collect()),
1094 Value::Object(object) => SigningValue::Dictionary(signing_dictionary(object)),
1095 Value::Null => SigningValue::Unknown("null".to_owned()),
1096 }
1097}