ServerTrustEvaluation.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. //
  2. // ServerTrustPolicy.swift
  3. //
  4. // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// Responsible for managing the mapping of `ServerTrustEvaluating` values to given hosts.
  26. open class ServerTrustManager {
  27. /// The dictionary of policies mapped to a particular host.
  28. open let evaluators: [String: ServerTrustEvaluating]
  29. /// Initializes the `ServerTrustManager` instance with the given evaluators.
  30. ///
  31. /// Since different servers and web services can have different leaf certificates, intermediate and even root
  32. /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
  33. /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
  34. /// pinning for host3 and disabling evaluation for host4.
  35. ///
  36. /// - Parameter evaluators: A dictionary of all evaluators mapped to a particular host.
  37. public init(evaluators: [String: ServerTrustEvaluating]) {
  38. self.evaluators = evaluators
  39. }
  40. /// Returns the `ServerTrustEvaluating` value for the given host, if one is set.
  41. ///
  42. /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override
  43. /// this method and implement more complex mapping implementations such as wildcards.
  44. ///
  45. /// - Parameter host: The host to use when searching for a matching policy.
  46. /// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise.
  47. open func serverTrustEvaluators(forHost host: String) -> ServerTrustEvaluating? {
  48. return evaluators[host]
  49. }
  50. }
  51. /// A protocol describing the API used to evaluate server trusts.
  52. public protocol ServerTrustEvaluating {
  53. #if os(Linux)
  54. // Implement this once Linux has API for evaluating server trusts.
  55. #else
  56. /// Evaluates the given `SecTrust` value for the given `host`.
  57. ///
  58. /// - Parameters:
  59. /// - trust: The `SecTrust` value to evaluate.
  60. /// - host: The host for which to evaluate the `SecTrust` value.
  61. /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`.
  62. func evaluate(_ trust: SecTrust, forHost host: String) -> Bool
  63. #endif
  64. }
  65. extension Array where Element == ServerTrustEvaluating {
  66. #if os(Linux)
  67. // Add this same convenience method for Linux.
  68. #else
  69. /// Evaluates the given `SecTrust` value for the given `host`.
  70. ///
  71. /// - Parameters:
  72. /// - trust: The `SecTrust` value to evaluate.
  73. /// - host: The host for which to evaluate the `SecTrust` value.
  74. /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
  75. func evaluate(_ trust: SecTrust, forHost host: String) -> Bool {
  76. for evaluator in self {
  77. guard evaluator.evaluate(trust, forHost: host) else { return false }
  78. }
  79. return true
  80. }
  81. #endif
  82. }
  83. // MARK: - Server Trust Evaluators
  84. /// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the
  85. /// host provided by the challenge. Applications are encouraged to always validate the host in production environments
  86. /// to guarantee the validity of the server's certificate chain.
  87. public final class DefaultTrustEvaluator: ServerTrustEvaluating {
  88. private let validateHost: Bool
  89. /// Creates a `DefaultTrustEvalutor`.
  90. ///
  91. /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. Defaults to `true`.
  92. public init(validateHost: Bool = true) {
  93. self.validateHost = validateHost
  94. }
  95. /// Evaluates the given `SecTrust` value for the given `host`.
  96. ///
  97. /// - Parameters:
  98. /// - trust: The `SecTrust` value to evaluate.
  99. /// - host: The host for which to evaluate the `SecTrust` value.
  100. /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
  101. public func evaluate(_ trust: SecTrust, forHost host: String) -> Bool {
  102. let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
  103. SecTrustSetPolicies(trust, policy)
  104. return trust.isValid
  105. }
  106. }
  107. /// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate
  108. /// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates.
  109. /// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS
  110. /// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production
  111. /// environments to guarantee the validity of the server's certificate chain.
  112. public final class RevocationTrustEvaluator: ServerTrustEvaluating {
  113. /// Represents the options to be use when evaluating the status of a certificate.
  114. /// Only Revocation Policy Constants are valid, and can be found in [Apple's documentation](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/policies/1563600-revocation_policy_constants).
  115. public struct Options: OptionSet {
  116. /// The raw value of the option.
  117. public let rawValue: CFOptionFlags
  118. /// Creates an `Options` value with the given `CFOptionFlags`.
  119. ///
  120. /// - Parameter rawValue: The `CFOptionFlags` value to initialize with.
  121. public init(rawValue: CFOptionFlags) {
  122. self.rawValue = rawValue
  123. }
  124. /// Perform revocation checking using the CRL (Certification Revocation List) method.
  125. public static let crl = Options(rawValue: kSecRevocationCRLMethod)
  126. /// Consult only locally cached replies; do not use network access.
  127. public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled)
  128. /// Perform revocation checking using OCSP (Online Certificate Status Protocol).
  129. public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod)
  130. /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred.
  131. public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL)
  132. /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a
  133. /// "best attempt" basis, where failure to reach the server is not considered fatal.
  134. public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse)
  135. /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the
  136. /// certificate and the value of `preferCRL`.
  137. public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod)
  138. }
  139. private let validateHost: Bool
  140. private let options: Options
  141. /// Creates a `RevocationTrustEvaluator`
  142. ///
  143. /// - Parameters:
  144. /// - options: The `Options` to use to check the revocation status of the certificate. Defaults to `.any`.
  145. /// - validateHost: Determines whether or not the evaluator should validate the host. Defaults to `true`.
  146. public init(options: Options = .any, validateHost: Bool = true) {
  147. self.validateHost = validateHost
  148. self.options = options
  149. }
  150. /// Evaluates the given `SecTrust` value for the given `host`.
  151. ///
  152. /// - Parameters:
  153. /// - trust: The `SecTrust` value to evaluate.
  154. /// - host: The host for which to evaluate the `SecTrust` value.
  155. /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
  156. public func evaluate(_ trust: SecTrust, forHost host: String) -> Bool {
  157. let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
  158. let revokedPolicy = SecPolicyCreateRevocation(options.rawValue)
  159. SecTrustSetPolicies(trust, [defaultPolicy, revokedPolicy] as CFTypeRef)
  160. return trust.isValid
  161. }
  162. }
  163. /// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned
  164. /// certificates match one of the server certificates. By validating both the certificate chain and host, certificate
  165. /// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
  166. /// Applications are encouraged to always validate the host and require a valid certificate chain in production
  167. /// environments.
  168. public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating {
  169. private let certificates: [SecCertificate]
  170. private let validateCertificateChain: Bool
  171. private let validateHost: Bool
  172. /// Creates a `PinnedCertificatesTrustEvaluator`.
  173. ///
  174. /// - Parameters:
  175. /// - certificates: The certificates to use to evalute the trust. Defaults to all `cer`, `crt`, and
  176. /// `der` certificates in `Bundle.main`.
  177. /// - validateCertificateChain: Determines whether the certificate chain should be evaluated or just the given
  178. /// certificate.
  179. /// - validateHost: Determines whether or not the evaluator should validate the host. Defaults to
  180. /// `true`.
  181. public init(certificates: [SecCertificate] = Bundle.main.certificates,
  182. validateCertificateChain: Bool = true,
  183. validateHost: Bool = true) {
  184. self.certificates = certificates
  185. self.validateCertificateChain = validateCertificateChain
  186. self.validateHost = validateHost
  187. }
  188. /// Evaluates the given `SecTrust` value for the given `host`.
  189. ///
  190. /// - Parameters:
  191. /// - trust: The `SecTrust` value to evaluate.
  192. /// - host: The host for which to evaluate the `SecTrust` value.
  193. /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
  194. public func evaluate(_ trust: SecTrust, forHost host: String) -> Bool {
  195. if validateCertificateChain {
  196. let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
  197. SecTrustSetPolicies(trust, policy)
  198. SecTrustSetAnchorCertificates(trust, certificates as CFArray)
  199. SecTrustSetAnchorCertificatesOnly(trust, true)
  200. return trust.isValid
  201. } else {
  202. let serverCertificatesData = Set(trust.certificateData)
  203. let pinnedCertificatesData = Set(certificates.data)
  204. return !serverCertificatesData.isDisjoint(with: pinnedCertificatesData)
  205. }
  206. }
  207. }
  208. /// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned
  209. /// public keys match one of the server certificate public keys. By validating both the certificate chain and host,
  210. /// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
  211. /// Applications are encouraged to always validate the host and require a valid certificate chain in production
  212. /// environments.
  213. public final class PublicKeysTrustEvaluator: ServerTrustEvaluating {
  214. private let keys: [SecKey]
  215. private let validateCertificateChain: Bool
  216. private let validateHost: Bool
  217. /// Creates a `PublicKeysTrustEvaluator`.
  218. ///
  219. /// - Parameters:
  220. /// - keys: The public keys to use to evaluate the trust. Defaults to the public keys of all
  221. /// `cer`, `crt`, and `der` certificates in `Bundle.main`.
  222. /// - validateCertificateChain: Determines whether the certificate chain should be evaluated.
  223. /// - validateHost: Determines whether or not the evaluator should validate the host. Defaults to
  224. /// `true`.
  225. public init(keys: [SecKey] = Bundle.main.publicKeys,
  226. validateCertificateChain: Bool = true,
  227. validateHost: Bool = true) {
  228. self.keys = keys
  229. self.validateCertificateChain = validateCertificateChain
  230. self.validateHost = validateHost
  231. }
  232. /// Evaluates the given `SecTrust` value for the given `host`.
  233. ///
  234. /// - Parameters:
  235. /// - trust: The `SecTrust` value to evaluate.
  236. /// - host: The host for which to evaluate the `SecTrust` value.
  237. /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
  238. public func evaluate(_ trust: SecTrust, forHost host: String) -> Bool {
  239. let certificateChainEvaluationPassed: Bool = {
  240. if validateCertificateChain {
  241. let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
  242. SecTrustSetPolicies(trust, policy)
  243. return trust.isValid
  244. } else {
  245. return true
  246. }
  247. }()
  248. guard certificateChainEvaluationPassed else { return false }
  249. outerLoop: for serverPublicKey in trust.publicKeys as [AnyHashable] {
  250. for pinnedPublicKey in keys as [AnyHashable] {
  251. if serverPublicKey == pinnedPublicKey {
  252. return true
  253. }
  254. }
  255. }
  256. return false
  257. }
  258. }
  259. /// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the
  260. /// evaluators consider it valid.
  261. public final class CompositeTrustEvaluator: ServerTrustEvaluating {
  262. private let evaluators: [ServerTrustEvaluating]
  263. /// Creates a `CompositeTrustEvaluator`.
  264. ///
  265. /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust.
  266. public init(evaluators: [ServerTrustEvaluating]) {
  267. self.evaluators = evaluators
  268. }
  269. /// Evaluates the given `SecTrust` value for the given `host`.
  270. ///
  271. /// - Parameters:
  272. /// - trust: The `SecTrust` value to evaluate.
  273. /// - host: The host for which to evaluate the `SecTrust` value.
  274. /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
  275. public func evaluate(_ trust: SecTrust, forHost host: String) -> Bool {
  276. return evaluators.evaluate(trust, forHost: host)
  277. }
  278. }
  279. /// Disables all evaluation which in turn will always consider any server trust as valid.
  280. public final class DisabledEvaluator: ServerTrustEvaluating {
  281. public init() { }
  282. /// Evaluates the given `SecTrust` value for the given `host`.
  283. ///
  284. /// - Parameters:
  285. /// - trust: The `SecTrust` value to evaluate.
  286. /// - host: The host for which to evaluate the `SecTrust` value.
  287. /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
  288. public func evaluate(_ trust: SecTrust, forHost host: String) -> Bool {
  289. return true
  290. }
  291. }
  292. public extension Bundle {
  293. /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle.
  294. var certificates: [SecCertificate] {
  295. return paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in
  296. guard
  297. let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
  298. let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil }
  299. return certificate
  300. }
  301. }
  302. /// Returns all public keys for the valid certificates in the bundle.
  303. var publicKeys: [SecKey] {
  304. return certificates.compactMap { $0.publicKey }
  305. }
  306. /// Returns all pathnames for the resources identified by the provided file extensions.
  307. ///
  308. /// - Parameter types: The filename extensions locate.
  309. /// - Returns: All pathnames for the given filename extensions.
  310. func paths(forResourcesOfTypes types: [String]) -> [String] {
  311. return Array(Set(types.flatMap { paths(forResourcesOfType: $0, inDirectory: nil) }))
  312. }
  313. }
  314. public extension SecTrust {
  315. /// Evaluates `self` and returns `true` if the evaluation succeeds with a value of `.unspecified` or `.proceed`.
  316. var isValid: Bool {
  317. var result = SecTrustResultType.invalid
  318. let status = SecTrustEvaluate(self, &result)
  319. return (status == errSecSuccess) ? result == .unspecified || result == .proceed : false
  320. }
  321. /// The public keys contained in `self`.
  322. var publicKeys: [SecKey] {
  323. return (0..<SecTrustGetCertificateCount(self)).compactMap { index in
  324. return SecTrustGetCertificateAtIndex(self, index)?.publicKey
  325. }
  326. }
  327. /// The `Data` values for all certificates contained in `self`.
  328. var certificateData: [Data] {
  329. return (0..<SecTrustGetCertificateCount(self)).compactMap { index in
  330. SecTrustGetCertificateAtIndex(self, index)
  331. }.data
  332. }
  333. }
  334. public extension Array where Element == SecCertificate {
  335. /// All `Data` values for the contained `SecCertificate` values.
  336. var data: [Data] {
  337. return map { SecCertificateCopyData($0) as Data }
  338. }
  339. }
  340. public extension SecCertificate {
  341. /// The public key for `self`, if it can be extracted.
  342. var publicKey: SecKey? {
  343. let policy = SecPolicyCreateBasicX509()
  344. var trust: SecTrust?
  345. let trustCreationStatus = SecTrustCreateWithCertificates(self, policy, &trust)
  346. guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil }
  347. return SecTrustCopyPublicKey(createdTrust)
  348. }
  349. }