Swift 应用安全:iOS/macOS 十大漏洞

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

引言:为什么 Swift 应用安全至关重要

Swift 是 Apple 为开发 iOS、macOS、watchOS 和 tvOS 应用而创建的一种强大且现代的编程语言。尽管内置了安全机制(ARC、安全内存管理、可选类型),但每年仍有成千上万的应用因开发者的错误而成为攻击的受害者。根据 OWASP Mobile Top 10 报告,移动应用中的大多数漏洞都出现在客户端。在本文中,我们将分析 Swift 应用中最常见的 10 个漏洞,提供代码示例,并展示如何避免它们。



1. 不安全的數據存儲 (Insecure Data Storage)

问题

开发者经常将敏感数据(令牌、密码、API 密钥)未加密地保存在 UserDefaults、Plist 文件或 Core Data 中。在越狱设备上,攻击者可以轻松访问这些数据。

易受攻击的代码示例

// 易受攻击的代码UserDefaults.standard.set("secret_token_123", forKey: "api_token")UserDefaults.standard.set("password123", forKey: "user_password")

解决方案

使用 Keychain 存储敏感数据。Swift 有方便的封装库,例如 KeychainSwift 或 Security framework。

// 使用 Keychain 安全存储import KeychainSwift

let keychain = KeychainSwift()keychain.set("secret_token_123", forKey: "api_token")keychain.set("password123", forKey: "user_password", withAccess: .accessibleWhenUnlockedThisDeviceOnly)


2. 代码注入和 SQL 注入 (Code Injection & SQL Injection)

问题

如果你的应用使用 SQLite、带有 NSPredicate 的 Core Data 或 WebView 来显示网页内容,攻击者可以通过用户输入注入恶意代码。

易受攻击的代码示例

// 易受攻击的 SQLite 查询let userInput = "1' OR '1'='1"let query = "SELECT * FROM users WHERE id = '\\(userInput)'"

解决方案

使用 参数化查询 或带有安全占位符的 NSPredicate。

// 带参数的安全查询let query = "SELECT * FROM users WHERE id = ?"let statement = try db.prepare(query)try statement.bind(1, userInput)


3. 不安全的网络通信 (Insecure Network Communication)

问题

使用 HTTP 而非 HTTPS,忽略 SSL 证书(App Transport Security)或未加密发送数据。

易受攻击的代码示例

// 易受攻击的代码:禁用 ATSlet url = URL(string: "http://example.com/api/login")!let task = URLSession.shared.dataTask(with: url) { data, response, error in    // 处理未受保护的数据}

解决方案

在 Info.plist 中配置 App Transport Security (ATS) 并使用 HTTPS。使用 SSL pinning 验证证书。

// 带 SSL Pinning 的安全请求(使用 Alamofire 示例)let evaluator = PinnedCertificatesTrustEvaluator(certificates: [certificate])let session = Session(serverTrustManager: ServerTrustManager(evaluators: ["example.com": evaluator]))session.request("https://example.com/api/login").responseJSON { response in    // 处理受保护的数据}


4. 通过 WebView 注入 (WebView Injection)

问题

在 WKWebView 中加载包含用户数据的 HTML 内容而不进行清理,可能导致 XSS 攻击和 cookie 窃取。

易受攻击的代码示例

// 易受攻击的代码let userComment = "<script>alert('XSS')</script>"let html                

博客

书籍推荐