Skip to main content

Crate security

Crate security 

Source
Available on macOS only.
Expand description

§security-rs

Safe Rust bindings for Apple’s Security framework on macOS.

§Installation

[dependencies]
security-rs = "0.7"

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.framework with retained opaque handles and ergonomic Rust wrappers.
  • 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-ffi Cargo feature, now exhaustively covering the non-deprecated macOS SecAccessControl / SecItem / SecKey / SecPolicy headers.
  • Internet password items with server-based account updates, binary secrets, and exact OSStatus errors.
  • Public-key import through PublicKey::from_data and fixed-width ECDSA signatures through EcdsaSignatureDigestRfc4754.
  • Safe modules for all primary logical areas:
    • keychain
    • identity
    • certificate
    • key
    • policy
    • trust
    • authorization
    • code
    • random_bytes
    • transform
    • secure_transport
    • cms
    • key_derivation
    • key_agreement
  • 17 numbered headless examples plus integration tests across every area.

§Quick start

use security::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let certificate = Certificate::from_der(&std::fs::read("tests/fixtures/test-cert.der")?)?;
    let policy = Policy::basic_x509()?;
    let mut trust = Trust::new(&certificate, &[policy])?;
    trust.set_anchor_certificates(&[certificate])?;
    trust.set_anchor_certificates_only(true)?;
    trust.evaluate()?;

    let encoded = Transform::encode_base64(b"hello")?;
    assert_eq!(Transform::decode_base64(encoded.as_bytes())?, b"hello");

    let random = SecureRandom::bytes(16)?;
    assert_eq!(random.len(), 16);
    Ok(())
}

§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 security::{AuditToken, Code, CodeSigningFlags, Requirement};

fn client_is_allowed(token: AuditToken) -> security::Result<bool> {
    let client = Code::guest_with_audit_token(&token)?;
    let requirement = Requirement::from_string(
        "anchor apple generic and certificate leaf[subject.OU] = \"TEAMID1234\"",
    )?;
    client.check_validity(CodeSigningFlags::empty(), Some(&requirement))?;
    Ok(client.task()?.entitlement("com.example.helper-client")?.is_some())
}

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 without base64 or zeroize. Certificate::from_pem and the other framework modules require the default full feature. Version 0.7 changes default-features = false to this reduced API. The default API remains unchanged. On other targets, the library has no API and the build script does not invoke Swift.

§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 security::{AccessControl, AccessControlFlags, AccessControlProtection, Keychain, KeychainOptions};

fn store_token(token: &[u8]) -> security::Result<()> {
    let presence = AccessControl::create(
        AccessControlProtection::WhenUnlockedThisDeviceOnly,
        AccessControlFlags::USER_PRESENCE,
    )?;
    let options = KeychainOptions::default()
        .data_protection_keychain(true)
        .access_control(presence);
    Keychain::set_with_options("api-token", "com.example.app", token, &options)
}

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 that SecPKCS12Import always stores the private key in the login keychain, so import_pkcs12_first returns SecurityError::Unsupported instead.
  • 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, and SecKey type 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_hostname is 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: SecRandomCopyBytes wrappers.
  • Transform: base64 encode/decode using deprecated but still functional SecTransform APIs.
  • 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_status returns a typed report; with evaluate_sec_trust = false the signer certificate is reported as not evaluated and the report carries the Trust to evaluate.
  • KeyDerivation: PBKDF2-style symmetric-key derivation through SecKeyDeriveFromPassword, with the derived bytes available as SecretBytes.
  • KeyAgreement: ephemeral P-256 key generation and ECDH shared-secret derivation.

§Examples

Run every numbered example:

for ex in examples/*.rs; do cargo run --example "$(basename "$ex" .rs)"; done

Key examples:

  • 01_keychain_password
  • 05_trust_evaluate
  • 07_code_signing_info
  • 11_cms_cert_bag
  • 13_key_agreement_shared_secret
  • 14_key_import_sign_verify
  • 15_key_encrypt_export
  • 17_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:

cargo test --features raw-ffi

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.


§API documentation

Safe Rust bindings for Apple’s Security.framework on macOS.

Re-exports§

pub use authorization::Authorization;full
pub use authorization::AuthorizationOptions;full
pub use certificate::Certificate;
pub use certificate::PublicKey;
pub use cms::Cms;full
pub use cms::CmsCertificateChainMode;full
pub use cms::CmsCertificateVerification;full
pub use cms::CmsDecoder;full
pub use cms::CmsDigestAlgorithm;full
pub use cms::CmsEncoder;full
pub use cms::CmsSignedAttributes;full
pub use cms::CmsSignerStatus;full
pub use cms::CmsSignerStatusReport;full
pub use code::AuditToken;full
pub use code::Code;full
pub use code::CodeSigningFlags;full
pub use code::CodeStatus;full
pub use code::Requirement;full
pub use code::SigningInformation;full
pub use code::SigningValue;full
pub use code::StaticCode;full
pub use code::Task;full
pub use error::OsStatus;
pub use error::Result;
pub use error::SecurityError;
pub use error::StatusError;
pub use identity::Identity;full
pub use key::EncryptionAlgorithm;
pub use key::ExternalFormat;
pub use key::ExternalItemType;
pub use key::KeyType;
pub use key::PrivateKey;
pub use key::SignatureAlgorithm;
pub use key_agreement::AgreementPrivateKey;full
pub use key_agreement::AgreementPublicKey;full
pub use key_derivation::DerivedKey;full
pub use key_derivation::KeyDerivation;full
pub use keychain::AccessControl;full
pub use keychain::AccessControlFlags;full
pub use keychain::AccessControlProtection;full
pub use keychain::InternetCredential;full
pub use keychain::InternetPassword;full
pub use keychain::Keychain;full
pub use keychain::KeychainEntry;full
pub use keychain::KeychainOptions;full
pub use policy::Policy;full
pub use policy::PolicyIdentifier;full
pub use policy::PolicyName;full
pub use policy::PolicyProperties;full
pub use policy::RevocationFlags;full
pub use random_bytes::SecureRandom;full
pub use secret::SecretBytes;full
pub use secure_transport::ProtocolVersion;full
pub use secure_transport::SecureTransportContext;full
pub use secure_transport::SecureTransportState;full
pub use transform::Transform;full
pub use trust::Trust;full
pub use trust::TrustOptions;full
pub use trust::TrustResultType;full

Modules§

async_apiasync
Executor-agnostic async wrappers for callback-based Security.framework APIs.
authorizationfull
Safe wrappers for Authorization Services APIs in Security.framework.
certificate
Safe wrappers for SecCertificateRef and public-key APIs in Security.framework.
cmsfull
Safe wrappers for CMS encoder and decoder APIs in Security.framework.
codefull
Safe wrappers for code-signing APIs such as SecCodeRef and SecTaskRef.
code_signingfull
Re-exports code-signing wrappers built on Security.framework.
error
Error types used by the Security.framework wrappers. Errors returned by the security-rs bindings.
ffiraw-ffi
Raw FFI declarations for the subset of Security.framework used by this crate.
identityfull
Safe wrappers for SecIdentityRef.
key
Safe wrappers for SecKeyRef algorithms and private-key APIs.
key_agreementfull
Safe wrappers for SecKeyRef key-agreement APIs.
key_derivationfull
Safe wrappers for password-based key-derivation APIs in Security.framework.
keychainfull
Safe wrappers for keychain and access-control APIs in Security.framework.
policyfull
Safe wrappers for SecPolicyRef and policy configuration APIs.
preludefull
Common imports for users of this crate.
randomfull
Re-exports secure-random wrappers built on SecRandomCopyBytes.
random_bytesfull
Safe wrappers for SecRandomCopyBytes.
secretfull
secure_transportfull
Safe wrappers for Secure Transport session APIs in Security.framework.
transformfull
Safe wrappers for Security Transforms APIs.
trustfull
Safe wrappers for SecTrustRef and trust-evaluation APIs.