ServerTrustPolicy.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. // ServerTrustPolicy.swift
  2. //
  3. // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
  24. public class ServerTrustPolicyManager {
  25. let policies: [String: ServerTrustPolicy]
  26. /**
  27. Initializes the `ServerTrustPolicyManager` instance with the given policies.
  28. Since different servers and web services can have different leaf certificates, intermediate and even root
  29. certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
  30. allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
  31. pinning for host3 and disabling evaluation for host4.
  32. - parameter policies: A dictionary of all policies mapped to a particular host.
  33. - returns: The new `ServerTrustPolicyManager` instance.
  34. */
  35. public init(policies: [String: ServerTrustPolicy]) {
  36. self.policies = policies
  37. }
  38. func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? {
  39. return policies[host]
  40. }
  41. }
  42. // MARK: -
  43. extension NSURLSession {
  44. private struct AssociatedKeys {
  45. static var ManagerKey = "NSURLSession.ServerTrustPolicyManager"
  46. }
  47. var serverTrustPolicyManager: ServerTrustPolicyManager? {
  48. get {
  49. return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager
  50. }
  51. set (manager) {
  52. objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  53. }
  54. }
  55. }
  56. // MARK: - ServerTrustPolicy
  57. /**
  58. The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
  59. connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
  60. with a given set of criteria to determine whether the server trust is valid and the connection should be made.
  61. Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
  62. vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
  63. to route all communication over an HTTPS connection with pinning enabled.
  64. - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
  65. validate the host provided by the challenge. Applications are encouraged to always
  66. validate the host in production environments to guarantee the validity of the server's
  67. certificate chain.
  68. - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
  69. considered valid if one of the pinned certificates match one of the server certificates.
  70. By validating both the certificate chain and host, certificate pinning provides a very
  71. secure form of server trust validation mitigating most, if not all, MITM attacks.
  72. Applications are encouraged to always validate the host and require a valid certificate
  73. chain in production environments.
  74. - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
  75. valid if one of the pinned public keys match one of the server certificate public keys.
  76. By validating both the certificate chain and host, public key pinning provides a very
  77. secure form of server trust validation mitigating most, if not all, MITM attacks.
  78. Applications are encouraged to always validate the host and require a valid certificate
  79. chain in production environments.
  80. - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
  81. - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust.
  82. */
  83. public enum ServerTrustPolicy {
  84. case PerformDefaultEvaluation(validateHost: Bool)
  85. case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
  86. case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
  87. case DisableEvaluation
  88. case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool)
  89. // MARK: - Bundle Location
  90. /**
  91. Returns all certificates within the given bundle with a `.cer` file extension.
  92. - parameter bundle: The bundle to search for all `.cer` files.
  93. - returns: All certificates within the given bundle.
  94. */
  95. public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] {
  96. var certificates: [SecCertificate] = []
  97. for path in bundle.pathsForResourcesOfType(".cer", inDirectory: nil) {
  98. if let
  99. certificateData = NSData(contentsOfFile: path),
  100. certificate = SecCertificateCreateWithData(nil, certificateData)
  101. {
  102. certificates.append(certificate)
  103. }
  104. }
  105. return certificates
  106. }
  107. /**
  108. Returns all public keys within the given bundle with a `.cer` file extension.
  109. - parameter bundle: The bundle to search for all `*.cer` files.
  110. - returns: All public keys within the given bundle.
  111. */
  112. public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] {
  113. var publicKeys: [SecKey] = []
  114. for certificate in certificatesInBundle(bundle) {
  115. if let publicKey = publicKeyForCertificate(certificate) {
  116. publicKeys.append(publicKey)
  117. }
  118. }
  119. return publicKeys
  120. }
  121. // MARK: - Evaluation
  122. /**
  123. Evaluates whether the server trust is valid for the given host.
  124. - parameter serverTrust: The server trust to evaluate.
  125. - parameter host: The host of the challenge protection space.
  126. - returns: Whether the server trust is valid.
  127. */
  128. public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool {
  129. var serverTrustIsValid = false
  130. switch self {
  131. case let .PerformDefaultEvaluation(validateHost):
  132. let policy = validateHost ? SecPolicyCreateSSL(1, host as CFString) : SecPolicyCreateBasicX509()
  133. SecTrustSetPolicies(serverTrust, [policy])
  134. serverTrustIsValid = trustIsValid(serverTrust)
  135. case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
  136. if validateCertificateChain {
  137. let policy = validateHost ? SecPolicyCreateSSL(1, host as CFString) : SecPolicyCreateBasicX509()
  138. SecTrustSetPolicies(serverTrust, [policy])
  139. SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates)
  140. SecTrustSetAnchorCertificatesOnly(serverTrust, 1)
  141. serverTrustIsValid = trustIsValid(serverTrust)
  142. } else {
  143. let serverCertificatesDataArray = certificateDataForTrust(serverTrust)
  144. //======================================================================================================
  145. // The following `[] +` is a temporary workaround for a Swift 2.0 compiler error. This workaround should
  146. // be removed once the following radar has been resolved:
  147. // - http://openradar.appspot.com/radar?id=6082025006039040
  148. //======================================================================================================
  149. let pinnedCertificatesDataArray = certificateDataForCertificates([] + pinnedCertificates)
  150. outerLoop: for serverCertificateData in serverCertificatesDataArray {
  151. for pinnedCertificateData in pinnedCertificatesDataArray {
  152. if serverCertificateData.isEqualToData(pinnedCertificateData) {
  153. serverTrustIsValid = true
  154. break outerLoop
  155. }
  156. }
  157. }
  158. }
  159. case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
  160. var certificateChainEvaluationPassed = true
  161. if validateCertificateChain {
  162. let policy = validateHost ? SecPolicyCreateSSL(1, host as CFString) : SecPolicyCreateBasicX509()
  163. SecTrustSetPolicies(serverTrust, [policy])
  164. certificateChainEvaluationPassed = trustIsValid(serverTrust)
  165. }
  166. if certificateChainEvaluationPassed {
  167. outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] {
  168. for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
  169. if serverPublicKey.isEqual(pinnedPublicKey) {
  170. serverTrustIsValid = true
  171. break outerLoop
  172. }
  173. }
  174. }
  175. }
  176. case .DisableEvaluation:
  177. serverTrustIsValid = true
  178. case let .CustomEvaluation(closure):
  179. serverTrustIsValid = closure(serverTrust: serverTrust, host: host)
  180. }
  181. return serverTrustIsValid
  182. }
  183. // MARK: - Private - Trust Validation
  184. private func trustIsValid(trust: SecTrust) -> Bool {
  185. var isValid = false
  186. var result = SecTrustResultType(kSecTrustResultInvalid)
  187. let status = SecTrustEvaluate(trust, &result)
  188. if status == errSecSuccess {
  189. let unspecified = SecTrustResultType(kSecTrustResultUnspecified)
  190. let proceed = SecTrustResultType(kSecTrustResultProceed)
  191. isValid = result == unspecified || result == proceed
  192. }
  193. return isValid
  194. }
  195. // MARK: - Private - Certificate Data
  196. private func certificateDataForTrust(trust: SecTrust) -> [NSData] {
  197. var certificates: [SecCertificate] = []
  198. for index in 0..<SecTrustGetCertificateCount(trust) {
  199. if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
  200. certificates.append(certificate)
  201. }
  202. }
  203. return certificateDataForCertificates(certificates)
  204. }
  205. private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] {
  206. return certificates.map { SecCertificateCopyData($0) as NSData }
  207. }
  208. // MARK: - Private - Public Key Extraction
  209. private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] {
  210. var publicKeys: [SecKey] = []
  211. for index in 0..<SecTrustGetCertificateCount(trust) {
  212. if let
  213. certificate = SecTrustGetCertificateAtIndex(trust, index),
  214. publicKey = publicKeyForCertificate(certificate)
  215. {
  216. publicKeys.append(publicKey)
  217. }
  218. }
  219. return publicKeys
  220. }
  221. private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? {
  222. var publicKey: SecKey?
  223. let policy = SecPolicyCreateBasicX509()
  224. var trust: SecTrust?
  225. let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
  226. if let trust = trust where trustCreationStatus == errSecSuccess {
  227. publicKey = SecTrustCopyPublicKey(trust)
  228. }
  229. return publicKey
  230. }
  231. }