
ios-security
Secure iOS apps with Keychain Services, CryptoKit encryption, biometric authentication (Face ID, Touch ID), Secure Enclave key storage, LAContext, App Transport Security (ATS), certificate pinning, data protection classes, and secure coding patterns. Use when implementing app security features, auditing privacy manifests, configuring App Transport Security, securing keychain access, adding biometric authentication, or encrypting sensitive data with CryptoKit.
- Installs
- 1.1K
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill ios-security- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads ios-security automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
iOS Security
Guidance for handling sensitive data, authenticating users, encrypting correctly, and following Apple's security best practices on iOS.
Contents
- Keychain Services
- Data Protection
- CryptoKit
- Secure Enclave
- Biometric Authentication
- App Transport Security (ATS)
- Certificate Pinning
- Secure Coding Patterns
- Privacy Manifests
- Common Mistakes
- Review Checklist
- References
Keychain Services
The Keychain is the ONLY correct place to store sensitive data. Never store passwords, tokens, API keys, or secrets in UserDefaults, files, or Core Data.
Storing Credentials
func saveToKeychain(account: String, data: Data, service: String) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: account,
kSecAttrService as String: service,
kSecValueData as String: data,
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
]
let status = SecItemAdd(query as CFDictionary, nil)
if status == errSecDuplicateItem {
let updateQuery: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: account,
kSecAttrService as String: service
]
let updates: [String: Any] = [kSecValueData as String: data]
let updateStatus = SecItemUpdate(updateQuery as CFDictionary, updates as CFDictionary)
guard updateStatus == errSecSuccess else {
throw KeychainError.updateFailed(updateStatus)
}
} else if status != errSecSuccess {
throw KeychainError.saveFailed(status)
}
}
Reading Credentials
func readFromKeychain(account: String, service: String) throws -> Data {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: account,
kSecAttrService as String: service,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne
]
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
guard status == errSecSuccess, let data = result as? Data else {
throw KeychainError.readFailed(status)
}
return data
}
Deleting Credentials
func deleteFromKeychain(account: String, service: String) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: account,
kSecAttrService as String: service
]
let status = SecItemDelete(query as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw KeychainError.deleteFailed(status)
}
}
kSecAttrAccessible Values
| Value | When Available | Device-Only | Use For |
|---|---|---|---|
kSecAttrAccessibleWhenUnlocked | Device unlocked | No | General credentials |
kSecAttrAccessibleWhenUnlockedThisDeviceOnly | Device unlocked | Yes | Sensitive credentials |
kSecAttrAccessibleAfterFirstUnlock | After first unlock | No | Background-accessible tokens |
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly | After first unlock | Yes | Background tokens, no backup |
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly | Passcode set + unlocked | Yes | Highest security |
Rules:
- Use
ThisDeviceOnlyvariants for sensitive data. Prevents backup/restore to other devices. - Use
AfterFirstUnlockfor tokens needed by background operations. - Use
WhenPasscodeSetThisDeviceOnlyfor most sensitive data. Item is deleted if passcode is removed. - NEVER use
kSecAttrAccessibleAlways(deprecated and insecure).
Keychain Access Groups
Share keychain items across apps from the same team:
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "shared-token",
kSecAttrAccessGroup as String: "TEAMID.com.company.shared"
]
@AppStorage vs Keychain
| Storage | Use For | Security |
|---|---|---|
@AppStorage / UserDefaults | Non-sensitive preferences (theme, onboarding state, feature flags) | Not encrypted at rest |
| Keychain | Passwords, tokens, API keys, secrets | Hardware-encrypted, access-controlled |
Rule: If the data would be embarrassing or dangerous if exposed, it goes in Keychain. Everything else can use @AppStorage.
// Non-sensitive preference -- @AppStorage is fine
@AppStorage("hasCompletedOnboarding") private var hasOnboarded = false
// Sensitive credential -- MUST use Keychain
// WRONG: @AppStorage("authToken") private var token = ""
// CORRECT: Use saveToKeychain(account:data:service:)
Data Protection
iOS encrypts files based on their protection class:
| Class | When Available | Use For |
|---|---|---|
.complete | Only when unlocked | Sensitive user data |
.completeUnlessOpen | Open handles survive lock | Active downloads, recordings |
.completeUntilFirstUserAuthentication | After first unlock (default) | Most app data |
.none | Always | Non-sensitive, system-needed data |
// Set file protection
try data.write(to: url, options: .completeFileProtection)
// Check protection level
let attributes = try FileManager.default.attributesOfItem(atPath: path)
let protection = attributes[.protectionKey] as? FileProtectionType
Use .complete for any file containing user-sensitive data. The default
.completeUntilFirstUserAuthentication is acceptable for general app data.
CryptoKit
Use CryptoKit for all cryptographic operations. Do not use CommonCrypto or the raw Security framework for new code.
Symmetric Encryption (AES-GCM)
import CryptoKit
let key = SymmetricKey(size: .bits256)
func encrypt(_ data: Data, using key: SymmetricKey) throws -> Data {
let sealed = try AES.GCM.seal(data, using: key)
guard let combined = sealed.combined else {
throw CryptoError.sealFailed
}
return combined
}
func decrypt(_ data: Data, using key: SymmetricKey) throws -> Data {
let box = try AES.GCM.SealedBox(combined: data)
return try AES.GCM.open(box, using: key)
}
Hashing
let hash = SHA256.hash(data: data)
let hashString = hash.compactMap { String(format: "%02x", $0) }.joined()
// Also available: SHA384, SHA512
HMAC (Message Authentication)
let key = SymmetricKey(size: .bits256)
// Sign
let signature = HMAC<SHA256>.authenticationCode(for: data, using: key)
// Verify
let isValid = HMAC<SHA256>.isValidAuthenticationCode(signature, authenticating: data, using: key)
For digital signatures (P256/ECDSA), key agreement (Curve25519), ChaChaPoly, and HKDF key derivation, see references/cryptokit-advanced.md.
Secure Enclave
For the highest security, store keys in the Secure Enclave. Keys never leave the hardware. Only P256 is supported.
guard SecureEnclave.isAvailable else { return }
let accessControl = SecAccessControlCreateWithFlags(
nil, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
[.privateKeyUsage, .biometryCurrentSet], nil
)!
let privateKey = try SecureEnclave.P256.Signing.PrivateKey(accessControl: accessControl)
let signature = try privateKey.signature(for: data) // May trigger biometric prompt
let isValid = privateKey.publicKey.isValidSignature(signature, for: data)
// Persist: store dataRepresentation in Keychain, restore with:
let restored = try SecureEnclave.P256.Signing.PrivateKey(
dataRepresentation: privateKey.dataRepresentation
)
Biometric Authentication
This section covers biometric protection for Keychain items and data
access. For user-facing biometric sign-in flows (LAContext.evaluatePolicy
as a login mechanism), see the authentication skill.
LocalAuthentication (Face ID / Touch ID)
import LocalAuthentication
func authenticateWithBiometrics() async throws -> Bool {
let context = LAContext()
var error: NSError?
guard context.canEvaluatePolicy(
.deviceOwnerAuthenticationWithBiometrics, error: &error
) else {
// Biometrics not available -- fall back to passcode
if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) {
return try await context.evaluatePolicy(
.deviceOwnerAuthentication,
localizedReason: "Authenticate to access your account"
)
}
throw AuthError.biometricsUnavailable
}
return try await context.evaluatePolicy(
.deviceOwnerAuthenticationWithBiometrics,
localizedReason: "Authenticate to access your account"
)
}
Info.plist Requirement
You MUST include NSFaceIDUsageDescription in Info.plist:
<key>NSFaceIDUsageDescription</key>
<string>Authenticate to access your secure data</string>
Missing this key causes a crash on Face ID devices.
LAContext Configuration
let context = LAContext()
context.localizedFallbackTitle = "Use Passcode"
context.touchIDAuthenticationAllowableReuseDuration = 30
let currentState = context.evaluatedPolicyDomainState // Compare to detect enrollment changes
Biometric + Keychain
Protect keychain items with biometric access:
let access = SecAccessControlCreateWithFlags(
nil,
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
.biometryCurrentSet,
nil
)!
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "auth-token",
kSecValueData as String: tokenData,
kSecAttrAccessControl as String: access,
kSecUseAuthenticationContext as String: LAContext()
]
SecAccessControl flags:
.biometryCurrentSet-- Requires biometry, invalidated if enrollment changes. Most secure..biometryAny-- Requires biometry, survives enrollment changes..userPresence-- Biometry or passcode. Most flexible.
App Transport Security (ATS)
ATS enforces HTTPS by default. Do NOT disable it.
What ATS Requires
- TLS 1.2 or later
- Forward secrecy cipher suites
- SHA-256 or better certificates
- 2048-bit or greater RSA keys (or 256-bit ECC)
Exception Domains (Last Resort)
<!-- Only for legacy servers you cannot upgrade -->
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>legacy-api.example.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
</dict>
</dict>
</dict>
Rules:
- NEVER set
NSAllowsArbitraryLoadsto true. Apple will reject the app. - Exception domains require justification in App Review notes.
- Use exception domains only for third-party servers you cannot control.
Certificate Pinning
Pin certificates for sensitive API connections to prevent MITM attacks.
URLSession Delegate Pinning
import CryptoKit
class PinnedSessionDelegate: NSObject, URLSessionDelegate {
// SHA-256 hash of the certificate's Subject Public Key Info
private let pinnedHashes: Set<String> = [
"base64EncodedSHA256HashOfSPKI=="
]
func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge
) async -> (URLSession.AuthChallengeDisposition, URLCredential?) {
guard let trust = challenge.protectionSpace.serverTrust,
let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate],
let certificate = chain.first else {
return (.cancelAuthenticationChallenge, nil)
}
guard let publicKey = SecCertificateCopyKey(certificate),
let publicKeyData = SecKeyCopyExternalRepresentation(
publicKey, nil
) as Data? else {
return (.cancelAuthenticationChallenge, nil)
}
let hash = SHA256.hash(data: publicKeyData)
let hashString = Data(hash).base64EncodedString()
if pinnedHashes.contains(hashString) {
return (.useCredential, URLCredential(trust: trust))
}
return (.cancelAuthenticationChallenge, nil)
}
}
Rules:
- Pin the public key hash, not the certificate. Certificates rotate; public keys are more stable.
- Always include at least one backup pin.
- Have a rotation plan. If all pinned keys expire, the app cannot connect.
- Consider a kill switch (remote config to disable pinning in emergency).
Secure Coding Patterns
Never Log Sensitive Data
// WRONG
logger.debug("User logged in with token: \(token)")
// CORRECT
logger.debug("User logged in successfully")
Clear Sensitive Data From Memory
var sensitiveData = Data(/* ... */)
defer {
sensitiveData.resetBytes(in: 0..<sensitiveData.count)
}
Validate All Input
guard let url = URL(string: input),
["https"].contains(url.scheme?.lowercased()) else {
throw SecurityError.invalidURL
}
let resolved = url.standardized.path
guard resolved.hasPrefix(allowedDirectory.path) else {
throw SecurityError.pathTraversal
}
API Key Placeholder Pattern
Use #error to prevent accidental commits of placeholder API keys:
// Forces a build error until the real key is configured
#error("Add your API key to Secrets.plist -- see README for setup")
private let apiKey = Secrets.value(for: "API_KEY")
Jailbreak Detection
Check for known jailbreak file paths (/Applications/Cydia.app, /usr/sbin/sshd, etc.) and sandbox escape. Jailbreak detection is not foolproof -- use it as one layer, not the only layer. See references/cryptokit-advanced.md for full implementation.
Privacy Manifests
Apps and SDKs must declare data access in PrivacyInfo.xcprivacy. See
references/privacy-manifest.md for required-reason API declarations and
security-related data collection details. For submission requirements and
compliance checklists, see references/app-review-guidelines.md.
Common Mistakes
- Storing secrets in UserDefaults. Tokens, passwords, API keys must go in Keychain.
- Hardcoded secrets in source. No API keys or credentials in Swift files.
- Disabling ATS globally.
NSAllowsArbitraryLoads = trueis a rejection risk. - Logging sensitive data. Never log tokens, passwords, or API keys.
- Missing PrivacyInfo.xcprivacy. Required for all apps using required-reason APIs.
- Using CommonCrypto instead of CryptoKit. CryptoKit is safer and modern.
- Missing NSFaceIDUsageDescription. Crashes on Face ID devices.
- Using
.biometryAnywhen.biometryCurrentSetis needed. The former survives enrollment changes, which may be undesirable for high-security items. - Path traversal vulnerabilities. Always resolve and validate paths.
- Missing concurrency annotations. Ensure Keychain wrapper types are Sendable; isolate UI-facing security prompts to
@MainActor.
Review Checklist
- Secrets in Keychain, not UserDefaults or files; no hardcoded credentials
- Correct
kSecAttrAccessiblevalue;ThisDeviceOnlyfor non-backup data - File protection class set for sensitive files (
.complete) - CryptoKit for encryption (not CommonCrypto); 256-bit symmetric keys
- Keys stored in Keychain or Secure Enclave
- Biometric auth with fallback;
NSFaceIDUsageDescriptionin Info.plist - Correct
SecAccessControlflags;LAContextconfigured - HTTPS enforced; no
NSAllowsArbitraryLoads; cert pinning for sensitive APIs - PrivacyInfo.xcprivacy present; all required-reason APIs declared
- No sensitive data in logs; Data cleared after use; URLs/paths validated
References
- CryptoKit advanced patterns: references/cryptokit-advanced.md
- Privacy manifest guide: references/privacy-manifest.md
- App Review security guidelines: references/app-review-guidelines.md
- File storage directory guide and protection: references/file-storage-patterns.md
FAQ
What does the ios-security skill do?
Secure iOS apps with Keychain Services, CryptoKit encryption, biometric authentication (Face ID, Touch ID), Secure Enclave key storage, LAContext, App Transport Security (ATS), certificate pinning, data protection classes, and secure coding patterns. Use when implementing app security features, auditing privacy manifests, configuring App Transport Security, securing keychain access, adding biometric authentication, or encrypting sensitive data with CryptoKit.
How do I install ios-security?
Run npx skills add https://github.com/dpearson2699/swift-ios-skills --skill ios-security in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/ios-security/ (personal) or .claude/skills/ios-security/ (project).
Which AI agents can use ios-security?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is ios-security safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains ios-security?
It is published by dpearson2699 in dpearson2699/swift-ios-skills. It has 1,106 recorded installs.
More from dpearson2699/swift-ios-skills
swiftui-animation
dpearson2699/swift-ios-skills
Implement, diagnose, or review SwiftUI motion using explicit and scoped implicit animations, springs, transitions, PhaseAnimator, KeyframeAnimator, matched geometry or navigation zoom, SF Symbol effects, and custom Animation types. Use when views should animate on state changes, insertion, removal, navigation, or multi-step choreography, or when motion must respect Reduce Motion and Swift concurrency.
ios-accessibility
dpearson2699/swift-ios-skills
Build and audit SwiftUI, UIKit, and AppKit accessibility for VoiceOver, Voice Control, Switch Control, Full Keyboard Access, Dynamic Type, focus restoration, labels/traits/actions, traversal, custom rotors, NSAccessibility, XCTest checks, adaptive system preferences, and App Store accessibility declarations. Use when implementing accessible UI, fixing an accessibility audit, testing assistive-technology behavior, or substantiating App Store Accessibility Nutrition Labels.
swiftui-performance
dpearson2699/swift-ios-skills
Profile, diagnose, and remediate SwiftUI runtime performance using code review, Instruments, and repeatable measurements. Use when a SwiftUI screen renders slowly, scrolling or animations hitch, view bodies update excessively, list identity churns, layout work spikes, or broad Observation dependencies raise CPU cost. Covers evidence-based triage, SwiftUI Instruments lanes, lazy-container guardrails, state lifetime, and before/after verification.
swiftui-patterns
dpearson2699/swift-ios-skills
Builds and reviews SwiftUI views with modern MV architecture, state, composition, isolated previews, and migration guidance. Covers @Observable ownership, @State/@Bindable/@Environment wiring, view decomposition, ViewModifiers, environment values, .task loading, iOS 26+ handoffs, Writing Tools, clipboard availability, and performance. Use when structuring SwiftUI state, managing @Observable, composing views, previewing meaningful UI states, or correcting SwiftUI patterns.
app-store-review
dpearson2699/swift-ios-skills
Audits App Store submission readiness and rejection risk across current review guidelines, PrivacyInfo.xcprivacy and required-reason APIs, privacy labels, ATT, StoreKit payments, metadata, entitlements, widgets, and Live Activities. Use when preparing a submission, responding to rejection, reconciling privacy evidence, or separating upload blockers from cleanup.
ios-networking
dpearson2699/swift-ios-skills
Build, review, or improve networking code in iOS/macOS apps using URLSession with async/await, structured concurrency, and modern Swift patterns. Use when working with REST APIs, downloading files, uploading data, WebSocket connections, pagination, retry logic, request middleware, caching, background transfers, or network reachability monitoring. Also use when handling HTTP requests, API clients, network error handling, or data fetching in Swift apps.
Popular security skills
azure-compliance
microsoft/azure-skills
Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance validation, and security posture checks. WHEN: compliance scan, security audit, BEFORE running azqr (compliance cli tool), Azure best practices, Key Vault expiration check, expired certificates, expiring secrets, orphaned resources, compliance assessment.
minimal-run-and-audit
lllllllama/rigorpilot-skills
Rigor Run skill for README-first deep learning repo reproduction. Use when the task is specifically to capture or normalize evidence from the selected smoke test or documented inference or evaluation command and write standardized reprooutputs/ files, including patch notes when repository files changed. Do not use for training execution, initial repo intake, generic environment setup, paper lookup, target selection, hidden scientific-meaning changes, or end-to-end orchestration by itself.
seo-audit
coreyhaines31/marketingskills
When the user wants to audit, review, or diagnose SEO issues on their site. Also use when the user mentions "SEO audit," "technical SEO," "why am I not ranking," "SEO issues," "on-page SEO," "meta tags review," "SEO health check," "my traffic dropped," "lost rankings," "not showing up in Google," "site isn't ranking," "Google update hit me," "page speed," "core web vitals," "crawl errors," "indexing issues," "stuck on page 2," "striking distance keywords," "title tag rewrite," "low CTR," "local SEO," "Google Business Profile," or "map pack." Use this even if the user just says something vague like "my SEO is bad" or "help with SEO" — start with an audit. For building pages at scale to target keywords, see programmatic-seo. For adding structured data, see schema. For AI search optimization, see ai-seo.
firebase-security-rules-auditor
firebase/agent-skills
Audits Firebase (Firestore, Cloud Storage) security rules for vulnerabilities, privilege escalation, role bypasses, create vs update inconsistencies, resource exhaustion, type safety, size limits, and hasOnly ownership checks. Use when auditing/reviewing rules, running red-team rule assessments, or scoring against auditor checklists. Don't use for Firebase CLI (login, deploy), Auth, Crashlytics, Remote Config, or database queries.
audit
pbakaus/impeccable
Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.
competitors
coreyhaines31/marketingskills
When the user wants to create competitor comparison or alternative pages for SEO and buyer-facing use. Also use when the user mentions 'alternative page,' 'vs page,' 'competitor comparison,' 'comparison page,' '[Product] vs [Product],' '[Product] alternative,' 'competitive landing pages,' 'how do we compare to X,' 'competitor teardown,' 'audit our competitor pages,' 'are our comparison pages out of date,' or 'competitive asset audit.' Use this for any content that positions your product against competitors. Covers four formats: singular alternative, plural alternatives, you vs competitor, and competitor vs competitor. For auditing existing claims (not researching competitors from scratch, which is competitor-profiling; not technical SEO on these pages, which is seo-audit), use the asset audit here. For internal battle cards and sales-specific competitor docs, see sales-enablement.