ServerTrustEvaluation.swift 38 KB

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