ServerTrustEvaluation.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. /// Determines whether all hosts for this `ServerTrustManager` must be evaluated. `true` by default.
  28. public let allHostsMustBeEvaluated: Bool
  29. /// The dictionary of policies mapped to a particular host.
  30. public let evaluators: [String: ServerTrustEvaluating]
  31. /// Initializes the `ServerTrustManager` instance with the given evaluators.
  32. ///
  33. /// Since different servers and web services can have different leaf certificates, intermediate and even root
  34. /// certificates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
  35. /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
  36. /// pinning for host3 and disabling evaluation for host4.
  37. ///
  38. /// - Parameters:
  39. /// - allHostsMustBeEvaluated: The value determining whether all hosts for this instance must be evaluated. `true`
  40. /// by default.
  41. /// - evaluators: A dictionary of evaluators mapped to hosts.
  42. public init(allHostsMustBeEvaluated: Bool = true, evaluators: [String: ServerTrustEvaluating]) {
  43. self.allHostsMustBeEvaluated = allHostsMustBeEvaluated
  44. self.evaluators = evaluators
  45. }
  46. /// Returns the `ServerTrustEvaluating` value for the given host, if one is set.
  47. ///
  48. /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override
  49. /// this method and implement more complex mapping implementations such as wildcards.
  50. ///
  51. /// - Parameter host: The host to use when searching for a matching policy.
  52. ///
  53. /// - Returns: The `ServerTrustEvaluating` value for the given host if found, `nil` otherwise.
  54. /// - Throws: `AFError.serverTrustEvaluationFailed` if `allHostsMustBeEvaluated` is `true` and no matching
  55. /// evaluators are found.
  56. open func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? {
  57. guard let evaluator = evaluators[host] else {
  58. if allHostsMustBeEvaluated {
  59. throw AFError.serverTrustEvaluationFailed(reason: .noRequiredEvaluator(host: host))
  60. }
  61. return nil
  62. }
  63. return evaluator
  64. }
  65. }
  66. /// A protocol describing the API used to evaluate server trusts.
  67. public protocol ServerTrustEvaluating {
  68. #if os(Linux)
  69. // Implement this once Linux has API for evaluating server trusts.
  70. #else
  71. /// Evaluates the given `SecTrust` value for the given `host`.
  72. ///
  73. /// - Parameters:
  74. /// - trust: The `SecTrust` value to evaluate.
  75. /// - host: The host for which to evaluate the `SecTrust` value.
  76. ///
  77. /// - Returns: A `Bool` indicating whether the evaluator considers the `SecTrust` value valid for `host`.
  78. func evaluate(_ trust: SecTrust, forHost host: String) throws
  79. #endif
  80. }
  81. // MARK: - Server Trust Evaluators
  82. /// An evaluator which uses the default server trust evaluation while allowing you to control whether to validate the
  83. /// host provided by the challenge. Applications are encouraged to always validate the host in production environments
  84. /// to guarantee the validity of the server's certificate chain.
  85. public final class DefaultTrustEvaluator: ServerTrustEvaluating {
  86. private let validateHost: Bool
  87. /// Creates a `DefaultTrustEvaluator`.
  88. ///
  89. /// - Parameter validateHost: Determines whether or not the evaluator should validate the host. `true` by default.
  90. public init(validateHost: Bool = true) {
  91. self.validateHost = validateHost
  92. }
  93. public func evaluate(_ trust: SecTrust, forHost host: String) throws {
  94. if validateHost {
  95. try trust.af.performValidation(forHost: host)
  96. }
  97. try trust.af.performDefaultValidation(forHost: host)
  98. }
  99. }
  100. /// An evaluator which Uses the default and revoked server trust evaluations allowing you to control whether to validate
  101. /// the host provided by the challenge as well as specify the revocation flags for testing for revoked certificates.
  102. /// Apple platforms did not start testing for revoked certificates automatically until iOS 10.1, macOS 10.12 and tvOS
  103. /// 10.1 which is demonstrated in our TLS tests. Applications are encouraged to always validate the host in production
  104. /// environments to guarantee the validity of the server's certificate chain.
  105. public final class RevocationTrustEvaluator: ServerTrustEvaluating {
  106. /// Represents the options to be use when evaluating the status of a certificate.
  107. /// 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).
  108. public struct Options: OptionSet {
  109. /// Perform revocation checking using the CRL (Certification Revocation List) method.
  110. public static let crl = Options(rawValue: kSecRevocationCRLMethod)
  111. /// Consult only locally cached replies; do not use network access.
  112. public static let networkAccessDisabled = Options(rawValue: kSecRevocationNetworkAccessDisabled)
  113. /// Perform revocation checking using OCSP (Online Certificate Status Protocol).
  114. public static let ocsp = Options(rawValue: kSecRevocationOCSPMethod)
  115. /// Prefer CRL revocation checking over OCSP; by default, OCSP is preferred.
  116. public static let preferCRL = Options(rawValue: kSecRevocationPreferCRL)
  117. /// Require a positive response to pass the policy. If the flag is not set, revocation checking is done on a
  118. /// "best attempt" basis, where failure to reach the server is not considered fatal.
  119. public static let requirePositiveResponse = Options(rawValue: kSecRevocationRequirePositiveResponse)
  120. /// Perform either OCSP or CRL checking. The checking is performed according to the method(s) specified in the
  121. /// certificate and the value of `preferCRL`.
  122. public static let any = Options(rawValue: kSecRevocationUseAnyAvailableMethod)
  123. /// The raw value of the option.
  124. public let rawValue: CFOptionFlags
  125. /// Creates an `Options` value with the given `CFOptionFlags`.
  126. ///
  127. /// - Parameter rawValue: The `CFOptionFlags` value to initialize with.
  128. public init(rawValue: CFOptionFlags) {
  129. self.rawValue = rawValue
  130. }
  131. }
  132. private let performDefaultValidation: Bool
  133. private let validateHost: Bool
  134. private let options: Options
  135. /// Creates a `RevocationTrustEvaluator`.
  136. ///
  137. /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
  138. /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
  139. ///
  140. /// - Parameters:
  141. /// - performDefaultValidation: Determines whether default validation should be performed in addition to
  142. /// evaluating the pinned certificates. `true` by default.
  143. /// - validateHost: Determines whether or not the evaluator should validate the host, in addition
  144. /// to performing the default evaluation, even if `performDefaultValidation` is
  145. /// `false`. `true` by default.
  146. /// - options: The `Options` to use to check the revocation status of the certificate. `.any`
  147. /// by default.
  148. public init(performDefaultValidation: Bool = true, validateHost: Bool = true, options: Options = .any) {
  149. self.performDefaultValidation = performDefaultValidation
  150. self.validateHost = validateHost
  151. self.options = options
  152. }
  153. public func evaluate(_ trust: SecTrust, forHost host: String) throws {
  154. if performDefaultValidation {
  155. try trust.af.performDefaultValidation(forHost: host)
  156. }
  157. if validateHost {
  158. try trust.af.performValidation(forHost: host)
  159. }
  160. if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) {
  161. try trust.af.evaluate(afterApplying: SecPolicy.af.revocation(options: options))
  162. } else {
  163. try trust.af.validate(policy: SecPolicy.af.revocation(options: options)) { status, result in
  164. AFError.serverTrustEvaluationFailed(reason: .revocationCheckFailed(output: .init(host, trust, status, result), options: options))
  165. }
  166. }
  167. }
  168. }
  169. /// Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned
  170. /// certificates match one of the server certificates. By validating both the certificate chain and host, certificate
  171. /// pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
  172. /// Applications are encouraged to always validate the host and require a valid certificate chain in production
  173. /// environments.
  174. public final class PinnedCertificatesTrustEvaluator: ServerTrustEvaluating {
  175. private let certificates: [SecCertificate]
  176. private let acceptSelfSignedCertificates: Bool
  177. private let performDefaultValidation: Bool
  178. private let validateHost: Bool
  179. /// Creates a `PinnedCertificatesTrustEvaluator`.
  180. ///
  181. /// - Parameters:
  182. /// - certificates: The certificates to use to evaluate the trust. All `cer`, `crt`, and `der`
  183. /// certificates in `Bundle.main` by default.
  184. /// - acceptSelfSignedCertificates: Adds the provided certificates as anchors for the trust evaluation, allowing
  185. /// self-signed certificates to pass. `false` by default. THIS SETTING SHOULD BE
  186. /// FALSE IN PRODUCTION!
  187. /// - performDefaultValidation: Determines whether default validation should be performed in addition to
  188. /// evaluating the pinned certificates. `true` by default.
  189. /// - validateHost: Determines whether or not the evaluator should validate the host, in addition
  190. /// to performing the default evaluation, even if `performDefaultValidation` is
  191. /// `false`. `true` by default.
  192. public init(certificates: [SecCertificate] = Bundle.main.af.certificates,
  193. acceptSelfSignedCertificates: Bool = false,
  194. performDefaultValidation: Bool = true,
  195. validateHost: Bool = true) {
  196. self.certificates = certificates
  197. self.acceptSelfSignedCertificates = acceptSelfSignedCertificates
  198. self.performDefaultValidation = performDefaultValidation
  199. self.validateHost = validateHost
  200. }
  201. public func evaluate(_ trust: SecTrust, forHost host: String) throws {
  202. guard !certificates.isEmpty else {
  203. throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
  204. }
  205. if acceptSelfSignedCertificates {
  206. try trust.af.setAnchorCertificates(certificates)
  207. }
  208. if performDefaultValidation {
  209. try trust.af.performDefaultValidation(forHost: host)
  210. }
  211. if validateHost {
  212. try trust.af.performValidation(forHost: host)
  213. }
  214. let serverCertificatesData = Set(trust.af.certificateData)
  215. let pinnedCertificatesData = Set(certificates.af.data)
  216. let pinnedCertificatesInServerData = !serverCertificatesData.isDisjoint(with: pinnedCertificatesData)
  217. if !pinnedCertificatesInServerData {
  218. throw AFError.serverTrustEvaluationFailed(reason: .certificatePinningFailed(host: host,
  219. trust: trust,
  220. pinnedCertificates: certificates,
  221. serverCertificates: trust.af.certificates))
  222. }
  223. }
  224. }
  225. /// Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned
  226. /// public keys match one of the server certificate public keys. By validating both the certificate chain and host,
  227. /// public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks.
  228. /// Applications are encouraged to always validate the host and require a valid certificate chain in production
  229. /// environments.
  230. public final class PublicKeysTrustEvaluator: ServerTrustEvaluating {
  231. private let keys: [SecKey]
  232. private let performDefaultValidation: Bool
  233. private let validateHost: Bool
  234. /// Creates a `PublicKeysTrustEvaluator`.
  235. ///
  236. /// - Note: Default and host validation will fail when using this evaluator with self-signed certificates. Use
  237. /// `PinnedCertificatesTrustEvaluator` if you need to use self-signed certificates.
  238. ///
  239. /// - Parameters:
  240. /// - keys: The `SecKey`s to use to validate public keys. Defaults to the public keys of all
  241. /// certificates included in the main bundle.
  242. /// - performDefaultValidation: Determines whether default validation should be performed in addition to
  243. /// evaluating the pinned certificates. `true` by default.
  244. /// - validateHost: Determines whether or not the evaluator should validate the host, in addition to
  245. /// performing the default evaluation, even if `performDefaultValidation` is `false`.
  246. /// `true` by default.
  247. public init(keys: [SecKey] = Bundle.main.af.publicKeys,
  248. performDefaultValidation: Bool = true,
  249. validateHost: Bool = true) {
  250. self.keys = keys
  251. self.performDefaultValidation = performDefaultValidation
  252. self.validateHost = validateHost
  253. }
  254. public func evaluate(_ trust: SecTrust, forHost host: String) throws {
  255. guard !keys.isEmpty else {
  256. throw AFError.serverTrustEvaluationFailed(reason: .noPublicKeysFound)
  257. }
  258. if performDefaultValidation {
  259. try trust.af.performDefaultValidation(forHost: host)
  260. }
  261. if validateHost {
  262. try trust.af.performValidation(forHost: host)
  263. }
  264. let pinnedKeysInServerKeys: Bool = {
  265. for serverPublicKey in trust.af.publicKeys {
  266. for pinnedPublicKey in keys {
  267. if serverPublicKey == pinnedPublicKey {
  268. return true
  269. }
  270. }
  271. }
  272. return false
  273. }()
  274. if !pinnedKeysInServerKeys {
  275. throw AFError.serverTrustEvaluationFailed(reason: .publicKeyPinningFailed(host: host,
  276. trust: trust,
  277. pinnedKeys: keys,
  278. serverKeys: trust.af.publicKeys))
  279. }
  280. }
  281. }
  282. /// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the
  283. /// evaluators consider it valid.
  284. public final class CompositeTrustEvaluator: ServerTrustEvaluating {
  285. private let evaluators: [ServerTrustEvaluating]
  286. /// Creates a `CompositeTrustEvaluator`.
  287. ///
  288. /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust.
  289. public init(evaluators: [ServerTrustEvaluating]) {
  290. self.evaluators = evaluators
  291. }
  292. public func evaluate(_ trust: SecTrust, forHost host: String) throws {
  293. try evaluators.evaluate(trust, forHost: host)
  294. }
  295. }
  296. /// Disables all evaluation which in turn will always consider any server trust as valid.
  297. ///
  298. /// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test
  299. /// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html).
  300. ///
  301. /// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!**
  302. @available(*, deprecated, renamed: "DisabledTrustEvaluator", message: "DisabledEvaluator has been renamed DisabledTrustEvaluator.")
  303. public typealias DisabledEvaluator = DisabledTrustEvaluator
  304. /// Disables all evaluation which in turn will always consider any server trust as valid.
  305. ///
  306. ///
  307. /// - Note: Instead of disabling server trust evaluation, it's a better idea to configure systems to properly trust test
  308. /// certificates, as outlined in [this Apple tech note](https://developer.apple.com/library/archive/qa/qa1948/_index.html).
  309. ///
  310. /// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!**
  311. public final class DisabledTrustEvaluator: ServerTrustEvaluating {
  312. /// Creates an instance.
  313. public init() {}
  314. public func evaluate(_ trust: SecTrust, forHost host: String) throws {}
  315. }
  316. // MARK: - Extensions
  317. extension Array where Element == ServerTrustEvaluating {
  318. #if os(Linux)
  319. // Add this same convenience method for Linux.
  320. #else
  321. /// Evaluates the given `SecTrust` value for the given `host`.
  322. ///
  323. /// - Parameters:
  324. /// - trust: The `SecTrust` value to evaluate.
  325. /// - host: The host for which to evaluate the `SecTrust` value.
  326. ///
  327. /// - Returns: Whether or not the evaluator considers the `SecTrust` value valid for `host`.
  328. public func evaluate(_ trust: SecTrust, forHost host: String) throws {
  329. for evaluator in self {
  330. try evaluator.evaluate(trust, forHost: host)
  331. }
  332. }
  333. #endif
  334. }
  335. extension Bundle: AlamofireExtended {}
  336. extension AlamofireExtension where ExtendedType: Bundle {
  337. /// Returns all valid `cer`, `crt`, and `der` certificates in the bundle.
  338. public var certificates: [SecCertificate] {
  339. paths(forResourcesOfTypes: [".cer", ".CER", ".crt", ".CRT", ".der", ".DER"]).compactMap { path in
  340. guard
  341. let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
  342. let certificate = SecCertificateCreateWithData(nil, certificateData) else { return nil }
  343. return certificate
  344. }
  345. }
  346. /// Returns all public keys for the valid certificates in the bundle.
  347. public var publicKeys: [SecKey] {
  348. certificates.af.publicKeys
  349. }
  350. /// Returns all pathnames for the resources identified by the provided file extensions.
  351. ///
  352. /// - Parameter types: The filename extensions locate.
  353. ///
  354. /// - Returns: All pathnames for the given filename extensions.
  355. public func paths(forResourcesOfTypes types: [String]) -> [String] {
  356. Array(Set(types.flatMap { type.paths(forResourcesOfType: $0, inDirectory: nil) }))
  357. }
  358. }
  359. extension SecTrust: AlamofireExtended {}
  360. extension AlamofireExtension where ExtendedType == SecTrust {
  361. /// Evaluates `self` after applying the `SecPolicy` value provided.
  362. ///
  363. /// - Parameter policy: The `SecPolicy` to apply to `self` before evaluation.
  364. ///
  365. /// - Throws: Any `Error` from applying the `SecPolicy` or from evaluation.
  366. @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *)
  367. public func evaluate(afterApplying policy: SecPolicy) throws {
  368. try apply(policy: policy).af.evaluate()
  369. }
  370. /// Attempts to validate `self` using the `SecPolicy` provided and transforming any error produced using the closure passed.
  371. ///
  372. /// - Parameters:
  373. /// - policy: The `SecPolicy` used to evaluate `self`.
  374. /// - errorProducer: The closure used transform the failed `OSStatus` and `SecTrustResultType`.
  375. /// - Throws: Any `Error` from applying the `policy`, or the result of `errorProducer` if validation fails.
  376. @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)")
  377. @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate(afterApplying:)")
  378. @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate(afterApplying:)")
  379. @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate(afterApplying:)")
  380. public func validate(policy: SecPolicy, errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws {
  381. try apply(policy: policy).af.validate(errorProducer: errorProducer)
  382. }
  383. /// Applies a `SecPolicy` to `self`, throwing if it fails.
  384. ///
  385. /// - Parameter policy: The `SecPolicy`.
  386. ///
  387. /// - Returns: `self`, with the policy applied.
  388. /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.policyApplicationFailed` reason.
  389. public func apply(policy: SecPolicy) throws -> SecTrust {
  390. let status = SecTrustSetPolicies(type, policy)
  391. guard status.af.isSuccess else {
  392. throw AFError.serverTrustEvaluationFailed(reason: .policyApplicationFailed(trust: type,
  393. policy: policy,
  394. status: status))
  395. }
  396. return type
  397. }
  398. /// Evaluate `self`, throwing an `Error` if evaluation fails.
  399. ///
  400. /// - Throws: `AFError.serverTrustEvaluationFailed` with reason `.trustValidationFailed` and associated error from
  401. /// the underlying evaluation.
  402. @available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *)
  403. public func evaluate() throws {
  404. var error: CFError?
  405. let evaluationSucceeded = SecTrustEvaluateWithError(type, &error)
  406. if !evaluationSucceeded {
  407. throw AFError.serverTrustEvaluationFailed(reason: .trustEvaluationFailed(error: error))
  408. }
  409. }
  410. /// Validate `self`, passing any failure values through `errorProducer`.
  411. ///
  412. /// - Parameter errorProducer: The closure used to transform the failed `OSStatus` and `SecTrustResultType` into an
  413. /// `Error`.
  414. /// - Throws: The `Error` produced by the `errorProducer` closure.
  415. @available(iOS, introduced: 10, deprecated: 12, renamed: "evaluate()")
  416. @available(macOS, introduced: 10.12, deprecated: 10.14, renamed: "evaluate()")
  417. @available(tvOS, introduced: 10, deprecated: 12, renamed: "evaluate()")
  418. @available(watchOS, introduced: 3, deprecated: 5, renamed: "evaluate()")
  419. public func validate(errorProducer: (_ status: OSStatus, _ result: SecTrustResultType) -> Error) throws {
  420. var result = SecTrustResultType.invalid
  421. let status = SecTrustEvaluate(type, &result)
  422. guard status.af.isSuccess && result.af.isSuccess else {
  423. throw errorProducer(status, result)
  424. }
  425. }
  426. /// Sets a custom certificate chain on `self`, allowing full validation of a self-signed certificate and its chain.
  427. ///
  428. /// - Parameter certificates: The `SecCertificate`s to add to the chain.
  429. /// - Throws: Any error produced when applying the new certificate chain.
  430. public func setAnchorCertificates(_ certificates: [SecCertificate]) throws {
  431. // Add additional anchor certificates.
  432. let status = SecTrustSetAnchorCertificates(type, certificates as CFArray)
  433. guard status.af.isSuccess else {
  434. throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: status,
  435. certificates: certificates))
  436. }
  437. // Trust only the set anchor certs.
  438. let onlyStatus = SecTrustSetAnchorCertificatesOnly(type, true)
  439. guard onlyStatus.af.isSuccess else {
  440. throw AFError.serverTrustEvaluationFailed(reason: .settingAnchorCertificatesFailed(status: onlyStatus,
  441. certificates: certificates))
  442. }
  443. }
  444. /// The public keys contained in `self`.
  445. public var publicKeys: [SecKey] {
  446. certificates.af.publicKeys
  447. }
  448. /// The `SecCertificate`s contained i `self`.
  449. public var certificates: [SecCertificate] {
  450. (0..<SecTrustGetCertificateCount(type)).compactMap { index in
  451. SecTrustGetCertificateAtIndex(type, index)
  452. }
  453. }
  454. /// The `Data` values for all certificates contained in `self`.
  455. public var certificateData: [Data] {
  456. certificates.af.data
  457. }
  458. /// Validates `self` after applying `SecPolicy.af.default`. This evaluation does not validate the hostname.
  459. ///
  460. /// - Parameter host: The hostname, used only in the error output if validation fails.
  461. /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason.
  462. public func performDefaultValidation(forHost host: String) throws {
  463. if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) {
  464. try evaluate(afterApplying: SecPolicy.af.default)
  465. } else {
  466. try validate(policy: SecPolicy.af.default) { status, result in
  467. AFError.serverTrustEvaluationFailed(reason: .defaultEvaluationFailed(output: .init(host, type, status, result)))
  468. }
  469. }
  470. }
  471. /// Validates `self` after applying `SecPolicy.af.hostname(host)`, which performs the default validation as well as
  472. /// hostname validation.
  473. ///
  474. /// - Parameter host: The hostname to use in the validation.
  475. /// - Throws: An `AFError.serverTrustEvaluationFailed` instance with a `.defaultEvaluationFailed` reason.
  476. public func performValidation(forHost host: String) throws {
  477. if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) {
  478. try evaluate(afterApplying: SecPolicy.af.hostname(host))
  479. } else {
  480. try validate(policy: SecPolicy.af.hostname(host)) { status, result in
  481. AFError.serverTrustEvaluationFailed(reason: .hostValidationFailed(output: .init(host, type, status, result)))
  482. }
  483. }
  484. }
  485. }
  486. extension SecPolicy: AlamofireExtended {}
  487. extension AlamofireExtension where ExtendedType == SecPolicy {
  488. /// Creates a `SecPolicy` instance which will validate server certificates but not require a host name match.
  489. public static let `default` = SecPolicyCreateSSL(true, nil)
  490. /// Creates a `SecPolicy` instance which will validate server certificates and much match the provided hostname.
  491. ///
  492. /// - Parameter hostname: The hostname to validate against.
  493. ///
  494. /// - Returns: The `SecPolicy`.
  495. public static func hostname(_ hostname: String) -> SecPolicy {
  496. SecPolicyCreateSSL(true, hostname as CFString)
  497. }
  498. /// Creates a `SecPolicy` which checks the revocation of certificates.
  499. ///
  500. /// - Parameter options: The `RevocationTrustEvaluator.Options` for evaluation.
  501. ///
  502. /// - Returns: The `SecPolicy`.
  503. /// - Throws: An `AFError.serverTrustEvaluationFailed` error with reason `.revocationPolicyCreationFailed`
  504. /// if the policy cannot be created.
  505. public static func revocation(options: RevocationTrustEvaluator.Options) throws -> SecPolicy {
  506. guard let policy = SecPolicyCreateRevocation(options.rawValue) else {
  507. throw AFError.serverTrustEvaluationFailed(reason: .revocationPolicyCreationFailed)
  508. }
  509. return policy
  510. }
  511. }
  512. extension Array: AlamofireExtended {}
  513. extension AlamofireExtension where ExtendedType == [SecCertificate] {
  514. /// All `Data` values for the contained `SecCertificate`s.
  515. public var data: [Data] {
  516. type.map { SecCertificateCopyData($0) as Data }
  517. }
  518. /// All public `SecKey` values for the contained `SecCertificate`s.
  519. public var publicKeys: [SecKey] {
  520. type.compactMap { $0.af.publicKey }
  521. }
  522. }
  523. extension SecCertificate: AlamofireExtended {}
  524. extension AlamofireExtension where ExtendedType == SecCertificate {
  525. /// The public key for `self`, if it can be extracted.
  526. public var publicKey: SecKey? {
  527. let policy = SecPolicyCreateBasicX509()
  528. var trust: SecTrust?
  529. let trustCreationStatus = SecTrustCreateWithCertificates(type, policy, &trust)
  530. guard let createdTrust = trust, trustCreationStatus == errSecSuccess else { return nil }
  531. return SecTrustCopyPublicKey(createdTrust)
  532. }
  533. }
  534. extension OSStatus: AlamofireExtended {}
  535. extension AlamofireExtension where ExtendedType == OSStatus {
  536. /// Returns whether `self` is `errSecSuccess`.
  537. public var isSuccess: Bool { type == errSecSuccess }
  538. }
  539. extension SecTrustResultType: AlamofireExtended {}
  540. extension AlamofireExtension where ExtendedType == SecTrustResultType {
  541. /// Returns whether `self is `.unspecified` or `.proceed`.
  542. public var isSuccess: Bool {
  543. type == .unspecified || type == .proceed
  544. }
  545. }