1use crate::base::{Error, Result};
9#[cfg(all(target_os = "macos", feature = "job-bless"))]
10use core_foundation::base::Boolean;
11use core_foundation::base::{CFTypeRef, TCFType};
12use core_foundation::bundle::CFBundleRef;
13use core_foundation::dictionary::{CFDictionary, CFDictionaryRef};
14#[cfg(all(target_os = "macos", feature = "job-bless"))]
15use core_foundation::error::CFError;
16#[cfg(all(target_os = "macos", feature = "job-bless"))]
17use core_foundation::error::CFErrorRef;
18use core_foundation::string::{CFString, CFStringRef};
19use security_framework_sys::authorization as sys;
20use security_framework_sys::base::errSecConversionError;
21use std::ffi::{CStr, CString};
22use std::fs::File;
23use std::marker::PhantomData;
24use std::mem::MaybeUninit;
25use std::os::raw::c_void;
26use std::ptr::addr_of;
27use sys::AuthorizationExternalForm;
28
29macro_rules! optional_str_to_cfref {
30 ($string:ident) => {{
31 $string
32 .map(CFString::new)
33 .map_or(std::ptr::null(), |cfs| cfs.as_concrete_TypeRef())
34 }};
35}
36
37macro_rules! cstring_or_err {
38 ($x:expr) => {{
39 CString::new($x).map_err(|_| Error::from_code(errSecConversionError))
40 }};
41}
42
43bitflags::bitflags! {
44 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46 pub struct Flags: sys::AuthorizationFlags {
47 const DEFAULTS = sys::kAuthorizationFlagDefaults;
50
51 const INTERACTION_ALLOWED = sys::kAuthorizationFlagInteractionAllowed;
53
54 const EXTEND_RIGHTS = sys::kAuthorizationFlagExtendRights;
57
58 const PARTIAL_RIGHTS = sys::kAuthorizationFlagPartialRights;
61
62 const DESTROY_RIGHTS = sys::kAuthorizationFlagDestroyRights;
64
65 const PREAUTHORIZE = sys::kAuthorizationFlagPreAuthorize;
68 }
69}
70
71impl Default for Flags {
72 #[inline(always)]
73 fn default() -> Self {
74 Self::DEFAULTS
75 }
76}
77
78#[repr(C)]
80pub struct AuthorizationItem(sys::AuthorizationItem);
81
82impl AuthorizationItem {
83 #[must_use]
88 pub fn name(&self) -> &str {
89 unsafe {
90 CStr::from_ptr(self.0.name)
91 .to_str()
92 .expect("AuthorizationItem::name failed to convert &str to CStr")
93 }
94 }
95
96 #[inline]
99 #[must_use]
100 pub fn value(&self) -> Option<&[u8]> {
101 if self.0.value.is_null() {
102 return None;
103 }
104
105 let value = unsafe { std::slice::from_raw_parts(self.0.value as *const u8, self.0.valueLength) };
106
107 Some(value)
108 }
109}
110
111#[derive(Debug)]
113#[repr(C)]
114pub struct AuthorizationItemSet<'a> {
115 inner: *const sys::AuthorizationItemSet,
116 phantom: PhantomData<&'a sys::AuthorizationItemSet>,
117}
118
119impl Drop for AuthorizationItemSet<'_> {
120 #[inline]
121 fn drop(&mut self) {
122 unsafe {
123 sys::AuthorizationFreeItemSet(self.inner.cast_mut());
124 }
125 }
126}
127
128#[derive(Debug)]
131pub struct AuthorizationItemSetStorage {
132 names: Vec<CString>,
136 values: Vec<Option<Vec<u8>>>,
137 items: Vec<sys::AuthorizationItem>,
138
139 pub set: sys::AuthorizationItemSet,
144}
145
146impl Default for AuthorizationItemSetStorage {
147 #[inline]
148 fn default() -> Self {
149 Self {
150 names: Vec::new(),
151 values: Vec::new(),
152 items: Vec::new(),
153 set: sys::AuthorizationItemSet {
154 count: 0,
155 items: std::ptr::null_mut(),
156 },
157 }
158 }
159}
160
161#[derive(Debug, Default)]
164pub struct AuthorizationItemSetBuilder {
165 storage: AuthorizationItemSetStorage,
166}
167
168impl AuthorizationItemSetBuilder {
170 #[inline(always)]
173 #[must_use]
174 pub fn new() -> Self {
175 Default::default()
176 }
177
178 pub fn add_right<N: Into<Vec<u8>>>(mut self, name: N) -> Result<Self> {
184 self.storage.names.push(cstring_or_err!(name)?);
185 self.storage.values.push(None);
186 Ok(self)
187 }
188
189 pub fn add_data<N, V>(mut self, name: N, value: V) -> Result<Self>
194 where
195 N: Into<Vec<u8>>,
196 V: Into<Vec<u8>>,
197 {
198 self.storage.names.push(cstring_or_err!(name)?);
199 self.storage.values.push(Some(value.into()));
200 Ok(self)
201 }
202
203 pub fn add_string<N, V>(mut self, name: N, value: V) -> Result<Self>
208 where
209 N: Into<Vec<u8>>,
210 V: Into<Vec<u8>>,
211 {
212 self.storage.names.push(cstring_or_err!(name)?);
213 self.storage
214 .values
215 .push(Some(cstring_or_err!(value)?.to_bytes().to_vec()));
216 Ok(self)
217 }
218
219 #[must_use]
222 pub fn build(mut self) -> AuthorizationItemSetStorage {
223 self.storage.items = self
224 .storage
225 .names
226 .iter()
227 .zip(self.storage.values.iter())
228 .map(|(n, v)| sys::AuthorizationItem {
229 name: n.as_ptr(),
230 value: v
231 .as_ref()
232 .map_or(std::ptr::null_mut(), |v| v.as_ptr() as *mut c_void),
233 valueLength: v.as_ref().map_or(0, |v| v.len()),
234 flags: 0,
235 })
236 .collect();
237
238 self.storage.set = sys::AuthorizationItemSet {
239 count: self.storage.items.len() as u32,
240 items: self.storage.items.as_ptr().cast_mut(),
241 };
242
243 self.storage
244 }
245}
246
247#[derive(Copy, Clone)]
249pub enum RightDefinition<'a> {
250 FromDictionary(&'a CFDictionary<CFStringRef, CFTypeRef>),
252
253 FromExistingRight(&'a str),
255}
256
257#[derive(Debug)]
260pub struct Authorization {
261 handle: sys::AuthorizationRef,
262 free_flags: Flags,
263}
264
265impl TryFrom<AuthorizationExternalForm> for Authorization {
266 type Error = Error;
267
268 #[cold]
270 fn try_from(external_form: AuthorizationExternalForm) -> Result<Self> {
271 let mut handle = MaybeUninit::<sys::AuthorizationRef>::uninit();
272
273 let status = unsafe {
274 sys::AuthorizationCreateFromExternalForm(&external_form, handle.as_mut_ptr())
275 };
276
277 if status != sys::errAuthorizationSuccess {
278 return Err(Error::from_code(status));
279 }
280
281 let auth = Self {
282 handle: unsafe { handle.assume_init() },
283 free_flags: Flags::default(),
284 };
285
286 Ok(auth)
287 }
288}
289
290impl Authorization {
291 #[inline]
294 #[allow(clippy::should_implement_trait)]
295 pub fn default() -> Result<Self> {
296 Self::new(None, None, Default::default())
297 }
298
299 #[allow(clippy::unnecessary_cast)]
310 pub fn new(
311 rights: Option<AuthorizationItemSetStorage>,
313 environment: Option<AuthorizationItemSetStorage>,
314 flags: Flags,
315 ) -> Result<Self> {
316 let rights_ptr = rights.as_ref().map_or(std::ptr::null(), |r| {
317 addr_of!(r.set) as *const sys::AuthorizationItemSet
318 });
319
320 let env_ptr = environment.as_ref().map_or(std::ptr::null(), |e| {
321 addr_of!(e.set) as *const sys::AuthorizationItemSet
322 });
323
324 let mut handle = MaybeUninit::<sys::AuthorizationRef>::uninit();
325
326 let status = unsafe {
327 sys::AuthorizationCreate(rights_ptr, env_ptr, flags.bits(), handle.as_mut_ptr())
328 };
329
330 if status != sys::errAuthorizationSuccess {
331 return Err(Error::from_code(status));
332 }
333
334 Ok(Self {
335 handle: unsafe { handle.assume_init() },
336 free_flags: Default::default(),
337 })
338 }
339
340 #[deprecated(since = "2.0.1", note = "Please use the TryFrom trait instead")]
342 pub fn from_external_form(external_form: sys::AuthorizationExternalForm) -> Result<Self> {
343 external_form.try_into()
344 }
345
346 #[inline(always)]
350 pub fn destroy_rights(mut self) {
351 self.free_flags = Flags::DESTROY_RIGHTS;
352 }
353
354 pub fn get_right<T: Into<Vec<u8>>>(name: T) -> Result<CFDictionary<CFString, CFTypeRef>> {
363 let name = cstring_or_err!(name)?;
364 let mut dict = MaybeUninit::<CFDictionaryRef>::uninit();
365
366 let status = unsafe { sys::AuthorizationRightGet(name.as_ptr(), dict.as_mut_ptr()) };
367
368 if status != sys::errAuthorizationSuccess {
369 return Err(Error::from_code(status));
370 }
371
372 let dict = unsafe { CFDictionary::wrap_under_create_rule(dict.assume_init()) };
373
374 Ok(dict)
375 }
376
377 pub fn right_exists<T: Into<Vec<u8>>>(name: T) -> Result<bool> {
383 let name = cstring_or_err!(name)?;
384
385 let status = unsafe { sys::AuthorizationRightGet(name.as_ptr(), std::ptr::null_mut()) };
386
387 Ok(status == sys::errAuthorizationSuccess)
388 }
389
390 pub fn remove_right<T: Into<Vec<u8>>>(&self, name: T) -> Result<()> {
397 let name = cstring_or_err!(name)?;
398
399 let status = unsafe { sys::AuthorizationRightRemove(self.handle, name.as_ptr()) };
400
401 if status != sys::errAuthorizationSuccess {
402 return Err(Error::from_code(status));
403 }
404
405 Ok(())
406 }
407
408 pub fn set_right<T: Into<Vec<u8>>>(
428 &self,
429 name: T,
430 definition: RightDefinition<'_>,
431 description: Option<&str>,
432 bundle: Option<CFBundleRef>,
433 locale: Option<&str>,
434 ) -> Result<()> {
435 let name = cstring_or_err!(name)?;
436
437 let definition_cfstring: CFString;
438 let definition_ref = match definition {
439 RightDefinition::FromDictionary(def) => def.as_CFTypeRef(),
440 RightDefinition::FromExistingRight(def) => {
441 definition_cfstring = CFString::new(def);
442 definition_cfstring.as_CFTypeRef()
443 },
444 };
445
446 let status = unsafe {
447 sys::AuthorizationRightSet(
448 self.handle,
449 name.as_ptr(),
450 definition_ref,
451 optional_str_to_cfref!(description),
452 bundle.unwrap_or(std::ptr::null_mut()),
453 optional_str_to_cfref!(locale),
454 )
455 };
456
457 if status != sys::errAuthorizationSuccess {
458 return Err(Error::from_code(status));
459 }
460
461 Ok(())
462 }
463
464 pub fn copy_info<T: Into<Vec<u8>>>(&self, tag: Option<T>) -> Result<AuthorizationItemSet<'_>> {
474 let tag_with_nul: CString;
475
476 let tag_ptr = match tag {
477 Some(tag) => {
478 tag_with_nul = cstring_or_err!(tag)?;
479 tag_with_nul.as_ptr()
480 },
481 None => std::ptr::null(),
482 };
483
484 let mut inner = MaybeUninit::<*mut sys::AuthorizationItemSet>::uninit();
485
486 let status = unsafe { sys::AuthorizationCopyInfo(self.handle, tag_ptr, inner.as_mut_ptr()) };
487
488 if status != sys::errAuthorizationSuccess {
489 return Err(Error::from(status));
490 }
491
492 let set = AuthorizationItemSet {
493 inner: unsafe { inner.assume_init() },
494 phantom: PhantomData,
495 };
496
497 Ok(set)
498 }
499
500 pub fn make_external_form(&self) -> Result<sys::AuthorizationExternalForm> {
503 let mut external_form = MaybeUninit::<sys::AuthorizationExternalForm>::uninit();
504
505 let status = unsafe { sys::AuthorizationMakeExternalForm(self.handle, external_form.as_mut_ptr()) };
506
507 if status != sys::errAuthorizationSuccess {
508 return Err(Error::from(status));
509 }
510
511 Ok(unsafe { external_form.assume_init() })
512 }
513
514 #[cfg(target_os = "macos")]
517 #[inline(always)]
518 pub fn execute_with_privileges<P, S, I>(
519 &self,
520 command: P,
521 arguments: I,
522 flags: Flags,
523 ) -> Result<()>
524 where
525 P: AsRef<std::path::Path>,
526 I: IntoIterator<Item = S>,
527 S: AsRef<std::ffi::OsStr>,
528 {
529 use std::os::unix::ffi::OsStrExt;
530
531 let arguments = arguments
532 .into_iter().flat_map(|a| CString::new(a.as_ref().as_bytes()))
533 .collect::<Vec<_>>();
534 self.execute_with_privileges_internal(command.as_ref().as_os_str().as_bytes(), &arguments, flags, false)?;
535 Ok(())
536 }
537
538 #[cfg(target_os = "macos")]
541 #[inline(always)]
542 pub fn execute_with_privileges_piped<P, S, I>(
543 &self,
544 command: P,
545 arguments: I,
546 flags: Flags,
547 ) -> Result<File>
548 where
549 P: AsRef<std::path::Path>,
550 I: IntoIterator<Item = S>,
551 S: AsRef<std::ffi::OsStr>,
552 {
553 use std::os::unix::ffi::OsStrExt;
554
555 let arguments = arguments
556 .into_iter().flat_map(|a| CString::new(a.as_ref().as_bytes()))
557 .collect::<Vec<_>>();
558 Ok(self.execute_with_privileges_internal(command.as_ref().as_os_str().as_bytes(), &arguments, flags, true)?.unwrap())
559 }
560
561 #[cfg(all(target_os = "macos", feature = "job-bless"))]
563 pub fn job_bless(&self, label: &str) -> Result<(), CFError> {
564 #[link(name = "ServiceManagement", kind = "framework")]
565 extern "C" {
566 static kSMDomainSystemLaunchd: CFStringRef;
567
568 fn SMJobBless(
569 domain: CFStringRef,
570 executableLabel: CFStringRef,
571 auth: sys::AuthorizationRef,
572 error: *mut CFErrorRef,
573 ) -> Boolean;
574 }
575
576 unsafe {
577 let mut error = std::ptr::null_mut();
578 SMJobBless(
579 kSMDomainSystemLaunchd,
580 CFString::new(label).as_concrete_TypeRef(),
581 self.handle,
582 &mut error,
583 );
584 if !error.is_null() {
585 return Err(CFError::wrap_under_create_rule(error));
586 }
587
588 Ok(())
589 }
590 }
591
592 #[cfg(target_os = "macos")]
594 fn execute_with_privileges_internal(
595 &self,
596 command: &[u8],
597 arguments: &[CString],
598 flags: Flags,
599 make_pipe: bool,
600 ) -> Result<Option<File>> {
601 use std::os::unix::io::{FromRawFd, RawFd};
602
603 let c_cmd = cstring_or_err!(command)?;
604
605 let mut c_args = arguments.iter().map(|a| a.as_ptr() as _).collect::<Vec<_>>();
606 c_args.push(std::ptr::null_mut());
607
608 let mut pipe: *mut libc::FILE = std::ptr::null_mut();
609
610 let status = unsafe {
611 sys::AuthorizationExecuteWithPrivileges(
612 self.handle,
613 c_cmd.as_ptr(),
614 flags.bits(),
615 c_args.as_ptr(),
616 if make_pipe { &mut pipe } else { std::ptr::null_mut() },
617 )
618 };
619
620 crate::cvt(status)?;
621 Ok(if make_pipe {
622 if pipe.is_null() {
623 return Err(Error::from_code(32)); }
625 Some(unsafe { File::from_raw_fd(libc::fileno(pipe) as RawFd) })
626 } else {
627 None
628 })
629 }
630}
631
632impl Drop for Authorization {
633 #[inline]
634 fn drop(&mut self) {
635 unsafe {
636 sys::AuthorizationFree(self.handle, self.free_flags.bits());
637 }
638 }
639}
640
641#[cfg(test)]
642mod tests {
643 use super::*;
644
645 #[test]
646 fn test_create_default_authorization() {
647 Authorization::default().unwrap();
648 }
649
650 #[test]
651 fn test_create_allowed_authorization() -> Result<()> {
652 let rights = AuthorizationItemSetBuilder::new()
653 .add_right("system.hdd.smart")?
654 .add_right("system.login.done")?
655 .build();
656
657 Authorization::new(Some(rights), None, Flags::EXTEND_RIGHTS).unwrap();
658
659 Ok(())
660 }
661
662 #[test]
663 fn test_create_then_destroy_allowed_authorization() -> Result<()> {
664 let rights = AuthorizationItemSetBuilder::new()
665 .add_right("system.hdd.smart")?
666 .add_right("system.login.done")?
667 .build();
668
669 let auth = Authorization::new(Some(rights), None, Flags::EXTEND_RIGHTS).unwrap();
670 auth.destroy_rights();
671
672 Ok(())
673 }
674
675 #[test]
676 fn test_create_authorization_requiring_interaction() -> Result<()> {
677 let rights = AuthorizationItemSetBuilder::new()
678 .add_right("system.privilege.admin")?
679 .build();
680
681 let error = Authorization::new(Some(rights), None, Flags::EXTEND_RIGHTS).unwrap_err();
682
683 assert_eq!(error.code(), sys::errAuthorizationInteractionNotAllowed);
684
685 Ok(())
686 }
687
688 fn create_credentials_env() -> Result<AuthorizationItemSetStorage> {
689 let set = AuthorizationItemSetBuilder::new()
690 .add_string("username", std::env::var("USER").expect("You must set the USER environment variable"))?
691 .add_string("password", std::env::var("PASSWORD").expect("You must set the PASSWORD environment varible"))?
692 .build();
693
694 Ok(set)
695 }
696
697 #[test]
698 fn test_create_authorization_with_bad_credentials() -> Result<()> {
699 let rights = AuthorizationItemSetBuilder::new()
700 .add_right("system.privilege.admin")?
701 .build();
702
703 let env = AuthorizationItemSetBuilder::new()
704 .add_string("username", "Tim Apple")?
705 .add_string("password", "butterfly")?
706 .build();
707
708 let error =
709 Authorization::new(Some(rights), Some(env), Flags::INTERACTION_ALLOWED).unwrap_err();
710
711 assert_eq!(error.code(), sys::errAuthorizationDenied);
712
713 Ok(())
714 }
715
716 #[test]
717 fn test_create_authorization_with_credentials() -> Result<()> {
718 if std::env::var_os("PASSWORD").is_none() {
719 return Ok(());
720 }
721
722 let rights = AuthorizationItemSetBuilder::new()
723 .add_right("system.privilege.admin")?
724 .build();
725
726 let env = create_credentials_env()?;
727
728 Authorization::new(Some(rights), Some(env), Flags::EXTEND_RIGHTS).unwrap();
729
730 Ok(())
731 }
732
733 #[test]
734 fn test_query_authorization_database() -> Result<()> {
735 assert!(Authorization::right_exists("system.hdd.smart")?);
736 assert!(!Authorization::right_exists("EMPTY")?);
737
738 let dict = Authorization::get_right("system.hdd.smart").unwrap();
739
740 let key = CFString::from_static_string("class");
741 assert!(dict.contains_key(&key));
742
743 let invalid_key = CFString::from_static_string("EMPTY");
744 assert!(!dict.contains_key(&invalid_key));
745
746 Ok(())
747 }
748
749 #[test]
751 fn test_modify_authorization_database() -> Result<()> {
752 if std::env::var_os("PASSWORD").is_none() {
753 return Ok(());
754 }
755
756 let rights = AuthorizationItemSetBuilder::new()
757 .add_right("config.modify.")?
758 .build();
759
760 let env = create_credentials_env()?;
761
762 let auth = Authorization::new(Some(rights), Some(env), Flags::EXTEND_RIGHTS).unwrap();
763
764 assert!(!Authorization::right_exists("TEST_RIGHT")?);
765
766 auth.set_right(
767 "TEST_RIGHT",
768 RightDefinition::FromExistingRight("system.hdd.smart"),
769 None,
770 None,
771 None,
772 )
773 .unwrap();
774
775 assert!(Authorization::right_exists("TEST_RIGHT")?);
776
777 auth.remove_right("TEST_RIGHT").unwrap();
778
779 assert!(!Authorization::right_exists("TEST_RIGHT")?);
780
781 Ok(())
782 }
783
784 #[test]
786 fn test_execute_with_privileges() -> Result<()> {
787 if std::env::var_os("PASSWORD").is_none() {
788 return Ok(());
789 }
790
791 let rights = AuthorizationItemSetBuilder::new()
792 .add_right("system.privilege.admin")?
793 .build();
794
795 let auth = Authorization::new(
796 Some(rights),
797 None,
798 Flags::DEFAULTS
799 | Flags::INTERACTION_ALLOWED
800 | Flags::PREAUTHORIZE
801 | Flags::EXTEND_RIGHTS,
802 )?;
803
804 let file = auth.execute_with_privileges_piped("/bin/ls", ["/"], Flags::DEFAULTS)?;
805
806 use std::io::{self, BufRead};
807 for line in io::BufReader::new(file).lines() {
808 let _ = line.unwrap();
809 }
810
811 Ok(())
812 }
813}