// SPDX-License-Identifier: MPL-2.0 using System.Collections.Concurrent; using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.Json; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenGenesisLINK.Addons.OSWebInterface; internal sealed class AdminHttpServer : IDisposable { private sealed record Session(UUID Principal, string Name, string Csrf, DateTimeOffset Expires); private sealed class Attempt { public int Count; public DateTimeOffset Reset = DateTimeOffset.UtcNow.AddMinutes(5); } private sealed record LoginRequest(string Username, string Password); private sealed record RegionRequest(string RegionId); private sealed record UpdateRequest(string Sha); private sealed record ImportRequest(string RegionId); private static readonly ILog Log = LogManager.GetLogger(typeof(AdminHttpServer)); private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); private readonly ConcurrentDictionary _scenes; private readonly ConcurrentDictionary _sessions = new(); private readonly ConcurrentDictionary _attempts = new(); private readonly HttpListener _listener = new(); private readonly CancellationTokenSource _stop = new(); private readonly AdminOperations _operations; private readonly LiveUpdateBridge _liveUpdate; private readonly Uri? _publicOrigin; private readonly string _loopbackHost; private Task? _acceptTask; private readonly DateTimeOffset _started = DateTimeOffset.UtcNow; public AdminHttpServer(ConcurrentDictionary scenes, string storage, int port, int retention, List<(string Name, Uri Uri)> services, LiveUpdateBridge liveUpdate, string publicOrigin) { _loopbackHost = $"127.0.0.1:{port}"; if (!string.IsNullOrWhiteSpace(publicOrigin)) { if (!Uri.TryCreate(publicOrigin, UriKind.Absolute, out Uri? parsed) || parsed.Scheme != Uri.UriSchemeHttps || parsed.AbsolutePath != "/" || parsed.Query.Length != 0 || parsed.Fragment.Length != 0 || parsed.UserInfo.Length != 0) throw new ArgumentException("PublicOrigin muss eine HTTPS-Origin ohne Pfad sein."); _publicOrigin = parsed; } _scenes = scenes; _operations = new AdminOperations(scenes, storage, retention, services); _liveUpdate = liveUpdate; // Binding to any public interface is deliberately unsupported. _listener.Prefixes.Add($"http://127.0.0.1:{port}/"); } public void Start() { _listener.Start(); _acceptTask = Task.Run(AcceptLoopAsync); } private async Task AcceptLoopAsync() { while (!_stop.IsCancellationRequested) { HttpListenerContext context; try { context = await _listener.GetContextAsync(); } catch (Exception e) when (e is HttpListenerException or ObjectDisposedException) { break; } _ = Task.Run(() => DispatchAsync(context)); } } private static string Token() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant(); private static async Task ReadJsonAsync(HttpListenerRequest req) where T : class { if (req.ContentLength64 > 16384 || req.ContentType is null || !req.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) return null; using var buffer = new MemoryStream(); byte[] block = new byte[4096]; int count; while ((count = await req.InputStream.ReadAsync(block)) > 0) { if (buffer.Length + count > 16384) return null; buffer.Write(block, 0, count); } try { return JsonSerializer.Deserialize(buffer.ToArray(), JsonOptions); } catch (JsonException) { return null; } } private static async Task SendAsync(HttpListenerResponse response, int code, object data) { response.StatusCode = code; response.ContentType = "application/json; charset=utf-8"; byte[] payload = JsonSerializer.SerializeToUtf8Bytes(data, JsonOptions); response.ContentLength64 = payload.Length; await response.OutputStream.WriteAsync(payload); } private static void SecurityHeaders(HttpListenerResponse r) { r.Headers["X-Content-Type-Options"] = "nosniff"; r.Headers["Referrer-Policy"] = "no-referrer"; r.Headers["X-Frame-Options"] = "DENY"; r.Headers["Cache-Control"] = "no-store, private"; r.Headers["Content-Security-Policy"] = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"; } private bool IsTrustedProxyRequest(HttpListenerRequest request) => _publicOrigin is not null && IPAddress.IsLoopback(request.RemoteEndPoint?.Address ?? IPAddress.None) && string.Equals(request.Headers["Host"], _loopbackHost, StringComparison.OrdinalIgnoreCase) && string.Equals(request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase) && string.Equals(request.Headers["X-Forwarded-Host"], _publicOrigin.Authority, StringComparison.OrdinalIgnoreCase); private bool SameOrigin(HttpListenerRequest request) { // Reverse proxy must send Host: 127.0.0.1:PORT to satisfy the listener // and replace X-Forwarded-Host/Proto with a configured HTTPS origin. string origin = request.Headers["Origin"] ?? ""; if (!string.IsNullOrEmpty(origin)) { if (!Uri.TryCreate(origin, UriKind.Absolute, out Uri? parsed)) return false; bool local = parsed.Scheme == Uri.UriSchemeHttp && string.Equals(parsed.Authority, _loopbackHost, StringComparison.OrdinalIgnoreCase); bool proxy = IsTrustedProxyRequest(request) && string.Equals(parsed.GetLeftPart(UriPartial.Authority), _publicOrigin!.GetLeftPart(UriPartial.Authority), StringComparison.OrdinalIgnoreCase); return local || proxy; } string fetchSite = request.Headers["Sec-Fetch-Site"] ?? ""; return fetchSite is "" or "same-origin" or "none"; } private bool TrySession(HttpListenerRequest request, out Session? session) { session = null; string? id = request.Cookies["ogl_admin"]?.Value; if (id is null || !_sessions.TryGetValue(id, out Session? s)) return false; if (s.Expires <= DateTimeOffset.UtcNow) { _sessions.TryRemove(id, out _); return false; } // UserLevel can be revoked while a session is active. Revalidate on each action. Scene? scene = _scenes.Values.FirstOrDefault(v => v.UserAccountService is not null); if (scene is null) return false; try { UserAccount? account = scene.UserAccountService?.GetUserAccount(UUID.Zero, s.Principal); if (account is null || account.UserLevel <= 0 || !account.LoginAllowed) return false; } catch (Exception e) { Log.Warn("[OS WEBINTERFACE] Account revalidation failed", e); return false; } session = s; return true; } private async Task LoginAsync(HttpListenerContext ctx) { var request = await ReadJsonAsync(ctx.Request); if (request is null || string.IsNullOrWhiteSpace(request.Username) || string.IsNullOrEmpty(request.Password) || request.Username.Length > 120 || request.Password.Length > 1024) { await SendAsync(ctx.Response, 400, new { error = "Ungültige Anmeldung" }); return; } string key = request.Username.Trim().ToLowerInvariant(); Attempt attempt = _attempts.GetOrAdd(key, _ => new Attempt()); lock (attempt) { if (attempt.Reset <= DateTimeOffset.UtcNow) { attempt.Count = 0; attempt.Reset = DateTimeOffset.UtcNow.AddMinutes(5); } if (++attempt.Count > 8) { ctx.Response.StatusCode = 429; return; } } string[] split = request.Username.Replace('.', ' ').Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (split.Length != 2) { await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" }); return; } Scene? scene = _scenes.Values.FirstOrDefault(s => s.UserAccountService is not null && s.AuthenticationService is not null); if (scene is null) { await SendAsync(ctx.Response, 503, new { error = "Authentifizierungsdienste nicht verfügbar" }); return; } try { UserAccount? account = scene.UserAccountService.GetUserAccount(UUID.Zero, split[0], split[1]); if (account is null || !account.LoginAllowed) { await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" }); return; } // Same password transformation as the simulator login service. string hashed = Util.Md5Hash(request.Password); string token = scene.AuthenticationService.Authenticate(account.PrincipalID, hashed, 30); if (string.IsNullOrWhiteSpace(token) || !UUID.TryParse(token, out UUID secureSession) || secureSession == UUID.Zero) { await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" }); return; } try { scene.AuthenticationService.Release(account.PrincipalID, token); } catch (Exception e) { Log.Warn("[OS WEBINTERFACE] Token cleanup failed", e); } if (account.UserLevel <= 0) { await SendAsync(ctx.Response, 403, new { error = "Access Denied – Keine Berechtigung." }); return; } lock (attempt) attempt.Count = 0; string sid = Token(); var session = new Session(account.PrincipalID, account.Name, Token(), DateTimeOffset.UtcNow.AddHours(1)); _sessions[sid] = session; bool secure = ctx.Request.IsSecureConnection || IsTrustedProxyRequest(ctx.Request); ctx.Response.AppendHeader("Set-Cookie", "ogl_admin=" + sid + "; Path=/; HttpOnly; SameSite=Strict; Max-Age=3600" + (secure ? "; Secure" : "")); await SendAsync(ctx.Response, 200, new { name = session.Name, csrf = session.Csrf, expires = session.Expires }); Log.Info("[OS WEBINTERFACE] Administrative session established"); } catch (Exception e) { Log.Error("[OS WEBINTERFACE] Authentication service error", e); await SendAsync(ctx.Response, 503, new { error = "Authentifizierungsdienst nicht verfügbar" }); } } private static async Task ServeResourceAsync(HttpListenerResponse response, string resource, string contentType) { using Stream? stream = typeof(AdminHttpServer).Assembly.GetManifestResourceStream( "os_webinterface.www." + resource); if (stream is null) { response.StatusCode = 404; return; } response.ContentType = contentType; response.ContentLength64 = stream.Length; await stream.CopyToAsync(response.OutputStream); } private bool ValidateMutation(HttpListenerRequest request, Session session) => SameOrigin(request) && string.Equals(request.Headers["X-OGL-CSRF"], session.Csrf, StringComparison.Ordinal); private async Task DispatchAsync(HttpListenerContext ctx) { try { SecurityHeaders(ctx.Response); HttpListenerRequest request = ctx.Request; string route = request.Url?.AbsolutePath ?? "/"; string method = request.HttpMethod; if (method == "GET" && route is "/" or "/index.html") { await ServeResourceAsync(ctx.Response, "index.html", "text/html; charset=utf-8"); return; } if (method == "GET" && route == "/style.css") { await ServeResourceAsync(ctx.Response, "style.css", "text/css; charset=utf-8"); return; } if (method == "GET" && route == "/app.js") { await ServeResourceAsync(ctx.Response, "app.js", "text/javascript; charset=utf-8"); return; } if (method == "POST" && route == "/api/login") { if (!SameOrigin(request)) { await SendAsync(ctx.Response, 403, new { error = "Origin nicht erlaubt" }); return; } await LoginAsync(ctx); return; } if (!route.StartsWith("/api/", StringComparison.Ordinal)) { await SendAsync(ctx.Response, 404, new { error = "Nicht gefunden" }); return; } if (!TrySession(request, out Session? session) || session is null) { await SendAsync(ctx.Response, 401, new { error = "Nicht angemeldet" }); return; } if (method != "GET" && !ValidateMutation(request, session)) { await SendAsync(ctx.Response, 403, new { error = "CSRF/Origin-Prüfung fehlgeschlagen" }); return; } if (method == "POST" && route == "/api/logout") { string? sid = request.Cookies["ogl_admin"]?.Value; if (sid is not null) _sessions.TryRemove(sid, out _); ctx.Response.AppendHeader("Set-Cookie", "ogl_admin=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0"); await SendAsync(ctx.Response, 200, new { ok = true }); return; } if (method == "GET" && route == "/api/me") { await SendAsync(ctx.Response, 200, new { name = session.Name, csrf = session.Csrf }); return; } if (method == "GET" && route == "/api/overview") { await SendAsync(ctx.Response, 200, new { started = _started, uptimeSeconds = (long)(DateTimeOffset.UtcNow - _started).TotalSeconds, memoryBytes = Environment.WorkingSet, gcBytes = GC.GetTotalMemory(false), regions = _operations.RegionSummary(), endpoints = _operations.PortSummary(), services = await _operations.ServiceSummaryAsync(_stop.Token) }); return; } if (method == "GET" && route == "/api/logs") { await SendAsync(ctx.Response, 200, new { content = _operations.LogTail() }); return; } if (method == "GET" && route == "/api/jobs") { await SendAsync(ctx.Response, 200, new { jobs = _operations.Jobs() }); return; } if (method == "POST" && route == "/api/regions/restart") { var payload = await ReadJsonAsync(request); if (payload is null || !_operations.Restart(payload.RegionId)) await SendAsync(ctx.Response, 404, new { error = "Region nicht gefunden" }); else await SendAsync(ctx.Response, 202, new { message = "Region-Neustart angefordert" }); return; } if (method == "POST" && route == "/api/oar/export") { var payload = await ReadJsonAsync(request); if (payload is null) { await SendAsync(ctx.Response, 400, new { error = "Region fehlt" }); return; } await SendAsync(ctx.Response, 202, _operations.Export(payload.RegionId)); return; } if (method == "POST" && route == "/api/oar/import") { string regionId = request.QueryString["region"] ?? ""; if (request.ContentLength64 <= 0 || request.ContentLength64 > AdminOperations.MaxUploadBytes || request.ContentType != "application/octet-stream") { await SendAsync(ctx.Response, 413, new { error = "Nur OAR-Dateien bis 2 GiB erlaubt" }); return; } var job = await _operations.ImportAsync(regionId, request.InputStream, request.ContentLength64, _stop.Token); await SendAsync(ctx.Response, 202, job); return; } if (method == "GET" && route == "/api/oar/download") { string id = request.QueryString["id"] ?? ""; string? file = _operations.ExportFile(id); if (file is null) { await SendAsync(ctx.Response, 404, new { error = "Archiv nicht verfügbar" }); return; } ctx.Response.ContentType = "application/octet-stream"; ctx.Response.Headers["Content-Disposition"] = "attachment; filename=\"region-" + id + ".oar\""; using var input = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read); ctx.Response.ContentLength64 = input.Length; await input.CopyToAsync(ctx.Response.OutputStream); return; } if (method == "GET" && route == "/api/updates/check") { await SendAsync(ctx.Response, 200, await _operations.CheckGitAsync(_stop.Token)); return; } if (method == "GET" && route == "/api/updates/live-status") { await SendAsync(ctx.Response, 200, await _liveUpdate.StatusAsync(_stop.Token)); return; } if (method == "POST" && route == "/api/updates/live-start") { await SendAsync(ctx.Response, 202, await _liveUpdate.StartAsync(_stop.Token)); return; } if (method == "POST" && route == "/api/updates/stage") { var payload = await ReadJsonAsync(request); if (payload is null) { await SendAsync(ctx.Response, 400, new { error = "Commit fehlt" }); return; } await SendAsync(ctx.Response, 200, await _operations.StageUpdateAsync(payload.Sha, _stop.Token)); return; } await SendAsync(ctx.Response, 404, new { error = "Route nicht gefunden" }); } catch (AdminOperations.OperationException e) { if (ctx.Response.OutputStream.CanWrite) await SendAsync(ctx.Response, e.Status, new { error = e.Message }); } catch (Exception e) { Log.Error("[OS WEBINTERFACE] Request failed", e); try { if (ctx.Response.OutputStream.CanWrite) await SendAsync(ctx.Response, 500, new { error = "Interner Fehler" }); } catch { } } finally { try { ctx.Response.Close(); } catch { } } } public void Dispose() { _stop.Cancel(); try { _listener.Stop(); _listener.Close(); } catch { } _operations.Dispose(); _liveUpdate.Dispose(); _sessions.Clear(); _stop.Dispose(); } }