2
0

ServerTrustEvaluation.swift 27 KB

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