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

365 lines
18 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 static let applicationFingerprint = Data(base64Encoded: "7dH5qqbP4LiANpOsC28VFALLLHuZyhWZjON7NKoO7T8=")!
private struct Session {
let expiry: Date
let administrator: Bool
}
private let signingKey = SymmetricKey(size: .bits256)
private var sessions: [String: Session] = [:]
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"),
("e2ds", "patientsbychartno", "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
case (let route, "GET") where route.starts(with: ["e2ds", "patientsbychartno"]):
return true
default:
return false
}
}
func reply(path: [String], method: String, body: Data, authorization: String?, query: [URLQueryItem], store: ServerStore) -> Reply {
if path == ["auth", "apploginr2"] || path == ["auth", "applogin"] {
return login(body)
}
let now = Date()
guard let authorization, authorization.hasPrefix("Bearer "),
let session = sessions[String(authorization.dropFirst(7))], session.expiry > now else {
return Reply(["errorMessage": "Auth token has expired"], status: "401 Unauthorized", errorCode: -8001511)
}
guard session.administrator else {
return Reply(["errorMessage": "Administrator login required"],
status: "403 Forbidden", errorCode: -1013)
}
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", "patientsbychartno", "GET"):
let argument = query.first(where: { $0.name == "chartno" })?.value
// CodeIgniter receives an already decoded query value and the controller calls urldecode again.
let chartNumber = argument
.map { $0.replacingOccurrences(of: "+", with: " ") }
.flatMap { $0.removingPercentEncoding ?? $0 } ?? ""
do {
guard !chartNumber.isEmpty, let patient = try store.patient(chartNumber: chartNumber) else {
return Reply(["patientInfo": []], errorCode: -100037)
}
// Imported Mac records store one display name without separate family / given names.
let emptyFields = ["strFirstName", "strMiddleName", "strGender", "strAge", "dtBirthdate",
"strEmail", "strSocialID", "strPhone", "strPhotoIDName", "dtRegisteredDateTime",
"strZipCode", "strAddress", "strMobile", "strRace", "strClassification", "strJob"]
var info: [String: Any] = Dictionary(uniqueKeysWithValues: emptyFields.map { ($0, "") })
info["strChartNo"] = patient.chartNumber
info["strLastName"] = patient.name
info["strlDoctor"] = [String]()
info["eSourceType"] = "eUnknownSourceType"
return Reply(["patientInfo": info])
} catch {
return Reply(status: "503 Service Unavailable", errorCode: -1005)
}
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.exp >= now.timeIntervalSince1970,
login.auth.exp < Double(Int32.max),
let administrator = role(for: login.auth) 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.expiry > now }
if sessions.count >= 32, let oldest = sessions.min(by: { $0.value.expiry < $1.value.expiry }) {
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] = Session(expiry: Date(timeIntervalSince1970: Double(expiry)), administrator: administrator)
if administrator {
event(type: "LOGIN", message: "Logged in to EzServer Web Console.")
}
return Reply(["token": token])
}
private func role(for auth: Login.Auth) -> Bool? {
guard let username = auth.decoded(auth.usr), let password = auth.decoded(auth.sec) else { return nil }
if username == Data(Self.admin.utf8) {
return Self.matches(SHA256.hash(data: password), passwordDigest) ? true : nil
}
// The bundled client uses the original temporary application account before user login.
let fingerprint = SHA256.hash(data: username + Data([0]) + password)
return Self.matches(fingerprint, Self.applicationFingerprint) ? false : nil
}
private static func matches<A: Sequence, B: Sequence>(_ lhs: A, _ rhs: B) -> Bool
where A.Element == UInt8, B.Element == UInt8 {
zip(lhs, rhs).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0
}
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
private enum CodingKeys: String, CodingKey { case enc, usr, sec, exp }
init(from decoder: Decoder) throws {
let fields = try decoder.container(keyedBy: CodingKeys.self)
enc = try fields.decode(String.self, forKey: .enc)
usr = try fields.decode(String.self, forKey: .usr)
sec = try fields.decode(String.self, forKey: .sec)
if let numeric = try? fields.decode(Double.self, forKey: .exp) {
exp = numeric
} else {
exp = Double(try fields.decode(String.self, forKey: .exp)) ?? 0
}
}
func decoded(_ value: String) -> Data? {
switch enc {
case "raw":
return Data(value.utf8)
case "b64":
return Data(base64Encoded: value)
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 Data(bytes)
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))
}
}