TLSEvaluationTests.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. //
  2. // TLSEvaluationTests.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 Alamofire
  25. import Foundation
  26. import XCTest
  27. private struct TestCertificates {
  28. static let rootCA = TestCertificates.certificate(withFileName: "expired.badssl.com-root-ca")
  29. static let intermediateCA1 = TestCertificates.certificate(withFileName: "expired.badssl.com-intermediate-ca-1")
  30. static let intermediateCA2 = TestCertificates.certificate(withFileName: "expired.badssl.com-intermediate-ca-2")
  31. static let leaf = TestCertificates.certificate(withFileName: "expired.badssl.com-leaf")
  32. static func certificate(withFileName fileName: String) -> SecCertificate {
  33. class Locater {}
  34. let filePath = Bundle(for: Locater.self).path(forResource: fileName, ofType: "cer")!
  35. let data = try! Data(contentsOf: URL(fileURLWithPath: filePath))
  36. let certificate = SecCertificateCreateWithData(nil, data as CFData)!
  37. return certificate
  38. }
  39. }
  40. // MARK: -
  41. private struct TestPublicKeys {
  42. static let rootCA = TestPublicKeys.publicKey(for: TestCertificates.rootCA)
  43. static let intermediateCA1 = TestPublicKeys.publicKey(for: TestCertificates.intermediateCA1)
  44. static let intermediateCA2 = TestPublicKeys.publicKey(for: TestCertificates.intermediateCA2)
  45. static let leaf = TestPublicKeys.publicKey(for: TestCertificates.leaf)
  46. static func publicKey(for certificate: SecCertificate) -> SecKey {
  47. let policy = SecPolicyCreateBasicX509()
  48. var trust: SecTrust?
  49. SecTrustCreateWithCertificates(certificate, policy, &trust)
  50. let publicKey = SecTrustCopyPublicKey(trust!)!
  51. return publicKey
  52. }
  53. }
  54. // MARK: -
  55. class TLSEvaluationExpiredLeafCertificateTestCase: BaseTestCase {
  56. let urlString = "https://expired.badssl.com/"
  57. let host = "expired.badssl.com"
  58. var configuration: URLSessionConfiguration!
  59. // MARK: Setup and Teardown
  60. override func setUp() {
  61. super.setUp()
  62. configuration = URLSessionConfiguration.ephemeral
  63. }
  64. // MARK: Default Behavior Tests
  65. func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() {
  66. // Given
  67. weak var expectation = self.expectation(description: "\(urlString)")
  68. let manager = SessionManager(configuration: configuration)
  69. var error: Error?
  70. // When
  71. manager.request(urlString)
  72. .response { resp in
  73. error = resp.error
  74. expectation?.fulfill()
  75. }
  76. waitForExpectations(timeout: timeout, handler: nil)
  77. // Then
  78. XCTAssertNotNil(error)
  79. if let error = error as? URLError {
  80. XCTAssertEqual(error.code, .serverCertificateUntrusted)
  81. } else if let error = error as? NSError {
  82. XCTAssertEqual(error.domain, kCFErrorDomainCFNetwork as String)
  83. XCTAssertEqual(error.code, Int(CFNetworkErrors.cfErrorHTTPSProxyConnectionFailure.rawValue))
  84. } else {
  85. XCTFail("error should be a URLError or NSError from CFNetwork")
  86. }
  87. }
  88. // MARK: Server Trust Policy - Perform Default Tests
  89. func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() {
  90. // Given
  91. let policies = [host: ServerTrustPolicy.performDefaultEvaluation(validateHost: true)]
  92. let manager = SessionManager(
  93. configuration: configuration,
  94. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  95. )
  96. weak var expectation = self.expectation(description: "\(urlString)")
  97. var error: Error?
  98. // When
  99. manager.request(urlString)
  100. .response { resp in
  101. error = resp.error
  102. expectation?.fulfill()
  103. }
  104. waitForExpectations(timeout: timeout, handler: nil)
  105. // Then
  106. XCTAssertNotNil(error, "error should not be nil")
  107. if let error = error as? URLError {
  108. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  109. } else {
  110. XCTFail("error should be an URLError")
  111. }
  112. }
  113. // MARK: Server Trust Policy - Certificate Pinning Tests
  114. func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
  115. // Given
  116. let certificates = [TestCertificates.leaf]
  117. let policies: [String: ServerTrustPolicy] = [
  118. host: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  119. ]
  120. let manager = SessionManager(
  121. configuration: configuration,
  122. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  123. )
  124. weak var expectation = self.expectation(description: "\(urlString)")
  125. var error: Error?
  126. // When
  127. manager.request(urlString)
  128. .response { resp in
  129. error = resp.error
  130. expectation?.fulfill()
  131. }
  132. waitForExpectations(timeout: timeout, handler: nil)
  133. // Then
  134. XCTAssertNotNil(error, "error should not be nil")
  135. if let error = error as? URLError {
  136. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  137. } else {
  138. XCTFail("error should be an URLError")
  139. }
  140. }
  141. func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
  142. // Given
  143. let certificates = [
  144. TestCertificates.leaf,
  145. TestCertificates.intermediateCA1,
  146. TestCertificates.intermediateCA2,
  147. TestCertificates.rootCA
  148. ]
  149. let policies: [String: ServerTrustPolicy] = [
  150. host: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  151. ]
  152. let manager = SessionManager(
  153. configuration: configuration,
  154. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  155. )
  156. weak var expectation = self.expectation(description: "\(urlString)")
  157. var error: Error?
  158. // When
  159. manager.request(urlString)
  160. .response { resp in
  161. error = resp.error
  162. expectation?.fulfill()
  163. }
  164. waitForExpectations(timeout: timeout, handler: nil)
  165. // Then
  166. XCTAssertNotNil(error, "error should not be nil")
  167. if let error = error as? URLError {
  168. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  169. } else {
  170. XCTFail("error should be an URLError")
  171. }
  172. }
  173. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
  174. // Given
  175. let certificates = [TestCertificates.leaf]
  176. let policies: [String: ServerTrustPolicy] = [
  177. host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  178. ]
  179. let manager = SessionManager(
  180. configuration: configuration,
  181. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  182. )
  183. weak var expectation = self.expectation(description: "\(urlString)")
  184. var error: Error?
  185. // When
  186. manager.request(urlString)
  187. .response { resp in
  188. error = resp.error
  189. expectation?.fulfill()
  190. }
  191. waitForExpectations(timeout: timeout, handler: nil)
  192. // Then
  193. XCTAssertNil(error, "error should be nil")
  194. }
  195. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
  196. // Given
  197. let certificates = [TestCertificates.intermediateCA2]
  198. let policies: [String: ServerTrustPolicy] = [
  199. host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  200. ]
  201. let manager = SessionManager(
  202. configuration: configuration,
  203. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  204. )
  205. weak var expectation = self.expectation(description: "\(urlString)")
  206. var error: Error?
  207. // When
  208. manager.request(urlString)
  209. .response { resp in
  210. error = resp.error
  211. expectation?.fulfill()
  212. }
  213. waitForExpectations(timeout: timeout, handler: nil)
  214. // Then
  215. XCTAssertNil(error, "error should be nil")
  216. }
  217. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
  218. // Given
  219. let certificates = [TestCertificates.rootCA]
  220. let policies: [String: ServerTrustPolicy] = [
  221. host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  222. ]
  223. let manager = SessionManager(
  224. configuration: configuration,
  225. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  226. )
  227. weak var expectation = self.expectation(description: "\(urlString)")
  228. var error: Error?
  229. // When
  230. manager.request(urlString)
  231. .response { resp in
  232. error = resp.error
  233. expectation?.fulfill()
  234. }
  235. waitForExpectations(timeout: timeout, handler: nil)
  236. // Then
  237. XCTAssertNil(error, "error should be nil")
  238. }
  239. // MARK: Server Trust Policy - Public Key Pinning Tests
  240. func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
  241. // Given
  242. let publicKeys = [TestPublicKeys.leaf]
  243. let policies: [String: ServerTrustPolicy] = [
  244. host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
  245. ]
  246. let manager = SessionManager(
  247. configuration: configuration,
  248. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  249. )
  250. weak var expectation = self.expectation(description: "\(urlString)")
  251. var error: Error?
  252. // When
  253. manager.request(urlString)
  254. .response { resp in
  255. error = resp.error
  256. expectation?.fulfill()
  257. }
  258. waitForExpectations(timeout: timeout, handler: nil)
  259. // Then
  260. XCTAssertNotNil(error, "error should not be nil")
  261. if let error = error as? URLError {
  262. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  263. } else {
  264. XCTFail("error should be an URLError")
  265. }
  266. }
  267. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
  268. // Given
  269. let publicKeys = [TestPublicKeys.leaf]
  270. let policies: [String: ServerTrustPolicy] = [
  271. host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  272. ]
  273. let manager = SessionManager(
  274. configuration: configuration,
  275. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  276. )
  277. weak var expectation = self.expectation(description: "\(urlString)")
  278. var error: Error?
  279. // When
  280. manager.request(urlString)
  281. .response { resp in
  282. error = resp.error
  283. expectation?.fulfill()
  284. }
  285. waitForExpectations(timeout: timeout, handler: nil)
  286. // Then
  287. XCTAssertNil(error, "error should be nil")
  288. }
  289. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
  290. // Given
  291. let publicKeys = [TestPublicKeys.intermediateCA2]
  292. let policies: [String: ServerTrustPolicy] = [
  293. host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  294. ]
  295. let manager = SessionManager(
  296. configuration: configuration,
  297. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  298. )
  299. weak var expectation = self.expectation(description: "\(urlString)")
  300. var error: Error?
  301. // When
  302. manager.request(urlString)
  303. .response { resp in
  304. error = resp.error
  305. expectation?.fulfill()
  306. }
  307. waitForExpectations(timeout: timeout, handler: nil)
  308. // Then
  309. XCTAssertNil(error, "error should be nil")
  310. }
  311. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
  312. // Given
  313. let publicKeys = [TestPublicKeys.rootCA]
  314. let policies: [String: ServerTrustPolicy] = [
  315. host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  316. ]
  317. let manager = SessionManager(
  318. configuration: configuration,
  319. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  320. )
  321. weak var expectation = self.expectation(description: "\(urlString)")
  322. var error: Error?
  323. // When
  324. manager.request(urlString)
  325. .response { resp in
  326. error = resp.error
  327. expectation?.fulfill()
  328. }
  329. waitForExpectations(timeout: timeout, handler: nil)
  330. // Then
  331. XCTAssertNil(error, "error should be nil")
  332. }
  333. // MARK: Server Trust Policy - Disabling Evaluation Tests
  334. func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
  335. // Given
  336. let policies = [host: ServerTrustPolicy.disableEvaluation]
  337. let manager = SessionManager(
  338. configuration: configuration,
  339. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  340. )
  341. weak var expectation = self.expectation(description: "\(urlString)")
  342. var error: Error?
  343. // When
  344. manager.request(urlString)
  345. .response { resp in
  346. error = resp.error
  347. expectation?.fulfill()
  348. }
  349. waitForExpectations(timeout: timeout, handler: nil)
  350. // Then
  351. XCTAssertNil(error, "error should be nil")
  352. }
  353. // MARK: Server Trust Policy - Custom Evaluation Tests
  354. func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
  355. // Given
  356. let policies = [
  357. host: ServerTrustPolicy.customEvaluation { _, _ in
  358. // Implement a custom evaluation routine here...
  359. return true
  360. }
  361. ]
  362. let manager = SessionManager(
  363. configuration: configuration,
  364. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  365. )
  366. weak var expectation = self.expectation(description: "\(urlString)")
  367. var error: Error?
  368. // When
  369. manager.request(urlString)
  370. .response { resp in
  371. error = resp.error
  372. expectation?.fulfill()
  373. }
  374. waitForExpectations(timeout: timeout, handler: nil)
  375. // Then
  376. XCTAssertNil(error, "error should be nil")
  377. }
  378. func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
  379. // Given
  380. let policies = [
  381. host: ServerTrustPolicy.customEvaluation { _, _ in
  382. // Implement a custom evaluation routine here...
  383. return false
  384. }
  385. ]
  386. let manager = SessionManager(
  387. configuration: configuration,
  388. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  389. )
  390. weak var expectation = self.expectation(description: "\(urlString)")
  391. var error: Error?
  392. // When
  393. manager.request(urlString)
  394. .response { resp in
  395. error = resp.error
  396. expectation?.fulfill()
  397. }
  398. waitForExpectations(timeout: timeout, handler: nil)
  399. // Then
  400. XCTAssertNotNil(error, "error should not be nil")
  401. if let error = error as? URLError {
  402. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  403. } else {
  404. XCTFail("error should be an URLError")
  405. }
  406. }
  407. }