diff --git a/iostest/tests/ios_macos.rs b/iostest/tests/ios_macos.rs index 1efcaeaa..f0b6cbce 100644 --- a/iostest/tests/ios_macos.rs +++ b/iostest/tests/ios_macos.rs @@ -22,9 +22,7 @@ use serial_test::serial; #[test] #[serial] fn insert_then_find_generic() { - let service_key = format!("{}", unsafe { - CFString::wrap_under_get_rule(kSecAttrService) - }); + let service_key = format!("{}", unsafe { CFString::wrap_under_get_rule(kSecAttrService) }); let mut names = vec![]; for _ in 0..4 { let name = generate_random_string(); @@ -48,7 +46,7 @@ fn insert_then_find_generic() { found += 1; } } - } + }, _ => panic!("Got a non-dictionary from a password search"), } } @@ -63,16 +61,12 @@ fn insert_then_find_generic() { #[cfg(target_os = "macos")] fn insert_then_find_generic_legacy() { let keychain = SecKeychain::default().unwrap(); - let service_key = format!("{}", unsafe { - CFString::wrap_under_get_rule(kSecAttrService) - }); + let service_key = format!("{}", unsafe { CFString::wrap_under_get_rule(kSecAttrService) }); // create 4 legacy and 4 modern generic passwords let mut legacy_names = vec![]; for _ in 0..4 { let name = generate_random_string(); - keychain - .set_generic_password(&name, &name, name.as_bytes()) - .unwrap(); + keychain.set_generic_password(&name, &name, name.as_bytes()).unwrap(); legacy_names.push(name); } let mut modern_names = vec![]; @@ -99,7 +93,7 @@ fn insert_then_find_generic_legacy() { found += 1; } } - } + }, _ => panic!("Got a non-dictionary from a password search"), } } @@ -121,12 +115,8 @@ fn insert_then_find_generic_legacy() { #[test] #[serial] fn find_leftover_test_generic_passwords() { - let service_key = format!("{}", unsafe { - CFString::wrap_under_get_rule(kSecAttrService) - }); - let username_key = format!("{}", unsafe { - CFString::wrap_under_get_rule(kSecAttrAccount) - }); + let service_key = format!("{}", unsafe { CFString::wrap_under_get_rule(kSecAttrService) }); + let username_key = format!("{}", unsafe { CFString::wrap_under_get_rule(kSecAttrAccount) }); let mut found: Vec = vec![]; let results = ItemSearchOptions::new() .class(ItemClass::generic_password()) @@ -148,7 +138,7 @@ fn find_leftover_test_generic_passwords() { } } } - } + }, _ => panic!("Got a non-dictionary from a password search"), } } diff --git a/security-framework-sys/src/cms.rs b/security-framework-sys/src/cms.rs index ea398403..6da3702e 100644 --- a/security-framework-sys/src/cms.rs +++ b/security-framework-sys/src/cms.rs @@ -28,7 +28,7 @@ pub enum CMSSignerStatus { kCMSSignerInvalidIndex = 5, } -pub type CMSSignedAttributes = u32; +pub type CMSSignedAttributes = u32; pub const kCMSAttrNone: CMSSignedAttributes = 0x0000; pub const kCMSAttrSmimeCapabilities: CMSSignedAttributes = 0x0001; pub const kCMSAttrSmimeEncryptionKeyPrefs: CMSSignedAttributes = 0x0002; @@ -111,15 +111,9 @@ extern "C" { content_type_out: *mut CFDataRef, ) -> OSStatus; - pub fn CMSDecoderCopyAllCerts( - decoder: CMSDecoderRef, - certs_out: *mut CFArrayRef, - ) -> OSStatus; + pub fn CMSDecoderCopyAllCerts(decoder: CMSDecoderRef, certs_out: *mut CFArrayRef) -> OSStatus; - pub fn CMSDecoderCopyContent( - decoder: CMSDecoderRef, - content_out: *mut CFDataRef, - ) -> OSStatus; + pub fn CMSDecoderCopyContent(decoder: CMSDecoderRef, content_out: *mut CFDataRef) -> OSStatus; pub fn CMSDecoderCopySignerSigningTime( decoder: CMSDecoderRef, @@ -146,7 +140,6 @@ extern "C" { certificate_refs: *mut CFArrayRef, ) -> OSStatus; - // CMS encoder pub static kCMSEncoderDigestAlgorithmSHA1: CFStringRef; @@ -161,15 +154,9 @@ extern "C" { digest_alogrithm: CFStringRef, ) -> OSStatus; - pub fn CMSEncoderAddSigners( - encoder: CMSEncoderRef, - signer_or_array: CFTypeRef, - ) -> OSStatus; + pub fn CMSEncoderAddSigners(encoder: CMSEncoderRef, signer_or_array: CFTypeRef) -> OSStatus; - pub fn CMSEncoderCopySigners( - encoder: CMSEncoderRef, - signers_out: *mut CFArrayRef, - ) -> OSStatus; + pub fn CMSEncoderCopySigners(encoder: CMSEncoderRef, signers_out: *mut CFArrayRef) -> OSStatus; pub fn CMSEncoderAddRecipients( encoder: CMSEncoderRef, diff --git a/security-framework-sys/src/item.rs b/security-framework-sys/src/item.rs index afdbdfce..920b8b4b 100644 --- a/security-framework-sys/src/item.rs +++ b/security-framework-sys/src/item.rs @@ -14,7 +14,7 @@ extern "C" { pub static kSecMatchTrustedOnly: CFStringRef; pub static kSecMatchCaseInsensitive: CFStringRef; #[cfg(target_os = "macos")] - pub static kSecMatchSubjectWholeString: CFStringRef; + pub static kSecMatchSubjectWholeString: CFStringRef; pub static kSecReturnData: CFStringRef; pub static kSecReturnAttributes: CFStringRef; diff --git a/security-framework/examples/client.rs b/security-framework/examples/client.rs index a352bf94..a9b35a72 100644 --- a/security-framework/examples/client.rs +++ b/security-framework/examples/client.rs @@ -4,17 +4,9 @@ use std::net::TcpStream; fn main() { let stream = TcpStream::connect("google.com:443").unwrap(); - let mut stream = ClientBuilder::new() - .handshake("google.com", stream) - .unwrap(); - println!( - "negotiated chipher: {:?}", - stream.context().negotiated_cipher().unwrap() - ); - println!( - "negotiated version: {:?}", - stream.context().negotiated_protocol_version().unwrap() - ); + let mut stream = ClientBuilder::new().handshake("google.com", stream).unwrap(); + println!("negotiated chipher: {:?}", stream.context().negotiated_cipher().unwrap()); + println!("negotiated version: {:?}", stream.context().negotiated_protocol_version().unwrap()); stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); stream.flush().unwrap(); diff --git a/security-framework/src/access_control.rs b/security-framework/src/access_control.rs index dfaa4541..26b1cfbd 100644 --- a/security-framework/src/access_control.rs +++ b/security-framework/src/access_control.rs @@ -2,18 +2,16 @@ use std::ptr::{self, null}; +use crate::base::{Error, Result}; +use core_foundation::base::{kCFAllocatorDefault, CFOptionFlags, TCFType}; use core_foundation::string::CFString; -use core_foundation::base::{TCFType, CFOptionFlags, kCFAllocatorDefault}; use security_framework_sys::access_control::{ - SecAccessControlGetTypeID, SecAccessControlCreateWithFlags, - kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, - kSecAttrAccessibleWhenUnlockedThisDeviceOnly, - kSecAttrAccessibleWhenUnlocked, - kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, - kSecAttrAccessibleAfterFirstUnlock + kSecAttrAccessibleAfterFirstUnlock, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, + kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, kSecAttrAccessibleWhenUnlocked, + kSecAttrAccessibleWhenUnlockedThisDeviceOnly, SecAccessControlCreateWithFlags, + SecAccessControlGetTypeID, }; -use security_framework_sys::base::{SecAccessControlRef, errSecParam}; -use crate::base::{Error, Result}; +use security_framework_sys::base::{errSecParam, SecAccessControlRef}; declare_TCFType! { /// A type representing sec access control settings. diff --git a/security-framework/src/authorization.rs b/security-framework/src/authorization.rs index 54acc612..a60cf8f9 100644 --- a/security-framework/src/authorization.rs +++ b/security-framework/src/authorization.rs @@ -2,11 +2,9 @@ /// # Potential improvements /// -/// * When generic specialization stabilizes prevent copying from `CString` -/// arguments. +/// * When generic specialization stabilizes prevent copying from `CString` arguments. /// * `AuthorizationCopyRightsAsync` /// * Provide constants for well known item names - use crate::base::{Error, Result}; #[cfg(all(target_os = "macos", feature = "job-bless"))] use core_foundation::base::Boolean; @@ -22,10 +20,10 @@ use security_framework_sys::authorization as sys; use security_framework_sys::base::errSecConversionError; use std::ffi::{CStr, CString}; use std::fs::File; +use std::marker::PhantomData; use std::mem::MaybeUninit; use std::os::raw::c_void; use std::ptr::addr_of; -use std::marker::PhantomData; use sys::AuthorizationExternalForm; macro_rules! optional_str_to_cfref { @@ -86,7 +84,8 @@ impl AuthorizationItem { /// /// If `name` isn't convertable to a `CString` it will return /// Err(errSecConversionError). - #[must_use] pub fn name(&self) -> &str { + #[must_use] + pub fn name(&self) -> &str { unsafe { CStr::from_ptr(self.0.name) .to_str() @@ -97,13 +96,13 @@ impl AuthorizationItem { /// The information pertaining to the name field. Do not rely on NULL /// termination of string data. #[inline] - #[must_use] pub fn value(&self) -> Option<&[u8]> { + #[must_use] + pub fn value(&self) -> Option<&[u8]> { if self.0.value.is_null() { return None; } - let value = - unsafe { std::slice::from_raw_parts(self.0.value as *const u8, self.0.valueLength) }; + let value = unsafe { std::slice::from_raw_parts(self.0.value as *const u8, self.0.valueLength) }; Some(value) } @@ -441,7 +440,7 @@ impl Authorization { RightDefinition::FromExistingRight(def) => { definition_cfstring = CFString::new(def); definition_cfstring.as_CFTypeRef() - } + }, }; let status = unsafe { @@ -478,14 +477,13 @@ impl Authorization { Some(tag) => { tag_with_nul = cstring_or_err!(tag)?; tag_with_nul.as_ptr() - } + }, None => std::ptr::null(), }; let mut inner = MaybeUninit::<*mut sys::AuthorizationItemSet>::uninit(); - let status = - unsafe { sys::AuthorizationCopyInfo(self.handle, tag_ptr, inner.as_mut_ptr()) }; + let status = unsafe { sys::AuthorizationCopyInfo(self.handle, tag_ptr, inner.as_mut_ptr()) }; if status != sys::errAuthorizationSuccess { return Err(Error::from(status)); @@ -504,8 +502,7 @@ impl Authorization { pub fn make_external_form(&self) -> Result { let mut external_form = MaybeUninit::::uninit(); - let status = - unsafe { sys::AuthorizationMakeExternalForm(self.handle, external_form.as_mut_ptr()) }; + let status = unsafe { sys::AuthorizationMakeExternalForm(self.handle, external_form.as_mut_ptr()) }; if status != sys::errAuthorizationSuccess { return Err(Error::from(status)); diff --git a/security-framework/src/certificate.rs b/security-framework/src/certificate.rs index 504e065b..81ea2e35 100644 --- a/security-framework/src/certificate.rs +++ b/security-framework/src/certificate.rs @@ -53,8 +53,7 @@ impl SecCertificate { pub fn from_der(der_data: &[u8]) -> Result { let der_data = CFData::from_buffer(der_data); unsafe { - let certificate = - SecCertificateCreateWithData(kCFAllocatorDefault, der_data.as_concrete_TypeRef()); + let certificate = SecCertificateCreateWithData(kCFAllocatorDefault, der_data.as_concrete_TypeRef()); if certificate.is_null() { Err(Error::from_code(errSecParam)) } else { @@ -73,7 +72,7 @@ impl SecCertificate { } /// Adds a certificate to a keychain. - #[cfg(target_os="macos")] + #[cfg(target_os = "macos")] pub fn add_to_keychain(&self, keychain: Option) -> Result<()> { let kch = match keychain { Some(kch) => kch, @@ -154,8 +153,7 @@ impl SecCertificate { #[cfg(any(feature = "OSX_10_12", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos"))] #[must_use] fn pk_to_der(&self, public_key: key::SecKey) -> Option> { - use security_framework_sys::item::kSecAttrKeyType; - use security_framework_sys::item::kSecAttrKeySizeInBits; + use security_framework_sys::item::{kSecAttrKeySizeInBits, kSecAttrKeyType}; let public_key_attributes = public_key.attributes(); let public_key_type = public_key_attributes @@ -208,8 +206,7 @@ impl SecCertificate { #[cfg(any(feature = "OSX_10_12", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos"))] fn get_asn1_header_bytes(pkt: CFString, ksz: u32) -> Option<&'static [u8]> { - use security_framework_sys::item::kSecAttrKeyTypeRSA; - use security_framework_sys::item::kSecAttrKeyTypeECSECPrimeRandom; + use security_framework_sys::item::{kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyTypeRSA}; if pkt == unsafe { CFString::wrap_under_get_rule(kSecAttrKeyTypeRSA) } && ksz == 2048 { return Some(&RSA_2048_ASN1_HEADER); @@ -217,14 +214,10 @@ fn get_asn1_header_bytes(pkt: CFString, ksz: u32) -> Option<&'static [u8]> { if pkt == unsafe { CFString::wrap_under_get_rule(kSecAttrKeyTypeRSA) } && ksz == 4096 { return Some(&RSA_4096_ASN1_HEADER); } - if pkt == unsafe { CFString::wrap_under_get_rule(kSecAttrKeyTypeECSECPrimeRandom) } - && ksz == 256 - { + if pkt == unsafe { CFString::wrap_under_get_rule(kSecAttrKeyTypeECSECPrimeRandom) } && ksz == 256 { return Some(&EC_DSA_SECP_256_R1_ASN1_HEADER); } - if pkt == unsafe { CFString::wrap_under_get_rule(kSecAttrKeyTypeECSECPrimeRandom) } - && ksz == 384 - { + if pkt == unsafe { CFString::wrap_under_get_rule(kSecAttrKeyTypeECSECPrimeRandom) } && ksz == 384 { return Some(&EC_DSA_SECP_384_R1_ASN1_HEADER); } None diff --git a/security-framework/src/cms.rs b/security-framework/src/cms.rs index e860434b..d499fb9b 100644 --- a/security-framework/src/cms.rs +++ b/security-framework/src/cms.rs @@ -23,10 +23,10 @@ use crate::trust::SecTrust; pub use decoder::CMSDecoder; pub use encoder::cms_encode_content; -pub use encoder::CMS_DIGEST_ALGORITHM_SHA1; -pub use encoder::CMS_DIGEST_ALGORITHM_SHA256; pub use encoder::CMSEncoder; pub use encoder::SignedAttributes; +pub use encoder::CMS_DIGEST_ALGORITHM_SHA1; +pub use encoder::CMS_DIGEST_ALGORITHM_SHA256; mod encoder { use super::*; @@ -59,7 +59,6 @@ mod encoder { } } - declare_TCFType! { /// A type representing CMS encoder CMSEncoder, CMSEncoderRef @@ -202,10 +201,7 @@ mod encoder { } /// Specifies which certificates to include in a signed CMS message - pub fn set_certificate_chain_mode( - &self, - certificate_chain_mode: CMSCertificateChainMode) -> Result<()> - { + pub fn set_certificate_chain_mode(&self, certificate_chain_mode: CMSCertificateChainMode) -> Result<()> { cvt(unsafe { CMSEncoderSetCertificateChainMode(self.0, certificate_chain_mode) })?; Ok(()) } @@ -241,8 +237,8 @@ mod encoder { pub fn get_signer_timestamp_with_policy( &self, timestamp_policy: Option, - signer_index: usize) -> Result - { + signer_index: usize, + ) -> Result { let mut out = CFAbsoluteTime::default(); cvt(unsafe { CMSEncoderCopySignerTimestampWithPolicy( @@ -325,10 +321,7 @@ mod decoder { } /// Feeds raw bytes of the message to be decoded into the decoder - pub fn update_message( - &self, - message: &[u8], - ) -> Result<()> { + pub fn update_message(&self, message: &[u8]) -> Result<()> { cvt(unsafe { CMSDecoderUpdateMessage(self.0, message.as_ptr() as _, message.len()) })?; Ok(()) } @@ -370,8 +363,8 @@ mod decoder { pub fn get_signer_status( &self, signer_index: usize, - policies: &[SecPolicy]) -> Result - { + policies: &[SecPolicy], + ) -> Result { let policies = CFArray::from_CFTypes(policies); let mut signer_status = CMSSignerStatus::kCMSSignerUnsigned; @@ -466,15 +459,18 @@ mod decoder { pub fn get_signer_timestamp_with_policy( &self, timestamp_policy: Option, - signer_index: usize) -> Result - { + signer_index: usize, + ) -> Result { let mut out = CFAbsoluteTime::default(); cvt(unsafe { CMSDecoderCopySignerTimestampWithPolicy( self.0, - timestamp_policy.map(|p| p.as_void_ptr()).unwrap_or(ptr::null()), + timestamp_policy + .map(|p| p.as_void_ptr()) + .unwrap_or(ptr::null()), signer_index, - &mut out) + &mut out, + ) })?; Ok(out) @@ -483,10 +479,12 @@ mod decoder { /// Returns an array containing the certificates from a timestamp response pub fn get_signer_timestamp_certificates( &self, - signer_index: usize) -> Result> - { + signer_index: usize, + ) -> Result> { let mut out: CFArrayRef = ptr::null_mut(); - cvt(unsafe { CMSDecoderCopySignerTimestampCertificates(self.0, signer_index, &mut out) })?; + cvt(unsafe { + CMSDecoderCopySignerTimestampCertificates(self.0, signer_index, &mut out) + })?; if out.is_null() { Ok(Vec::new()) @@ -500,10 +498,10 @@ mod decoder { #[cfg(test)] mod tests { - use security_framework_sys::cms::CMSSignerStatus; use crate::cms::{cms_encode_content, CMSDecoder, SignedAttributes}; use crate::import_export::{ImportedIdentity, Pkcs12ImportOptions}; use crate::policy::SecPolicy; + use security_framework_sys::cms::CMSSignerStatus; const KEYSTORE: &[u8] = include_bytes!("../test/cms/keystore.p12"); const ENCRYPTED_CMS: &[u8] = include_bytes!("../test/cms/encrypted.p7m"); diff --git a/security-framework/src/identity.rs b/security-framework/src/identity.rs index 33775251..9223979a 100644 --- a/security-framework/src/identity.rs +++ b/security-framework/src/identity.rs @@ -1,17 +1,17 @@ //! Identity support. -use core_foundation::base::TCFType; -use core_foundation::base::ToVoid; +use core_foundation::base::{TCFType, ToVoid}; use core_foundation::dictionary::CFMutableDictionary; use security_framework_sys::base::SecIdentityRef; -use security_framework_sys::identity::{SecIdentityCopyCertificate, SecIdentityCopyPrivateKey, SecIdentityGetTypeID}; +use security_framework_sys::identity::{ + SecIdentityCopyCertificate, SecIdentityCopyPrivateKey, SecIdentityGetTypeID, +}; use security_framework_sys::item::kSecValueRef; use security_framework_sys::keychain_item::SecItemDelete; use std::fmt; use std::ptr; -use crate::base::Error; -use crate::base::Result; +use crate::base::{Error, Result}; use crate::certificate::SecCertificate; use crate::cvt; use crate::key::SecKey; diff --git a/security-framework/src/import_export.rs b/security-framework/src/import_export.rs index 378a2d5b..2fd3c1e0 100644 --- a/security-framework/src/import_export.rs +++ b/security-framework/src/import_export.rs @@ -113,14 +113,14 @@ impl Pkcs12ImportOptions { let trust = raw_item .find(kSecImportItemTrust) .map(|trust| SecTrust::wrap_under_get_rule(*trust as *mut _)); - let cert_chain = raw_item.find(kSecImportItemCertChain.cast()).map( - |cert_chain| { + let cert_chain = raw_item + .find(kSecImportItemCertChain.cast()) + .map(|cert_chain| { CFArray::::wrap_under_get_rule((*cert_chain).cast()) .iter() .map(|c| c.clone()) .collect() - }, - ); + }); let identity = raw_item .find(kSecImportItemIdentity) .map(|identity| SecIdentity::wrap_under_get_rule(*identity as *mut _)); diff --git a/security-framework/src/item.rs b/security-framework/src/item.rs index 2185241b..d85906d1 100644 --- a/security-framework/src/item.rs +++ b/security-framework/src/item.rs @@ -12,7 +12,7 @@ use core_foundation_sys::base::{CFCopyDescription, CFGetTypeID, CFRelease, CFTyp use core_foundation_sys::string::CFStringRef; use security_framework_sys::item::*; use security_framework_sys::keychain_item::{ - SecItemAdd, SecItemCopyMatching, SecItemDelete, SecItemUpdate + SecItemAdd, SecItemCopyMatching, SecItemDelete, SecItemUpdate, }; use std::collections::HashMap; use std::fmt; @@ -74,17 +74,22 @@ pub struct KeyClass(CFStringRef); impl KeyClass { /// `kSecAttrKeyClassPublic` #[inline(always)] - #[must_use] pub fn public() -> Self { + #[must_use] + pub fn public() -> Self { unsafe { Self(kSecAttrKeyClassPublic) } } + /// `kSecAttrKeyClassPrivate` #[inline(always)] - #[must_use] pub fn private() -> Self { + #[must_use] + pub fn private() -> Self { unsafe { Self(kSecAttrKeyClassPrivate) } } + /// `kSecAttrKeyClassSymmetric` #[inline(always)] - #[must_use] pub fn symmetric() -> Self { + #[must_use] + pub fn symmetric() -> Self { unsafe { Self(kSecAttrKeyClassSymmetric) } } } @@ -234,7 +239,7 @@ impl ItemSearchOptions { self.service = Some(CFString::new(service)); self } - + /// Search for an item with exactly the given subject. #[inline(always)] pub fn subject(&mut self, subject: &str) -> &mut Self { @@ -314,22 +319,16 @@ impl ItemSearchOptions { if let Some(case_insensitive) = self.case_insensitive { params.add( &kSecMatchCaseInsensitive.to_void(), - &CFBoolean::from(case_insensitive).to_void() + &CFBoolean::from(case_insensitive).to_void(), ); } if let Some(key_class) = self.key_class { - params.add( - &kSecAttrKeyClass.to_void(), - &key_class.0.to_void() - ); + params.add(&kSecAttrKeyClass.to_void(), &key_class.0.to_void()); } if self.load_refs { - params.add( - &kSecReturnRef.to_void(), - &CFBoolean::true_value().to_void(), - ); + params.add(&kSecReturnRef.to_void(), &CFBoolean::true_value().to_void()); } if self.load_attributes { @@ -347,17 +346,11 @@ impl ItemSearchOptions { } if let Some(limit) = self.limit { - params.add( - &kSecMatchLimit.to_void(), - &limit.to_value().to_void(), - ); + params.add(&kSecMatchLimit.to_void(), &limit.to_value().to_void()); } if let Some(ref label) = self.label { - params.add( - &kSecAttrLabel.to_void(), - &label.to_void(), - ); + params.add(&kSecAttrLabel.to_void(), &label.to_void()); } if let Some(ref trusted_only) = self.trusted_only { @@ -368,60 +361,39 @@ impl ItemSearchOptions { } else { CFBoolean::false_value() }) - .to_void() + .to_void(), ); } if let Some(ref service) = self.service { - params.add( - &kSecAttrService.to_void(), - &service.to_void(), - ); + params.add(&kSecAttrService.to_void(), &service.to_void()); } - + #[cfg(target_os = "macos")] { if let Some(ref subject) = self.subject { - params.add( - &kSecMatchSubjectWholeString.to_void(), - &subject.to_void(), - ); + params.add(&kSecMatchSubjectWholeString.to_void(), &subject.to_void()); } } if let Some(ref account) = self.account { - params.add( - &kSecAttrAccount.to_void(), - &account.to_void(), - ); + params.add(&kSecAttrAccount.to_void(), &account.to_void()); } if let Some(ref access_group) = self.access_group { - params.add( - &kSecAttrAccessGroup.to_void(), - &access_group.to_void(), - ); + params.add(&kSecAttrAccessGroup.to_void(), &access_group.to_void()); } if let Some(ref pub_key_hash) = self.pub_key_hash { - params.add( - &kSecAttrPublicKeyHash.to_void(), - &pub_key_hash.to_void(), - ); + params.add(&kSecAttrPublicKeyHash.to_void(), &pub_key_hash.to_void()); } if let Some(ref serial_number) = self.serial_number { - params.add( - &kSecAttrSerialNumber.to_void(), - &serial_number.to_void(), - ); + params.add(&kSecAttrSerialNumber.to_void(), &serial_number.to_void()); } if let Some(ref app_label) = self.app_label { - params.add( - &kSecAttrApplicationLabel.to_void(), - &app_label.to_void(), - ); + params.add(&kSecAttrApplicationLabel.to_void(), &app_label.to_void()); } params.to_immutable() @@ -558,7 +530,7 @@ impl fmt::Debug for SearchResult { debug.field(&k, &v); } debug.finish() - } + }, Self::Other => write!(fmt, "SearchResult::Other"), } } @@ -580,7 +552,7 @@ impl SearchResult { let val: String = match CFGetTypeID(*v) { cfstring if cfstring == CFString::type_id() => { format!("{}", CFString::wrap_under_get_rule((*v).cast())) - } + }, cfdata if cfdata == CFData::type_id() => { let buf = CFData::wrap_under_get_rule((*v).cast()); let mut vec = Vec::new(); @@ -630,7 +602,16 @@ impl ItemAddOptions { #[inline] #[must_use] pub fn new(value: ItemAddValue) -> Self { - Self{ value, label: None, location: None, service: None, account_name: None, comment: None, description: None, access_group: None } + Self { + value, + label: None, + location: None, + service: None, + account_name: None, + comment: None, + description: None, + access_group: None, + } } /// Specifies the `kSecAttrAccount` attribute. @@ -639,42 +620,49 @@ impl ItemAddOptions { self.account_name = Some(account_name.as_ref().into()); self } + /// Specifies the `kSecAttrAccessGroup` attribute. #[inline] pub fn set_access_group(&mut self, access_group: impl AsRef) -> &mut Self { self.access_group = Some(access_group.as_ref().into()); self } + /// Specifies the `kSecAttrComment` attribute. #[inline] pub fn set_comment(&mut self, comment: impl AsRef) -> &mut Self { self.comment = Some(comment.as_ref().into()); self } + /// Specifies the `kSecAttrDescription` attribute. #[inline] pub fn set_description(&mut self, description: impl AsRef) -> &mut Self { self.description = Some(description.as_ref().into()); self } + /// Specifies the `kSecAttrLabel` attribute. #[inline] pub fn set_label(&mut self, label: impl AsRef) -> &mut Self { self.label = Some(label.as_ref().into()); self } + /// Specifies which keychain to add the item to. #[inline] pub fn set_location(&mut self, location: Location) -> &mut Self { self.location = Some(location); self } + /// Specifies the `kSecAttrService` attribute. #[inline] pub fn set_service(&mut self, service: impl AsRef) -> &mut Self { self.service = Some(service.as_ref().into()); self } + /// Populates a `CFDictionary` to be passed to `add_item`. #[deprecated(since = "3.0.0", note = "use `ItemAddOptions::add` instead")] // CFDictionary should not be exposed in public Rust APIs. @@ -705,7 +693,7 @@ impl ItemAddOptions { ); } #[cfg(target_os = "macos")] - Location::DefaultFileKeychain => {} + Location::DefaultFileKeychain => {}, #[cfg(target_os = "macos")] Location::FileKeychain(keychain) => { dict.add(&unsafe { kSecUseKeychain }.to_void(), &keychain.to_void()); @@ -733,6 +721,7 @@ impl ItemAddOptions { dict.to_immutable() } + /// Adds the item to the keychain. /// /// Translates to `SecItemAdd`. @@ -776,6 +765,7 @@ impl AddRef { AddRef::Certificate(_) => Some(ItemClass::certificate()), } } + fn ref_(&self) -> CFTypeRef { match self { AddRef::Key(key) => key.as_CFTypeRef(), @@ -826,54 +816,63 @@ impl ItemUpdateOptions { self.value = Some(value); self } + /// Specifies the `kSecClass` attribute. #[inline] pub fn set_class(&mut self, class: ItemClass) -> &mut Self { self.class = Some(class); self } + /// Specifies the `kSecAttrAccount` attribute. #[inline] pub fn set_account_name(&mut self, account_name: impl AsRef) -> &mut Self { self.account_name = Some(account_name.as_ref().into()); self } + /// Specifies the `kSecAttrAccessGroup` attribute. #[inline] pub fn set_access_group(&mut self, access_group: impl AsRef) -> &mut Self { self.access_group = Some(access_group.as_ref().into()); self } + /// Specifies the `kSecAttrComment` attribute. #[inline] pub fn set_comment(&mut self, comment: impl AsRef) -> &mut Self { self.comment = Some(comment.as_ref().into()); self } + /// Specifies the `kSecAttrDescription` attribute. #[inline] pub fn set_description(&mut self, description: impl AsRef) -> &mut Self { self.description = Some(description.as_ref().into()); self } + /// Specifies the `kSecAttrLabel` attribute. #[inline] pub fn set_label(&mut self, label: impl AsRef) -> &mut Self { self.label = Some(label.as_ref().into()); self } + /// Specifies which keychain to add the item to. #[inline] pub fn set_location(&mut self, location: Location) -> &mut Self { self.location = Some(location); self } + /// Specifies the `kSecAttrService` attribute. #[inline] pub fn set_service(&mut self, service: impl AsRef) -> &mut Self { self.service = Some(service.as_ref().into()); self } + /// Populates a `CFDictionary` to be passed to `update_item`. // CFDictionary should not be exposed in public Rust APIs. #[inline] @@ -910,7 +909,7 @@ impl ItemUpdateOptions { ); } #[cfg(target_os = "macos")] - Location::DefaultFileKeychain => {} + Location::DefaultFileKeychain => {}, #[cfg(target_os = "macos")] Location::FileKeychain(keychain) => { dict.add(&unsafe { kSecUseKeychain }.to_void(), &keychain.to_void()); diff --git a/security-framework/src/key.rs b/security-framework/src/key.rs index fe70037a..73971529 100644 --- a/security-framework/src/key.rs +++ b/security-framework/src/key.rs @@ -27,14 +27,14 @@ use security_framework_sys::{item::{ kSecAttrIsPermanent, kSecAttrLabel, kSecAttrKeyType, kSecAttrKeySizeInBits, kSecPrivateKeyAttrs, kSecAttrAccessControl }}; -#[cfg(target_os="macos")] +#[cfg(target_os = "macos")] use security_framework_sys::item::{ kSecAttrKeyType3DES, kSecAttrKeyTypeDSA, kSecAttrKeyTypeAES, kSecAttrKeyTypeDES, kSecAttrKeyTypeRC4, kSecAttrKeyTypeCAST, }; -use security_framework_sys::key::SecKeyGetTypeID; use security_framework_sys::base::SecKeyRef; +use security_framework_sys::key::SecKeyGetTypeID; #[cfg(any(feature = "OSX_10_12", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos"))] pub use security_framework_sys::key::Algorithm; @@ -126,7 +126,6 @@ impl KeyType { unsafe { Self(kSecAttrKeyTypeECSECPrimeRandom) } } - pub(crate) fn to_str(self) -> CFString { unsafe { CFString::wrap_under_get_rule(self.0) } } @@ -156,7 +155,7 @@ impl SecKey { #[deprecated(note = "Use SecKey::new")] pub fn generate(attributes: CFDictionary) -> Result { let mut error: CFErrorRef = ::std::ptr::null_mut(); - let sec_key = unsafe { SecKeyCreateRandomKey(attributes.as_concrete_TypeRef(), &mut error)}; + let sec_key = unsafe { SecKeyCreateRandomKey(attributes.as_concrete_TypeRef(), &mut error) }; if !error.is_null() { Err(unsafe { CFError::wrap_under_create_rule(error) }) } else { @@ -298,7 +297,9 @@ impl SecKey { shared_info: Option<&[u8]>, ) -> Result, CFError> { use core_foundation::data::CFData; - use security_framework_sys::item::{kSecKeyKeyExchangeParameterRequestedSize, kSecKeyKeyExchangeParameterSharedInfo}; + use security_framework_sys::item::{ + kSecKeyKeyExchangeParameterRequestedSize, kSecKeyKeyExchangeParameterSharedInfo, + }; unsafe { let mut params = vec![( @@ -381,26 +382,31 @@ impl GenerateKeyOptions { self.key_type = Some(key_type); self } + /// Set `size_in_bits` pub fn set_size_in_bits(&mut self, size_in_bits: u32) -> &mut Self { self.size_in_bits = Some(size_in_bits); self } + /// Set `label` pub fn set_label(&mut self, label: impl Into) -> &mut Self { self.label = Some(label.into()); self } + /// Set `token` pub fn set_token(&mut self, token: Token) -> &mut Self { self.token = Some(token); self } + /// Set `location` pub fn set_location(&mut self, location: Location) -> &mut Self { self.location = Some(location); self } + /// Set `access_control` pub fn set_access_control(&mut self, access_control: SecAccessControl) -> &mut Self { self.access_control = Some(access_control); @@ -442,18 +448,9 @@ impl GenerateKeyOptions { let mut attribute_key_values = vec![ (unsafe { kSecAttrKeyType }.to_void(), key_type.to_void()), - ( - unsafe { kSecAttrKeySizeInBits }.to_void(), - size_in_bits.to_void(), - ), - ( - unsafe { kSecPrivateKeyAttrs }.to_void(), - private_attributes.to_void(), - ), - ( - unsafe { kSecPublicKeyAttrs }.to_void(), - public_attributes.to_void(), - ), + (unsafe { kSecAttrKeySizeInBits }.to_void(), size_in_bits.to_void()), + (unsafe { kSecPrivateKeyAttrs }.to_void(), private_attributes.to_void()), + (unsafe { kSecPublicKeyAttrs }.to_void(), public_attributes.to_void()), ]; let label = self.label.as_deref().map(CFString::new); if let Some(label) = &label { diff --git a/security-framework/src/lib.rs b/security-framework/src/lib.rs index 47c49391..98d465e2 100644 --- a/security-framework/src/lib.rs +++ b/security-framework/src/lib.rs @@ -37,6 +37,8 @@ pub mod base; #[cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos"))] pub mod certificate; pub mod cipher_suite; +#[cfg(target_os = "macos")] +pub mod cms; #[cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos"))] pub mod identity; #[cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos"))] @@ -57,8 +59,6 @@ pub mod secure_transport; pub mod trust; #[cfg(target_os = "macos")] pub mod trust_settings; -#[cfg(target_os = "macos")] -pub mod cms; #[cfg(target_os = "macos")] trait Pkcs12ImportOptionsInternals { diff --git a/security-framework/src/os/macos/certificate.rs b/security-framework/src/os/macos/certificate.rs index b50ee52d..8b61c9a8 100644 --- a/security-framework/src/os/macos/certificate.rs +++ b/security-framework/src/os/macos/certificate.rs @@ -1,8 +1,7 @@ //! OSX specific extensions to certificate functionality. use core_foundation::array::{CFArray, CFArrayIterator}; -use core_foundation::base::TCFType; -use core_foundation::base::ToVoid; +use core_foundation::base::{TCFType, ToVoid}; use core_foundation::data::CFData; use core_foundation::dictionary::CFDictionary; use core_foundation::error::CFError; @@ -31,8 +30,7 @@ pub trait SecCertificateExt { /// /// The `keys` argument can optionally be used to filter the properties loaded to an explicit /// subset. - fn properties(&self, keys: Option<&[CertificateOid]>) - -> Result; + fn properties(&self, keys: Option<&[CertificateOid]>) -> Result; /// Returns the SHA-256 fingerprint of the certificate. fn fingerprint(&self) -> Result<[u8; 32], CFError> { unimplemented!() } @@ -42,10 +40,7 @@ impl SecCertificateExt for SecCertificate { fn common_name(&self) -> Result { unsafe { let mut string = ptr::null(); - cvt(SecCertificateCopyCommonName( - self.as_concrete_TypeRef(), - &mut string, - ))?; + cvt(SecCertificateCopyCommonName(self.as_concrete_TypeRef(), &mut string))?; Ok(CFString::wrap_under_create_rule(string).to_string()) } } @@ -66,18 +61,12 @@ impl SecCertificateExt for SecCertificate { #[allow(deprecated)] unsafe { let mut key = ptr::null_mut(); - cvt(SecCertificateCopyPublicKey( - self.as_concrete_TypeRef(), - &mut key, - ))?; + cvt(SecCertificateCopyPublicKey(self.as_concrete_TypeRef(), &mut key))?; Ok(SecKey::wrap_under_create_rule(key)) } } - fn properties( - &self, - keys: Option<&[CertificateOid]>, - ) -> Result { + fn properties(&self, keys: Option<&[CertificateOid]>) -> Result { unsafe { let keys = keys.map(|oids| { let oids = oids.iter().map(|oid| oid.to_str()).collect::>(); @@ -94,9 +83,7 @@ impl SecCertificateExt for SecCertificate { let dictionary = SecCertificateCopyValues(self.as_concrete_TypeRef(), keys, &mut error); if error.is_null() { - Ok(CertificateProperties(CFDictionary::wrap_under_create_rule( - dictionary, - ))) + Ok(CertificateProperties(CFDictionary::wrap_under_create_rule(dictionary))) } else { Err(CFError::wrap_under_create_rule(error)) } @@ -119,7 +106,8 @@ pub struct CertificateProperties(CFDictionary); impl CertificateProperties { /// Retrieves a specific property identified by its OID. - #[must_use] pub fn get(&self, oid: CertificateOid) -> Option { + #[must_use] + pub fn get(&self, oid: CertificateOid) -> Option { unsafe { self.0.find(oid.as_ptr().cast::()).map(|value| { CertificateProperty(CFDictionary::wrap_under_get_rule(*value as *mut _)) @@ -144,14 +132,11 @@ impl CertificateProperty { #[must_use] pub fn get(&self) -> PropertyType { unsafe { - let type_ = - CFString::wrap_under_get_rule(*self.0.get(kSecPropertyKeyType.to_void()) as *mut _); + let type_ = CFString::wrap_under_get_rule(*self.0.get(kSecPropertyKeyType.to_void()) as *mut _); let value = self.0.get(kSecPropertyKeyValue.to_void()); if type_ == CFString::wrap_under_get_rule(kSecPropertyTypeSection) { - PropertyType::Section(PropertySection(CFArray::wrap_under_get_rule( - (*value).cast(), - ))) + PropertyType::Section(PropertySection(CFArray::wrap_under_get_rule((*value).cast()))) } else if type_ == CFString::wrap_under_get_rule(kSecPropertyTypeString) { PropertyType::String(CFString::wrap_under_get_rule((*value).cast())) } else { @@ -235,10 +220,7 @@ mod test { fn fingerprint() { let certificate = certificate(); let fingerprint = p!(certificate.fingerprint()); - assert_eq!( - "af9dd180a326ae08b37e6398f9262f8b9d4c55674a233a7c84975024f873655d", - hex::encode(fingerprint) - ); + assert_eq!("af9dd180a326ae08b37e6398f9262f8b9d4c55674a233a7c84975024f873655d", hex::encode(fingerprint)); } #[test] diff --git a/security-framework/src/os/macos/code_signing.rs b/security-framework/src/os/macos/code_signing.rs index ba033524..ff12d827 100644 --- a/security-framework/src/os/macos/code_signing.rs +++ b/security-framework/src/os/macos/code_signing.rs @@ -1,15 +1,15 @@ //! Code signing services. -use std::{fmt::Debug, mem::MaybeUninit, str::FromStr}; - -use core_foundation::{ - base::{TCFType, TCFTypeRef, ToVoid}, - data::CFDataRef, - dictionary::CFMutableDictionary, - number::CFNumber, - string::{CFString, CFStringRef}, - url::CFURL, -}; +use std::fmt::Debug; +use std::mem::MaybeUninit; +use std::str::FromStr; + +use core_foundation::base::{TCFType, TCFTypeRef, ToVoid}; +use core_foundation::data::CFDataRef; +use core_foundation::dictionary::CFMutableDictionary; +use core_foundation::number::CFNumber; +use core_foundation::string::{CFString, CFStringRef}; +use core_foundation::url::CFURL; use libc::pid_t; use security_framework_sys::code_signing::{ kSecCSBasicValidateOnly, kSecCSCheckAllArchitectures, kSecCSCheckGatekeeperArchitectures, @@ -354,9 +354,7 @@ mod test { let requirement: SecRequirement = "anchor apple".parse().unwrap(); assert_eq!( - code.check_validity(Flags::NONE, &requirement) - .unwrap_err() - .code(), + code.check_validity(Flags::NONE, &requirement).unwrap_err().code(), // "code failed to satisfy specified code requirement(s)" -67050 ); @@ -369,9 +367,7 @@ mod test { let requirement: SecRequirement = "anchor apple".parse().unwrap(); assert_eq!( - code.check_validity(Flags::NONE, &requirement) - .unwrap_err() - .code(), + code.check_validity(Flags::NONE, &requirement).unwrap_err().code(), // "code object is not signed at all" -67062 ); @@ -478,9 +474,7 @@ mod test { attrs.set_audit_token(token_data.as_concrete_TypeRef()); assert_eq!( - SecCode::copy_guest_with_attribues(None, &attrs, Flags::NONE) - .unwrap_err() - .code(), + SecCode::copy_guest_with_attribues(None, &attrs, Flags::NONE).unwrap_err().code(), // "UNIX[No such process]" 100003 ); diff --git a/security-framework/src/os/macos/digest_transform.rs b/security-framework/src/os/macos/digest_transform.rs index bcdee832..ef7dceff 100644 --- a/security-framework/src/os/macos/digest_transform.rs +++ b/security-framework/src/os/macos/digest_transform.rs @@ -154,9 +154,7 @@ impl Builder { transform.set_attribute(&key, data)?; let result = transform.execute()?; - Ok(CFData::wrap_under_get_rule( - result.as_CFTypeRef() as CFDataRef - )) + Ok(CFData::wrap_under_get_rule(result.as_CFTypeRef() as CFDataRef)) } } } @@ -168,28 +166,15 @@ mod test { #[test] fn md5() { let data = CFData::from_buffer("The quick brown fox jumps over the lazy dog".as_bytes()); - let hash = Builder::new() - .type_(DigestType::md5()) - .execute(&data) - .unwrap(); - assert_eq!( - hex::encode(hash.bytes()), - "9e107d9d372bb6826bd81d3542a419d6" - ); + let hash = Builder::new().type_(DigestType::md5()).execute(&data).unwrap(); + assert_eq!(hex::encode(hash.bytes()), "9e107d9d372bb6826bd81d3542a419d6"); } #[test] fn hmac_sha1() { let data = CFData::from_buffer("The quick brown fox jumps over the lazy dog".as_bytes()); let key = CFData::from_buffer(b"key"); - let hash = Builder::new() - .type_(DigestType::hmac_sha1()) - .hmac_key(key) - .execute(&data) - .unwrap(); - assert_eq!( - hex::encode(hash.bytes()), - "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9" - ); + let hash = Builder::new().type_(DigestType::hmac_sha1()).hmac_key(key).execute(&data).unwrap(); + assert_eq!(hex::encode(hash.bytes()), "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9"); } } diff --git a/security-framework/src/os/macos/encrypt_transform.rs b/security-framework/src/os/macos/encrypt_transform.rs index b489c14d..c98d4733 100644 --- a/security-framework/src/os/macos/encrypt_transform.rs +++ b/security-framework/src/os/macos/encrypt_transform.rs @@ -196,9 +196,7 @@ impl Builder { transform.set_attribute(&key, data)?; let result = transform.execute()?; - Ok(CFData::wrap_under_get_rule( - result.as_CFTypeRef() as CFDataRef - )) + Ok(CFData::wrap_under_get_rule(result.as_CFTypeRef() as CFDataRef)) } } } diff --git a/security-framework/src/os/macos/identity.rs b/security-framework/src/os/macos/identity.rs index 0f8da464..e8940846 100644 --- a/security-framework/src/os/macos/identity.rs +++ b/security-framework/src/os/macos/identity.rs @@ -30,7 +30,7 @@ impl SecIdentityExt for SecIdentity { unsafe { let mut identity = ptr::null_mut(); cvt(SecIdentityCreateWithCertificate( - if keychains.len() > 0 {keychains.as_CFTypeRef()} else {ptr::null()}, + if keychains.len() > 0 { keychains.as_CFTypeRef() } else { ptr::null() }, certificate.as_concrete_TypeRef(), &mut identity, ))?; diff --git a/security-framework/src/os/macos/import_export.rs b/security-framework/src/os/macos/import_export.rs index 830d9483..004afec0 100644 --- a/security-framework/src/os/macos/import_export.rs +++ b/security-framework/src/os/macos/import_export.rs @@ -203,17 +203,11 @@ impl<'a> ImportOptions<'a> { for item in raw_items.iter() { let type_id = item.type_of(); if type_id == SecCertificate::type_id() { - items.certificates.push(SecCertificate::wrap_under_get_rule( - item.as_CFTypeRef() as *mut _, - )); + items.certificates.push(SecCertificate::wrap_under_get_rule(item.as_CFTypeRef() as *mut _)); } else if type_id == SecIdentity::type_id() { - items.identities.push(SecIdentity::wrap_under_get_rule( - item.as_CFTypeRef() as *mut _, - )); + items.identities.push(SecIdentity::wrap_under_get_rule(item.as_CFTypeRef() as *mut _)); } else if type_id == SecKey::type_id() { - items - .keys - .push(SecKey::wrap_under_get_rule(item.as_CFTypeRef() as *mut _)); + items.keys.push(SecKey::wrap_under_get_rule(item.as_CFTypeRef() as *mut _)); } else { panic!("Got bad type from SecItemImport: {type_id}"); } diff --git a/security-framework/src/os/macos/keychain.rs b/security-framework/src/os/macos/keychain.rs index bce5e00a..4ab9a75b 100644 --- a/security-framework/src/os/macos/keychain.rs +++ b/security-framework/src/os/macos/keychain.rs @@ -222,11 +222,11 @@ impl KeychainSettings { Some(lock_interval) => { self.0.useLockInterval = 1; self.0.lockInterval = lock_interval; - } + }, None => { self.0.useLockInterval = 0; self.0.lockInterval = i32::max_value() as u32; - } + }, } } } diff --git a/security-framework/src/os/macos/passwords.rs b/security-framework/src/os/macos/passwords.rs index 46b0a570..299ca731 100644 --- a/security-framework/src/os/macos/passwords.rs +++ b/security-framework/src/os/macos/passwords.rs @@ -46,6 +46,7 @@ impl AsRef<[u8]> for SecKeychainItemPassword { impl Deref for SecKeychainItemPassword { type Target = [u8]; + #[inline(always)] fn deref(&self) -> &Self::Target { self.as_ref() @@ -89,8 +90,7 @@ impl SecKeychainItem { /// The underlying system supports passwords with 0 values, so this /// returns a vector of bytes rather than a string. /// -/// * `keychains` is an array of keychains to search or None to search -/// the default keychain. +/// * `keychains` is an array of keychains to search or None to search the default keychain. /// * `service` is the name of the service to search for. /// * `account` is the name of the account to search for. pub fn find_generic_password( @@ -167,8 +167,7 @@ pub fn find_internet_password( server.len() as u32, server.as_ptr().cast(), security_domain.map_or(0, |s| s.len() as u32), - security_domain - .map_or(ptr::null(), |s| s.as_ptr().cast()), + security_domain.map_or(ptr::null(), |s| s.as_ptr().cast()), account.len() as u32, account.as_ptr().cast(), path.len() as u32, @@ -328,8 +327,7 @@ impl SecKeychain { server.len() as u32, server.as_ptr().cast(), security_domain.map_or(0, |s| s.len() as u32), - security_domain - .map_or(ptr::null(), |s| s.as_ptr().cast()), + security_domain.map_or(ptr::null(), |s| s.as_ptr().cast()), account.len() as u32, account.as_ptr().cast(), path.len() as u32, @@ -479,8 +477,7 @@ mod test { .expect("default keychain") .set_generic_password(service, account, &pw2) .expect("set_generic_password2"); - let (found, item) = - find_generic_password(None, service, account).expect("find_generic_password2"); + let (found, item) = find_generic_password(None, service, account).expect("find_generic_password2"); assert_eq!(found.to_owned(), pw2); item.delete(); diff --git a/security-framework/src/os/macos/secure_transport.rs b/security-framework/src/os/macos/secure_transport.rs index 222e7f66..216813dd 100644 --- a/security-framework/src/os/macos/secure_transport.rs +++ b/security-framework/src/os/macos/secure_transport.rs @@ -42,13 +42,11 @@ pub trait SslContextExt { /// If enabled, server identity changes are allowed during renegotiation. /// /// It is disabled by default to protect against triple handshake attacks. - /// fn allow_server_identity_change(&self) -> Result; /// If enabled, server identity changes are allowed during renegotiation. /// /// It is disabled by default to protect against triple handshake attacks. - /// #[deprecated(note = "kSSLSessionOptionAllowServerIdentityChange is deprecated by Apple")] fn set_allow_server_identity_change(&mut self, value: bool) -> Result<()>; @@ -67,12 +65,10 @@ pub trait SslContextExt { /// If enabled, the handshake process will pause and return when the client /// hello is recieved to support server name identification. - /// fn break_on_client_hello(&self) -> Result; /// If enabled, the handshake process will pause and return when the client /// hello is recieved to support server name identification. - /// #[deprecated(note = "kSSLSessionOptionBreakOnClientHello is deprecated by Apple")] fn set_break_on_client_hello(&mut self, value: bool) -> Result<()>; } @@ -214,10 +210,7 @@ mod test { let handle = thread::spawn(move || { let dir = p!(tempdir()); - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); let identity = identity(dir.path()); p!(ctx.set_certificate(&identity, &[])); @@ -229,10 +222,7 @@ mod test { assert_eq!(&buf[..], b"hello world!"); }); - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_break_on_server_auth(true)); let stream = p!(TcpStream::connect(("localhost", port))); @@ -293,10 +283,7 @@ mod test { let handle = thread::spawn(move || { let dir = p!(tempdir()); - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); let identity = identity(dir.path()); p!(ctx.set_certificate(&identity, &[])); @@ -305,9 +292,7 @@ mod test { }); let stream = p!(TcpStream::connect(("localhost", port))); - assert!(ClientBuilder::new() - .handshake("foobar.com", stream) - .is_err()); + assert!(ClientBuilder::new().handshake("foobar.com", stream).is_err()); handle.join().unwrap(); } @@ -321,10 +306,7 @@ mod test { let handle = thread::spawn(move || { let dir = p!(tempdir()); - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); let identity = identity(dir.path()); p!(ctx.set_certificate(&identity, &[])); @@ -353,10 +335,7 @@ mod test { let handle = thread::spawn(move || { let dir = p!(tempdir()); - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); let identity = identity(dir.path()); p!(ctx.set_certificate(&identity, &[])); p!(ctx.set_enabled_ciphers(&[ @@ -374,10 +353,7 @@ mod test { p!(stream.read(&mut buf)); }); - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_break_on_server_auth(true)); p!(ctx.set_enabled_ciphers(&[ CipherSuite::TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, @@ -405,10 +381,7 @@ mod test { fn dh_params() { let params = include_bytes!("../../../test/dhparam.der"); - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); assert!(p!(ctx.diffie_hellman_params()).is_none()); p!(ctx.set_diffie_hellman_params(params)); assert_eq!(p!(ctx.diffie_hellman_params()).unwrap(), ¶ms[..]); @@ -422,10 +395,7 @@ mod test { let handle = thread::spawn(move || { let dir = p!(tempdir()); - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); let identity = identity(dir.path()); p!(ctx.set_certificate(&identity, &[])); p!(ctx.set_client_side_authenticate(SslAuthenticate::TRY)); @@ -438,10 +408,7 @@ mod test { p!(stream.read(&mut buf)); }); - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_break_on_server_auth(true)); let stream = p!(TcpStream::connect(("localhost", port))); @@ -465,10 +432,7 @@ mod test { let handle = thread::spawn(move || { let dir = p!(tempdir()); - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); let identity = identity(dir.path()); p!(ctx.set_certificate(&identity, &[])); p!(ctx.set_client_side_authenticate(SslAuthenticate::ALWAYS)); @@ -477,15 +441,12 @@ mod test { match ctx.handshake(stream) { Ok(_) => panic!("unexpected success"), - Err(HandshakeError::Failure(_)) => {} + Err(HandshakeError::Failure(_)) => {}, Err(err) => panic!("unexpected error {err:?}"), } }); - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_break_on_server_auth(true)); let stream = p!(TcpStream::connect(("localhost", port))); @@ -497,7 +458,7 @@ mod test { match stream.handshake() { Ok(_) => panic!("unexpected success"), - Err(HandshakeError::Failure(_)) => {} + Err(HandshakeError::Failure(_)) => {}, Err(err) => panic!("unexpected error {err:?}"), } @@ -512,10 +473,7 @@ mod test { let handle = thread::spawn(move || { let dir = p!(tempdir()); - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); let identity = identity(dir.path()); p!(ctx.set_certificate(&identity, &[])); p!(ctx.set_client_side_authenticate(SslAuthenticate::ALWAYS)); @@ -524,15 +482,12 @@ mod test { match ctx.handshake(stream) { Ok(_) => panic!("unexpected success"), - Err(HandshakeError::Failure(_)) => {} + Err(HandshakeError::Failure(_)) => {}, Err(err) => panic!("unexpected error {err:?}"), } }); - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_break_on_server_auth(true)); let dir = p!(tempdir()); let identity = identity(dir.path()); @@ -547,7 +502,7 @@ mod test { match stream.handshake() { Ok(_) => panic!("unexpected success"), - Err(HandshakeError::Failure(_)) => {} + Err(HandshakeError::Failure(_)) => {}, Err(err) => panic!("unexpected error {err:?}"), } @@ -556,10 +511,7 @@ mod test { #[test] fn certificate_authorities() { - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); assert!(p!(ctx.certificate_authorities()).is_none()); p!(ctx.set_certificate_authorities(&[certificate()])); assert_eq!(p!(ctx.certificate_authorities()).unwrap().len(), 1); diff --git a/security-framework/src/os/macos/transform.rs b/security-framework/src/os/macos/transform.rs index 12011884..da4cf619 100644 --- a/security-framework/src/os/macos/transform.rs +++ b/security-framework/src/os/macos/transform.rs @@ -18,9 +18,7 @@ unsafe impl Send for SecTransform {} impl SecTransform { /// Sets an attribute of the transform. pub fn set_attribute(&mut self, key: &CFString, value: &T) -> Result<(), CFError> - where - T: TCFType, - { + where T: TCFType { unsafe { let mut error = ptr::null_mut(); SecTransformSetAttribute( diff --git a/security-framework/src/passwords.rs b/security-framework/src/passwords.rs index e8ea6cf0..34f02c03 100644 --- a/security-framework/src/passwords.rs +++ b/security-framework/src/passwords.rs @@ -29,9 +29,7 @@ pub fn set_generic_password(service: &str, account: &str, password: &[u8]) -> Re /// Set a generic password using the given password options. /// Creates or updates a keychain entry. -pub fn set_generic_password_options( - password: &[u8], - mut options: PasswordOptions) -> Result<()> { +pub fn set_generic_password_options(password: &[u8], mut options: PasswordOptions) -> Result<()> { set_password_internal(&mut options, password) } diff --git a/security-framework/src/passwords_options.rs b/security-framework/src/passwords_options.rs index 7b111398..57f04635 100644 --- a/security-framework/src/passwords_options.rs +++ b/security-framework/src/passwords_options.rs @@ -1,13 +1,14 @@ //! Support for password options, to be used with the passwords module -use core_foundation::{string::CFString, base::{CFType, TCFType, CFOptionFlags}, number::CFNumber}; -use security_framework_sys::{access_control::*, item::kSecAttrAccessGroup, keychain::{SecAuthenticationType, SecProtocolType}}; +use crate::access_control::SecAccessControl; +use core_foundation::base::{CFOptionFlags, CFType, TCFType}; +use core_foundation::number::CFNumber; +use core_foundation::string::CFString; +use security_framework_sys::access_control::*; use security_framework_sys::item::{ - kSecAttrAccessControl, kSecAttrAccount, kSecAttrAuthenticationType, kSecAttrPath, kSecAttrPort, kSecAttrProtocol, - kSecAttrSecurityDomain, kSecAttrServer, kSecAttrService, kSecClass, kSecClassGenericPassword, - kSecClassInternetPassword, + kSecAttrAccessControl, kSecAttrAccessGroup, kSecAttrAccount, kSecAttrAuthenticationType, kSecAttrPath, kSecAttrPort, kSecAttrProtocol, kSecAttrSecurityDomain, kSecAttrServer, kSecAttrService, kSecClass, kSecClassGenericPassword, kSecClassInternetPassword }; -use crate::access_control::SecAccessControl; +use security_framework_sys::keychain::{SecAuthenticationType, SecProtocolType}; /// `PasswordOptions` constructor pub struct PasswordOptions { @@ -48,20 +49,15 @@ impl PasswordOptions { /// Create a new generic password options /// Generic passwords are identified by service and account. They have other /// attributes, but this interface doesn't allow specifying them. - #[must_use] pub fn new_generic_password(service: &str, account: &str) -> Self { + #[must_use] + pub fn new_generic_password(service: &str, account: &str) -> Self { let query = vec![ ( unsafe { CFString::wrap_under_get_rule(kSecClass) }, unsafe { CFString::wrap_under_get_rule(kSecClassGenericPassword).into_CFType() }, ), - ( - unsafe { CFString::wrap_under_get_rule(kSecAttrService) }, - CFString::from(service).into_CFType(), - ), - ( - unsafe { CFString::wrap_under_get_rule(kSecAttrAccount) }, - CFString::from(account).into_CFType(), - ), + (unsafe { CFString::wrap_under_get_rule(kSecAttrService) }, CFString::from(service).into_CFType()), + (unsafe { CFString::wrap_under_get_rule(kSecAttrAccount) }, CFString::from(account).into_CFType()), ]; #[allow(deprecated)] Self { query } @@ -70,7 +66,8 @@ impl PasswordOptions { /// Create a new internet password options /// Internet passwords are identified by a number of attributes. /// They can have others, but this interface doesn't allow specifying them. - #[must_use] pub fn new_internet_password( + #[must_use] + pub fn new_internet_password( server: &str, security_domain: Option<&str>, account: &str, @@ -84,22 +81,10 @@ impl PasswordOptions { unsafe { CFString::wrap_under_get_rule(kSecClass) }, unsafe { CFString::wrap_under_get_rule(kSecClassInternetPassword) }.into_CFType(), ), - ( - unsafe { CFString::wrap_under_get_rule(kSecAttrServer) }, - CFString::from(server).into_CFType(), - ), - ( - unsafe { CFString::wrap_under_get_rule(kSecAttrPath) }, - CFString::from(path).into_CFType(), - ), - ( - unsafe { CFString::wrap_under_get_rule(kSecAttrAccount) }, - CFString::from(account).into_CFType(), - ), - ( - unsafe { CFString::wrap_under_get_rule(kSecAttrProtocol) }, - CFNumber::from(protocol as i32).into_CFType(), - ), + (unsafe { CFString::wrap_under_get_rule(kSecAttrServer) }, CFString::from(server).into_CFType()), + (unsafe { CFString::wrap_under_get_rule(kSecAttrPath) }, CFString::from(path).into_CFType()), + (unsafe { CFString::wrap_under_get_rule(kSecAttrAccount) }, CFString::from(account).into_CFType()), + (unsafe { CFString::wrap_under_get_rule(kSecAttrProtocol) }, CFNumber::from(protocol as i32).into_CFType()), ( unsafe { CFString::wrap_under_get_rule(kSecAttrAuthenticationType) }, CFNumber::from(authentication_type as i32).into_CFType(), @@ -126,9 +111,7 @@ impl PasswordOptions { #[allow(deprecated)] self.query.push(( unsafe { CFString::wrap_under_get_rule(kSecAttrAccessControl) }, - SecAccessControl::create_with_flags(options.bits()) - .unwrap() - .into_CFType(), + SecAccessControl::create_with_flags(options.bits()).unwrap().into_CFType(), )); } diff --git a/security-framework/src/policy.rs b/security-framework/src/policy.rs index f70a97c5..fec04474 100644 --- a/security-framework/src/policy.rs +++ b/security-framework/src/policy.rs @@ -1,9 +1,7 @@ //! Security Policies support. -use core_foundation::base::CFOptionFlags; -use core_foundation::base::TCFType; +use core_foundation::base::{CFOptionFlags, TCFType}; use core_foundation::string::CFString; -use security_framework_sys::base::errSecParam; -use security_framework_sys::base::SecPolicyRef; +use security_framework_sys::base::{errSecParam, SecPolicyRef}; use security_framework_sys::policy::*; use std::fmt; use std::ptr; diff --git a/security-framework/src/random.rs b/security-framework/src/random.rs index 7bd7f614..51d7f436 100644 --- a/security-framework/src/random.rs +++ b/security-framework/src/random.rs @@ -1,6 +1,6 @@ //! Randomness support. -use security_framework_sys::random::{SecRandomCopyBytes, SecRandomRef, kSecRandomDefault}; +use security_framework_sys::random::{kSecRandomDefault, SecRandomCopyBytes, SecRandomRef}; use std::io; /// A source of random data. diff --git a/security-framework/src/secure_transport.rs b/security-framework/src/secure_transport.rs index c22c9758..fa80d621 100644 --- a/security-framework/src/secure_transport.rs +++ b/security-framework/src/secure_transport.rs @@ -5,9 +5,9 @@ //! To connect as a client to a server with a certificate trusted by the system: //! //! ```rust +//! use security_framework::secure_transport::ClientBuilder; //! use std::io::prelude::*; //! use std::net::TcpStream; -//! use security_framework::secure_transport::ClientBuilder; //! //! let stream = TcpStream::connect("google.com:443").unwrap(); //! let mut stream = ClientBuilder::new().handshake("google.com", stream).unwrap(); @@ -23,16 +23,16 @@ //! `ClientBuilder`: //! //! ```rust,no_run +//! use security_framework::secure_transport::ClientBuilder; //! use std::io::prelude::*; //! use std::net::TcpStream; -//! use security_framework::secure_transport::ClientBuilder; //! //! # let root_cert = unsafe { std::mem::zeroed() }; //! let stream = TcpStream::connect("my_server.com:443").unwrap(); //! let mut stream = ClientBuilder::new() -//! .anchor_certificates(&[root_cert]) -//! .handshake("my_server.com", stream) -//! .unwrap(); +//! .anchor_certificates(&[root_cert]) +//! .handshake("my_server.com", stream) +//! .unwrap(); //! //! stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); //! let mut page = vec![]; @@ -45,9 +45,9 @@ //! To run a server: //! //! ```rust,no_run +//! use security_framework::secure_transport::{SslConnectionType, SslContext, SslProtocolSide}; //! use std::net::TcpListener; //! use std::thread; -//! use security_framework::secure_transport::{SslContext, SslProtocolSide, SslConnectionType}; //! //! // Create a TCP listener and start accepting on it. //! let mut listener = TcpListener::bind("0.0.0.0:443").unwrap(); @@ -70,7 +70,6 @@ //! let mut stream = ctx.handshake(stream).unwrap(); //! }); //! } -//! //! ``` #[allow(unused_imports)] use core_foundation::array::{CFArray, CFArrayRef}; @@ -114,11 +113,10 @@ use security_framework_sys::base::errSecParam; pub struct SslProtocolSide(SSLProtocolSide); impl SslProtocolSide { - /// The server side of the session. - pub const SERVER: Self = Self(kSSLServerSide); - /// The client side of the session. pub const CLIENT: Self = Self(kSSLClientSide); + /// The server side of the session. + pub const SERVER: Self = Self(kSSLServerSide); } /// Specifies the type of TLS session. @@ -126,11 +124,10 @@ impl SslProtocolSide { pub struct SslConnectionType(SSLConnectionType); impl SslConnectionType { - /// A traditional TLS stream. - pub const STREAM: Self = Self(kSSLStreamType); - /// A DTLS session. pub const DATAGRAM: Self = Self(kSSLDatagramType); + /// A traditional TLS stream. + pub const STREAM: Self = Self(kSSLStreamType); } /// An error or intermediate state after a TLS handshake attempt. @@ -283,9 +280,7 @@ impl MidHandshakeClientBuilder { let stream = match result { Ok(stream) => return Ok(stream), Err(HandshakeError::Interrupted(stream)) => stream, - Err(HandshakeError::Failure(err)) => { - return Err(ClientHandshakeError::Failure(err)) - } + Err(HandshakeError::Failure(err)) => return Err(ClientHandshakeError::Failure(err)), }; if stream.would_block() { @@ -309,7 +304,7 @@ impl MidHandshakeClientBuilder { None => { result = stream.handshake(); continue; - } + }, }; trust.set_anchor_certificates(&certs)?; trust.set_trust_anchor_certificates_only(self.trust_certs_only)?; @@ -502,11 +497,7 @@ impl SslContext { pub fn set_peer_domain_name(&mut self, peer_name: &str) -> Result<()> { unsafe { // SSLSetPeerDomainName doesn't need a null terminated string - cvt(SSLSetPeerDomainName( - self.0, - peer_name.as_ptr().cast(), - peer_name.len(), - )) + cvt(SSLSetPeerDomainName(self.0, peer_name.as_ptr().cast(), peer_name.len())) } } @@ -516,11 +507,7 @@ impl SslContext { let mut len = 0; cvt(SSLGetPeerDomainNameLength(self.0, &mut len))?; let mut buf = vec![0; len]; - cvt(SSLGetPeerDomainName( - self.0, - buf.as_mut_ptr().cast(), - &mut len, - ))?; + cvt(SSLGetPeerDomainName(self.0, buf.as_mut_ptr().cast(), &mut len))?; Ok(String::from_utf8(buf).unwrap()) } } @@ -905,18 +892,18 @@ where Ok(Ok(0)) => { ret = errSSLClosedNoNotify; break; - } + }, Ok(Ok(len)) => start += len, Ok(Err(e)) => { ret = translate_err(&e); conn.err = Some(e); break; - } + }, Err(e) => { ret = errSecIO; conn.panic = Some(e); break; - } + }, } } @@ -942,18 +929,18 @@ where Ok(Ok(0)) => { ret = errSSLClosedNoNotify; break; - } + }, Ok(Ok(len)) => start += len, Ok(Err(e)) => { ret = translate_err(&e); conn.err = Some(e); break; - } + }, Err(e) => { ret = errSecIO; conn.panic = Some(e); break; - } + }, } } @@ -1000,11 +987,11 @@ impl SslStream { stream: self, error: Error::from_code(reason), })) - } + }, err => { self.check_panic(); Err(HandshakeError::Failure(Error::from_code(err))) - } + }, } } @@ -1351,9 +1338,7 @@ impl ClientBuilder { } fn ctx_into_stream(&self, domain: &str, stream: S) -> Result> - where - S: Read + Write, - { + where S: Read + Write { let mut ctx = SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)?; if self.use_sni { @@ -1462,9 +1447,7 @@ impl ServerBuilder { /// Initiates a new SSL/TLS session over a stream. pub fn handshake(&self, stream: S) -> Result> - where - S: Read + Write, - { + where S: Read + Write { match self.new_ssl_context()?.handshake(stream) { Ok(stream) => Ok(stream), Err(HandshakeError::Interrupted(stream)) => Err(*stream.error()), @@ -1488,10 +1471,7 @@ mod test { #[test] fn connect() { - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_peer_domain_name("google.com")); let stream = p!(TcpStream::connect("google.com:443")); p!(ctx.handshake(stream)); @@ -1499,24 +1479,18 @@ mod test { #[test] fn connect_bad_domain() { - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_peer_domain_name("foobar.com")); let stream = p!(TcpStream::connect("google.com:443")); match ctx.handshake(stream) { Ok(_) => panic!("expected failure"), - Err(_) => {} + Err(_) => {}, } } #[test] fn load_page() { - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_peer_domain_name("google.com")); let stream = p!(TcpStream::connect("google.com:443")); let mut stream = p!(ctx.handshake(stream)); @@ -1573,10 +1547,7 @@ mod test { if let Err(HandshakeError::Interrupted(stream)) = result { assert!(stream.server_auth_completed()); - assert_eq!( - i, 0, - "Session ticket resumption did not work, server auth was not skipped" - ); + assert_eq!(i, 0, "Session ticket resumption did not work, server auth was not skipped"); result = stream.handshake(); } else { assert_eq!(i, 1, "Unexpectedly skipped server auth"); @@ -1589,10 +1560,7 @@ mod test { #[test] #[cfg(feature = "alpn")] fn client_alpn_accept() { - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_peer_domain_name("google.com")); p!(ctx.set_alpn_protocols(&vec!["h2"])); let stream = p!(TcpStream::connect("google.com:443")); @@ -1603,10 +1571,7 @@ mod test { #[test] #[cfg(feature = "alpn")] fn client_alpn_reject() { - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_peer_domain_name("google.com")); p!(ctx.set_alpn_protocols(&vec!["h2c"])); let stream = p!(TcpStream::connect("google.com:443")); @@ -1662,10 +1627,7 @@ mod test { #[test] #[cfg_attr(any(target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos"), ignore)] // FIXME what's going on with ios? fn cipher_configuration() { - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); let ciphers = p!(ctx.enabled_ciphers()); let ciphers = ciphers .iter() @@ -1680,10 +1642,7 @@ mod test { fn test_builder_whitelist_ciphers() { let stream = p!(TcpStream::connect("google.com:443")); - let ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); assert!(p!(ctx.enabled_ciphers()).len() > 1); let ciphers = p!(ctx.enabled_ciphers()); @@ -1700,10 +1659,7 @@ mod test { fn test_builder_blacklist_ciphers() { let stream = p!(TcpStream::connect("google.com:443")); - let ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); let num = p!(ctx.enabled_ciphers()).len(); assert!(num > 1); @@ -1718,19 +1674,13 @@ mod test { #[test] fn idle_context_peer_trust() { - let ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); assert!(ctx.peer_trust2().is_err()); } #[test] fn peer_id() { - let mut ctx = p!(SslContext::new( - SslProtocolSide::SERVER, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)); assert!(p!(ctx.peer_id()).is_none()); p!(ctx.set_peer_id(b"foobar")); assert_eq!(p!(ctx.peer_id()), Some(&b"foobar"[..])); @@ -1738,10 +1688,7 @@ mod test { #[test] fn peer_domain_name() { - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); assert_eq!("", p!(ctx.peer_domain_name())); p!(ctx.set_peer_domain_name("foobar.com")); assert_eq!("foobar.com", p!(ctx.peer_domain_name())); @@ -1768,10 +1715,7 @@ mod test { } } - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_peer_domain_name("google.com")); let stream = p!(TcpStream::connect("google.com:443")); let _ = ctx.handshake(ExplodingStream(stream)); @@ -1798,10 +1742,7 @@ mod test { } } - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_peer_domain_name("google.com")); let stream = p!(TcpStream::connect("google.com:443")); let _ = ctx.handshake(ExplodingStream(stream)); @@ -1809,10 +1750,7 @@ mod test { #[test] fn zero_length_buffers() { - let mut ctx = p!(SslContext::new( - SslProtocolSide::CLIENT, - SslConnectionType::STREAM - )); + let mut ctx = p!(SslContext::new(SslProtocolSide::CLIENT, SslConnectionType::STREAM)); p!(ctx.set_peer_domain_name("google.com")); let stream = p!(TcpStream::connect("google.com:443")); let mut stream = ctx.handshake(stream).unwrap(); diff --git a/security-framework/src/trust.rs b/security-framework/src/trust.rs index 69440d3d..99883ccf 100644 --- a/security-framework/src/trust.rs +++ b/security-framework/src/trust.rs @@ -214,11 +214,7 @@ impl SecTrust { /// Returns the public key for a leaf certificate after it has been evaluated. #[inline] pub fn copy_public_key(&mut self) -> Result { - unsafe { - Ok(SecKey::wrap_under_create_rule(SecTrustCopyPublicKey( - self.0, - ))) - } + unsafe { Ok(SecKey::wrap_under_create_rule(SecTrustCopyPublicKey(self.0))) } } /// Evaluates trust. @@ -247,8 +243,7 @@ impl SecTrust { #[cfg(not(any(feature = "OSX_10_14", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos")))] #[allow(deprecated)] { - use security_framework_sys::base::errSecNotTrusted; - use security_framework_sys::base::errSecTrustSettingDeny; + use security_framework_sys::base::{errSecNotTrusted, errSecTrustSettingDeny}; let code = match self.evaluate() { Ok(res) if res.success() => return Ok(()), diff --git a/security-framework/src/trust_settings.rs b/security-framework/src/trust_settings.rs index 8ccdedc2..e2889f51 100644 --- a/security-framework/src/trust_settings.rs +++ b/security-framework/src/trust_settings.rs @@ -7,8 +7,7 @@ use core_foundation::number::CFNumber; use core_foundation::string::CFString; use core_foundation_sys::base::CFTypeRef; -use security_framework_sys::base::errSecNoTrustSettings; -use security_framework_sys::base::errSecSuccess; +use security_framework_sys::base::{errSecNoTrustSettings, errSecSuccess}; use security_framework_sys::trust_settings::*; use std::ptr; @@ -127,7 +126,7 @@ impl TrustSettings { /// /// It is not possible to modify per-user trust settings when not running in a GUI /// environment, if you try it will return error `2070: errSecInternalComponent` - #[cfg(target_os="macos")] + #[cfg(target_os = "macos")] pub fn set_trust_settings_always(&self, cert: &SecCertificate) -> Result<()> { let domain = self.domain; let trust_settings: CFTypeRef = ptr::null_mut(); @@ -152,14 +151,11 @@ impl TrustSettings { /// given domain `None` is returned. /// /// Otherwise, the specific trust settings are aggregated and returned. - pub fn tls_trust_settings_for_certificate(&self, cert: &SecCertificate) - -> Result> { + pub fn tls_trust_settings_for_certificate(&self, cert: &SecCertificate) -> Result> { let trust_settings = unsafe { let mut array_ptr: CFArrayRef = ptr::null_mut(); let cert_ptr = cert.as_CFTypeRef() as *mut _; - cvt(SecTrustSettingsCopyTrustSettings(cert_ptr, - self.domain.into(), - &mut array_ptr))?; + cvt(SecTrustSettingsCopyTrustSettings(cert_ptr, self.domain.into(), &mut array_ptr))?; CFArray::::wrap_under_create_rule(array_ptr) }; @@ -295,11 +291,9 @@ mod test { fn test_unknown_cert_is_not_trusted() { let ts = TrustSettings::new(Domain::System); let cert = certificate(); - assert_eq!(ts.tls_trust_settings_for_certificate(&cert) - .err() - .unwrap() - .message(), - Some("The specified item could not be found in the keychain.".into())); + assert_eq!( + ts.tls_trust_settings_for_certificate(&cert).err().unwrap().message(), + Some("The specified item could not be found in the keychain.".into()) + ); } } - diff --git a/systest/src/main.rs b/systest/src/main.rs index 55178724..15795b00 100644 --- a/systest/src/main.rs +++ b/systest/src/main.rs @@ -18,6 +18,7 @@ use security_framework_sys::certificate::*; #[cfg(target_os = "macos")] use security_framework_sys::certificate_oids::*; use security_framework_sys::cipher_suite::*; +use security_framework_sys::cms::*; #[cfg(target_os = "macos")] use security_framework_sys::code_signing::*; #[cfg(target_os = "macos")] @@ -39,6 +40,5 @@ use security_framework_sys::secure_transport::*; use security_framework_sys::transform::*; use security_framework_sys::trust::*; use security_framework_sys::trust_settings::*; -use security_framework_sys::cms::*; include!(concat!(env!("OUT_DIR"), "/all.rs"));