TLSEvaluationTests.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. private let expiredURLString = "https://expired.badssl.com/"
  57. private let expiredHost = "expired.badssl.com"
  58. private let revokedURLString = "https://revoked.badssl.com"
  59. private let revokedHost = "revoked.badssl.com"
  60. private var configuration: URLSessionConfiguration!
  61. // MARK: Setup and Teardown
  62. override func setUp() {
  63. super.setUp()
  64. configuration = URLSessionConfiguration.ephemeral
  65. configuration.urlCache = nil
  66. configuration.urlCredentialStorage = nil
  67. }
  68. // MARK: Default Behavior Tests
  69. func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() {
  70. // On iOS 8.0 - 8.4, this test passes by itself, but fails for no explanable reason when run with the rest of
  71. // the suite. Because of this, there's no reliable way to run all these tests together pre iOS 9, so let's
  72. // disable this one when run against the entire test suite.
  73. guard #available(iOS 9.0, *) else { return }
  74. // Given
  75. let expectation = self.expectation(description: "\(expiredURLString)")
  76. let manager = SessionManager(configuration: configuration)
  77. var error: Error?
  78. // When
  79. manager.request(expiredURLString)
  80. .response { resp in
  81. error = resp.error
  82. expectation.fulfill()
  83. }
  84. waitForExpectations(timeout: timeout, handler: nil)
  85. // Then
  86. XCTAssertNotNil(error)
  87. if let error = error as? URLError {
  88. XCTAssertEqual(error.code, .serverCertificateUntrusted)
  89. } else if let error = error as? NSError {
  90. XCTAssertEqual(error.domain, kCFErrorDomainCFNetwork as String)
  91. XCTAssertEqual(error.code, Int(CFNetworkErrors.cfErrorHTTPSProxyConnectionFailure.rawValue))
  92. } else {
  93. XCTFail("error should be a URLError or NSError from CFNetwork")
  94. }
  95. }
  96. func testThatRevokedCertificateRequestFailsWithNoServerTrustPolicy() {
  97. // Given
  98. let expectation = self.expectation(description: "\(revokedURLString)")
  99. let manager = SessionManager(configuration: configuration)
  100. var error: Error?
  101. // When
  102. manager.request(revokedURLString)
  103. .response { resp in
  104. error = resp.error
  105. expectation.fulfill()
  106. }
  107. waitForExpectations(timeout: timeout, handler: nil)
  108. // Then
  109. if #available(iOS 10.1, macOS 10.12, tvOS 10.1, *) {
  110. // Apple appears to have started revocation tests as part of default evaluation in 10.1
  111. XCTAssertNotNil(error)
  112. } else {
  113. XCTAssertNil(error)
  114. }
  115. }
  116. // MARK: Server Trust Policy - Perform Default Tests
  117. func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() {
  118. // Given
  119. let policies = [expiredHost: ServerTrustPolicy.performDefaultEvaluation(validateHost: true)]
  120. let manager = SessionManager(
  121. configuration: configuration,
  122. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  123. )
  124. let expectation = self.expectation(description: "\(expiredURLString)")
  125. var error: Error?
  126. // When
  127. manager.request(expiredURLString)
  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 testThatRevokedCertificateRequestSucceedsWithDefaultServerTrustPolicy() {
  142. // Given
  143. let defaultPolicy = ServerTrustPolicy.performDefaultEvaluation(validateHost: true)
  144. let policies = [revokedHost: defaultPolicy]
  145. let manager = SessionManager(
  146. configuration: configuration,
  147. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  148. )
  149. let expectation = self.expectation(description: "\(revokedURLString)")
  150. var error: Error?
  151. // When
  152. manager.request(revokedURLString)
  153. .response { resp in
  154. error = resp.error
  155. expectation.fulfill()
  156. }
  157. waitForExpectations(timeout: timeout, handler: nil)
  158. // Then
  159. if #available(iOS 10.1, macOS 10.12, tvOS 10.1, *) {
  160. // Apple appears to have started revocation tests as part of default evaluation in 10.1
  161. XCTAssertNotNil(error)
  162. } else {
  163. XCTAssertNil(error)
  164. }
  165. }
  166. // MARK: Server Trust Policy - Perform Revoked Tests
  167. func testThatRevokedCertificateRequestFailsWithRevokedServerTrustPolicy() {
  168. // Given
  169. let policy = ServerTrustPolicy.performRevokedEvaluation(
  170. validateHost: true,
  171. revocationFlags: kSecRevocationUseAnyAvailableMethod
  172. )
  173. let policies = [revokedHost: policy]
  174. let manager = SessionManager(
  175. configuration: configuration,
  176. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  177. )
  178. let expectation = self.expectation(description: "\(revokedURLString)")
  179. var error: Error?
  180. // When
  181. manager.request(revokedURLString)
  182. .response { resp in
  183. error = resp.error
  184. expectation.fulfill()
  185. }
  186. waitForExpectations(timeout: timeout, handler: nil)
  187. // Then
  188. XCTAssertNotNil(error, "error should not be nil")
  189. if let error = error as? URLError {
  190. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  191. } else {
  192. XCTFail("error should be an URLError")
  193. }
  194. }
  195. // MARK: Server Trust Policy - Certificate Pinning Tests
  196. func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
  197. // Given
  198. let certificates = [TestCertificates.leaf]
  199. let policies: [String: ServerTrustPolicy] = [
  200. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  201. ]
  202. let manager = SessionManager(
  203. configuration: configuration,
  204. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  205. )
  206. let expectation = self.expectation(description: "\(expiredURLString)")
  207. var error: Error?
  208. // When
  209. manager.request(expiredURLString)
  210. .response { resp in
  211. error = resp.error
  212. expectation.fulfill()
  213. }
  214. waitForExpectations(timeout: timeout, handler: nil)
  215. // Then
  216. XCTAssertNotNil(error, "error should not be nil")
  217. if let error = error as? URLError {
  218. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  219. } else {
  220. XCTFail("error should be an URLError")
  221. }
  222. }
  223. func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
  224. // Given
  225. let certificates = [
  226. TestCertificates.leaf,
  227. TestCertificates.intermediateCA1,
  228. TestCertificates.intermediateCA2,
  229. TestCertificates.rootCA
  230. ]
  231. let policies: [String: ServerTrustPolicy] = [
  232. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  233. ]
  234. let manager = SessionManager(
  235. configuration: configuration,
  236. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  237. )
  238. let expectation = self.expectation(description: "\(expiredURLString)")
  239. var error: Error?
  240. // When
  241. manager.request(expiredURLString)
  242. .response { resp in
  243. error = resp.error
  244. expectation.fulfill()
  245. }
  246. waitForExpectations(timeout: timeout, handler: nil)
  247. // Then
  248. XCTAssertNotNil(error, "error should not be nil")
  249. if let error = error as? URLError {
  250. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  251. } else {
  252. XCTFail("error should be an URLError")
  253. }
  254. }
  255. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
  256. // Given
  257. let certificates = [TestCertificates.leaf]
  258. let policies: [String: ServerTrustPolicy] = [
  259. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  260. ]
  261. let manager = SessionManager(
  262. configuration: configuration,
  263. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  264. )
  265. let expectation = self.expectation(description: "\(expiredURLString)")
  266. var error: Error?
  267. // When
  268. manager.request(expiredURLString)
  269. .response { resp in
  270. error = resp.error
  271. expectation.fulfill()
  272. }
  273. waitForExpectations(timeout: timeout, handler: nil)
  274. // Then
  275. XCTAssertNil(error, "error should be nil")
  276. }
  277. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
  278. // Given
  279. let certificates = [TestCertificates.intermediateCA2]
  280. let policies: [String: ServerTrustPolicy] = [
  281. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  282. ]
  283. let manager = SessionManager(
  284. configuration: configuration,
  285. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  286. )
  287. let expectation = self.expectation(description: "\(expiredURLString)")
  288. var error: Error?
  289. // When
  290. manager.request(expiredURLString)
  291. .response { resp in
  292. error = resp.error
  293. expectation.fulfill()
  294. }
  295. waitForExpectations(timeout: timeout, handler: nil)
  296. // Then
  297. XCTAssertNil(error, "error should be nil")
  298. }
  299. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
  300. // Given
  301. let certificates = [TestCertificates.rootCA]
  302. let policies: [String: ServerTrustPolicy] = [
  303. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  304. ]
  305. let manager = SessionManager(
  306. configuration: configuration,
  307. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  308. )
  309. let expectation = self.expectation(description: "\(expiredURLString)")
  310. var error: Error?
  311. // When
  312. manager.request(expiredURLString)
  313. .response { resp in
  314. error = resp.error
  315. expectation.fulfill()
  316. }
  317. waitForExpectations(timeout: timeout, handler: nil)
  318. // Then
  319. #if os(iOS) || os(macOS)
  320. if #available(iOS 10.1, macOS 10.12.0, *) {
  321. XCTAssertNotNil(error, "error should not be nil")
  322. } else {
  323. XCTAssertNil(error, "error should be nil")
  324. }
  325. #else
  326. XCTAssertNil(error, "error should be nil")
  327. #endif
  328. }
  329. // MARK: Server Trust Policy - Public Key Pinning Tests
  330. func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
  331. // Given
  332. let publicKeys = [TestPublicKeys.leaf]
  333. let policies: [String: ServerTrustPolicy] = [
  334. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
  335. ]
  336. let manager = SessionManager(
  337. configuration: configuration,
  338. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  339. )
  340. let expectation = self.expectation(description: "\(expiredURLString)")
  341. var error: Error?
  342. // When
  343. manager.request(expiredURLString)
  344. .response { resp in
  345. error = resp.error
  346. expectation.fulfill()
  347. }
  348. waitForExpectations(timeout: timeout, handler: nil)
  349. // Then
  350. XCTAssertNotNil(error, "error should not be nil")
  351. if let error = error as? URLError {
  352. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  353. } else {
  354. XCTFail("error should be an URLError")
  355. }
  356. }
  357. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
  358. // Given
  359. let publicKeys = [TestPublicKeys.leaf]
  360. let policies: [String: ServerTrustPolicy] = [
  361. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  362. ]
  363. let manager = SessionManager(
  364. configuration: configuration,
  365. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  366. )
  367. let expectation = self.expectation(description: "\(expiredURLString)")
  368. var error: Error?
  369. // When
  370. manager.request(expiredURLString)
  371. .response { resp in
  372. error = resp.error
  373. expectation.fulfill()
  374. }
  375. waitForExpectations(timeout: timeout, handler: nil)
  376. // Then
  377. XCTAssertNil(error, "error should be nil")
  378. }
  379. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
  380. // Given
  381. let publicKeys = [TestPublicKeys.intermediateCA2]
  382. let policies: [String: ServerTrustPolicy] = [
  383. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  384. ]
  385. let manager = SessionManager(
  386. configuration: configuration,
  387. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  388. )
  389. let expectation = self.expectation(description: "\(expiredURLString)")
  390. var error: Error?
  391. // When
  392. manager.request(expiredURLString)
  393. .response { resp in
  394. error = resp.error
  395. expectation.fulfill()
  396. }
  397. waitForExpectations(timeout: timeout, handler: nil)
  398. // Then
  399. XCTAssertNil(error, "error should be nil")
  400. }
  401. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
  402. // Given
  403. let publicKeys = [TestPublicKeys.rootCA]
  404. let policies: [String: ServerTrustPolicy] = [
  405. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  406. ]
  407. let manager = SessionManager(
  408. configuration: configuration,
  409. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  410. )
  411. let expectation = self.expectation(description: "\(expiredURLString)")
  412. var error: Error?
  413. // When
  414. manager.request(expiredURLString)
  415. .response { resp in
  416. error = resp.error
  417. expectation.fulfill()
  418. }
  419. waitForExpectations(timeout: timeout, handler: nil)
  420. // Then
  421. #if os(iOS) || os(macOS)
  422. if #available(iOS 10.1, macOS 10.12.0, *) {
  423. XCTAssertNotNil(error, "error should not be nil")
  424. } else {
  425. XCTAssertNil(error, "error should be nil")
  426. }
  427. #else
  428. XCTAssertNil(error, "error should be nil")
  429. #endif
  430. }
  431. // MARK: Server Trust Policy - Disabling Evaluation Tests
  432. func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
  433. // Given
  434. let policies = [expiredHost: ServerTrustPolicy.disableEvaluation]
  435. let manager = SessionManager(
  436. configuration: configuration,
  437. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  438. )
  439. let expectation = self.expectation(description: "\(expiredURLString)")
  440. var error: Error?
  441. // When
  442. manager.request(expiredURLString)
  443. .response { resp in
  444. error = resp.error
  445. expectation.fulfill()
  446. }
  447. waitForExpectations(timeout: timeout, handler: nil)
  448. // Then
  449. XCTAssertNil(error, "error should be nil")
  450. }
  451. // MARK: Server Trust Policy - Custom Evaluation Tests
  452. func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
  453. // Given
  454. let policies = [
  455. expiredHost: ServerTrustPolicy.customEvaluation { _, _ in
  456. // Implement a custom evaluation routine here...
  457. return true
  458. }
  459. ]
  460. let manager = SessionManager(
  461. configuration: configuration,
  462. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  463. )
  464. let expectation = self.expectation(description: "\(expiredURLString)")
  465. var error: Error?
  466. // When
  467. manager.request(expiredURLString)
  468. .response { resp in
  469. error = resp.error
  470. expectation.fulfill()
  471. }
  472. waitForExpectations(timeout: timeout, handler: nil)
  473. // Then
  474. XCTAssertNil(error, "error should be nil")
  475. }
  476. func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
  477. // Given
  478. let policies = [
  479. expiredHost: ServerTrustPolicy.customEvaluation { _, _ in
  480. // Implement a custom evaluation routine here...
  481. return false
  482. }
  483. ]
  484. let manager = SessionManager(
  485. configuration: configuration,
  486. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  487. )
  488. let expectation = self.expectation(description: "\(expiredURLString)")
  489. var error: Error?
  490. // When
  491. manager.request(expiredURLString)
  492. .response { resp in
  493. error = resp.error
  494. expectation.fulfill()
  495. }
  496. waitForExpectations(timeout: timeout, handler: nil)
  497. // Then
  498. XCTAssertNotNil(error, "error should not be nil")
  499. if let error = error as? URLError {
  500. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  501. } else {
  502. XCTFail("error should be an URLError")
  503. }
  504. }
  505. }