TLSEvaluationTests.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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 - Certificate Pinning Tests
  167. func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
  168. // Given
  169. let certificates = [TestCertificates.leaf]
  170. let policies: [String: ServerTrustPolicy] = [
  171. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  172. ]
  173. let manager = SessionManager(
  174. configuration: configuration,
  175. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  176. )
  177. let expectation = self.expectation(description: "\(expiredURLString)")
  178. var error: Error?
  179. // When
  180. manager.request(expiredURLString)
  181. .response { resp in
  182. error = resp.error
  183. expectation.fulfill()
  184. }
  185. waitForExpectations(timeout: timeout, handler: nil)
  186. // Then
  187. XCTAssertNotNil(error, "error should not be nil")
  188. if let error = error as? URLError {
  189. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  190. } else {
  191. XCTFail("error should be an URLError")
  192. }
  193. }
  194. func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
  195. // Given
  196. let certificates = [
  197. TestCertificates.leaf,
  198. TestCertificates.intermediateCA1,
  199. TestCertificates.intermediateCA2,
  200. TestCertificates.rootCA
  201. ]
  202. let policies: [String: ServerTrustPolicy] = [
  203. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  204. ]
  205. let manager = SessionManager(
  206. configuration: configuration,
  207. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  208. )
  209. let expectation = self.expectation(description: "\(expiredURLString)")
  210. var error: Error?
  211. // When
  212. manager.request(expiredURLString)
  213. .response { resp in
  214. error = resp.error
  215. expectation.fulfill()
  216. }
  217. waitForExpectations(timeout: timeout, handler: nil)
  218. // Then
  219. XCTAssertNotNil(error, "error should not be nil")
  220. if let error = error as? URLError {
  221. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  222. } else {
  223. XCTFail("error should be an URLError")
  224. }
  225. }
  226. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
  227. // Given
  228. let certificates = [TestCertificates.leaf]
  229. let policies: [String: ServerTrustPolicy] = [
  230. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  231. ]
  232. let manager = SessionManager(
  233. configuration: configuration,
  234. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  235. )
  236. let expectation = self.expectation(description: "\(expiredURLString)")
  237. var error: Error?
  238. // When
  239. manager.request(expiredURLString)
  240. .response { resp in
  241. error = resp.error
  242. expectation.fulfill()
  243. }
  244. waitForExpectations(timeout: timeout, handler: nil)
  245. // Then
  246. XCTAssertNil(error, "error should be nil")
  247. }
  248. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
  249. // Given
  250. let certificates = [TestCertificates.intermediateCA2]
  251. let policies: [String: ServerTrustPolicy] = [
  252. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  253. ]
  254. let manager = SessionManager(
  255. configuration: configuration,
  256. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  257. )
  258. let expectation = self.expectation(description: "\(expiredURLString)")
  259. var error: Error?
  260. // When
  261. manager.request(expiredURLString)
  262. .response { resp in
  263. error = resp.error
  264. expectation.fulfill()
  265. }
  266. waitForExpectations(timeout: timeout, handler: nil)
  267. // Then
  268. XCTAssertNil(error, "error should be nil")
  269. }
  270. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
  271. // Given
  272. let certificates = [TestCertificates.rootCA]
  273. let policies: [String: ServerTrustPolicy] = [
  274. expiredHost: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  275. ]
  276. let manager = SessionManager(
  277. configuration: configuration,
  278. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  279. )
  280. let expectation = self.expectation(description: "\(expiredURLString)")
  281. var error: Error?
  282. // When
  283. manager.request(expiredURLString)
  284. .response { resp in
  285. error = resp.error
  286. expectation.fulfill()
  287. }
  288. waitForExpectations(timeout: timeout, handler: nil)
  289. // Then
  290. #if os(iOS) || os(macOS)
  291. if #available(iOS 10.1, macOS 10.12.0, *) {
  292. XCTAssertNotNil(error, "error should not be nil")
  293. } else {
  294. XCTAssertNil(error, "error should be nil")
  295. }
  296. #else
  297. XCTAssertNil(error, "error should be nil")
  298. #endif
  299. }
  300. // MARK: Server Trust Policy - Public Key Pinning Tests
  301. func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
  302. // Given
  303. let publicKeys = [TestPublicKeys.leaf]
  304. let policies: [String: ServerTrustPolicy] = [
  305. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
  306. ]
  307. let manager = SessionManager(
  308. configuration: configuration,
  309. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  310. )
  311. let expectation = self.expectation(description: "\(expiredURLString)")
  312. var error: Error?
  313. // When
  314. manager.request(expiredURLString)
  315. .response { resp in
  316. error = resp.error
  317. expectation.fulfill()
  318. }
  319. waitForExpectations(timeout: timeout, handler: nil)
  320. // Then
  321. XCTAssertNotNil(error, "error should not be nil")
  322. if let error = error as? URLError {
  323. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  324. } else {
  325. XCTFail("error should be an URLError")
  326. }
  327. }
  328. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
  329. // Given
  330. let publicKeys = [TestPublicKeys.leaf]
  331. let policies: [String: ServerTrustPolicy] = [
  332. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  333. ]
  334. let manager = SessionManager(
  335. configuration: configuration,
  336. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  337. )
  338. let expectation = self.expectation(description: "\(expiredURLString)")
  339. var error: Error?
  340. // When
  341. manager.request(expiredURLString)
  342. .response { resp in
  343. error = resp.error
  344. expectation.fulfill()
  345. }
  346. waitForExpectations(timeout: timeout, handler: nil)
  347. // Then
  348. XCTAssertNil(error, "error should be nil")
  349. }
  350. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
  351. // Given
  352. let publicKeys = [TestPublicKeys.intermediateCA2]
  353. let policies: [String: ServerTrustPolicy] = [
  354. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  355. ]
  356. let manager = SessionManager(
  357. configuration: configuration,
  358. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  359. )
  360. let expectation = self.expectation(description: "\(expiredURLString)")
  361. var error: Error?
  362. // When
  363. manager.request(expiredURLString)
  364. .response { resp in
  365. error = resp.error
  366. expectation.fulfill()
  367. }
  368. waitForExpectations(timeout: timeout, handler: nil)
  369. // Then
  370. XCTAssertNil(error, "error should be nil")
  371. }
  372. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
  373. // Given
  374. let publicKeys = [TestPublicKeys.rootCA]
  375. let policies: [String: ServerTrustPolicy] = [
  376. expiredHost: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  377. ]
  378. let manager = SessionManager(
  379. configuration: configuration,
  380. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  381. )
  382. let expectation = self.expectation(description: "\(expiredURLString)")
  383. var error: Error?
  384. // When
  385. manager.request(expiredURLString)
  386. .response { resp in
  387. error = resp.error
  388. expectation.fulfill()
  389. }
  390. waitForExpectations(timeout: timeout, handler: nil)
  391. // Then
  392. #if os(iOS) || os(macOS)
  393. if #available(iOS 10.1, macOS 10.12.0, *) {
  394. XCTAssertNotNil(error, "error should not be nil")
  395. } else {
  396. XCTAssertNil(error, "error should be nil")
  397. }
  398. #else
  399. XCTAssertNil(error, "error should be nil")
  400. #endif
  401. }
  402. // MARK: Server Trust Policy - Disabling Evaluation Tests
  403. func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
  404. // Given
  405. let policies = [expiredHost: ServerTrustPolicy.disableEvaluation]
  406. let manager = SessionManager(
  407. configuration: configuration,
  408. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  409. )
  410. let expectation = self.expectation(description: "\(expiredURLString)")
  411. var error: Error?
  412. // When
  413. manager.request(expiredURLString)
  414. .response { resp in
  415. error = resp.error
  416. expectation.fulfill()
  417. }
  418. waitForExpectations(timeout: timeout, handler: nil)
  419. // Then
  420. XCTAssertNil(error, "error should be nil")
  421. }
  422. // MARK: Server Trust Policy - Custom Evaluation Tests
  423. func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
  424. // Given
  425. let policies = [
  426. expiredHost: ServerTrustPolicy.customEvaluation { _, _ in
  427. // Implement a custom evaluation routine here...
  428. return true
  429. }
  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. XCTAssertNil(error, "error should be nil")
  446. }
  447. func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
  448. // Given
  449. let policies = [
  450. expiredHost: ServerTrustPolicy.customEvaluation { _, _ in
  451. // Implement a custom evaluation routine here...
  452. return false
  453. }
  454. ]
  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. XCTAssertNotNil(error, "error should not be nil")
  470. if let error = error as? URLError {
  471. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  472. } else {
  473. XCTFail("error should be an URLError")
  474. }
  475. }
  476. }