TLSEvaluationTests.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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 evaluators = [expiredHost: DefaultTrustEvaluator(validateHost: true)]
  118. let manager = SessionManager(
  119. configuration: configuration,
  120. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  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 = DefaultTrustEvaluator()
  144. let evaluators = [revokedHost: defaultPolicy]
  145. let manager = SessionManager(
  146. configuration: configuration,
  147. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  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 = RevocationTrustEvaluator()
  170. let evaluators = [expiredHost: policy]
  171. let manager = SessionManager(
  172. configuration: configuration,
  173. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  174. )
  175. let expectation = self.expectation(description: "\(expiredURLString)")
  176. var error: Error?
  177. // When
  178. manager.request(expiredURLString)
  179. .response { resp in
  180. error = resp.error
  181. expectation.fulfill()
  182. }
  183. waitForExpectations(timeout: timeout, handler: nil)
  184. // Then
  185. XCTAssertNotNil(error, "error should not be nil")
  186. if let error = error as? URLError {
  187. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  188. } else {
  189. XCTFail("error should be an URLError")
  190. }
  191. }
  192. func testThatRevokedCertificateRequestFailsWithRevokedServerTrustPolicy() {
  193. // Given
  194. let policy = RevocationTrustEvaluator()
  195. let evaluators = [revokedHost: policy]
  196. let manager = SessionManager(
  197. configuration: configuration,
  198. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  199. )
  200. let expectation = self.expectation(description: "\(revokedURLString)")
  201. var error: Error?
  202. // When
  203. manager.request(revokedURLString)
  204. .response { resp in
  205. error = resp.error
  206. expectation.fulfill()
  207. }
  208. waitForExpectations(timeout: timeout, handler: nil)
  209. // Then
  210. XCTAssertNotNil(error, "error should not be nil")
  211. if let error = error as? URLError {
  212. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  213. } else {
  214. XCTFail("error should be an URLError")
  215. }
  216. }
  217. // MARK: Server Trust Policy - Certificate Pinning Tests
  218. func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
  219. // Given
  220. let certificates = [TestCertificates.leaf]
  221. let evaluators = [
  222. expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates)
  223. ]
  224. let manager = SessionManager(
  225. configuration: configuration,
  226. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  227. )
  228. let expectation = self.expectation(description: "\(expiredURLString)")
  229. var error: Error?
  230. // When
  231. manager.request(expiredURLString)
  232. .response { resp in
  233. error = resp.error
  234. expectation.fulfill()
  235. }
  236. waitForExpectations(timeout: timeout, handler: nil)
  237. // Then
  238. XCTAssertNotNil(error, "error should not be nil")
  239. if let error = error as? URLError {
  240. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  241. } else {
  242. XCTFail("error should be an URLError")
  243. }
  244. }
  245. func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
  246. // Given
  247. let certificates = [
  248. TestCertificates.leaf,
  249. TestCertificates.intermediateCA1,
  250. TestCertificates.intermediateCA2,
  251. TestCertificates.rootCA
  252. ]
  253. let evaluators = [
  254. expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates)
  255. ]
  256. let manager = SessionManager(
  257. configuration: configuration,
  258. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  259. )
  260. let expectation = self.expectation(description: "\(expiredURLString)")
  261. var error: Error?
  262. // When
  263. manager.request(expiredURLString)
  264. .response { resp in
  265. error = resp.error
  266. expectation.fulfill()
  267. }
  268. waitForExpectations(timeout: timeout, handler: nil)
  269. // Then
  270. XCTAssertNotNil(error, "error should not be nil")
  271. if let error = error as? URLError {
  272. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  273. } else {
  274. XCTFail("error should be an URLError")
  275. }
  276. }
  277. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
  278. // Given
  279. let certificates = [TestCertificates.leaf]
  280. let evaluators = [
  281. expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates, validateCertificateChain: false)
  282. ]
  283. let manager = SessionManager(
  284. configuration: configuration,
  285. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  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 testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
  300. // Given
  301. let certificates = [TestCertificates.intermediateCA2]
  302. let evaluators = [
  303. expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates, validateCertificateChain: false)
  304. ]
  305. let manager = SessionManager(
  306. configuration: configuration,
  307. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  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. XCTAssertNil(error, "error should be nil")
  320. }
  321. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
  322. // Given
  323. let certificates = [TestCertificates.rootCA]
  324. let evaluators = [
  325. expiredHost: PinnedCertificatesTrustEvaluator(certificates: certificates, validateCertificateChain: false)
  326. ]
  327. let manager = SessionManager(
  328. configuration: configuration,
  329. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  330. )
  331. let expectation = self.expectation(description: "\(expiredURLString)")
  332. var error: Error?
  333. // When
  334. manager.request(expiredURLString)
  335. .response { resp in
  336. error = resp.error
  337. expectation.fulfill()
  338. }
  339. waitForExpectations(timeout: timeout, handler: nil)
  340. // Then
  341. if #available(iOS 10.1, macOS 10.12.0, tvOS 10.1, *) {
  342. XCTAssertNotNil(error, "error should not be nil")
  343. } else {
  344. XCTAssertNil(error, "error should be nil")
  345. }
  346. }
  347. // MARK: Server Trust Policy - Public Key Pinning Tests
  348. func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
  349. // Given
  350. let publicKeys = [TestPublicKeys.leaf]
  351. let evaluators = [
  352. expiredHost: PublicKeysTrustEvaluator(keys: publicKeys)
  353. ]
  354. let manager = SessionManager(
  355. configuration: configuration,
  356. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  357. )
  358. let expectation = self.expectation(description: "\(expiredURLString)")
  359. var error: Error?
  360. // When
  361. manager.request(expiredURLString)
  362. .response { resp in
  363. error = resp.error
  364. expectation.fulfill()
  365. }
  366. waitForExpectations(timeout: timeout, handler: nil)
  367. // Then
  368. XCTAssertNotNil(error, "error should not be nil")
  369. if let error = error as? URLError {
  370. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  371. } else {
  372. XCTFail("error should be an URLError")
  373. }
  374. }
  375. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
  376. // Given
  377. let publicKeys = [TestPublicKeys.leaf]
  378. let evaluators = [
  379. expiredHost: PublicKeysTrustEvaluator(keys: publicKeys, validateCertificateChain: false)
  380. ]
  381. let manager = SessionManager(
  382. configuration: configuration,
  383. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  384. )
  385. let expectation = self.expectation(description: "\(expiredURLString)")
  386. var error: Error?
  387. // When
  388. manager.request(expiredURLString)
  389. .response { resp in
  390. error = resp.error
  391. expectation.fulfill()
  392. }
  393. waitForExpectations(timeout: timeout, handler: nil)
  394. // Then
  395. XCTAssertNil(error, "error should be nil")
  396. }
  397. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
  398. // Given
  399. let publicKeys = [TestPublicKeys.intermediateCA2]
  400. let evaluators = [
  401. expiredHost: PublicKeysTrustEvaluator(keys: publicKeys, validateCertificateChain: false)
  402. ]
  403. let manager = SessionManager(
  404. configuration: configuration,
  405. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  406. )
  407. let expectation = self.expectation(description: "\(expiredURLString)")
  408. var error: Error?
  409. // When
  410. manager.request(expiredURLString)
  411. .response { resp in
  412. error = resp.error
  413. expectation.fulfill()
  414. }
  415. waitForExpectations(timeout: timeout, handler: nil)
  416. // Then
  417. XCTAssertNil(error, "error should be nil")
  418. }
  419. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
  420. // Given
  421. let publicKeys = [TestPublicKeys.rootCA]
  422. let evaluators = [
  423. expiredHost: PublicKeysTrustEvaluator(keys: publicKeys, validateCertificateChain: false)
  424. ]
  425. let manager = SessionManager(
  426. configuration: configuration,
  427. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  428. )
  429. let expectation = self.expectation(description: "\(expiredURLString)")
  430. var error: Error?
  431. // When
  432. manager.request(expiredURLString)
  433. .response { resp in
  434. error = resp.error
  435. expectation.fulfill()
  436. }
  437. waitForExpectations(timeout: timeout, handler: nil)
  438. // Then
  439. if #available(iOS 10.1, macOS 10.12.0, tvOS 10.1, *) {
  440. XCTAssertNotNil(error, "error should not be nil")
  441. } else {
  442. XCTAssertNil(error, "error should be nil")
  443. }
  444. }
  445. // MARK: Server Trust Policy - Disabling Evaluation Tests
  446. func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
  447. // Given
  448. let evaluators = [expiredHost: DisabledEvaluator()]
  449. let manager = SessionManager(
  450. configuration: configuration,
  451. serverTrustManager: ServerTrustManager(evaluators: evaluators)
  452. )
  453. let expectation = self.expectation(description: "\(expiredURLString)")
  454. var error: Error?
  455. // When
  456. manager.request(expiredURLString)
  457. .response { resp in
  458. error = resp.error
  459. expectation.fulfill()
  460. }
  461. waitForExpectations(timeout: timeout, handler: nil)
  462. // Then
  463. XCTAssertNil(error, "error should be nil")
  464. }
  465. }