字符串插值安全:防止注入式攻击与格式化漏洞
深度解析 Swift 字符串插值底层机制,构建对 SQL、Shell 和 HTML 上下文安全的类型安全插值器。 · 难度:入门 · +10XP
字符串插值安全:防止注入式攻击与格式化漏洞
Swift 的 StringInterpolation 是可定制的,但不当使用可能导致安全漏洞。本教程将指导你创建领域特定的安全插值类型:SQLInterpolation 自动转义单引号,ShellInterpolation 过滤特殊字符,HTMLInterpolation 编码实体。你将学习如何实现 ExpressibleByStringInterpolation 协议,如何创建带上下文的插值分段,以及如何使用 @dynamicMemberLookup 提供安全字段访问。
struct SafeSQL: ExpressibleByStringInterpolation {
struct StringInterpolation: StringInterpolationProtocol {
var sqlString = ""
mutating func appendLiteral(_ literal: String) { sqlString += literal }
mutating func appendInterpolation(_ value: String) {
sqlString += "'" + value.replacingOccurrences(of: "'", with: "''") + "'"
}
}
let raw: String
init(stringInterpolation: StringInterpolation) { raw = stringInterpolation.sqlString }
}
let name = "O'Brien"
let query: SafeSQL = "SELECT * FROM users WHERE name = \(name)"