ServerTrustPolicy.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 `ServerTrustPolicy` objects to a given host.
  26. public class ServerTrustPolicyManager {
  27. /// The dictionary of policies mapped to a particular host.
  28. public let policies: [String: ServerTrustPolicy]
  29. /**
  30. Initializes the `ServerTrustPolicyManager` instance with the given policies.
  31. Since different servers and web services can have different leaf certificates, intermediate and even root
  32. certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
  33. allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
  34. pinning for host3 and disabling evaluation for host4.
  35. - parameter policies: A dictionary of all policies mapped to a particular host.
  36. - returns: The new `ServerTrustPolicyManager` instance.
  37. */
  38. public init(policies: [String: ServerTrustPolicy]) {
  39. self.policies = policies
  40. }
  41. /**
  42. Returns the `ServerTrustPolicy` for the given host if applicable.
  43. By default, this method will return the policy that perfectly matches the given host. Subclasses could override
  44. this method and implement more complex mapping implementations such as wildcards.
  45. - parameter host: The host to use when searching for a matching policy.
  46. - returns: The server trust policy for the given host if found.
  47. */
  48. public func serverTrustPolicyForHost(_ host: String) -> ServerTrustPolicy? {
  49. return policies[host]
  50. }
  51. }
  52. // MARK: -
  53. extension URLSession {
  54. private struct AssociatedKeys {
  55. static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
  56. }
  57. var serverTrustPolicyManager: ServerTrustPolicyManager? {
  58. get {
  59. return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
  60. }
  61. set (manager) {
  62. objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  63. }
  64. }
  65. }
  66. // MARK: - ServerTrustPolicy
  67. /**
  68. The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
  69. connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
  70. with a given set of criteria to determine whether the server trust is valid and the connection should be made.
  71. Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
  72. vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
  73. to route all communication over an HTTPS connection with pinning enabled.
  74. - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
  75. validate the host provided by the challenge. Applications are encouraged to always
  76. validate the host in production environments to guarantee the validity of the server's
  77. certificate chain.
  78. - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
  79. considered valid if one of the pinned certificates match one of the server certificates.
  80. By validating both the certificate chain and host, certificate pinning provides a very
  81. secure form of server trust validation mitigating most, if not all, MITM attacks.
  82. Applications are encouraged to always validate the host and require a valid certificate
  83. chain in production environments.
  84. - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
  85. valid if one of the pinned public keys match one of the server certificate public keys.
  86. By validating both the certificate chain and host, public key pinning provides a very
  87. secure form of server trust validation mitigating most, if not all, MITM attacks.
  88. Applications are encouraged to always validate the host and require a valid certificate
  89. chain in production environments.
  90. - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
  91. - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust.
  92. */
  93. public enum ServerTrustPolicy {
  94. case performDefaultEvaluation(validateHost: Bool)
  95. case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
  96. case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
  97. case disableEvaluation
  98. case customEvaluation((serverTrust: SecTrust, host: String) -> Bool)
  99. // MARK: - Bundle Location
  100. /**
  101. Returns all certificates within the given bundle with a `.cer` file extension.
  102. - parameter bundle: The bundle to search for all `.cer` files.
  103. - returns: All certificates within the given bundle.
  104. */
  105. public static func certificatesInBundle(_ bundle: Bundle = Bundle.main) -> [SecCertificate] {
  106. var certificates: [SecCertificate] = []
  107. let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
  108. bundle.pathsForResources(ofType: fileExtension, inDirectory: nil)
  109. }.flatten())
  110. for path in paths {
  111. if let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)),
  112. let certificate = SecCertificateCreateWithData(nil, certificateData)
  113. {
  114. certificates.append(certificate)
  115. }
  116. }
  117. return certificates
  118. }
  119. /**
  120. Returns all public keys within the given bundle with a `.cer` file extension.
  121. - parameter bundle: The bundle to search for all `*.cer` files.
  122. - returns: All public keys within the given bundle.
  123. */
  124. public static func publicKeysInBundle(_ bundle: Bundle = Bundle.main) -> [SecKey] {
  125. var publicKeys: [SecKey] = []
  126. for certificate in certificatesInBundle(bundle) {
  127. if let publicKey = publicKeyForCertificate(certificate) {
  128. publicKeys.append(publicKey)
  129. }
  130. }
  131. return publicKeys
  132. }
  133. // MARK: - Evaluation
  134. /**
  135. Evaluates whether the server trust is valid for the given host.
  136. - parameter serverTrust: The server trust to evaluate.
  137. - parameter host: The host of the challenge protection space.
  138. - returns: Whether the server trust is valid.
  139. */
  140. public func evaluateServerTrust(_ serverTrust: SecTrust, isValidForHost host: String) -> Bool {
  141. var serverTrustIsValid = false
  142. switch self {
  143. case let .performDefaultEvaluation(validateHost):
  144. let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
  145. SecTrustSetPolicies(serverTrust, [policy])
  146. serverTrustIsValid = trustIsValid(serverTrust)
  147. case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
  148. if validateCertificateChain {
  149. let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
  150. SecTrustSetPolicies(serverTrust, [policy])
  151. SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
  152. SecTrustSetAnchorCertificatesOnly(serverTrust, true)
  153. serverTrustIsValid = trustIsValid(serverTrust)
  154. } else {
  155. let serverCertificatesDataArray = certificateDataForTrust(serverTrust)
  156. let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates)
  157. outerLoop: for serverCertificateData in serverCertificatesDataArray {
  158. for pinnedCertificateData in pinnedCertificatesDataArray {
  159. if serverCertificateData == pinnedCertificateData {
  160. serverTrustIsValid = true
  161. break outerLoop
  162. }
  163. }
  164. }
  165. }
  166. case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
  167. var certificateChainEvaluationPassed = true
  168. if validateCertificateChain {
  169. let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
  170. SecTrustSetPolicies(serverTrust, [policy])
  171. certificateChainEvaluationPassed = trustIsValid(serverTrust)
  172. }
  173. if certificateChainEvaluationPassed {
  174. outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] {
  175. for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
  176. if serverPublicKey.isEqual(pinnedPublicKey) {
  177. serverTrustIsValid = true
  178. break outerLoop
  179. }
  180. }
  181. }
  182. }
  183. case .disableEvaluation:
  184. serverTrustIsValid = true
  185. case let .customEvaluation(closure):
  186. serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
  187. }
  188. return serverTrustIsValid
  189. }
  190. // MARK: - Private - Trust Validation
  191. private func trustIsValid(_ trust: SecTrust) -> Bool {
  192. var isValid = false
  193. var result = SecTrustResultType.invalid
  194. let status = SecTrustEvaluate(trust, &result)
  195. if status == errSecSuccess {
  196. let unspecified = SecTrustResultType.unspecified
  197. let proceed = SecTrustResultType.proceed
  198. isValid = result == unspecified || result == proceed
  199. }
  200. return isValid
  201. }
  202. // MARK: - Private - Certificate Data
  203. private func certificateDataForTrust(_ trust: SecTrust) -> [Data] {
  204. var certificates: [SecCertificate] = []
  205. for index in 0..<SecTrustGetCertificateCount(trust) {
  206. if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
  207. certificates.append(certificate)
  208. }
  209. }
  210. return certificateDataForCertificates(certificates)
  211. }
  212. private func certificateDataForCertificates(_ certificates: [SecCertificate]) -> [Data] {
  213. return certificates.map { SecCertificateCopyData($0) as Data }
  214. }
  215. // MARK: - Private - Public Key Extraction
  216. private static func publicKeysForTrust(_ trust: SecTrust) -> [SecKey] {
  217. var publicKeys: [SecKey] = []
  218. for index in 0..<SecTrustGetCertificateCount(trust) {
  219. if let certificate = SecTrustGetCertificateAtIndex(trust, index),
  220. let publicKey = publicKeyForCertificate(certificate)
  221. {
  222. publicKeys.append(publicKey)
  223. }
  224. }
  225. return publicKeys
  226. }
  227. private static func publicKeyForCertificate(_ certificate: SecCertificate) -> SecKey? {
  228. var publicKey: SecKey?
  229. let policy = SecPolicyCreateBasicX509()
  230. var trust: SecTrust?
  231. let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
  232. if let trust = trust, trustCreationStatus == errSecSuccess {
  233. publicKey = SecTrustCopyPublicKey(trust)
  234. }
  235. return publicKey
  236. }
  237. }