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

300 lines
14 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 let signingKey = SymmetricKey(size: .bits256)
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"),
("auth", "applogin", "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 allowsNetworkAccess(_ path: [String], method: String) -> Bool {
switch (path, method) {
case (["auth", "apploginr2"], "POST"), (["auth", "applogin"], "POST"),
(["e2ds", "useraccountsbynamer2", "name", Self.admin.lowercased()], "GET"):
return true
default:
return false
}
}
func reply(path: [String], method: String, body: Data, authorization: String?, store: ServerStore) -> Reply {
if path == ["auth", "apploginr2"] || path == ["auth", "applogin"] {
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.decoded(login.auth.usr) == Self.admin,
login.auth.exp >= now.timeIntervalSince1970,
login.auth.exp < Double(Int32.max),
let password = login.auth.decoded(login.auth.sec),
zip(SHA256.hash(data: Data(password.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 expiry = Int(login.auth.exp)
guard let token = try? makeToken(login, issuedAt: Int(now.timeIntervalSince1970), expiry: expiry) else {
return Reply(status: "503 Service Unavailable", errorCode: -1005)
}
sessions[token] = Date(timeIntervalSince1970: Double(expiry))
event(type: "LOGIN", message: "Logged in to EzServer Web Console.")
return Reply(["token": token])
}
private func makeToken(_ login: Login, issuedAt: Int, expiry: Int) throws -> String {
func base64URL(_ bytes: Data) -> String {
bytes.base64EncodedString().replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
}
let header = try JSONSerialization.data(withJSONObject: ["typ": "JWT", "alg": "HS256"],
options: .sortedKeys)
let payload = try JSONSerialization.data(withJSONObject: [
"enc": login.auth.enc,
"iss": login.auth.usr,
"aud": "http://www.ewoosoft.com",
"iat": issuedAt,
"exp": expiry,
"clientName": login.client?.name ?? "Legacy",
"clientVersion": login.client?.ver ?? "0.0.0",
], options: .sortedKeys)
let message = base64URL(header) + "." + base64URL(payload)
let signature = HMAC<SHA256>.authenticationCode(for: Data(message.utf8), using: signingKey)
return message + "." + base64URL(Data(signature))
}
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
func decoded(_ value: String) -> String? {
switch enc {
case "raw":
return value
case "b64":
return Data(base64Encoded: value).flatMap { String(data: $0, encoding: .utf8) }
case "hex":
let digits = Array(value.utf8)
guard digits.count.isMultiple(of: 2) else { return nil }
var bytes: [UInt8] = []
for index in stride(from: 0, to: digits.count, by: 2) {
guard let byte = UInt8(String(decoding: digits[index...index + 1], as: UTF8.self), radix: 16)
else { return nil }
bytes.append(byte)
}
return String(bytes: bytes, encoding: .utf8)
default:
return nil
}
}
}
struct Client: Decodable {
let name: String
let ver: String
}
let auth: Auth
let client: Client?
}
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))
}
}