Compare commits

..

58 Commits

Author SHA1 Message Date
Christoph Hagen
db5311074a Update device state with unlock error 2024-03-11 00:41:26 +01:00
Christoph Hagen
e0e2a1cb06 Allow absolute key path 2023-12-25 20:12:43 +01:00
Christoph Hagen
c9d13bb150 Detect environment 2023-12-19 21:43:58 +01:00
Christoph Hagen
7968f64581 Reduce amount of logging 2023-12-12 23:08:50 +01:00
Christoph Hagen
ad1c959ead Log all messages instead of printing 2023-12-10 19:34:30 +01:00
Christoph Hagen
1a1eeb6547 Fix system status update 2023-12-10 19:32:09 +01:00
Christoph Hagen
5e72137d0e Fix error 2023-12-08 20:28:24 +01:00
Christoph Hagen
b9f1827b63 Test logger 2023-12-08 20:26:17 +01:00
Christoph Hagen
4489092a6f Attempt to see logs properly 2023-12-08 19:54:51 +01:00
Christoph Hagen
160c9a1a97 Attempt to fix socket data processing 2023-12-08 19:40:49 +01:00
Christoph Hagen
d9bd0c6e30 Fix race condition waiting for message delivery 2023-12-08 16:55:47 +01:00
Christoph Hagen
9feab409ab Improve socket connection and logging 2023-12-08 16:28:48 +01:00
Christoph Hagen
1917d1d10e Fix header key 2023-12-08 16:12:37 +01:00
Christoph Hagen
17d7a8e6c4 Fix run 2023-12-08 15:58:57 +01:00
Christoph Hagen
c25c4f3dc6 Improve logging and shutdown 2023-12-08 15:57:33 +01:00
Christoph Hagen
2e11023096 Check device message size 2023-12-08 15:53:01 +01:00
Christoph Hagen
7652bb24a3 Improve message result clarity 2023-12-08 15:43:29 +01:00
Christoph Hagen
e76029270a Update to challenge-response system 2023-12-08 12:39:10 +01:00
Christoph Hagen
ac22fcd4eb Remove key error enum 2023-12-06 09:53:24 +01:00
Christoph Hagen
b2b3c74586 Move to new Vapor main 2023-12-06 09:49:26 +01:00
Christoph Hagen
eb10ae6626 Update LICENSE 2023-12-06 09:48:52 +01:00
Christoph Hagen
f4864127f8 Update device authentication 2023-12-06 09:05:41 +01:00
Christoph Hagen
6117ae8305 Ignore more resources 2023-12-06 09:05:16 +01:00
Christoph Hagen
18fd850413 Improve logging of errors 2023-11-28 11:26:43 +01:00
Christoph Hagen
f60cb3c05a Rework shutdown procedure 2023-11-28 11:20:29 +01:00
Christoph Hagen
ab2a14e00b Create metric list and log start once 2023-11-28 08:46:26 +01:00
Christoph Hagen
7f1b9a5d96 Log server start 2023-11-27 18:17:00 +01:00
Christoph Hagen
a217db1945 Allow log path specification 2023-11-22 11:48:50 +01:00
Christoph Hagen
9c85f955e4 Fix shutdown procedure 2023-11-10 15:08:33 +01:00
Christoph Hagen
621d2af22b Close socket on shutdown 2023-11-10 15:04:20 +01:00
Christoph Hagen
1369a621ad Attempt socket bugfix 2023-11-10 15:01:37 +01:00
Christoph Hagen
9f20563877 Update logic to async 2023-11-10 13:45:42 +01:00
Christoph Hagen
b8c7256b9d Simplify async scheduler 2023-11-09 13:12:32 +01:00
Christoph Hagen
39766467e6 Remove uses of Task 2023-11-08 10:24:50 +01:00
Christoph Hagen
037d146aba Fix error due to dependency update 2023-10-24 19:09:49 +02:00
Christoph Hagen
00ac95df01 Update clairvoyant 2023-10-01 19:26:31 +02:00
Christoph Hagen
810bff0eb3 Remove build script 2023-09-07 18:14:00 +02:00
Christoph Hagen
fe5128fa8b Fix bug with socket 2023-09-07 16:06:42 +02:00
Christoph Hagen
ef71e42341 Remove migration 2023-09-07 16:06:35 +02:00
Christoph Hagen
44b776ef32 Wait to write metrics 2023-09-07 16:00:02 +02:00
Christoph Hagen
253017c429 Fix decoding 2023-09-07 15:57:30 +02:00
Christoph Hagen
c6b51c98fb Ignore invalid points 2023-09-07 15:49:00 +02:00
Christoph Hagen
66a04781d3 Attempt fix 2023-09-07 15:33:10 +02:00
Christoph Hagen
bc104a9040 Check bug 2023-09-07 15:30:35 +02:00
Christoph Hagen
e52f44f168 Attempt metric log migration 2023-09-07 15:23:44 +02:00
Christoph Hagen
04248b04af Update clairvoyant 2023-09-07 14:13:28 +02:00
Christoph Hagen
e77efe795c Move socket operations to device manager 2023-09-07 14:05:41 +02:00
Christoph Hagen
107b609aea Treat messages as data 2023-08-09 16:26:07 +02:00
Christoph Hagen
5d4adf8b15 More logging 2023-08-08 16:32:25 +02:00
Christoph Hagen
a53c12b02c Add logging 2023-08-08 16:06:41 +02:00
Christoph Hagen
aad6e32082 Add build script 2023-08-08 16:06:28 +02:00
Christoph Hagen
9dd0045c4b Update API with device id 2023-08-08 15:17:59 +02:00
Christoph Hagen
23fd5055cd Move to newer metrics version 2023-02-17 00:09:51 +01:00
Christoph Hagen
e96b85b1cc Log more metrics 2023-02-06 21:57:42 +01:00
Christoph Hagen
b3c58ce4c7 Improve logging 2023-02-06 21:44:56 +01:00
Christoph Hagen
790662a1ec Remove empty keys file 2023-01-31 19:16:38 +01:00
Christoph Hagen
21a4f4ecae Add server status 2023-01-31 19:10:57 +01:00
Christoph Hagen
52cb76d4c8 Read config from file 2023-01-31 19:10:33 +01:00
28 changed files with 714 additions and 593 deletions

3
.gitignore vendored
View File

@ -2,3 +2,6 @@
Package.resolved
.swiftpm
.build
Resources/config.json
Resources/logs
Resources/keys

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) <year> <copyright holders>
Copyright (c) 2023 Christoph Hagen
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

View File

@ -4,28 +4,25 @@ import PackageDescription
let package = Package(
name: "SesameServer",
platforms: [
.macOS(.v10_15)
.macOS(.v12)
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"),
.package(url: "https://github.com/christophhagen/Clairvoyant", from: "0.13.0"),
.package(url: "https://github.com/christophhagen/ClairvoyantVapor", from: "0.5.0"),
.package(url: "https://github.com/christophhagen/ClairvoyantBinaryCodable", from: "0.3.1"),
.package(url: "https://github.com/apple/swift-crypto.git", "1.0.0" ..< "4.0.0"),
],
targets: [
.target(
.executableTarget(
name: "App",
dependencies: [
.product(name: "Vapor", package: "vapor")
],
swiftSettings: [
// Enable better optimizations when building in Release configuration. Despite the use of
// the `.unsafeFlags` construct required by SwiftPM, this flag is recommended for Release
// builds. See <https://github.com/swift-server/guides/blob/main/docs/building.md#building-for-production> for details.
.unsafeFlags(["-cross-module-optimization"], .when(configuration: .release))
.product(name: "Vapor", package: "vapor"),
.product(name: "Clairvoyant", package: "Clairvoyant"),
.product(name: "ClairvoyantVapor", package: "ClairvoyantVapor"),
.product(name: "ClairvoyantBinaryCodable", package: "ClairvoyantBinaryCodable"),
.product(name: "Crypto", package: "swift-crypto"),
]
),
.executableTarget(name: "Run", dependencies: [.target(name: "App")]),
.testTarget(name: "AppTests", dependencies: [
.target(name: "App"),
.product(name: "XCTVapor", package: "vapor"),
])
)
]
)

View File

@ -0,0 +1,6 @@
{
"port": 6003,
"keyFileName": "keys",
"deviceTimeout": 20,
"authenticationTokens" : [],
}

View File

@ -1,2 +0,0 @@
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000

View File

@ -0,0 +1,5 @@
import Foundation
enum Message {
}

View File

@ -0,0 +1,9 @@
import Foundation
import RoutingKit
extension SesameRoute {
var path: PathComponent {
.init(stringLiteral: rawValue)
}
}

View File

@ -0,0 +1,5 @@
import Foundation
enum SignedMessage {
}

View File

@ -1,90 +0,0 @@
import Foundation
import NIOCore
/**
Encapsulates a response from a device.
*/
struct DeviceResponse {
/// Shorthand property for a timeout event.
static var deviceTimedOut: DeviceResponse {
.init(event: .deviceTimedOut)
}
/// Shorthand property for a disconnected event.
static var deviceNotConnected: DeviceResponse {
.init(event: .deviceNotConnected)
}
/// Shorthand property for a connected event.
static var deviceConnected: DeviceResponse {
.init(event: .deviceConnected)
}
/// Shorthand property for an unexpected socket event.
static var unexpectedSocketEvent: DeviceResponse {
.init(event: .unexpectedSocketEvent)
}
/// Shorthand property for an invalid message.
static var invalidMessageData: DeviceResponse {
.init(event: .invalidMessageData)
}
/// Shorthand property for missing body data.
static var noBodyData: DeviceResponse {
.init(event: .noBodyData)
}
/// Shorthand property for a busy connection
static var operationInProgress: DeviceResponse {
.init(event: .operationInProgress)
}
/// The response to a key from the server
let event: MessageResult
/// The index of the next key to use
let response: Message?
/**
Decode a message from a buffer.
The buffer must contain `Message.length+1` bytes. The first byte denotes the event type,
the remaining bytes contain the message.
- Parameter buffer: The buffer where the message bytes are stored
*/
init?(_ buffer: ByteBuffer) {
guard let byte = buffer.getBytes(at: 0, length: 1) else {
print("No bytes received from device")
return nil
}
guard let event = MessageResult(rawValue: byte[0]) else {
print("Unknown response \(byte[0]) received from device")
return nil
}
self.event = event
guard let data = buffer.getSlice(at: 1, length: Message.length) else {
self.response = nil
return
}
self.response = Message(decodeFrom: data)
}
/**
Create a response from an event without a message from the device.
- Parameter event: The response from the device.
*/
init(event: MessageResult) {
self.event = event
self.response = nil
}
/// Get the reponse encoded in bytes.
var encoded: Data {
guard let message = response else {
return Data([event.rawValue])
}
return Data([event.rawValue]) + message.encoded
}
}

View File

@ -0,0 +1,17 @@
import Foundation
extension Data {
func convert<T>(into value: T) -> T {
withUnsafeBytes {
$0.baseAddress!.load(as: T.self)
}
}
init<T>(from value: T) {
var target = value
self = Swift.withUnsafeBytes(of: &target) {
Data($0)
}
}
}

View File

@ -40,20 +40,3 @@ extension Data {
}
}
}
extension Data {
func convert<T>(into value: T) -> T {
withUnsafeBytes {
$0.baseAddress!.load(as: T.self)
}
}
init<T>(from value: T) {
var target = value
self = Swift.withUnsafeBytes(of: &target) {
Data($0)
}
}
}

View File

@ -16,4 +16,7 @@ extension UInt32 {
var encoded: Data {
Data(from: CFSwapInt32HostToLittle(self))
}
/// The size of a `UInt32` when converted to data
static let byteSize = MemoryLayout<UInt32>.size
}

View File

@ -0,0 +1,8 @@
import Foundation
extension Message {
/// The byte length of an encoded message content
static let size: Int = 2 + 2 * UInt32.byteSize
}

View File

@ -1,151 +0,0 @@
import Foundation
import NIOCore
#if canImport(CryptoKit)
import CryptoKit
#else
import Crypto
#endif
/**
An authenticated message to or from the device.
*/
struct Message: Equatable, Hashable {
/// The message authentication code for the message (32 bytes)
let mac: Data
/// The message content
let content: Content
/**
Create an authenticated message
- Parameter mac: The message authentication code
- Parameter content: The message content
*/
init(mac: Data, content: Content) {
self.mac = mac
self.content = content
}
}
extension Message {
/**
The message content without authentication.
*/
struct Content: Equatable, Hashable {
/// The time of message creation, in UNIX time (seconds since 1970)
let time: UInt32
/// The counter of the message (for freshness)
let id: UInt32
/**
Create new message content.
- Parameter time: The time of message creation,
- Parameter id: The counter of the message
*/
init(time: UInt32, id: UInt32) {
self.time = time
self.id = id
}
/**
Decode message content from data.
The data consists of two `UInt32` encoded in little endian format
- Warning: The sequence must contain at least 8 bytes, or the function will crash.
- Parameter data: The sequence containing the bytes.
*/
init<T: Sequence>(decodeFrom data: T) where T.Element == UInt8 {
self.time = UInt32(data: Data(data.prefix(MemoryLayout<UInt32>.size)))
self.id = UInt32(data: Data(data.dropFirst(MemoryLayout<UInt32>.size)))
}
/// The byte length of an encoded message content
static var length: Int {
MemoryLayout<UInt32>.size * 2
}
/// The message content encoded to data
var encoded: Data {
time.encoded + id.encoded
}
}
}
extension Message {
/// The length of a message in bytes
static var length: Int {
SHA256.byteCount + Content.length
}
/**
Decode a message from a byte buffer.
The buffer must contain at least `Message.length` bytes, or it will return `nil`.
- Parameter buffer: The buffer containing the bytes.
*/
init?(decodeFrom buffer: ByteBuffer) {
guard let data = buffer.getBytes(at: 0, length: Message.length) else {
return nil
}
self.init(decodeFrom: data)
}
/// The message encoded to data
var encoded: Data {
mac + content.encoded
}
var bytes: [UInt8] {
Array(encoded)
}
/**
Create a message from received bytes.
- Parameter data: The sequence of bytes
- Note: The sequence must contain at least `Message.length` bytes, or the function will crash.
*/
init<T: Sequence>(decodeFrom data: T) where T.Element == UInt8 {
let count = SHA256.byteCount
self.mac = Data(data.prefix(count))
self.content = .init(decodeFrom: Array(data.dropFirst(count)))
}
/**
Check if the message contains a valid authentication code
- Parameter key: The key used to sign the message.
- Returns: `true`, if the message is valid.
*/
func isValid(using key: SymmetricKey) -> Bool {
HMAC<SHA256>.isValidAuthenticationCode(mac, authenticating: content.encoded, using: key)
}
}
extension Message.Content {
/**
Calculate an authentication code for the message content.
- Parameter key: The key to use to sign the content.
- Returns: The new message signed with the key.
*/
func authenticate(using key: SymmetricKey) -> Message {
let mac = HMAC<SHA256>.authenticationCode(for: encoded, using: key)
return .init(mac: Data(mac.map { $0 }), content: self)
}
/**
Calculate an authentication code for the message content and convert everything to data.
- Parameter key: The key to use to sign the content.
- Returns: The new message signed with the key, serialized to bytes.
*/
func authenticateAndSerialize(using key: SymmetricKey) -> Data {
let encoded = self.encoded
let mac = HMAC<SHA256>.authenticationCode(for: encoded, using: key)
return Data(mac.map { $0 }) + encoded
}
}

View File

@ -4,73 +4,227 @@ import Foundation
A result from sending a key to the device.
*/
enum MessageResult: UInt8 {
// MARK: Device status
/// Text content was received, although binary data was expected
/// The message was accepted.
case messageAccepted = 0
/// The web socket received text while waiting for binary data.
case textReceived = 1
/// A socket event on the device was unexpected (not binary data)
/// An unexpected socket event occured while performing the exchange.
case unexpectedSocketEvent = 2
/// The size of the payload (i.e. message) was invalid, or the data could not be read
case invalidMessageData = 3
/// The received message size is invalid.
case invalidMessageSizeFromRemote = 3
/// The transmitted message could not be authenticated using the key
case messageAuthenticationFailed = 4
/// The message signature was incorrect.
case invalidSignatureFromRemote = 4
/// The message time was not within the acceptable bounds
case messageTimeMismatch = 5
/// The server challenge of the message did not match previous messages
case invalidServerChallengeFromRemote = 5
/// A later key has been used, invalidating this key (to prevent replay attacks after blocked communication)
case messageCounterInvalid = 6
/// The client challenge of the message did not match previous messages
case invalidClientChallengeFromRemote = 6
/// The key was accepted by the device, and the door will be opened
case messageAccepted = 7
/// An unexpected or unsupported message type was received
case invalidMessageTypeFromRemote = 7
/// A message is already being processed
case tooManyRequests = 8
/// The received message result was not ``messageAccepted``
case invalidMessageResultFromRemote = 9
/// The request did not contain body data with the key
case noBodyData = 10
/// An invalid Url parameter was set sending a message to the device over a local connection
case invalidUrlParameter = 10
// MARK: Server status
/// The body data posting a message was missing or of wrong length
case noOrInvalidBodyDataFromRemote = 21
/// The authentication token for the server was invalid
case invalidServerAuthenticationFromRemote = 22
/// The request took too long to complete
case deviceTimedOut = 23
/// The device is not connected to the server via web socket
case deviceNotConnected = 24
/// The device sent a response of invalid size
case invalidMessageSizeFromDevice = 25
/// The header with the authentication token was missing or invalid (not a hex string) from a server request.
case missingOrInvalidAuthenticationHeaderFromRemote = 26
/// The server produced an internal error (500)
case internalServerError = 27
// MARK: Remote status
/// The url string is not a valid url
case serverUrlInvalid = 31
/// The device key or auth token is missing for a request.
case noKeyAvailable = 32
/// The Sesame server behind the proxy could not be found (502)
case serviceBehindProxyUnavailable = 33
/// The server url could not be found (404)
case pathOnServerNotFound = 34
/// The url session request returned an unknown response
case unexpectedUrlResponseType = 35
/// The request to the server returned an unhandled HTTP code
case unexpectedServerResponseCode = 36
/// A valid server challenge was received
case deviceAvailable = 37
case invalidSignatureFromDevice = 38
case invalidMessageTypeFromDevice = 39
case unknownMessageResultFromDevice = 40
/// The device sent a message with an invalid client challenge
case invalidClientChallengeFromDevice = 41
/// The device used an invalid server challenge in a response
case invalidServerChallengeFromDevice = 42
/// The unlock process was successfully completed
case unlocked = 43
}
/// The device is not connected
case deviceNotConnected = 12
/// The device did not respond within the timeout
case deviceTimedOut = 13
/// Another message is being processed by the device
case operationInProgress = 14
/// The device is connected
case deviceConnected = 15
extension MessageResult: Error {
}
extension MessageResult: CustomStringConvertible {
var description: String {
switch self {
case .messageAccepted:
return "Message accepted"
case .textReceived:
return "The device received unexpected text"
case .unexpectedSocketEvent:
return "Unexpected socket event for the device"
case .invalidMessageData:
return "Invalid message data"
case .messageAuthenticationFailed:
case .invalidMessageSizeFromRemote:
return "Invalid message data from remote"
case .invalidSignatureFromRemote:
return "Message authentication failed"
case .messageTimeMismatch:
return "Message time invalid"
case .messageCounterInvalid:
return "Message counter invalid"
case .messageAccepted:
return "Message accepted"
case .noBodyData:
return "No body data included in the request"
case .deviceNotConnected:
return "Device not connected"
case .invalidServerChallengeFromRemote:
return "Server challenge mismatch"
case .invalidClientChallengeFromRemote:
return "Wrong client challenge sent"
case .invalidMessageTypeFromRemote:
return "Message type from remote invalid"
case .tooManyRequests:
return "Device busy"
case .invalidMessageResultFromRemote:
return "Invalid message result"
case .invalidUrlParameter:
return "The url parameter could not be found"
case .noOrInvalidBodyDataFromRemote:
return "Invalid body data in server request"
case .invalidServerAuthenticationFromRemote:
return "Invalid server token"
case .deviceTimedOut:
return "The device did not respond"
case .operationInProgress:
return "Another operation is in progress"
case .deviceConnected:
return "The device is connected"
case .deviceNotConnected:
return "Device not connected to server"
case .invalidMessageSizeFromDevice:
return "Invalid device message size"
case .missingOrInvalidAuthenticationHeaderFromRemote:
return "Invalid server token format"
case .internalServerError:
return "Internal server error"
case .serverUrlInvalid:
return "Invalid server url"
case .noKeyAvailable:
return "No key available"
case .serviceBehindProxyUnavailable:
return "Service behind proxy not found"
case .pathOnServerNotFound:
return "Invalid server path"
case .unexpectedUrlResponseType:
return "Unexpected URL response"
case .unexpectedServerResponseCode:
return "Unexpected server response code"
case .deviceAvailable:
return "Device available"
case .invalidSignatureFromDevice:
return "Invalid device signature"
case .invalidMessageTypeFromDevice:
return "Message type from device invalid"
case .unknownMessageResultFromDevice:
return "Unknown message result"
case .invalidClientChallengeFromDevice:
return "Device sent invalid client challenge"
case .invalidServerChallengeFromDevice:
return "Invalid"
case .unlocked:
return "Unlocked"
}
}
}
extension MessageResult: Codable {
}
extension MessageResult {
var encoded: Data {
Data([rawValue])
}
}
extension MessageResult {
init(httpCode: Int) {
switch httpCode {
case 200: self = .messageAccepted
case 204: self = .noOrInvalidBodyDataFromRemote
case 403: self = .invalidServerAuthenticationFromRemote
case 404: self = .pathOnServerNotFound
case 408: self = .deviceTimedOut
case 412: self = .deviceNotConnected
case 413: self = .invalidMessageSizeFromDevice
case 422: self = .missingOrInvalidAuthenticationHeaderFromRemote
case 429: self = .tooManyRequests
case 500: self = .internalServerError
case 501: self = .unexpectedServerResponseCode
case 502: self = .serviceBehindProxyUnavailable
default: self = .unexpectedServerResponseCode
}
}
var statusCode: Int {
switch self {
case .messageAccepted: return 200 // ok
case .noOrInvalidBodyDataFromRemote: return 204 // noContent
case .invalidServerAuthenticationFromRemote: return 403 // forbidden
case .pathOnServerNotFound: return 404 // notFound
case .deviceTimedOut: return 408 // requestTimeout
case .invalidMessageSizeFromRemote: return 411 // lengthRequired
case .deviceNotConnected: return 412 // preconditionFailed
case .invalidMessageSizeFromDevice: return 413 // payloadTooLarge
case .missingOrInvalidAuthenticationHeaderFromRemote: return 422 // unprocessableEntity
case .tooManyRequests: return 429 // tooManyRequests
case .internalServerError: return 500 // internalServerError
case .unexpectedServerResponseCode: return 501 // notImplemented
case .serviceBehindProxyUnavailable: return 502 // badGateway
default: return 501 // == unexpectedServerResponseCode
}
}
}

View File

@ -1,46 +0,0 @@
import Foundation
import NIOCore
#if canImport(CryptoKit)
import CryptoKit
#else
import Crypto
#endif
struct ServerMessage {
static let authTokenSize = SHA256.byteCount
static let length = authTokenSize + Message.length
let authToken: Data
let message: Message
/**
Decode a message from a byte buffer.
The buffer must contain at least `ServerMessage.length` bytes, or it will return `nil`.
- Parameter buffer: The buffer containing the bytes.
*/
init?(decodeFrom buffer: ByteBuffer) {
guard let data = buffer.getBytes(at: 0, length: ServerMessage.length) else {
return nil
}
self.authToken = Data(data.prefix(ServerMessage.authTokenSize))
self.message = Message(decodeFrom: Data(data.dropFirst(ServerMessage.authTokenSize)))
}
var encoded: Data {
authToken + message.encoded
}
static func token(from buffer: ByteBuffer) -> Data? {
guard buffer.readableBytes == authTokenSize else {
return nil
}
guard let bytes = buffer.getBytes(at: 0, length: authTokenSize) else {
return nil
}
return Data(bytes)
}
}

View File

@ -0,0 +1,14 @@
import Foundation
#if canImport(CryptoKit)
import CryptoKit
#else
import Crypto
#endif
enum SesameHeader {
static let authenticationHeader = "Authorization"
static let serverAuthenticationTokenSize = SHA256.byteCount
}

View File

@ -3,10 +3,7 @@ import Foundation
/**
The active urls on the server, for the device and the remote to connect
*/
enum RouteAPI: String {
/// Check the device status
case getDeviceStatus = "status"
enum SesameRoute: String {
/// Send a message to the server, to relay to the device
case postMessage = "message"

View File

@ -0,0 +1,15 @@
import Foundation
#if canImport(CryptoKit)
import CryptoKit
#else
import Crypto
#endif
extension SignedMessage {
/// The length of a message in bytes
static var size: Int {
SHA256.byteCount + Message.size
}
}

View File

@ -3,11 +3,71 @@ import Foundation
struct Config {
/// The port where the server runs
static let port = 6003
let port: Int
/// The name of the file in the `Resources` folder containing the device authentication token
static let keyFileName = "keys"
/**
The path to the file containing the containing the device authentication token.
If the path is relative, then it is relative to the `Resources` folder.
*/
let keyFileName: String
/// The seconds to wait for a response from the device
static let deviceTimeout: Int64 = 20
let deviceTimeout: Int64
/// The authentication tokens to use for monitoring of the service
let authenticationTokens: Set<String>
/**
The path to the folder where the metric logs are stored
If no path is provided, then a folder `logs` in the resources directory is created.
If the path is relative, then it is assumed relative to the resources directory.
*/
let logPath: String?
func logURL(possiblyRelativeTo resourcesDirectory: URL) -> URL {
guard let logPath else {
return resourcesDirectory.appendingPathComponent("logs")
}
return Config.url(logPath, possiblyRelativeTo: resourcesDirectory)
}
func keyURL(possiblyRelativeTo resourcesDirectory: URL) -> URL {
Config.url(keyFileName, possiblyRelativeTo: resourcesDirectory)
}
private static func url(_ name: String, possiblyRelativeTo resourcesDirectory: URL) -> URL {
guard !name.hasPrefix("/") else {
return .init(fileURLWithPath: name)
}
return resourcesDirectory.appendingPathComponent(name)
}
}
extension Config: Codable {
}
extension Config {
init(loadFrom url: URL) throws {
guard FileManager.default.fileExists(atPath: url.path) else {
printAndFlush("No configuration file found at \(url.path)")
fatalError("No configuration file found")
}
let data: Data
do {
data = try Data(contentsOf: url)
} catch {
printAndFlush("Failed to read config data: \(error)")
throw error
}
do {
self = try JSONDecoder().decode(Config.self, from: data)
} catch {
printAndFlush("Failed to decode config data: \(error)")
throw error
}
}
}

View File

@ -1,72 +1,157 @@
import Foundation
import WebSocketKit
import Vapor
import Clairvoyant
final class DeviceManager {
/// The connection to the device
private var connection: WebSocket?
/// The authentication token of the device for the socket connection
private let deviceKey: Data
/// The authentication token of the remote
private let remoteKey: Data
/// Indicate that the socket is fully initialized with an authorized device
var deviceIsAuthenticated = false
private var isOpeningNewConnection = false
/// Indicator for device availability
private let deviceTimeout: Int64
private let deviceConnectedMetric: Metric<Bool>
private let messagesToDeviceMetric: Metric<Int>
let serverStatus: Metric<ServerStatus>
var deviceIsConnected: Bool {
deviceIsAuthenticated && !(connection?.isClosed ?? true)
guard let connection, !connection.isClosed else {
return false
}
return true
}
/// A promise to finish the request once the device responds or times out
private var requestInProgress: EventLoopPromise<DeviceResponse>?
private var requestInProgress: CheckedContinuation<Data, Error>?
private var receivedMessageData: Data?
init(deviceKey: Data, remoteKey: Data) {
var logger: Logger?
private func printAndFlush(_ message: String) {
logger?.notice(.init(stringLiteral: message))
}
init(deviceKey: Data, remoteKey: Data, deviceTimeout: Int64, serverStatus: Metric<ServerStatus>) {
self.deviceKey = deviceKey
self.remoteKey = remoteKey
self.deviceTimeout = deviceTimeout
self.deviceConnectedMetric = .init(
"sesame.connected",
name: "Device connection",
description: "Shows if the device is connected via WebSocket")
self.messagesToDeviceMetric = .init(
"sesame.messages",
name: "Forwarded Messages",
description: "The number of messages transmitted to the device")
self.serverStatus = serverStatus
}
func updateDeviceConnectionMetrics() async {
let isConnected = deviceIsConnected
_ = try? await serverStatus.update(isConnected ? .nominal : .reducedFunctionality)
_ = try? await deviceConnectedMetric.update(isConnected)
}
private func updateMessageCountMetric() async {
let lastValue = await messagesToDeviceMetric.lastValue()?.value ?? 0
_ = try? await messagesToDeviceMetric.update(lastValue + 1)
}
// MARK: API
var deviceStatus: String {
deviceIsConnected ? "1" : "0"
func sendMessageToDevice(_ message: Data, authToken: Data, on eventLoop: EventLoop) async throws -> Data {
guard message.count == SignedMessage.size else {
throw MessageResult.invalidMessageSizeFromRemote
}
guard SHA256.hash(data: authToken) == remoteKey else {
throw MessageResult.invalidServerAuthenticationFromRemote
}
guard let socket = connection, !socket.isClosed else {
// Ensure that metric is updated
didCloseDeviceSocket()
throw MessageResult.deviceNotConnected
}
guard receivedMessageData == nil else {
throw MessageResult.tooManyRequests
}
// Indicate that a message is in transit
receivedMessageData = Data()
do {
try await socket.send(Array(message))
} catch {
throw MessageResult.deviceNotConnected
}
startTimeoutForDeviceRequest(on: eventLoop)
// Check if a full message has already been received
if let receivedMessageData, receivedMessageData.count == SignedMessage.size {
self.receivedMessageData = nil
return receivedMessageData
}
// Wait until a fill message is received, or a timeout occurs
let result: Data = try await withCheckedThrowingContinuation { continuation in
self.requestInProgress = continuation
}
await updateMessageCountMetric()
return result
}
func sendMessageToDevice(_ message: Message, on eventLoop: EventLoop) -> EventLoopFuture<DeviceResponse> {
guard let socket = connection, !socket.isClosed else {
connection = nil
return eventLoop.makeSucceededFuture(.deviceNotConnected)
}
guard requestInProgress == nil else {
return eventLoop.makeSucceededFuture(.operationInProgress)
}
requestInProgress = eventLoop.makePromise(of: DeviceResponse.self)
socket.send(message.bytes, promise: nil)
eventLoop.scheduleTask(in: .seconds(Config.deviceTimeout)) { [weak self] in
guard let promise = self?.requestInProgress else {
private func startTimeoutForDeviceRequest(on eventLoop: EventLoop) {
eventLoop.scheduleTask(in: .seconds(deviceTimeout)) { [weak self] in
guard let self else {
log("[WARN] No reference to self after timeout of message")
return
}
self?.requestInProgress = nil
promise.succeed(.deviceTimedOut)
self.resumeDeviceRequest(with: .deviceTimedOut)
}
return requestInProgress!.futureResult
}
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
private func resumeDeviceRequest(with data: Data) {
guard let receivedMessageData else {
log("[WARN] Received \(data.count) bytes after message completion")
self.requestInProgress = nil
return
}
print("Device authenticated")
deviceIsAuthenticated = true
let newData = receivedMessageData + data
if newData.count < SignedMessage.size {
// Wait for more data
self.receivedMessageData = newData
return
}
self.receivedMessageData = nil
guard let requestInProgress else {
log("[WARN] Received \(newData.count) bytes, but no continuation to resume")
return
}
self.requestInProgress = nil
guard newData.count == SignedMessage.size else {
log("[WARN] Received \(newData.count) bytes, expected \(SignedMessage.size) for a message.")
requestInProgress.resume(throwing: MessageResult.invalidMessageSizeFromDevice)
return
}
requestInProgress.resume(returning: newData)
}
private func resumeDeviceRequest(with result: MessageResult) {
guard let receivedMessageData else {
self.requestInProgress = nil
return
}
self.receivedMessageData = nil
guard let requestInProgress else {
log("[WARN] Request in progress (\(receivedMessageData.count) bytes), but no continuation found for result: \(result)")
return
}
self.requestInProgress = nil
requestInProgress.resume(throwing: result)
}
func authenticateRemote(_ token: Data) -> Bool {
@ -74,42 +159,69 @@ final class DeviceManager {
return hash == remoteKey
}
func processDeviceResponse(_ data: ByteBuffer) {
guard let promise = requestInProgress else {
func processDeviceResponse(_ buffer: ByteBuffer) {
guard let data = buffer.getData(at: 0, length: buffer.readableBytes) else {
log("[WARN] Failed to get data buffer received from device")
self.resumeDeviceRequest(with: .invalidMessageSizeFromDevice)
return
}
defer { requestInProgress = nil }
promise.succeed(DeviceResponse(data) ?? .unexpectedSocketEvent)
self.resumeDeviceRequest(with: data)
}
func didCloseDeviceSocket() {
guard !isOpeningNewConnection else {
return
}
deviceIsAuthenticated = false
guard connection != nil else {
print("Socket closed, but no connection anyway")
return
}
connection = nil
print("Socket closed")
Task {
await updateDeviceConnectionMetrics()
}
}
func removeDeviceConnection() {
deviceIsAuthenticated = false
guard let socket = connection else {
return
}
try? socket.close().wait()
func removeDeviceConnection() async {
try? await connection?.close()
connection = nil
print("Removed device connection")
await updateDeviceConnectionMetrics()
}
func createNewDeviceConnection(_ socket: WebSocket) {
isOpeningNewConnection = true
removeDeviceConnection()
func createNewDeviceConnection(socket: WebSocket, auth: String) async {
guard let key = Data(fromHexEncodedString: auth),
SHA256.hash(data: key) == self.deviceKey else {
log("[WARN] Invalid device key while opening socket")
try? await socket.close()
return
}
await removeDeviceConnection()
connection = socket
print("Socket connected")
isOpeningNewConnection = false
socket.eventLoop.execute {
socket.pingInterval = .seconds(10)
socket.onText { [weak self] socket, text in
self?.printAndFlush("[WARN] Received text over socket: \(text)")
// Close connection to prevent spamming the log
try? await socket.close()
guard let self else {
log("[WARN] No reference to self to handle text over socket")
return
}
self.didCloseDeviceSocket()
}
socket.onBinary { [weak self] _, data in
guard let self else {
log("[WARN] No reference to self to process binary data on socket")
return
}
self.processDeviceResponse(data)
}
socket.onClose.whenComplete { [weak self] _ in
guard let self else {
log("[WARN] No reference to self to handle socket closing")
return
}
self.didCloseDeviceSocket()
}
}
await updateDeviceConnectionMetrics()
}
}

View File

@ -0,0 +1,10 @@
import Foundation
import Vapor
import Clairvoyant
extension MultiThreadedEventLoopGroup: AsyncScheduler {
public func schedule(asyncJob: @escaping @Sendable () async throws -> Void) {
_ = any().makeFutureWithTask(asyncJob)
}
}

16
Sources/App/Print.swift Normal file
View File

@ -0,0 +1,16 @@
import Foundation
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
func printAndFlush(_ message: String) {
print(message)
flushStdout()
}
func flushStdout() {
fflush(stdout)
}

View File

@ -1,43 +1,94 @@
import Vapor
import Clairvoyant
import ClairvoyantVapor
import ClairvoyantBinaryCodable
var deviceManager: DeviceManager!
enum ServerError: Error {
case invalidAuthenticationFileContent
case invalidAuthenticationToken
}
private var provider: VaporMetricProvider!
private var asyncScheduler = MultiThreadedEventLoopGroup(numberOfThreads: 2)
private let df: DateFormatter = {
let df = DateFormatter()
df.dateStyle = .short
df.timeStyle = .short
return df
}()
// configures your application
public func configure(_ app: Application) throws {
app.http.server.configuration.port = Config.port
public func configure(_ app: Application) async throws {
let storageFolder = URL(fileURLWithPath: app.directory.resourcesDirectory)
let keyFile = storageFolder.appendingPathComponent(Config.keyFileName)
let authContent: [Data] = try String(contentsOf: keyFile)
let configUrl = storageFolder.appendingPathComponent("config.json")
let config = try Config(loadFrom: configUrl)
let logFolder = config.logURL(possiblyRelativeTo: storageFolder)
let monitor = MetricObserver(logFileFolder: logFolder, logMetricId: "sesame.log")
MetricObserver.standard = monitor
let status = Metric<ServerStatus>("sesame.status")
try await status.update(.initializing)
app.http.server.configuration.port = config.port
let keyFile = config.keyURL(possiblyRelativeTo: storageFolder)
let (deviceKey, remoteKey) = try loadKeys(at: keyFile)
deviceManager = DeviceManager(deviceKey: deviceKey, remoteKey: remoteKey, deviceTimeout: config.deviceTimeout, serverStatus: status)
deviceManager.logger = app.logger
routes(app)
provider = .init(observer: monitor, accessManager: config.authenticationTokens)
provider.asyncScheduler = asyncScheduler
provider.registerRoutes(app)
monitor.saveCurrentListOfMetricsToLogFolder()
// Update the metric of the device and server status
await deviceManager.updateDeviceConnectionMetrics()
log("[\(df.string(from: Date()))] Server started")
}
public func shutdown() async {
// Gracefully shut down by closing potentially open socket
await deviceManager.removeDeviceConnection()
do {
try await asyncScheduler.shutdownGracefully()
} catch {
printAndFlush("Failed to shut down MultiThreadedEventLoopGroup: \(error)")
}
printAndFlush("[\(df.string(from: Date()))] Server shutdown")
}
private func loadKeys(at url: URL) throws -> (deviceKey: Data, remoteKey: Data) {
let authContent: [Data] = try String(contentsOf: url)
.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.map {
guard let key = Data(fromHexEncodedString: $0) else {
throw ServerError.invalidAuthenticationToken
fatalError("Invalid key data: Failed to convert hex to binary.")
}
guard key.count == SHA256.byteCount else {
throw ServerError.invalidAuthenticationToken
fatalError("Invalid key data: Length should be \(SHA256.byteCount), not \(key.count)")
}
return key
}
guard authContent.count == 2 else {
throw ServerError.invalidAuthenticationFileContent
fatalError("Invalid keys: Expected 2, found \(authContent.count)")
}
let deviceKey = authContent[0]
let remoteKey = authContent[1]
deviceManager = DeviceManager(deviceKey: deviceKey, remoteKey: remoteKey)
try routes(app)
// Gracefully shut down by closing potentially open socket
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + .seconds(5)) {
_ = app.server.onShutdown.always { _ in
deviceManager.removeDeviceConnection()
}
return (deviceKey: authContent[0], remoteKey: authContent[1])
}
func log(_ message: String) {
guard let observer = MetricObserver.standard else {
printAndFlush(message)
return
}
asyncScheduler.schedule {
await observer.log(message)
flushStdout()
}
}

View File

@ -0,0 +1,50 @@
import Vapor
import Dispatch
import Logging
/// This extension is temporary and can be removed once Vapor gets this support.
private extension Vapor.Application {
static let baseExecutionQueue = DispatchQueue(label: "vapor.codes.entrypoint")
func runFromAsyncMainEntrypoint() async throws {
try await withCheckedThrowingContinuation { continuation in
Vapor.Application.baseExecutionQueue.async { [self] in
do {
try self.run()
continuation.resume()
} catch {
continuation.resume(throwing: error)
}
}
}
}
}
@main
enum Entrypoint {
static func main() async throws {
var env = try Environment.detect()
try LoggingSystem.bootstrap(from: &env)
let app = Application(env)
func cleanup() async {
await shutdown()
app.shutdown()
}
do {
try await configure(app)
} catch {
app.logger.report(error: error)
await cleanup()
throw error
}
do {
try await app.runFromAsyncMainEntrypoint()
await cleanup()
} catch {
await cleanup()
throw error
}
}
}

View File

@ -1,91 +1,48 @@
import Vapor
extension RouteAPI {
var path: PathComponent {
.init(stringLiteral: rawValue)
}
var pathParameter: PathComponent {
.parameter(rawValue)
}
}
private func messageTransmission(_ req: Request) -> EventLoopFuture<DeviceResponse> {
guard let body = req.body.data else {
return req.eventLoop.makeSucceededFuture(.noBodyData)
}
guard let message = ServerMessage(decodeFrom: body) else {
return req.eventLoop.makeSucceededFuture(.invalidMessageData)
}
guard deviceManager.authenticateRemote(message.authToken) else {
return req.eventLoop.makeSucceededFuture(.invalidMessageData)
}
return deviceManager.sendMessageToDevice(message.message, on: req.eventLoop)
}
private func deviceStatus(_ req: Request) -> EventLoopFuture<DeviceResponse> {
guard let body = req.body.data else {
return req.eventLoop.makeSucceededFuture(.noBodyData)
}
guard let authToken = ServerMessage.token(from: body) else {
return req.eventLoop.makeSucceededFuture(.invalidMessageData)
}
guard deviceManager.authenticateRemote(authToken) else {
return req.eventLoop.makeSucceededFuture(.invalidMessageData)
}
guard deviceManager.deviceIsConnected else {
return req.eventLoop.makeSucceededFuture(.deviceNotConnected)
}
return req.eventLoop.makeSucceededFuture(.deviceConnected)
}
func routes(_ app: Application) throws {
/**
Get the connection status of the device.
The request expects the authentication token of the remote in the body data of the POST request.
The request returns one byte of data, which is the raw value of a `MessageResult`.
Possible results are `noBodyData`, `invalidMessageData`, `deviceNotConnected`, `deviceConnected`.
*/
app.post(RouteAPI.getDeviceStatus.path) { req in
deviceStatus(req).map {
Response(status: .ok, body: .init(data: $0.encoded))
}
}
func routes(_ app: Application) {
/**
Post a message to the device for unlocking.
The expects a `ServerMessage` in the body data of the POST request, containing the valid remote authentication token and the message to send to the device.
The expects a `Message` in the body data of the POST request, containing the message to send to the device.
Expects a header ``RouteAPI.authenticationHeader`` with the hexencoded authentication token with binary length ``ServerMessage.authTokenSize``.
The request returns one or `Message.length+1` bytes of data, where the first byte is the raw value of a `MessageResult`,
and the optional following bytes contain the response message of the device. This request does not complete until either the device responds or the request times out. The timeout is specified by `KeyManagement.deviceTimeout`.
The request returns the ``ServerMessage.messageSize`` bytes of data constituting the device response,
or a status code corresponding to a ``MessageResult``.
This request does not complete until either the device responds or the request times out.
The timeout is specified by the configuration parameter `deviceTimeout`.
*/
app.post(RouteAPI.postMessage.path) { req in
messageTransmission(req).map {
Response(status: .ok, body: .init(data: $0.encoded))
app.post(SesameRoute.postMessage.path) { request async throws in
do {
guard let authString = request.headers.first(name: SesameHeader.authenticationHeader),
let authToken = Data(fromHexEncodedString: authString),
authToken.count == SesameHeader.serverAuthenticationTokenSize else {
throw MessageResult.missingOrInvalidAuthenticationHeaderFromRemote
}
guard let body = request.body.data,
let message = body.getData(at: 0, length: body.readableBytes) else {
throw MessageResult.noOrInvalidBodyDataFromRemote
}
let responseMessage = try await deviceManager.sendMessageToDevice(message, authToken: authToken, on: request.eventLoop)
return Response(status: .ok, body: .init(data: responseMessage))
} catch let error as MessageResult {
return Response(status: .init(statusCode: error.statusCode))
}
}
/**
Start a new websocket connection for the device to receive messages from the server
- Returns: Nothing
- Note: The first message from the device over the connection must be a valid auth token.
Start a new websocket connection for the device to receive messages from the server.
The request must contain a header ``RouteAPI.socketAuthenticationHeader`` with a valid authentication token.
*/
app.webSocket(RouteAPI.socket.path) { req, socket in
socket.onBinary { _, data in
deviceManager.processDeviceResponse(data)
app.webSocket(SesameRoute.socket.path) { request, socket async in
guard let authToken = request.headers.first(name: SesameHeader.authenticationHeader) else {
try? await socket.close()
return
}
socket.onText { _, text in
deviceManager.authenticateDevice(hash: text)
}
_ = socket.onClose.always { _ in
deviceManager.didCloseDeviceSocket()
}
deviceManager.createNewDeviceConnection(socket)
await deviceManager.createNewDeviceConnection(socket: socket, auth: authToken)
}
}

View File

@ -1,9 +0,0 @@
import App
import Vapor
var env = try Environment.detect()
try LoggingSystem.bootstrap(from: &env)
let app = Application(env)
defer { app.shutdown() }
try configure(app)
try app.run()

View File

@ -1,53 +0,0 @@
@testable import App
import XCTVapor
final class AppTests: XCTestCase {
func testEncodingUInt32() {
let input: UInt32 = 123
let data = input.encoded
let output = UInt32(data: data)
XCTAssertEqual(input, output)
}
func testEncodingContent() {
let input = Message.Content(time: 1234567890, id: 23456789)
let data = Array(input.encoded)
let output = Message.Content(decodeFrom: data)
XCTAssertEqual(input, output)
let data2 = [42, 42] + data
let output2 = Message.Content(decodeFrom: data2[2...])
XCTAssertEqual(input, output2)
}
func testEncodingMessage() {
let input = Message(mac: Data(repeating: 42, count: 32),
content: Message.Content(time: 1234567890, id: 23456789))
let data = input.encoded
let buffer = ByteBuffer(data: data)
let output = Message(decodeFrom: buffer)
XCTAssertEqual(input, output)
}
func testSigning() throws {
let key = SymmetricKey(size: .bits256)
let content = Message.Content(time: 1234567890, id: 23456789)
let input = content.authenticate(using: key)
XCTAssertTrue(input.isValid(using: key))
let data = content.authenticateAndSerialize(using: key)
let decoded = Message(decodeFrom: ByteBuffer(data: data))
XCTAssertNotNil(decoded)
XCTAssertTrue(decoded!.isValid(using: key))
XCTAssertEqual(decoded!, input)
XCTAssertEqual(content, input.content)
}
func testMessageTransmission() throws {
let app = Application(.testing)
defer { app.shutdown() }
try configure(app)
// How to open a socket via request?
}
}