TLSEvaluationTests.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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 disabled_testRevokedCertificateRequestBehaviorWithNoServerTrustPolicy() {
  97. // Disabled due to the instability of due revocation testing of default evaluation from all platforms. This
  98. // test is left for debugging purposes only. Should not be committed into the test suite while enabled.
  99. // Given
  100. let expectation = self.expectation(description: "\(revokedURLString)")
  101. let manager = SessionManager(configuration: configuration)
  102. var error: Error?
  103. // When
  104. manager.request(revokedURLString)
  105. .response { resp in
  106. error = resp.error
  107. expectation.fulfill()
  108. }
  109. waitForExpectations(timeout: timeout, handler: nil)
  110. // Then
  111. if #available(iOS 10.1, macOS 10.12, tvOS 10.1, *) {
  112. // Apple appears to have started revocation tests as part of default evaluation in 10.1
  113. XCTAssertNotNil(error)
  114. } else {
  115. XCTAssertNil(error)
  116. }
  117. }
  118. // MARK: Server Trust Policy - Perform Default Tests
  119. func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() {
  120. // Given
  121. let policies = [expiredHost: ServerTrustPolicy.performDefaultEvaluation(validateHost: true)]
  122. let manager = SessionManager(
  123. configuration: configuration,
  124. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  125. )
  126. let expectation = self.expectation(description: "\(expiredURLString)")
  127. var error: Error?
  128. // When
  129. manager.request(expiredURLString)
  130. .response { resp in
  131. error = resp.error
  132. expectation.fulfill()
  133. }
  134. waitForExpectations(timeout: timeout, handler: nil)
  135. // Then
  136. XCTAssertNotNil(error, "error should not be nil")
  137. if let error = error as? URLError {
  138. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  139. } else {
  140. XCTFail("error should be an URLError")
  141. }
  142. }
  143. func disabled_testRevokedCertificateRequestBehaviorWithDefaultServerTrustPolicy() {
  144. // Disabled due to the instability of due revocation testing of default evaluation from all platforms. This
  145. // test is left for debugging purposes only. Should not be committed into the test suite while enabled.
  146. // Given
  147. let defaultPolicy = ServerTrustPolicy.performDefaultEvaluation(validateHost: true)
  148. let policies = [revokedHost: defaultPolicy]
  149. let manager = SessionManager(
  150. configuration: configuration,
  151. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  152. )
  153. let expectation = self.expectation(description: "\(revokedURLString)")
  154. var error: Error?
  155. // When
  156. manager.request(revokedURLString)
  157. .response { resp in
  158. error = resp.error
  159. expectation.fulfill()
  160. }
  161. waitForExpectations(timeout: timeout, handler: nil)
  162. // Then
  163. if #available(iOS 10.1, macOS 10.12, tvOS 10.1, *) {
  164. // Apple appears to have started revocation tests as part of default evaluation in 10.1
  165. XCTAssertNotNil(error)
  166. } else {
  167. XCTAssertNil(error)
  168. }
  169. }
  170. // MARK: Server Trust Policy - Perform Revoked Tests
  171. func testThatExpiredCertificateRequestFailsWithRevokedServerTrustPolicy() {
  172. // Given
  173. let policy = ServerTrustPolicy.performRevokedEvaluation(
  174. validateHost: true,
  175. revocationFlags: kSecRevocationUseAnyAvailableMethod
  176. )
  177. let policies = [expiredHost: policy]
  178. let manager = SessionManager(
  179. configuration: configuration,
  180. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  181. )
  182. let expectation = self.expectation(description: "\(expiredURLString)")
  183. var error: Error?
  184. // When
  185. manager.request(expiredURLString)
  186. .response { resp in
  187. error = resp.error
  188. expectation.fulfill()
  189. }
  190. waitForExpectations(timeout: timeout, handler: nil)
  191. // Then
  192. XCTAssertNotNil(error, "error should not be nil")
  193. if let error = error as? URLError {
  194. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  195. } else {
  196. XCTFail("error should be an URLError")
  197. }
  198. }
  199. func testThatRevokedCertificateRequestFailsWithRevokedServerTrustPolicy() {
  200. // Given
  201. let policy = ServerTrustPolicy.performRevokedEvaluation(
  202. validateHost: true,
  203. revocationFlags: kSecRevocationUseAnyAvailableMethod
  204. )
  205. let policies = [revokedHost: policy]
  206. let manager = SessionManager(
  207. configuration: configuration,
  208. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  209. )
  210. let expectation = self.expectation(description: "\(revokedURLString)")
  211. var error: Error?
  212. // When
  213. manager.request(revokedURLString)
  214. .response { resp in
  215. error = resp.error
  216. expectation.fulfill()
  217. }
  218. waitForExpectations(timeout: timeout, handler: nil)
  219. // Then
  220. XCTAssertNotNil(error, "error should not be nil")
  221. if let error = error as? URLError {
  222. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  223. } else {
  224. XCTFail("error should be an URLError")
  225. }
  226. }
  227. // MARK: Server Trust Policy - Certificate Pinning Tests
  228. func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
  229. // Given
  230. let certificates = [TestCertificates.leaf]
  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 testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
  256. // Given
  257. let certificates = [
  258. TestCertificates.leaf,
  259. TestCertificates.intermediateCA1,
  260. TestCertificates.intermediateCA2,
  261. TestCertificates.rootCA
  262. ]
  263. let policies: [String: ServerTrustPolicy] = [
  264. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  265. ]
  266. let manager = SessionManager(
  267. configuration: configuration,
  268. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  269. )
  270. let expectation = self.expectation(description: "\(expiredURLString)")
  271. var error: Error?
  272. // When
  273. manager.request(expiredURLString)
  274. .response { resp in
  275. error = resp.error
  276. expectation.fulfill()
  277. }
  278. waitForExpectations(timeout: timeout, handler: nil)
  279. // Then
  280. XCTAssertNotNil(error, "error should not be nil")
  281. if let error = error as? URLError {
  282. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  283. } else {
  284. XCTFail("error should be an URLError")
  285. }
  286. }
  287. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
  288. // Given
  289. let certificates = [TestCertificates.leaf]
  290. let policies: [String: ServerTrustPolicy] = [
  291. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  292. ]
  293. let manager = SessionManager(
  294. configuration: configuration,
  295. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  296. )
  297. let expectation = self.expectation(description: "\(expiredURLString)")
  298. var error: Error?
  299. // When
  300. manager.request(expiredURLString)
  301. .response { resp in
  302. error = resp.error
  303. expectation.fulfill()
  304. }
  305. waitForExpectations(timeout: timeout, handler: nil)
  306. // Then
  307. XCTAssertNil(error, "error should be nil")
  308. }
  309. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
  310. // Given
  311. let certificates = [TestCertificates.intermediateCA2]
  312. let policies: [String: ServerTrustPolicy] = [
  313. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  314. ]
  315. let manager = SessionManager(
  316. configuration: configuration,
  317. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  318. )
  319. let expectation = self.expectation(description: "\(expiredURLString)")
  320. var error: Error?
  321. // When
  322. manager.request(expiredURLString)
  323. .response { resp in
  324. error = resp.error
  325. expectation.fulfill()
  326. }
  327. waitForExpectations(timeout: timeout, handler: nil)
  328. // Then
  329. XCTAssertNil(error, "error should be nil")
  330. }
  331. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
  332. // Given
  333. let certificates = [TestCertificates.rootCA]
  334. let policies: [String: ServerTrustPolicy] = [
  335. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  336. ]
  337. let manager = SessionManager(
  338. configuration: configuration,
  339. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  340. )
  341. let expectation = self.expectation(description: "\(expiredURLString)")
  342. var error: Error?
  343. // When
  344. manager.request(expiredURLString)
  345. .response { resp in
  346. error = resp.error
  347. expectation.fulfill()
  348. }
  349. waitForExpectations(timeout: timeout, handler: nil)
  350. // Then
  351. if #available(iOS 10.1, macOS 10.12.0, tvOS 10.1, *) {
  352. XCTAssertNotNil(error, "error should not be nil")
  353. } else {
  354. XCTAssertNil(error, "error should be nil")
  355. }
  356. }
  357. // MARK: Server Trust Policy - Public Key Pinning Tests
  358. func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
  359. // Given
  360. let publicKeys = [TestPublicKeys.leaf]
  361. let policies: [String: ServerTrustPolicy] = [
  362. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
  363. ]
  364. let manager = SessionManager(
  365. configuration: configuration,
  366. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  367. )
  368. let expectation = self.expectation(description: "\(expiredURLString)")
  369. var error: Error?
  370. // When
  371. manager.request(expiredURLString)
  372. .response { resp in
  373. error = resp.error
  374. expectation.fulfill()
  375. }
  376. waitForExpectations(timeout: timeout, handler: nil)
  377. // Then
  378. XCTAssertNotNil(error, "error should not be nil")
  379. if let error = error as? URLError {
  380. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  381. } else {
  382. XCTFail("error should be an URLError")
  383. }
  384. }
  385. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
  386. // Given
  387. let publicKeys = [TestPublicKeys.leaf]
  388. let policies: [String: ServerTrustPolicy] = [
  389. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  390. ]
  391. let manager = SessionManager(
  392. configuration: configuration,
  393. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  394. )
  395. let expectation = self.expectation(description: "\(expiredURLString)")
  396. var error: Error?
  397. // When
  398. manager.request(expiredURLString)
  399. .response { resp in
  400. error = resp.error
  401. expectation.fulfill()
  402. }
  403. waitForExpectations(timeout: timeout, handler: nil)
  404. // Then
  405. XCTAssertNil(error, "error should be nil")
  406. }
  407. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
  408. // Given
  409. let publicKeys = [TestPublicKeys.intermediateCA2]
  410. let policies: [String: ServerTrustPolicy] = [
  411. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  412. ]
  413. let manager = SessionManager(
  414. configuration: configuration,
  415. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  416. )
  417. let expectation = self.expectation(description: "\(expiredURLString)")
  418. var error: Error?
  419. // When
  420. manager.request(expiredURLString)
  421. .response { resp in
  422. error = resp.error
  423. expectation.fulfill()
  424. }
  425. waitForExpectations(timeout: timeout, handler: nil)
  426. // Then
  427. XCTAssertNil(error, "error should be nil")
  428. }
  429. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
  430. // Given
  431. let publicKeys = [TestPublicKeys.rootCA]
  432. let policies: [String: ServerTrustPolicy] = [
  433. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  434. ]
  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. if #available(iOS 10.1, macOS 10.12.0, tvOS 10.1, *) {
  450. XCTAssertNotNil(error, "error should not be nil")
  451. } else {
  452. XCTAssertNil(error, "error should be nil")
  453. }
  454. }
  455. // MARK: Server Trust Policy - Disabling Evaluation Tests
  456. func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
  457. // Given
  458. let policies = [expiredHost: ServerTrustPolicy.disableEvaluation]
  459. let manager = SessionManager(
  460. configuration: configuration,
  461. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  462. )
  463. let expectation = self.expectation(description: "\(expiredURLString)")
  464. var error: Error?
  465. // When
  466. manager.request(expiredURLString)
  467. .response { resp in
  468. error = resp.error
  469. expectation.fulfill()
  470. }
  471. waitForExpectations(timeout: timeout, handler: nil)
  472. // Then
  473. XCTAssertNil(error, "error should be nil")
  474. }
  475. // MARK: Server Trust Policy - Custom Evaluation Tests
  476. func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
  477. // Given
  478. let policies = [
  479. expiredHost: ServerTrustPolicy.customEvaluation { _, _ in
  480. // Implement a custom evaluation routine here...
  481. return true
  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. XCTAssertNil(error, "error should be nil")
  499. }
  500. func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
  501. // Given
  502. let policies = [
  503. expiredHost: ServerTrustPolicy.customEvaluation { _, _ in
  504. // Implement a custom evaluation routine here...
  505. return false
  506. }
  507. ]
  508. let manager = SessionManager(
  509. configuration: configuration,
  510. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  511. )
  512. let expectation = self.expectation(description: "\(expiredURLString)")
  513. var error: Error?
  514. // When
  515. manager.request(expiredURLString)
  516. .response { resp in
  517. error = resp.error
  518. expectation.fulfill()
  519. }
  520. waitForExpectations(timeout: timeout, handler: nil)
  521. // Then
  522. XCTAssertNotNil(error, "error should not be nil")
  523. if let error = error as? URLError {
  524. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  525. } else {
  526. XCTFail("error should be an URLError")
  527. }
  528. }
  529. }