Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计通过

ios-securityiOS 安全

Agent Skill

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查。它适合让 Agent 梳理敏感配置、检查依赖风险、分析鉴权逻辑或生成安全复核清单。使用时不能把工具输出直接当最终结论,涉及密钥、令牌、用户数据或生产系统时,应先确认最小权限、脱敏方式和操作边界。

总安装

26,928

周安装

1,116

GitHub Stars

517

下载量

8,624
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:ios-security(iOS 安全)
来源仓库:https://github.com/dpearson2699/swift-ios-skills
仓库路径:skills/ios-security
安装命令:
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill ios-security
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill ios-security

简介

使用钥匙串、CryptoKit、生物识别身份验证和 Apple 安全最佳实践来保护 iOS 应用程序的安全。

  • 涵盖用于凭证存储的钥匙串服务、数据保护文件类以及用于加密、散列和 HMAC 操作的 CryptoKit
  • 包括 Secure Enclave 密钥存储、使用 LocalAuthentication 的生物识别身份验证(Face ID/Touch ID)以及 LAContext 配置
  • 强制实施应用程序传输安全 (ATS) 要求、证书固定模式,并解释不同敏感度级别的 kSecAttrAccessible 值
  • 提供安全的编码模式:输入验证、敏感数据清除、日志规则、越狱检测;包括隐私清单和应用程序审查合规清单

SKILL.md

iOS Security

Guidance for handling sensitive data, authenticating users, encrypting correctly, and following Apple's security best practices on iOS.

Contents

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

ValueWhen AvailableDevice-OnlyUse For
kSecAttrAccessibleWhenUnlockedDevice unlockedNoGeneral credentials
kSecAttrAccessibleWhenUnlockedThisDeviceOnlyDevice unlockedYesSensitive credentials
kSecAttrAccessibleAfterFirstUnlockAfter first unlockNoBackground-accessible tokens
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnlyAfter first unlockYesBackground tokens, no backup
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnlyPasscode set + unlockedYesHighest security

Rules:

  • Use ThisDeviceOnly variants for sensitive data. Prevents backup/restore to other devices.
  • Use AfterFirstUnlock for tokens needed by background operations.
  • Use WhenPasscodeSetThisDeviceOnly for 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

StorageUse ForSecurity
@AppStorage / UserDefaultsNon-sensitive preferences (theme, onboarding state, feature flags)Not encrypted at rest
KeychainPasswords, tokens, API keys, secretsHardware-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:

ClassWhen AvailableUse For
.completeOnly when unlockedSensitive user data
.completeUnlessOpenOpen handles survive lockActive downloads, recordings
.completeUntilFirstUserAuthenticationAfter first unlock (default)Most app data
.noneAlwaysNon-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 NSAllowsArbitraryLoads to 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

  1. Storing secrets in UserDefaults. Tokens, passwords, API keys must go in Keychain.
  2. Hardcoded secrets in source. No API keys or credentials in Swift files.
  3. Disabling ATS globally. NSAllowsArbitraryLoads = true is a rejection risk.
  4. Logging sensitive data. Never log tokens, passwords, or API keys.
  5. Missing PrivacyInfo.xcprivacy. Required for all apps using required-reason APIs.
  6. Using CommonCrypto instead of CryptoKit. CryptoKit is safer and modern.
  7. Missing NSFaceIDUsageDescription. Crashes on Face ID devices.
  8. Using .biometryAny when .biometryCurrentSet is needed. The former survives enrollment changes, which may be undesirable for high-security items.
  9. Path traversal vulnerabilities. Always resolve and validate paths.
  10. 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 kSecAttrAccessible value; ThisDeviceOnly for 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; NSFaceIDUsageDescription in Info.plist
  • Correct SecAccessControl flags; LAContext configured
  • 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

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.48%
按下载量换算3,060

Claude

29.52%
按下载量换算2,546

Cursor

19.91%
按下载量换算1,717

Gemini CLI

9.95%
按下载量换算858

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills