TLSEvaluationTests.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. let urlString = "https://expired.badssl.com/"
  57. let host = "expired.badssl.com"
  58. var configuration: URLSessionConfiguration!
  59. // MARK: Setup and Teardown
  60. override func setUp() {
  61. super.setUp()
  62. configuration = URLSessionConfiguration.ephemeral
  63. }
  64. // MARK: Default Behavior Tests
  65. func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() {
  66. // Given
  67. weak var expectation = self.expectation(description: "\(urlString)")
  68. let manager = SessionManager(configuration: configuration)
  69. var error: Error?
  70. // When
  71. manager.request(urlString)
  72. .response { resp in
  73. error = resp.error
  74. expectation?.fulfill()
  75. }
  76. waitForExpectations(timeout: timeout, handler: nil)
  77. // Then
  78. XCTAssertNotNil(error)
  79. if let error = error as? URLError {
  80. XCTAssertEqual(error.code, .serverCertificateUntrusted)
  81. } else if let error = error as? NSError {
  82. XCTAssertEqual(error.domain, kCFErrorDomainCFNetwork as String)
  83. XCTAssertEqual(error.code, Int(CFNetworkErrors.cfErrorHTTPSProxyConnectionFailure.rawValue))
  84. } else {
  85. XCTFail("error should be a URLError or NSError from CFNetwork")
  86. }
  87. }
  88. // MARK: Server Trust Policy - Perform Default Tests
  89. func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() {
  90. // Given
  91. let policies = [host: ServerTrustPolicy.performDefaultEvaluation(validateHost: true)]
  92. let manager = SessionManager(
  93. configuration: configuration,
  94. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  95. )
  96. weak var expectation = self.expectation(description: "\(urlString)")
  97. var error: Error?
  98. // When
  99. manager.request(urlString)
  100. .response { resp in
  101. error = resp.error
  102. expectation?.fulfill()
  103. }
  104. waitForExpectations(timeout: timeout, handler: nil)
  105. // Then
  106. XCTAssertNotNil(error, "error should not be nil")
  107. if let error = error as? URLError {
  108. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  109. } else {
  110. XCTFail("error should be an URLError")
  111. }
  112. }
  113. // MARK: Server Trust Policy - Certificate Pinning Tests
  114. func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
  115. // Given
  116. let certificates = [TestCertificates.leaf]
  117. let policies: [String: ServerTrustPolicy] = [
  118. host: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  119. ]
  120. let manager = SessionManager(
  121. configuration: configuration,
  122. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  123. )
  124. weak var expectation = self.expectation(description: "\(urlString)")
  125. var error: Error?
  126. // When
  127. manager.request(urlString)
  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 testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
  142. // Given
  143. let certificates = [
  144. TestCertificates.leaf,
  145. TestCertificates.intermediateCA1,
  146. TestCertificates.intermediateCA2,
  147. TestCertificates.rootCA
  148. ]
  149. let policies: [String: ServerTrustPolicy] = [
  150. host: .pinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  151. ]
  152. let manager = SessionManager(
  153. configuration: configuration,
  154. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  155. )
  156. weak var expectation = self.expectation(description: "\(urlString)")
  157. var error: Error?
  158. // When
  159. manager.request(urlString)
  160. .response { resp in
  161. error = resp.error
  162. expectation?.fulfill()
  163. }
  164. waitForExpectations(timeout: timeout, handler: nil)
  165. // Then
  166. XCTAssertNotNil(error, "error should not be nil")
  167. if let error = error as? URLError {
  168. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  169. } else {
  170. XCTFail("error should be an URLError")
  171. }
  172. }
  173. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
  174. // Given
  175. let certificates = [TestCertificates.leaf]
  176. let policies: [String: ServerTrustPolicy] = [
  177. host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  178. ]
  179. let manager = SessionManager(
  180. configuration: configuration,
  181. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  182. )
  183. weak var expectation = self.expectation(description: "\(urlString)")
  184. var error: Error?
  185. // When
  186. manager.request(urlString)
  187. .response { resp in
  188. error = resp.error
  189. expectation?.fulfill()
  190. }
  191. waitForExpectations(timeout: timeout, handler: nil)
  192. // Then
  193. XCTAssertNil(error, "error should be nil")
  194. }
  195. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
  196. // Given
  197. let certificates = [TestCertificates.intermediateCA2]
  198. let policies: [String: ServerTrustPolicy] = [
  199. host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  200. ]
  201. let manager = SessionManager(
  202. configuration: configuration,
  203. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  204. )
  205. weak var expectation = self.expectation(description: "\(urlString)")
  206. var error: Error?
  207. // When
  208. manager.request(urlString)
  209. .response { resp in
  210. error = resp.error
  211. expectation?.fulfill()
  212. }
  213. waitForExpectations(timeout: timeout, handler: nil)
  214. // Then
  215. XCTAssertNil(error, "error should be nil")
  216. }
  217. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
  218. // Given
  219. let certificates = [TestCertificates.rootCA]
  220. let policies: [String: ServerTrustPolicy] = [
  221. host: .pinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  222. ]
  223. let manager = SessionManager(
  224. configuration: configuration,
  225. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  226. )
  227. weak var expectation = self.expectation(description: "\(urlString)")
  228. var error: Error?
  229. // When
  230. manager.request(urlString)
  231. .response { resp in
  232. error = resp.error
  233. expectation?.fulfill()
  234. }
  235. waitForExpectations(timeout: timeout, handler: nil)
  236. // Then
  237. #if os(iOS) || os(macOS)
  238. if #available(iOS 10.0, macOS 10.12.0, *) {
  239. XCTAssertNotNil(error, "error should not be nil")
  240. } else {
  241. XCTAssertNil(error, "error should be nil")
  242. }
  243. #else
  244. XCTAssertNil(error, "error should be nil")
  245. #endif
  246. }
  247. // MARK: Server Trust Policy - Public Key Pinning Tests
  248. func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
  249. // Given
  250. let publicKeys = [TestPublicKeys.leaf]
  251. let policies: [String: ServerTrustPolicy] = [
  252. host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
  253. ]
  254. let manager = SessionManager(
  255. configuration: configuration,
  256. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  257. )
  258. weak var expectation = self.expectation(description: "\(urlString)")
  259. var error: Error?
  260. // When
  261. manager.request(urlString)
  262. .response { resp in
  263. error = resp.error
  264. expectation?.fulfill()
  265. }
  266. waitForExpectations(timeout: timeout, handler: nil)
  267. // Then
  268. XCTAssertNotNil(error, "error should not be nil")
  269. if let error = error as? URLError {
  270. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  271. } else {
  272. XCTFail("error should be an URLError")
  273. }
  274. }
  275. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
  276. // Given
  277. let publicKeys = [TestPublicKeys.leaf]
  278. let policies: [String: ServerTrustPolicy] = [
  279. host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  280. ]
  281. let manager = SessionManager(
  282. configuration: configuration,
  283. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  284. )
  285. weak var expectation = self.expectation(description: "\(urlString)")
  286. var error: Error?
  287. // When
  288. manager.request(urlString)
  289. .response { resp in
  290. error = resp.error
  291. expectation?.fulfill()
  292. }
  293. waitForExpectations(timeout: timeout, handler: nil)
  294. // Then
  295. XCTAssertNil(error, "error should be nil")
  296. }
  297. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
  298. // Given
  299. let publicKeys = [TestPublicKeys.intermediateCA2]
  300. let policies: [String: ServerTrustPolicy] = [
  301. host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  302. ]
  303. let manager = SessionManager(
  304. configuration: configuration,
  305. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  306. )
  307. weak var expectation = self.expectation(description: "\(urlString)")
  308. var error: Error?
  309. // When
  310. manager.request(urlString)
  311. .response { resp in
  312. error = resp.error
  313. expectation?.fulfill()
  314. }
  315. waitForExpectations(timeout: timeout, handler: nil)
  316. // Then
  317. XCTAssertNil(error, "error should be nil")
  318. }
  319. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
  320. // Given
  321. let publicKeys = [TestPublicKeys.rootCA]
  322. let policies: [String: ServerTrustPolicy] = [
  323. host: .pinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  324. ]
  325. let manager = SessionManager(
  326. configuration: configuration,
  327. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  328. )
  329. weak var expectation = self.expectation(description: "\(urlString)")
  330. var error: Error?
  331. // When
  332. manager.request(urlString)
  333. .response { resp in
  334. error = resp.error
  335. expectation?.fulfill()
  336. }
  337. waitForExpectations(timeout: timeout, handler: nil)
  338. // Then
  339. #if os(iOS) || os(macOS)
  340. if #available(iOS 10.0, macOS 10.12.0, *) {
  341. XCTAssertNotNil(error, "error should not be nil")
  342. } else {
  343. XCTAssertNil(error, "error should be nil")
  344. }
  345. #else
  346. XCTAssertNil(error, "error should be nil")
  347. #endif
  348. }
  349. // MARK: Server Trust Policy - Disabling Evaluation Tests
  350. func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
  351. // Given
  352. let policies = [host: ServerTrustPolicy.disableEvaluation]
  353. let manager = SessionManager(
  354. configuration: configuration,
  355. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  356. )
  357. weak var expectation = self.expectation(description: "\(urlString)")
  358. var error: Error?
  359. // When
  360. manager.request(urlString)
  361. .response { resp in
  362. error = resp.error
  363. expectation?.fulfill()
  364. }
  365. waitForExpectations(timeout: timeout, handler: nil)
  366. // Then
  367. XCTAssertNil(error, "error should be nil")
  368. }
  369. // MARK: Server Trust Policy - Custom Evaluation Tests
  370. func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
  371. // Given
  372. let policies = [
  373. host: ServerTrustPolicy.customEvaluation { _, _ in
  374. // Implement a custom evaluation routine here...
  375. return true
  376. }
  377. ]
  378. let manager = SessionManager(
  379. configuration: configuration,
  380. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  381. )
  382. weak var expectation = self.expectation(description: "\(urlString)")
  383. var error: Error?
  384. // When
  385. manager.request(urlString)
  386. .response { resp in
  387. error = resp.error
  388. expectation?.fulfill()
  389. }
  390. waitForExpectations(timeout: timeout, handler: nil)
  391. // Then
  392. XCTAssertNil(error, "error should be nil")
  393. }
  394. func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
  395. // Given
  396. let policies = [
  397. host: ServerTrustPolicy.customEvaluation { _, _ in
  398. // Implement a custom evaluation routine here...
  399. return false
  400. }
  401. ]
  402. let manager = SessionManager(
  403. configuration: configuration,
  404. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  405. )
  406. weak var expectation = self.expectation(description: "\(urlString)")
  407. var error: Error?
  408. // When
  409. manager.request(urlString)
  410. .response { resp in
  411. error = resp.error
  412. expectation?.fulfill()
  413. }
  414. waitForExpectations(timeout: timeout, handler: nil)
  415. // Then
  416. XCTAssertNotNil(error, "error should not be nil")
  417. if let error = error as? URLError {
  418. XCTAssertEqual(error.code, .cancelled, "code should be cancelled")
  419. } else {
  420. XCTFail("error should be an URLError")
  421. }
  422. }
  423. }