Use hashed device tokens

This commit is contained in:
Christoph Hagen 2022-05-01 13:28:06 +02:00
parent aa0646ba87
commit 75c4a37e40
3 changed files with 18 additions and 13 deletions

View File

@ -8,7 +8,7 @@ final class DeviceManager {
private var connection: WebSocket?
/// The authentication token of the device for the socket connection
private let deviceKey: String
private let deviceKey: Data
/// The authentication token of the remote
private let remoteKey: Data
@ -26,7 +26,7 @@ final class DeviceManager {
/// A promise to finish the request once the device responds or times out
private var requestInProgress: EventLoopPromise<DeviceResponse>?
init(deviceKey: String, remoteKey: Data) {
init(deviceKey: Data, remoteKey: Data) {
self.deviceKey = deviceKey
self.remoteKey = remoteKey
}
@ -57,8 +57,9 @@ final class DeviceManager {
return requestInProgress!.futureResult
}
func authenticateDevice(psk: String) {
guard psk == self.deviceKey else {
func authenticateDevice(hash: String) {
guard let key = Data(fromHexEncodedString: hash),
SHA256.hash(data: key) == self.deviceKey else {
print("Invalid device key")
_ = connection?.close()
deviceIsAuthenticated = false

View File

@ -4,7 +4,7 @@ var deviceManager: DeviceManager!
enum ServerError: Error {
case invalidAuthenticationFileContent
case invalidRemoteAuthenticationToken
case invalidAuthenticationToken
}
// configures your application
@ -13,20 +13,24 @@ public func configure(_ app: Application) throws {
let storageFolder = URL(fileURLWithPath: app.directory.resourcesDirectory)
let keyFile = storageFolder.appendingPathComponent(Config.keyFileName)
let authContent = try String(contentsOf: keyFile)
let authContent: [Data] = try String(contentsOf: keyFile)
.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.map {
guard let key = Data(fromHexEncodedString: $0) else {
throw ServerError.invalidAuthenticationToken
}
guard key.count == SHA256.byteCount else {
throw ServerError.invalidAuthenticationToken
}
return key
}
guard authContent.count == 2 else {
throw ServerError.invalidAuthenticationFileContent
}
let deviceKey = authContent[0]
guard let remoteKey = Data(fromHexEncodedString: authContent[1]) else {
throw ServerError.invalidRemoteAuthenticationToken
}
guard remoteKey.count == SHA256.byteCount else {
throw ServerError.invalidRemoteAuthenticationToken
}
let remoteKey = authContent[1]
deviceManager = DeviceManager(deviceKey: deviceKey, remoteKey: remoteKey)
try routes(app)

View File

@ -80,7 +80,7 @@ func routes(_ app: Application) throws {
deviceManager.processDeviceResponse(data)
}
socket.onText { _, text in
deviceManager.authenticateDevice(psk: text)
deviceManager.authenticateDevice(hash: text)
}
_ = socket.onClose.always { _ in