TLSEvaluationTests.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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.certificateWithFileName("expired.badssl.com-root-ca")
  29. static let IntermediateCA1 = TestCertificates.certificateWithFileName("expired.badssl.com-intermediate-ca-1")
  30. static let IntermediateCA2 = TestCertificates.certificateWithFileName("expired.badssl.com-intermediate-ca-2")
  31. static let Leaf = TestCertificates.certificateWithFileName("expired.badssl.com-leaf")
  32. static func certificateWithFileName(fileName: String) -> SecCertificate {
  33. class Bundle {}
  34. let filePath = NSBundle(forClass: Bundle.self).pathForResource(fileName, ofType: "cer")!
  35. let data = NSData(contentsOfFile: filePath)!
  36. let certificate = SecCertificateCreateWithData(nil, data)!
  37. return certificate
  38. }
  39. }
  40. // MARK: -
  41. private struct TestPublicKeys {
  42. static let RootCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.RootCA)
  43. static let IntermediateCA1 = TestPublicKeys.publicKeyForCertificate(TestCertificates.IntermediateCA1)
  44. static let IntermediateCA2 = TestPublicKeys.publicKeyForCertificate(TestCertificates.IntermediateCA2)
  45. static let Leaf = TestPublicKeys.publicKeyForCertificate(TestCertificates.Leaf)
  46. static func publicKeyForCertificate(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 URL = "https://expired.badssl.com/"
  57. let host = "expired.badssl.com"
  58. var configuration: NSURLSessionConfiguration!
  59. // MARK: Setup and Teardown
  60. override func setUp() {
  61. super.setUp()
  62. configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
  63. }
  64. // MARK: Default Behavior Tests
  65. func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() {
  66. // Given
  67. weak var expectation = expectationWithDescription("\(URL)")
  68. let manager = Manager(configuration: configuration)
  69. var error: NSError?
  70. // When
  71. manager.request(.GET, URL)
  72. .response { _, _, _, responseError in
  73. error = responseError
  74. expectation?.fulfill()
  75. }
  76. waitForExpectationsWithTimeout(timeout, handler: nil)
  77. // Then
  78. XCTAssertNotNil(error)
  79. if let error = error where error.domain == NSURLErrorDomain {
  80. XCTAssertEqual(error.code, NSURLErrorServerCertificateUntrusted)
  81. } else if let error = error where error.domain == (kCFErrorDomainCFNetwork as String) {
  82. XCTAssertEqual(error.code, Int(CFNetworkErrors.CFErrorHTTPSProxyConnectionFailure.rawValue))
  83. } else {
  84. XCTFail("error should be an NSError")
  85. }
  86. }
  87. // MARK: Server Trust Policy - Perform Default Tests
  88. func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() {
  89. // Given
  90. let policies = [host: ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)]
  91. let manager = Manager(
  92. configuration: configuration,
  93. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  94. )
  95. weak var expectation = expectationWithDescription("\(URL)")
  96. var error: NSError?
  97. // When
  98. manager.request(.GET, URL)
  99. .response { _, _, _, responseError in
  100. error = responseError
  101. expectation?.fulfill()
  102. }
  103. waitForExpectationsWithTimeout(timeout, handler: nil)
  104. // Then
  105. XCTAssertNotNil(error, "error should not be nil")
  106. if let code = error?.code {
  107. XCTAssertEqual(code, NSURLErrorCancelled, "code should be cancelled")
  108. } else {
  109. XCTFail("error should be an NSError")
  110. }
  111. }
  112. // MARK: Server Trust Policy - Certificate Pinning Tests
  113. func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
  114. // Given
  115. let certificates = [TestCertificates.Leaf]
  116. let policies: [String: ServerTrustPolicy] = [
  117. host: .PinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  118. ]
  119. let manager = Manager(
  120. configuration: configuration,
  121. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  122. )
  123. weak var expectation = expectationWithDescription("\(URL)")
  124. var error: NSError?
  125. // When
  126. manager.request(.GET, URL)
  127. .response { _, _, _, responseError in
  128. error = responseError
  129. expectation?.fulfill()
  130. }
  131. waitForExpectationsWithTimeout(timeout, handler: nil)
  132. // Then
  133. XCTAssertNotNil(error, "error should not be nil")
  134. if let code = error?.code {
  135. XCTAssertEqual(code, NSURLErrorCancelled, "code should be cancelled")
  136. } else {
  137. XCTFail("error should be an NSError")
  138. }
  139. }
  140. func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
  141. // Given
  142. let certificates = [
  143. TestCertificates.Leaf,
  144. TestCertificates.IntermediateCA1,
  145. TestCertificates.IntermediateCA2,
  146. TestCertificates.RootCA
  147. ]
  148. let policies: [String: ServerTrustPolicy] = [
  149. host: .PinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
  150. ]
  151. let manager = Manager(
  152. configuration: configuration,
  153. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  154. )
  155. weak var expectation = expectationWithDescription("\(URL)")
  156. var error: NSError?
  157. // When
  158. manager.request(.GET, URL)
  159. .response { _, _, _, responseError in
  160. error = responseError
  161. expectation?.fulfill()
  162. }
  163. waitForExpectationsWithTimeout(timeout, handler: nil)
  164. // Then
  165. XCTAssertNotNil(error, "error should not be nil")
  166. if let code = error?.code {
  167. XCTAssertEqual(code, NSURLErrorCancelled, "code should be cancelled")
  168. } else {
  169. XCTFail("error should be an NSError")
  170. }
  171. }
  172. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
  173. // Given
  174. let certificates = [TestCertificates.Leaf]
  175. let policies: [String: ServerTrustPolicy] = [
  176. host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  177. ]
  178. let manager = Manager(
  179. configuration: configuration,
  180. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  181. )
  182. weak var expectation = expectationWithDescription("\(URL)")
  183. var error: NSError?
  184. // When
  185. manager.request(.GET, URL)
  186. .response { _, _, _, responseError in
  187. error = responseError
  188. expectation?.fulfill()
  189. }
  190. waitForExpectationsWithTimeout(timeout, handler: nil)
  191. // Then
  192. XCTAssertNil(error, "error should be nil")
  193. }
  194. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
  195. // Given
  196. let certificates = [TestCertificates.IntermediateCA2]
  197. let policies: [String: ServerTrustPolicy] = [
  198. host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  199. ]
  200. let manager = Manager(
  201. configuration: configuration,
  202. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  203. )
  204. weak var expectation = expectationWithDescription("\(URL)")
  205. var error: NSError?
  206. // When
  207. manager.request(.GET, URL)
  208. .response { _, _, _, responseError in
  209. error = responseError
  210. expectation?.fulfill()
  211. }
  212. waitForExpectationsWithTimeout(timeout, handler: nil)
  213. // Then
  214. XCTAssertNil(error, "error should be nil")
  215. }
  216. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
  217. // Given
  218. let certificates = [TestCertificates.RootCA]
  219. let policies: [String: ServerTrustPolicy] = [
  220. host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
  221. ]
  222. let manager = Manager(
  223. configuration: configuration,
  224. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  225. )
  226. weak var expectation = expectationWithDescription("\(URL)")
  227. var error: NSError?
  228. // When
  229. manager.request(.GET, URL)
  230. .response { _, _, _, responseError in
  231. error = responseError
  232. expectation?.fulfill()
  233. }
  234. waitForExpectationsWithTimeout(timeout, handler: nil)
  235. // Then
  236. XCTAssertNil(error, "error should be nil")
  237. }
  238. // MARK: Server Trust Policy - Public Key Pinning Tests
  239. func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
  240. // Given
  241. let publicKeys = [TestPublicKeys.Leaf]
  242. let policies: [String: ServerTrustPolicy] = [
  243. host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
  244. ]
  245. let manager = Manager(
  246. configuration: configuration,
  247. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  248. )
  249. weak var expectation = expectationWithDescription("\(URL)")
  250. var error: NSError?
  251. // When
  252. manager.request(.GET, URL)
  253. .response { _, _, _, responseError in
  254. error = responseError
  255. expectation?.fulfill()
  256. }
  257. waitForExpectationsWithTimeout(timeout, handler: nil)
  258. // Then
  259. XCTAssertNotNil(error, "error should not be nil")
  260. if let code = error?.code {
  261. XCTAssertEqual(code, NSURLErrorCancelled, "code should be cancelled")
  262. } else {
  263. XCTFail("error should be an NSError")
  264. }
  265. }
  266. func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
  267. // Given
  268. let publicKeys = [TestPublicKeys.Leaf]
  269. let policies: [String: ServerTrustPolicy] = [
  270. host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  271. ]
  272. let manager = Manager(
  273. configuration: configuration,
  274. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  275. )
  276. weak var expectation = expectationWithDescription("\(URL)")
  277. var error: NSError?
  278. // When
  279. manager.request(.GET, URL)
  280. .response { _, _, _, responseError in
  281. error = responseError
  282. expectation?.fulfill()
  283. }
  284. waitForExpectationsWithTimeout(timeout, handler: nil)
  285. // Then
  286. XCTAssertNil(error, "error should be nil")
  287. }
  288. func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
  289. // Given
  290. let publicKeys = [TestPublicKeys.IntermediateCA2]
  291. let policies: [String: ServerTrustPolicy] = [
  292. host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  293. ]
  294. let manager = Manager(
  295. configuration: configuration,
  296. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  297. )
  298. weak var expectation = expectationWithDescription("\(URL)")
  299. var error: NSError?
  300. // When
  301. manager.request(.GET, URL)
  302. .response { _, _, _, responseError in
  303. error = responseError
  304. expectation?.fulfill()
  305. }
  306. waitForExpectationsWithTimeout(timeout, handler: nil)
  307. // Then
  308. XCTAssertNil(error, "error should be nil")
  309. }
  310. func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
  311. // Given
  312. let publicKeys = [TestPublicKeys.RootCA]
  313. let policies: [String: ServerTrustPolicy] = [
  314. host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
  315. ]
  316. let manager = Manager(
  317. configuration: configuration,
  318. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  319. )
  320. weak var expectation = expectationWithDescription("\(URL)")
  321. var error: NSError?
  322. // When
  323. manager.request(.GET, URL)
  324. .response { _, _, _, responseError in
  325. error = responseError
  326. expectation?.fulfill()
  327. }
  328. waitForExpectationsWithTimeout(timeout, handler: nil)
  329. // Then
  330. XCTAssertNil(error, "error should be nil")
  331. }
  332. // MARK: Server Trust Policy - Disabling Evaluation Tests
  333. func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
  334. // Given
  335. let policies = [host: ServerTrustPolicy.DisableEvaluation]
  336. let manager = Manager(
  337. configuration: configuration,
  338. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  339. )
  340. weak var expectation = expectationWithDescription("\(URL)")
  341. var error: NSError?
  342. // When
  343. manager.request(.GET, URL)
  344. .response { _, _, _, responseError in
  345. error = responseError
  346. expectation?.fulfill()
  347. }
  348. waitForExpectationsWithTimeout(timeout, handler: nil)
  349. // Then
  350. XCTAssertNil(error, "error should be nil")
  351. }
  352. // MARK: Server Trust Policy - Custom Evaluation Tests
  353. func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
  354. // Given
  355. let policies = [
  356. host: ServerTrustPolicy.CustomEvaluation { _, _ in
  357. // Implement a custom evaluation routine here...
  358. return true
  359. }
  360. ]
  361. let manager = Manager(
  362. configuration: configuration,
  363. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  364. )
  365. weak var expectation = expectationWithDescription("\(URL)")
  366. var error: NSError?
  367. // When
  368. manager.request(.GET, URL)
  369. .response { _, _, _, responseError in
  370. error = responseError
  371. expectation?.fulfill()
  372. }
  373. waitForExpectationsWithTimeout(timeout, handler: nil)
  374. // Then
  375. XCTAssertNil(error, "error should be nil")
  376. }
  377. func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
  378. // Given
  379. let policies = [
  380. host: ServerTrustPolicy.CustomEvaluation { _, _ in
  381. // Implement a custom evaluation routine here...
  382. return false
  383. }
  384. ]
  385. let manager = Manager(
  386. configuration: configuration,
  387. serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
  388. )
  389. weak var expectation = expectationWithDescription("\(URL)")
  390. var error: NSError?
  391. // When
  392. manager.request(.GET, URL)
  393. .response { _, _, _, responseError in
  394. error = responseError
  395. expectation?.fulfill()
  396. }
  397. waitForExpectationsWithTimeout(timeout, handler: nil)
  398. // Then
  399. XCTAssertNotNil(error, "error should not be nil")
  400. if let code = error?.code {
  401. XCTAssertEqual(code, NSURLErrorCancelled, "code should be cancelled")
  402. } else {
  403. XCTFail("error should be an NSError")
  404. }
  405. }
  406. }