security-rs
Safe Rust bindings for Apple's Security framework on macOS.
Installation
[]
= "0.8"
Requires macOS 12 or later and Rust 1.82 or later. Some APIs need a newer macOS and return an
error on older systems: PKCS#12 import needs macOS 15 (see below), certificate validity dates
need macOS 15, and the AppleSslServer/AppleSslClient-style policy identifiers need macOS 15.4.
Highlights
- Swift bridge over
Security.frameworkwith retained opaque handles and ergonomic Rust wrappers. - No Rust dependencies, including development and build dependencies.
- Structured bridge values use a shared C ABI, with no text format.
- Wrappers for the 158 top-level functions listed as verified in
COVERAGE_AUDIT.md. That audit counts a self-selected set of 321 functions from 25 headers (163 marked exempt), not the whole framework or its constants. - Raw C FFI preserved behind the
raw-ffiCargo feature, now exhaustively covering the non-deprecated macOSSecAccessControl/SecItem/SecKey/SecPolicyheaders. - Internet password items with server-based account updates, binary secrets, and exact
OSStatuserrors. - Public-key import through
PublicKey::from_dataand fixed-width ECDSA signatures throughEcdsaSignatureDigestRfc4754. - Safe modules for all primary logical areas:
keychainidentitycertificatekeypolicytrustauthorizationcoderandom_bytestransformsecure_transportcmskey_derivationkey_agreement
- 17 numbered headless examples plus integration tests across every area.
Quick start
use *;
Identifying a peer process
Look peers up by audit token, never by PID: a PID can be reused by another process between the
lookup and the check. Code::task() only works for code looked up by audit token (or the current
process) and returns SecurityError::Unsupported otherwise.
use ;
Code::from_xpc_message wraps SecCodeCreateWithXPCMessage for a received XPC message.
ECDSA signatures
PublicKey::from_data(point, KeyType::EcSecPrimeRandom, 256) imports an uncompressed X9.63 P-256 public point.
The point has 65 bytes, with 0x04 before the two 32-byte coordinates.
Use SignatureAlgorithm::EcdsaSignatureDigestRfc4754 with a SHA-256 digest and a 64-byte r || s signature.
The caller selects the hash and checks the signature length.
verify_signature returns false for a signature that does not match.
These APIs support macOS 12.
For public-key verification alone, set default-features = false.
This mode supplies PublicKey, Certificate, PrivateKey, the algorithm types, and error types.
Certificate::from_pem and the other framework modules require the default full feature.
Both feature sets have no Rust dependencies.
On other targets, the library has no API and the build script does not invoke Swift.
Version 0.8
The bridge exchanges structured values through SecurityBridgeABI.h, which Swift imports.
Rust maps each configuration field to the shared #[repr(C)] records.
Strings, data, arrays, and dictionary keys use a pointer and a length.
Rust owns input buffers until the call returns.
Swift copies inputs before an asynchronous request starts.
Swift owns each result handle and its child buffers until Rust releases the handle with security_release_handle.
APIs that previously used a serialization value now use security::Value.
This enum preserves signed integers, unsigned integers, real numbers, strings, data, dates, URLs, arrays, and dictionaries.
Data uses Value::Data, not a base64 object.
Dates use Value::Date with Unix seconds, not a dictionary.
Policy configuration and the public-key signature APIs keep their existing Rust arguments.
The flag types use native integer fields and preserve their constants, bit operations, and checked constructors.
The crate decodes PEM base64 itself.
Secret buffers use volatile writes and a compiler fence before deallocation.
The async feature uses a standard-library future and waker.
Raw Core Foundation declarations and security::error::NullPointerError now belong to this crate, not apple-cf.
Keychain items
Secrets are bytes and come back as SecretBytes, which zeroizes its buffer on drop and redacts
Debug. Items default to AccessControlProtection::WhenUnlocked. KeychainOptions selects the
protection class (including the ThisDeviceOnly classes), the data protection keychain, an access
group, synchronization, an AccessControl (for example user presence), and an LAContext from
localauthentication-rs
(LAContext::as_raw_la_context) to bind a read to an authentication the user already passed.
use ;
AccessControl wraps a real SecAccessControlRef. The object cannot be changed after creation, so
Clone shares it. cryptokit-rs Secure Enclave key creation and apple-localauthentication's
LAContext::evaluate_access_control take the same AccessControl (both crates re-export it).
AccessControl::as_ptr lends the borrowed ref to other FFI code; it is valid while the
AccessControl is alive.
InternetPassword::set updates an item by server and adds it if none exists.
InternetPassword::get returns an InternetCredential, or None if the item is absent or the user cancels.
InternetPassword::delete reports an error if the item does not exist.
If a SecItem call fails, use SecurityError::code() to get the exact OSStatus.
For SecurityError::Status(error), error.operation identifies the failed SecItem call.
Compare the status with security::error::status::{SUCCESS, ITEM_NOT_FOUND, USER_CANCELED, AUTH_FAILED}.
If a read result lacks a string account or data secret, InternetPassword::get returns SecurityError::UnexpectedType.
The data protection keychain, access groups, synchronizable items and access-controlled items need
a signed process with a keychain access group entitlement; unsigned tools get
errSecMissingEntitlement (security::error::status::MISSING_ENTITLEMENT).
Area overview
Keychain: generic-password CRUD for binary secrets with protection class, data protection keychain, access group, synchronizable, access-control and authentication-context options; service account listing; access-control creation.InternetPassword: internet-password CRUD by server with account updates and binary secrets.Identity: PKCS#12 import, certificate access, identity creation, preference lookup/updates, system-identity management, and private-key attribute inspection. PKCS#12 import needs macOS 15: before thatSecPKCS12Importalways stores the private key in the login keychain, soimport_pkcs12_firstreturnsSecurityError::Unsupportedinstead.Certificate: DER/PEM loading, Security item import/export, descriptions, values, preferences, summaries, names, emails, serials, validity dates, and public keys.Key: raw/private-key import, modern signing, RSA encryption/decryption, external representations, block-size inspection, andSecKeytype IDs.Policy/Trust: basic X.509, SSL, revocation, generic property builders, policy type IDs, custom anchors, verify dates, exceptions, OCSP / SCT inputs, async evaluation, derived keys, and evaluated trust results.Policy::ssl(server, hostname)verifies the hostname;Policy::ssl_any_hostnameis the explicit opt-out.Authorization: authorization creation, external-form round trips, info inspection, synchronous / async rights acquisition, and destroying shared rights on drop.Code: current-process code objects, audit-token and XPC peer lookup, host / guest lookup, requirements, dynamic and static validation, resource validation, memory mapping, and task entitlement inspection.RandomBytes:SecRandomCopyByteswrappers.Transform: base64 encode/decode using deprecated but still functionalSecTransformAPIs.SecureTransport: minimal context creation, protocol bounds, and state inspection.CMS: certificate-bag helpers plus low-level encoder / decoder access for content, signers, recipients, timestamps, detached payloads, and chain configuration.CmsDecoder::signer_statusreturns a typed report; withevaluate_sec_trust = falsethe signer certificate is reported as not evaluated and the report carries theTrustto evaluate.KeyDerivation: PBKDF2-style symmetric-key derivation throughSecKeyDeriveFromPassword, with the derived bytes available asSecretBytes.KeyAgreement: ephemeral P-256 key generation and ECDH shared-secret derivation.
Examples
Run every numbered example:
for; do ; done
Key examples:
01_keychain_password05_trust_evaluate07_code_signing_info11_cms_cert_bag13_key_agreement_shared_secret14_key_import_sign_verify15_key_encrypt_export17_internet_password
Raw FFI
Enable the legacy raw C declarations when you need direct Security.framework symbols. The raw-ffi feature now exposes the non-deprecated macOS-available SecAccessControl.h, SecItem.h, SecKey.h, and SecPolicy.h surfaces end-to-end:
The default API path stays on the Swift bridge so Rust code does not call the C-only framework surface directly.
Coverage notes
See COVERAGE.md for the header audit and per-area implementation / partial / skipped status.
License
Licensed under either of Apache-2.0 or MIT at your option.