Swift 应用安全:初学者必知的十大漏洞
\n\n使用 Swift 为 iOS 和 macOS 开发应用时,需要特别关注安全性。即使是很小的错误也可能导致数据泄露或应用被破解。本文将介绍初学者最常遇到的 10 个常见漏洞,并展示如何避免它们。
\n\n1. 在 UserDefaults 中不安全地存储数据
\n许多新手会将敏感数据(如密码、令牌)保存在 UserDefaults 中。这是一个公共区域,数据以明文形式存储。
// ❌ 危险\nUserDefaults.standard.set("secret_password", forKey: "userPass")\n\n// ✅ 安全——使用 Keychain\nimport Security\nlet query: [String: Any] = [\n kSecClass as String: kSecClassGenericPassword,\n kSecAttrAccount as String: "userPass",\n kSecValueData as String: "secret_password".data(using: .utf8)!\n]\nSecItemAdd(query as CFDictionary, nil)\n\n\n2. Core Data 中的 SQL 注入
\n使用包含用户输入的字符串谓词会为 SQL 注入打开通道。
\n// ❌ 存在漏洞\nlet input = "admin' OR '1'='1"\nlet predicate = NSPredicate(format: "name == %@", input)\n\n// ✅ 安全——使用参数化查询\nlet safePredicate = NSPredicate(format: "name == %@", input)\n\n\n3. 缺少输入验证
\n信任用户输入是主要错误之一。攻击者可以通过文本字段发送恶意数据。
\nfunc processUserInput(_ text: String) {\n // ❌ 允许任何输入\n let url = URL(string: "https://api.example.com/search?q=\\(text)")\n \n // ✅ 检查并转义\n guard let encoded = text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return }\n let safeUrl = URL(string: "https://api.example.com/search?q=\\(encoded)")\n}\n\n\n4. 不安全的网络连接(使用 HTTP 而非 HTTPS)
\n使用 HTTP 会使数据容易被拦截。请始终使用 HTTPS。
\n// ❌ 危险\nlet config = URLSessionConfiguration.default\nconfig.waitsForConnectivity = false\n\n// ✅ 安全——强制使用 HTTPS\nlet config = URLSessionConfiguration.default\nconfig.connectionProxyDictionary?.removeAll()\nconfig.tlsMinimumSupportedProtocolVersion = .TLSv12\n\n\n5. 通过日志泄露数据
\n开发者经常在 production 版本中留下包含敏感数据的 print() 语句。
// ❌ 危险\nprint("User token: \\(token)")\n\n// ✅ 安全——使用条件编译\n#if DEBUG\nprint("Debug: token length = \\(token.count)")\n#endif\n\n\n6. 内存管理不当(循环引用)
\n内存泄漏可能导致 DoS 攻击。在闭包中使用弱引用。
\n// ❌ 内存泄漏\nclass ViewController: UIViewController {\n var handler: (() -> Void)?\n override func viewDidLoad() {\n handler = {\n self.view.backgroundColor = .red // 强引用\n }\n }\n}\n\n// ✅ 安全——弱引用\nhandler = { [weak self] in\n self?.view.backgroundColor = .red\n}\n\n\n7. 缺少 URL 方案验证
\n恶意应用可能会拦截您应用的 URL 方案。
\n// ❌ 存在漏洞\nfunc application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {\n // 处理任何 URL\n return true\n}\n\n// ✅ 安全——验证来源\nfunc application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {\n guard let sourceApp = options[.sourceApplication] as? String,\n sourceApp == "com.trusted.app" else {\n return false\n }\n // 处理 URL\n return true\n}\n\n\n