Files
ezServer-MacOS/Sources/EzServerMac/WebConsoleAPI.swift
T

236 lines
11 KiB
Swift

import CommonCrypto
import CryptoKit
import Foundation
// Runs on LocalServer's serial request queue.
final class WebConsoleAPI {
struct Reply {
let status: String
let body: [String: Any]
init(_ values: [String: Any] = [:], status: String = "200 OK", errorCode: Int = 0) {
self.status = status
body = values.merging(["errorCode": errorCode]) { _, code in code }
}
}
private static let admin = "Master Admin"
private static let wireKey = Data(base64Encoded: "fCVpkpDy3QII1bJ0uklkvQ==")!
private static let wireIV = Data(base64Encoded: "p+O8XWH7eWQw1xifYtxx5Q==")!
private let passwordDigest = SHA256.hash(data: Data(
(ProcessInfo.processInfo.environment["EZSERVER_CONSOLE_PASSWORD"] ?? "0000").utf8
))
private var sessions: [String: Date] = [:]
private var events: [[String: Any]] = []
private var failures = 0
private var lockedUntil = Date.distantPast
func handles(_ path: [String], method: String) -> Bool {
guard path.count >= 2 else { return false }
switch (path[0], path[1], method) {
case ("auth", "apploginr2", "POST"),
("e2ds", "useraccountsbynamer2", "GET"),
("e2ds", "useraccountsfornames", "GET"),
("analytics", "eventsforsearch", "POST"),
("analytics", "eventsr2", "POST"),
("settings", "fileserversettings", "GET"),
("settings", "dbserversettings", "GET"),
("settings", "checkvaliddbconnection", "POST"),
("settings", "dirsforaccessible", "POST"),
("settings", "settingvaluesp2", "GET"),
("settings", "settingvalues", "GET"),
("e2ds", "patientsocialids", "GET"),
("settings", "fileserversettings", "PUT"),
("settings", "dbserversettings", "PUT"),
("settings", "settingvalues", "POST"),
("e2ds", "patientsocialids", "PUT"):
return true
default:
return false
}
}
func reply(path: [String], method: String, body: Data, authorization: String?, store: ServerStore) -> Reply {
if path == ["auth", "apploginr2"] {
return login(body)
}
let now = Date()
guard let authorization, authorization.hasPrefix("Bearer "),
let expires = sessions[String(authorization.dropFirst(7))], expires > now else {
return Reply(["errorMessage": "Auth token has expired"], status: "401 Unauthorized", errorCode: -8001511)
}
let input = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
switch (path[0], path[1], method) {
case ("e2ds", "useraccountsbynamer2", "GET"):
guard path == ["e2ds", "useraccountsbynamer2", "name", Self.admin.lowercased()] else {
return Reply(status: "404 Not Found", errorCode: -100037)
}
return Reply(["accountInfo": ["strAccountName": Self.admin, "strGrade": "M"]])
case ("e2ds", "useraccountsfornames", "GET"):
return Reply(["strlUserName": [Self.admin]])
case ("settings", "fileserversettings", "GET"):
return Reply(["FileServerSettings": ["dataFilePath": store.files.path, "subDataFilePath": "",
"linkFilePath": "", "ioSensorFilePath": "",
"useFileManagerSettings": false]])
case ("settings", "dbserversettings", "GET"):
return Reply(["DBServerSettings": ["hostname": "SQLite", "port": 0]])
case ("settings", "checkvaliddbconnection", "POST"):
return Reply(["ValidDBConnection": false])
case ("settings", "dirsforaccessible", "POST"):
let dirs = (input["dirs"] as? [[String: Any]] ?? []).map { item -> [String: Any] in
var checked = item
checked["errorCode"] = (item["dir"] as? String) == store.files.path ? 0 : -1002
return checked
}
return Reply(["dirs": dirs])
case ("settings", "settingvalues", "GET"):
guard path == ["settings", "settingvalues", "section", "passwordpolicy"] else {
return Reply(["data": []], errorCode: -100037)
}
do {
let policy = try store.passwordPolicy()
return Reply(["data": policy.sorted { $0.key < $1.key }.map {
["section": "PasswordPolicy", "key": $0.key, "value": $0.value]
}])
} catch {
return Reply(status: "503 Service Unavailable", errorCode: -1005)
}
case ("settings", "settingvalues", "POST") where path.count == 2:
guard let rows = input["data"] as? [[String: String]], (1...8).contains(rows.count) else {
return Reply(status: "400 Bad Request", errorCode: -1021)
}
var changes: [String: String] = [:]
for row in rows {
guard row["section"] == "PasswordPolicy", let key = row["key"],
let value = row["value"], changes[key] == nil else {
return Reply(status: "400 Bad Request", errorCode: -1021)
}
changes[key] = value
}
do {
try store.updatePasswordPolicy(changes)
event(type: "SETTINGS", message: "Updated password policy.")
return Reply()
} catch StoreError.invalid {
return Reply(status: "400 Bad Request", errorCode: -1021)
} catch {
return Reply(status: "503 Service Unavailable", errorCode: -1005)
}
case ("settings", "settingvaluesp2", "GET"):
guard path == ["settings", "settingvaluesp2", "section", "protectpatientsocialids", "key", "isenabled"] else {
return Reply(["data": []], errorCode: -100037)
}
return Reply(["data": [["section": "ProtectPatientSocialIDs", "key": "isEnabled", "value": "false"]]])
case ("e2ds", "patientsocialids", "GET"):
return Reply(["protectedSocialIDs": 0, "unprotectedSocialIDs": 0])
case ("analytics", "eventsforsearch", "POST"):
return search(input)
case ("analytics", "eventsr2", "POST"):
guard input["eventType"] as? String == "LOGOUT" else {
return Reply(status: "400 Bad Request", errorCode: -1021)
}
sessions.removeValue(forKey: String(authorization.dropFirst(7)))
event(type: "LOGOUT", message: "Logged out of EzServer Web Console.")
return Reply()
case ("settings", "fileserversettings", "PUT"):
return Reply(["errorMessage": "Change the images folder in the EzServer menu."],
status: "409 Conflict", errorCode: -1017)
default:
return Reply(["errorMessage": "This setting is unavailable for the local SQLite server."],
status: "409 Conflict", errorCode: -1017)
}
}
private func login(_ body: Data) -> Reply {
let now = Date()
guard now >= lockedUntil else {
return Reply(["errorMessage": "Too many attempts. Try again in one minute.",
"accountLockoutThreshold": 8, "failedLoginCount": failures],
status: "429 Too Many Requests", errorCode: -8001001)
}
guard let request = try? JSONDecoder().decode(LoginRequest.self, from: body),
let login = Self.decrypt(request.data),
login.auth.enc == "raw", login.auth.usr == Self.admin,
login.auth.exp >= now.timeIntervalSince1970,
zip(SHA256.hash(data: Data(login.auth.sec.utf8)), passwordDigest)
.reduce(UInt8(0), { $0 | ($1.0 ^ $1.1) }) == 0 else {
failures += 1
if failures >= 8 {
lockedUntil = now.addingTimeInterval(60)
failures = 0
}
return Reply(["errorMessage": "Invalid user name or password",
"accountLockoutThreshold": 8, "failedLoginCount": failures],
status: "401 Unauthorized", errorCode: -8001001)
}
failures = 0
sessions = sessions.filter { $0.value > now }
if sessions.count >= 32, let oldest = sessions.min(by: { $0.value < $1.value }) {
sessions.removeValue(forKey: oldest.key)
}
let token = UUID().uuidString + UUID().uuidString
sessions[token] = now.addingTimeInterval(600)
event(type: "LOGIN", message: "Logged in to EzServer Web Console.")
return Reply(["token": token])
}
private func event(type: String, message: String) {
events.append(["id": UUID().uuidString, "eventType": String(type.prefix(100)),
"appName": "EzServer Web Console", "userName": Self.admin,
"message": String(message.prefix(512)), "created": ISO8601DateFormatter().string(from: Date())])
if events.count > 250 { events.removeFirst() }
}
private func search(_ input: [String: Any]) -> Reply {
let from = input["startDate"] as? String ?? ""
let through = input["endDate"] as? String ?? ""
let user = input["userName"] as? String ?? ""
let type = input["eventType"] as? String ?? ""
let matches = events.reversed().filter { item in
let day = (item["created"] as? String ?? "").prefix(10)
return (from.isEmpty || day >= from.prefix(10)) && (through.isEmpty || day <= through.prefix(10))
&& (user.isEmpty || item["userName"] as? String == user)
&& (type.isEmpty || item["eventType"] as? String == type)
}
let size = min(100, max(1, input["numRows"] as? Int ?? 20))
let page = min(matches.count, max(0, input["pageNum"] as? Int ?? 0))
return Reply(["numTotalEvents": matches.count, "pagedEvents": Array(matches.dropFirst(page * size).prefix(size))])
}
private struct LoginRequest: Decodable { let data: String }
private struct Login: Decodable {
struct Auth: Decodable {
let enc: String
let usr: String
let sec: String
let exp: Double
}
let auth: Auth
}
private static func decrypt(_ encoded: String) -> Login? {
// The original Web Console uses AES-CBC with ISO/IEC 9797-1 method 2 padding.
guard let ciphertext = Data(base64Encoded: encoded), !ciphertext.isEmpty,
ciphertext.count.isMultiple(of: kCCBlockSizeAES128) else { return nil }
var output = Data(count: ciphertext.count)
let capacity = output.count
var length = 0
let result = output.withUnsafeMutableBytes { plain in
ciphertext.withUnsafeBytes { cipher in
wireKey.withUnsafeBytes { key in
wireIV.withUnsafeBytes { iv in
CCCrypt(CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES), 0,
key.baseAddress, wireKey.count, iv.baseAddress,
cipher.baseAddress, ciphertext.count, plain.baseAddress, capacity, &length)
}
}
}
}
guard result == kCCSuccess, length == ciphertext.count,
let marker = output.lastIndex(where: { $0 != 0 }), output[marker] == 0x80,
output.count - marker <= kCCBlockSizeAES128 else { return nil }
return try? JSONDecoder().decode(Login.self, from: output.prefix(upTo: marker))
}
}