-
Notifications
You must be signed in to change notification settings - Fork 48
/
SSLServiceTests.swift
426 lines (305 loc) · 10.4 KB
/
SSLServiceTests.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//
// SocketTests.swift
// BlueSocket
//
// Created by Bill Abt on 3/15/16.
// Copyright © 2016 IBM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
import Foundation
import Dispatch
#if os(Linux)
import Glibc
#endif
import Socket
@testable import SSLService
class SSLServiceTests: XCTestCase {
let QUIT: String = "QUIT"
let port: Int32 = 1337
let host: String = "127.0.0.1"
let path: String = "/tmp/server.test.socket"
let password = "kitura"
var configuration: SSLService.Configuration? = nil
var certPath: URL? = nil
var keyPath: URL? = nil
var p12Path: URL? = nil
/// Test for bundle usage.
static var useBundles: Bool {
if let bundle = SSLServiceTests.bundle {
let path = bundle.path(forResource: "cert", ofType: "p12")
return path != nil
} else {
return false
}
}
#if os(Linux)
static let bundle: Bundle? = nil
#else
static let bundle: Bundle? = Bundle(for: SSLServiceTests.self)
#endif
#if os(Linux)
let enableSSL = true
#else
let enableSSL = false
#endif
///
/// Platform independent utility function to locate test files.
///
/// - Parameters:
/// - resource: The name of the resource to find.
/// - ofType: The type (i.e. extension) of the resource.
///
/// - Returns: URL for the resource or nil if a path to the resource cannot be found.
///
static public func getFilePath(for resource: String, ofType: String) -> URL? {
var path: URL
if SSLServiceTests.useBundles, let bundle = SSLServiceTests.bundle {
guard let bPath = bundle.path(forResource: resource, ofType: ofType) else {
return nil
}
path = URL(fileURLWithPath: bPath)
} else {
path = URL(fileURLWithPath: #file).appendingPathComponent("../certs/" + resource + "." + ofType).standardized
}
return path
}
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func createConfiguration() {
self.certPath = SSLServiceTests.getFilePath(for: "cert", ofType: "pem")
XCTAssertNotNil(self.certPath)
self.keyPath = SSLServiceTests.getFilePath(for: "key", ofType: "pem")
XCTAssertNotNil(self.keyPath)
self.p12Path = SSLServiceTests.getFilePath(for: "cert", ofType: "p12")
XCTAssertNotNil(self.p12Path)
#if os(Linux)
self.configuration = SSLService.Configuration(withCACertificateDirectory: nil, usingCertificateFile: self.certPath?.path, withKeyFile: self.keyPath?.path, usingSelfSignedCerts: true)
#else
self.configuration = SSLService.Configuration(withChainFilePath: self.p12Path?.path, withPassword: self.password, usingSelfSignedCerts: true)
#endif
}
func createEmbeddedCertConfiguration() {
let certPath = SSLServiceTests.getFilePath(for: "cert", ofType: "der")
XCTAssertNotNil(self.certPath)
print("Using embedded cert: \(certPath!)")
self.configuration = SSLService.Configuration(clientAllowsSelfSignedCertificates: true, embeddedServerCertPaths: [certPath!])
}
func createSecureHelper(family: Socket.ProtocolFamily = .inet, useEmbeddedCert: Bool) throws -> Socket {
let socket = try Socket.create(family: family)
XCTAssertNotNil(socket)
XCTAssertFalse(socket.isConnected)
XCTAssertTrue(socket.isBlocking)
if enableSSL {
if useEmbeddedCert {
self.createEmbeddedCertConfiguration()
}
else {
#if os(Linux)
self.createConfiguration() //cannot use this function as a client on Apple platforms
#else
self.configuration = SSLService.Configuration(clientAllowsSelfSignedCertificates: true) //simple client connection accepting self signed certs
#endif
}
let service = try SSLService(usingConfiguration: self.configuration!)
XCTAssertNotNil(service)
socket.delegate = service
}
return socket
}
func launchSecureServerHelper(family: Socket.ProtocolFamily = .inet) {
let queue: DispatchQueue? = DispatchQueue.global(qos: .userInteractive)
guard let pQueue = queue else {
print("Unable to access global interactive QOS queue")
XCTFail()
return
}
pQueue.async { [unowned self] in
do {
try self.secureServerHelper(family: family)
} catch let error {
guard let socketError = error as? Socket.Error else {
print("Unexpected error...")
XCTFail()
return
}
print("launchSecureServerHelper Error reported:\n \(socketError.description)")
XCTFail()
}
}
}
func secureServerHelper(family: Socket.ProtocolFamily = .inet) throws {
var keepRunning: Bool = true
var listenSocket: Socket? = nil
do {
try listenSocket = Socket.create(family: family)
guard let listener = listenSocket else {
print("Unable to unwrap socket...")
XCTFail()
return
}
var socket: Socket
if enableSSL {
self.createConfiguration()
let service = try SSLService(usingConfiguration: self.configuration!)
XCTAssertNotNil(service)
listener.delegate = service
}
// Setting up TCP...
try listener.listen(on: Int(port), maxBacklogSize: 10)
print("Listening on port: \(port)")
socket = try listener.acceptClientConnection()
print("Accepted connection from: \(socket.remoteHostname) on port \(socket.remotePort), Secure? \(socket.signature!.isSecure)")
try socket.write(from: "Hello, type 'QUIT' to end session\n")
var bytesRead = 0
repeat {
var readData = Data()
bytesRead = try socket.read(into: &readData)
if bytesRead > 0 {
guard let response = NSString(data: readData, encoding: String.Encoding.utf8.rawValue) else {
print("Error decoding response...")
readData.count = 0
XCTFail()
break
}
if response.hasPrefix(QUIT) {
keepRunning = false
}
// TCP or UNIX?
if family == .inet || family == .inet6 {
print("Server received from connection at \(socket.remoteHostname):\(socket.remotePort): \(response) ")
} else {
print("Server received from connection at \(socket.remotePath!): \(response) ")
}
let reply = "Server response: \n\(response)\n"
try socket.write(from: reply)
}
if bytesRead == 0 {
break
}
} while keepRunning
socket.close()
XCTAssertFalse(socket.isActive)
} catch let error {
guard let socketError = error as? Socket.Error else {
print("Unexpected error...")
XCTFail()
return
}
// This error is expected when we're shutting it down...
if socketError.errorCode == Int32(Socket.SOCKET_ERR_WRITE_FAILED) {
return
}
print("serverHelper Error reported: \(socketError.description)")
XCTFail()
}
}
func readAndPrint(socket: Socket, data: inout Data) throws -> String? {
data.count = 0
let bytesRead = try socket.read(into: &data)
if bytesRead > 0 {
print("Read \(bytesRead) from socket...")
guard let response = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) else {
print("Error accessing received data...")
XCTFail()
return nil
}
print("Response:\n\(response)")
return String(describing: response)
}
return nil
}
func test_SSLConfiguration() {
self.createConfiguration()
}
func testSecureReadWrite(useEmbeddedCert : Bool) {
let hostname = "127.0.0.1"
let port: Int32 = 1337
var data = Data()
do {
// Launch the server helper...
launchSecureServerHelper()
// Need to wait for the server to come up...
#if os(Linux)
_ = Glibc.sleep(2)
#else
_ = Darwin.sleep(2)
#endif
// Create the signature...
let signature = try Socket.Signature(protocolFamily: .inet, socketType: .stream, proto: .tcp, hostname: hostname, port: port)!
// Create the socket...
let socket = try createSecureHelper(useEmbeddedCert: useEmbeddedCert)
// Defer cleanup...
defer {
// Close the socket...
socket.close()
XCTAssertFalse(socket.isActive)
}
print("\nAttempting to connect to host: \(hostname):\(port)...")
// Connect to the server helper...
try socket.connect(using: signature)
if !socket.isConnected {
fatalError("Failed to connect to the server...")
}
print("\nConnected to host: \(hostname):\(port)")
print("\tSocket signature: \(socket.signature!.description)\n")
_ = try readAndPrint(socket: socket, data: &data)
let hello = "Hello from client..."
try socket.write(from: hello)
print("Wrote '\(hello)' to socket...")
let response = try readAndPrint(socket: socket, data: &data)
XCTAssertNotNil(response)
XCTAssertEqual(response, "Server response: \n\(hello)\n")
try socket.write(from: "QUIT")
print("Sent quit to server...")
// Need to wait for the server to go down before continuing...
#if os(Linux)
_ = Glibc.sleep(1)
#else
_ = Darwin.sleep(1)
#endif
} catch let error {
// See if it's a socket error or something else...
guard let socketError = error as? Socket.Error else {
print("Unexpected error...")
XCTFail()
return
}
print("testReadWrite Error reported: \(socketError.description)")
XCTFail()
}
}
func testSecureReadWrite_A_SelfSigned() {
testSecureReadWrite(useEmbeddedCert: false)
}
func testSecureReadWrite_B_Embedded() {
testSecureReadWrite(useEmbeddedCert: true)
}
#if os(Linux)
static var allTests = [
("testSSLConfiguration", test_SSLConfiguration),
("testSecureReadWrite", testSecureReadWrite_A_SelfSigned),
]
#else
static var allTests = [
("testSSLConfiguration", test_SSLConfiguration),
("testSecureReadWrite", testSecureReadWrite_A_SelfSigned),
("testSecureReadWriteEmbedded", testSecureReadWrite_B_Embedded),
]
#endif
}