TLSEvaluationTests.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. //
  2. // TLSEvaluationTests.swift
  3. //
  4. // Copyright (c) 2014-2017 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. // Given
  71. let expectation = self.expectation(description: "\(expiredURLString)")
  72. let manager = SessionManager(configuration: configuration)
  73. var error: Error?
  74. // When
  75. manager.request(expiredURLString)
  76. .response { resp in
  77. error = resp.error
  78. expectation.fulfill()
  79. }
  80. waitForExpectations(timeout: timeout, handler: nil)
  81. // Then
  82. XCTAssertNotNil(error)
  83. if let error = error as? URLError {
  84. XCTAssertEqual(error.code, .serverCertificateUntrusted)
  85. } else if let error = error as NSError? {
  86. XCTAssertEqual(error.domain, kCFErrorDomainCFNetwork as String)
  87. XCTAssertEqual(error.code, Int(CFNetworkErrors.cfErrorHTTPSProxyConnectionFailure.rawValue))
  88. } else {
  89. XCTFail("error should be a URLError or NSError from CFNetwork")
  90. }
  91. }
  92. func disabled_testRevokedCertificateRequestBehaviorWithNoServerTrustPolicy() {
  93. // Disabled due to the instability of due revocation testing of default evaluation from all platforms. This
  94. // test is left for debugging purposes only. Should not be committed into the test suite while enabled.
  95. // Given
  96. let expectation = self.expectation(description: "\(revokedURLString)")
  97. let manager = SessionManager(configuration: configuration)
  98. var error: Error?
  99. // When
  100. manager.request(revokedURLString)
  101. .response { resp in
  102. error = resp.error
  103. expectation.fulfill()
  104. }
  105. waitForExpectations(timeout: timeout, handler: nil)
  106. // Then
  107. if #available(iOS 10.1, macOS 10.12, tvOS 10.1, *) {
  108. // Apple appears to have started revocation tests as part of default evaluation in 10.1
  109. XCTAssertNotNil(error)
  110. } else {
  111. XCTAssertNil(error)
  112. }
  113. }
  114. // MARK: Server Trust Policy - Perform Default Tests
  115. func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() {
  116. // Given
  117. let policies = [expiredHost: ServerTrustPolicy.performDefaultEvaluation(validateHost: true)]
  118. let manager = SessionManager(
  119. configuration: configuration,
  120. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  121. )
  122. let expectation = self.expectation(description: "\(expiredURLString)")
  123. var error: Error?
  124. // When
  125. manager.request(expiredURLString)
  126. .response { resp in
  127. error = resp.error
  128. expectation.fulfill()
  129. }
  130. waitForExpectations(timeout: timeout, handler: nil)
  131. // Then
  132. XCTAssertNotNil(error, "error should not be nil")
  133. if let error = error as? URLError {
  134. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  135. } else {
  136. XCTFail("error should be an URLError")
  137. }
  138. }
  139. func disabled_testRevokedCertificateRequestBehaviorWithDefaultServerTrustPolicy() {
  140. // Disabled due to the instability of due revocation testing of default evaluation from all platforms. This
  141. // test is left for debugging purposes only. Should not be committed into the test suite while enabled.
  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 testThatExpiredCertificateRequestFailsWithRevokedServerTrustPolicy() {
  168. // Given
  169. let policy = ServerTrustPolicy.performRevokedEvaluation(
  170. validateHost: true,
  171. revocationFlags: kSecRevocationUseAnyAvailableMethod
  172. )
  173. let policies = [expiredHost: policy]
  174. let manager = SessionManager(
  175. configuration: configuration,
  176. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  177. )
  178. let expectation = self.expectation(description: "\(expiredURLString)")
  179. var error: Error?
  180. // When
  181. manager.request(expiredURLString)
  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. func testThatRevokedCertificateRequestFailsWithRevokedServerTrustPolicy() {
  196. // Given
  197. let policy = ServerTrustPolicy.performRevokedEvaluation(
  198. validateHost: true,
  199. revocationFlags: kSecRevocationUseAnyAvailableMethod
  200. )
  201. let policies = [revokedHost: policy]
  202. let manager = SessionManager(
  203. configuration: configuration,
  204. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  205. )
  206. let expectation = self.expectation(description: "\(revokedURLString)")
  207. var error: Error?
  208. // When
  209. manager.request(revokedURLString)
  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. // MARK: Server Trust Policy - Certificate Pinning Tests
  224. func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
  225. // Given
  226. let certificates = [TestCertificates.leaf]
  227. let policies: [String: ServerTrustPolicy] = [
  228. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  229. ]
  230. let manager = SessionManager(
  231. configuration: configuration,
  232. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  233. )
  234. let expectation = self.expectation(description: "\(expiredURLString)")
  235. var error: Error?
  236. // When
  237. manager.request(expiredURLString)
  238. .response { resp in
  239. error = resp.error
  240. expectation.fulfill()
  241. }
  242. waitForExpectations(timeout: timeout, handler: nil)
  243. // Then
  244. XCTAssertNotNil(error, "error should not be nil")
  245. if let error = error as? URLError {
  246. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  247. } else {
  248. XCTFail("error should be an URLError")
  249. }
  250. }
  251. func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
  252. // Given
  253. let certificates = [
  254. TestCertificates.leaf,
  255. TestCertificates.intermediateCA1,
  256. TestCertificates.intermediateCA2,
  257. TestCertificates.rootCA
  258. ]
  259. let policies: [String: ServerTrustPolicy] = [
  260. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  261. ]
  262. let manager = SessionManager(
  263. configuration: configuration,
  264. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  265. )
  266. let expectation = self.expectation(description: "\(expiredURLString)")
  267. var error: Error?
  268. // When
  269. manager.request(expiredURLString)
  270. .response { resp in
  271. error = resp.error
  272. expectation.fulfill()
  273. }
  274. waitForExpectations(timeout: timeout, handler: nil)
  275. // Then
  276. XCTAssertNotNil(error, "error should not be nil")
  277. if let error = error as? URLError {
  278. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  279. } else {
  280. XCTFail("error should be an URLError")
  281. }
  282. }
  283. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
  284. // Given
  285. let certificates = [TestCertificates.leaf]
  286. let policies: [String: ServerTrustPolicy] = [
  287. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  288. ]
  289. let manager = SessionManager(
  290. configuration: configuration,
  291. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  292. )
  293. let expectation = self.expectation(description: "\(expiredURLString)")
  294. var error: Error?
  295. // When
  296. manager.request(expiredURLString)
  297. .response { resp in
  298. error = resp.error
  299. expectation.fulfill()
  300. }
  301. waitForExpectations(timeout: timeout, handler: nil)
  302. // Then
  303. XCTAssertNil(error, "error should be nil")
  304. }
  305. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
  306. // Given
  307. let certificates = [TestCertificates.intermediateCA2]
  308. let policies: [String: ServerTrustPolicy] = [
  309. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  310. ]
  311. let manager = SessionManager(
  312. configuration: configuration,
  313. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  314. )
  315. let expectation = self.expectation(description: "\(expiredURLString)")
  316. var error: Error?
  317. // When
  318. manager.request(expiredURLString)
  319. .response { resp in
  320. error = resp.error
  321. expectation.fulfill()
  322. }
  323. waitForExpectations(timeout: timeout, handler: nil)
  324. // Then
  325. XCTAssertNil(error, "error should be nil")
  326. }
  327. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
  328. // Given
  329. let certificates = [TestCertificates.rootCA]
  330. let policies: [String: ServerTrustPolicy] = [
  331. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  332. ]
  333. let manager = SessionManager(
  334. configuration: configuration,
  335. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  336. )
  337. let expectation = self.expectation(description: "\(expiredURLString)")
  338. var error: Error?
  339. // When
  340. manager.request(expiredURLString)
  341. .response { resp in
  342. error = resp.error
  343. expectation.fulfill()
  344. }
  345. waitForExpectations(timeout: timeout, handler: nil)
  346. // Then
  347. if #available(iOS 10.1, macOS 10.12.0, tvOS 10.1, *) {
  348. XCTAssertNotNil(error, "error should not be nil")
  349. } else {
  350. XCTAssertNil(error, "error should be nil")
  351. }
  352. }
  353. // MARK: Server Trust Policy - Public Key Pinning Tests
  354. func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
  355. // Given
  356. let publicKeys = [TestPublicKeys.leaf]
  357. let policies: [String: ServerTrustPolicy] = [
  358. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
  359. ]
  360. let manager = SessionManager(
  361. configuration: configuration,
  362. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  363. )
  364. let expectation = self.expectation(description: "\(expiredURLString)")
  365. var error: Error?
  366. // When
  367. manager.request(expiredURLString)
  368. .response { resp in
  369. error = resp.error
  370. expectation.fulfill()
  371. }
  372. waitForExpectations(timeout: timeout, handler: nil)
  373. // Then
  374. XCTAssertNotNil(error, "error should not be nil")
  375. if let error = error as? URLError {
  376. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  377. } else {
  378. XCTFail("error should be an URLError")
  379. }
  380. }
  381. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
  382. // Given
  383. let publicKeys = [TestPublicKeys.leaf]
  384. let policies: [String: ServerTrustPolicy] = [
  385. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  386. ]
  387. let manager = SessionManager(
  388. configuration: configuration,
  389. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  390. )
  391. let expectation = self.expectation(description: "\(expiredURLString)")
  392. var error: Error?
  393. // When
  394. manager.request(expiredURLString)
  395. .response { resp in
  396. error = resp.error
  397. expectation.fulfill()
  398. }
  399. waitForExpectations(timeout: timeout, handler: nil)
  400. // Then
  401. XCTAssertNil(error, "error should be nil")
  402. }
  403. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
  404. // Given
  405. let publicKeys = [TestPublicKeys.intermediateCA2]
  406. let policies: [String: ServerTrustPolicy] = [
  407. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  408. ]
  409. let manager = SessionManager(
  410. configuration: configuration,
  411. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  412. )
  413. let expectation = self.expectation(description: "\(expiredURLString)")
  414. var error: Error?
  415. // When
  416. manager.request(expiredURLString)
  417. .response { resp in
  418. error = resp.error
  419. expectation.fulfill()
  420. }
  421. waitForExpectations(timeout: timeout, handler: nil)
  422. // Then
  423. XCTAssertNil(error, "error should be nil")
  424. }
  425. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
  426. // Given
  427. let publicKeys = [TestPublicKeys.rootCA]
  428. let policies: [String: ServerTrustPolicy] = [
  429. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  430. ]
  431. let manager = SessionManager(
  432. configuration: configuration,
  433. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  434. )
  435. let expectation = self.expectation(description: "\(expiredURLString)")
  436. var error: Error?
  437. // When
  438. manager.request(expiredURLString)
  439. .response { resp in
  440. error = resp.error
  441. expectation.fulfill()
  442. }
  443. waitForExpectations(timeout: timeout, handler: nil)
  444. // Then
  445. if #available(iOS 10.1, macOS 10.12.0, tvOS 10.1, *) {
  446. XCTAssertNotNil(error, "error should not be nil")
  447. } else {
  448. XCTAssertNil(error, "error should be nil")
  449. }
  450. }
  451. // MARK: Server Trust Policy - Disabling Evaluation Tests
  452. func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
  453. // Given
  454. let policies = [expiredHost: ServerTrustPolicy.disableEvaluation]
  455. let manager = SessionManager(
  456. configuration: configuration,
  457. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  458. )
  459. let expectation = self.expectation(description: "\(expiredURLString)")
  460. var error: Error?
  461. // When
  462. manager.request(expiredURLString)
  463. .response { resp in
  464. error = resp.error
  465. expectation.fulfill()
  466. }
  467. waitForExpectations(timeout: timeout, handler: nil)
  468. // Then
  469. XCTAssertNil(error, "error should be nil")
  470. }
  471. // MARK: Server Trust Policy - Custom Evaluation Tests
  472. func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
  473. // Given
  474. let policies = [
  475. expiredHost: ServerTrustPolicy.customEvaluation { _, _ in
  476. // Implement a custom evaluation routine here...
  477. return true
  478. }
  479. ]
  480. let manager = SessionManager(
  481. configuration: configuration,
  482. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  483. )
  484. let expectation = self.expectation(description: "\(expiredURLString)")
  485. var error: Error?
  486. // When
  487. manager.request(expiredURLString)
  488. .response { resp in
  489. error = resp.error
  490. expectation.fulfill()
  491. }
  492. waitForExpectations(timeout: timeout, handler: nil)
  493. // Then
  494. XCTAssertNil(error, "error should be nil")
  495. }
  496. func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
  497. // Given
  498. let policies = [
  499. expiredHost: ServerTrustPolicy.customEvaluation { _, _ in
  500. // Implement a custom evaluation routine here...
  501. return false
  502. }
  503. ]
  504. let manager = SessionManager(
  505. configuration: configuration,
  506. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  507. )
  508. let expectation = self.expectation(description: "\(expiredURLString)")
  509. var error: Error?
  510. // When
  511. manager.request(expiredURLString)
  512. .response { resp in
  513. error = resp.error
  514. expectation.fulfill()
  515. }
  516. waitForExpectations(timeout: timeout, handler: nil)
  517. // Then
  518. XCTAssertNotNil(error, "error should not be nil")
  519. if let error = error as? URLError {
  520. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  521. } else {
  522. XCTFail("error should be an URLError")
  523. }
  524. }
  525. }