Files
opengenesislinkserver/addons/SysApi/SysApiHost.cs
T

358 lines
16 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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.Services.Interfaces;
namespace OpenGenesisLINK.SysApi;
public sealed class SysApiHost : IDisposable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(SysApiHost));
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private readonly record struct AdminSession(UUID Avatar, string Name, string Csrf, DateTimeOffset Expires);
private sealed record LoginInput(string Username, string Password);
private sealed class Attempts { public int Count; public DateTimeOffset Until = DateTimeOffset.UtcNow.AddMinutes(5); }
private readonly HttpListener _http = new();
private readonly CancellationTokenSource _stop = new();
private readonly ConcurrentDictionary<string, AdminSession> _sessions = new();
private readonly ConcurrentDictionary<string, Attempts> _attempts = new();
private readonly IUserAccountService _accounts;
private readonly IAuthenticationService _auth;
private readonly byte[] _portalToken;
private readonly Uri? _publicOrigin;
private readonly string _localAuthority;
private readonly DateTimeOffset _startup = DateTimeOffset.UtcNow;
private Task? _listenerTask;
private int _disposed;
public SysApiHost(int localPort, string publicOrigin, IUserAccountService accounts,
IAuthenticationService auth, string portalToken)
{
if (localPort is < 1025 or > 65535) throw new ArgumentOutOfRangeException(nameof(localPort));
_accounts = accounts ?? throw new ArgumentNullException(nameof(accounts));
_auth = auth ?? throw new ArgumentNullException(nameof(auth));
if (portalToken.Length != 128 || !portalToken.All(Uri.IsHexDigit))
throw new ArgumentException("Invalid portal token", nameof(portalToken));
_portalToken = Encoding.ASCII.GetBytes(portalToken);
_localAuthority = "127.0.0.1:" + localPort;
if (publicOrigin.Length != 0)
{
if (!Uri.TryCreate(publicOrigin, UriKind.Absolute, out var address) ||
address.Scheme != Uri.UriSchemeHttps || address.AbsolutePath != "/" ||
address.UserInfo.Length != 0 || address.Query.Length != 0 || address.Fragment.Length != 0)
throw new ArgumentException("PublicOrigin must be an HTTPS origin without path or query");
_publicOrigin = address;
}
// Public port 8850 is reserved for HTTPS termination via an ACME-provisioned proxy.
// Never bind the internal module directly to the public interface.
_http.Prefixes.Add($"http://127.0.0.1:{localPort}/");
}
public void Start()
{
_http.Start();
_listenerTask = Task.Run(ServeAsync);
}
private async Task ServeAsync()
{
while (!_stop.IsCancellationRequested)
{
HttpListenerContext request;
try { request = await _http.GetContextAsync(); }
catch (Exception e) when (e is HttpListenerException or ObjectDisposedException) { break; }
_ = Task.Run(() => HandleAsync(request));
}
}
private static string RandomSecret() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
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'; img-src 'self' data:; " +
"script-src 'self'; style-src 'self'; connect-src 'self'; form-action 'self'; " +
"frame-ancestors 'none'; base-uri 'none'; object-src 'none'";
}
private bool IsTrustedProxy(HttpListenerRequest req) =>
_publicOrigin is not null &&
IPAddress.IsLoopback(req.RemoteEndPoint?.Address ?? IPAddress.None) &&
string.Equals(req.Headers["Host"], _localAuthority, StringComparison.OrdinalIgnoreCase) &&
string.Equals(req.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase) &&
string.Equals(req.Headers["X-Forwarded-Host"], _publicOrigin.Authority, StringComparison.OrdinalIgnoreCase);
private bool SameOrigin(HttpListenerRequest req)
{
string origin = req.Headers["Origin"] ?? "";
string fetchSite = req.Headers["Sec-Fetch-Site"] ?? "";
if (fetchSite.Length > 0 && fetchSite is not ("same-origin" or "none")) return false;
if (origin.Length == 0) return true;
if (!Uri.TryCreate(origin, UriKind.Absolute, out Uri? parsed)) return false;
bool direct = parsed.Scheme == "http" &&
string.Equals(parsed.Authority, _localAuthority, StringComparison.OrdinalIgnoreCase);
bool proxy = IsTrustedProxy(req) && string.Equals(
parsed.GetLeftPart(UriPartial.Authority),
_publicOrigin!.GetLeftPart(UriPartial.Authority),
StringComparison.OrdinalIgnoreCase);
return direct || proxy;
}
private bool HasPortalToken(HttpListenerRequest req)
{
string header = req.Headers["Authorization"] ?? "";
if (!header.StartsWith("Bearer ", StringComparison.Ordinal) || header.Length != 135)
return false;
return CryptographicOperations.FixedTimeEquals(
Encoding.ASCII.GetBytes(header[7..]), _portalToken);
}
private bool TryAdmin(HttpListenerRequest req, out AdminSession s)
{
s = default;
string? sid = req.Cookies["ogl_sysapi"]?.Value;
if (sid is null || !_sessions.TryGetValue(sid, out var candidate)) return false;
if (candidate.Expires < DateTimeOffset.UtcNow) { _sessions.TryRemove(sid, out _); return false; }
try
{
var account = _accounts.GetUserAccount(UUID.Zero, candidate.Avatar);
if (account is null || account.UserLevel < 200 || !account.LoginAllowed)
{
_sessions.TryRemove(sid, out _);
return false;
}
}
catch (Exception ex) { Log.Warn("[SYS.API] Session authorization unavailable", ex); return false; }
s = candidate;
return true;
}
private static async Task<T?> ReadInput<T>(HttpListenerRequest req) where T : class
{
if (req.ContentLength64 > 16384 ||
!(req.ContentType?.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) ?? false))
return null;
using var ms = new MemoryStream();
byte[] buffer = new byte[4096];
int n;
while ((n = await req.InputStream.ReadAsync(buffer)) > 0)
{
if (ms.Length + n > 16384) return null;
ms.Write(buffer.AsSpan(0, n));
}
try { return JsonSerializer.Deserialize<T>(ms.ToArray(), Json); }
catch (JsonException) { return null; }
}
private static async Task ReplyAsync(HttpListenerResponse r, int status, object data)
{
r.StatusCode = status;
r.ContentType = "application/json; charset=utf-8";
byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(data, Json);
r.ContentLength64 = bytes.Length;
await r.OutputStream.WriteAsync(bytes);
}
private static async Task AssetAsync(HttpListenerResponse r, string suffix, string mime)
{
var asm = typeof(SysApiHost).Assembly;
string? name = asm.GetManifestResourceNames().FirstOrDefault(x =>
x.EndsWith(".www." + suffix, StringComparison.Ordinal));
if (name is null) { r.StatusCode = 404; return; }
using var content = asm.GetManifestResourceStream(name);
if (content is null) { r.StatusCode = 404; return; }
r.ContentType = mime;
r.ContentLength64 = content.Length;
await content.CopyToAsync(r.OutputStream);
}
private async Task LoginAsync(HttpListenerContext context)
{
var req = context.Request;
var data = await ReadInput<LoginInput>(req);
if (data is null || string.IsNullOrWhiteSpace(data.Username) ||
string.IsNullOrWhiteSpace(data.Password) || data.Username.Length > 128 || data.Password.Length > 1024)
{
await ReplyAsync(context.Response, 400, new { error = "Invalid login request" });
return;
}
string key = data.Username.Trim().ToLowerInvariant();
Attempts throttle = _attempts.GetOrAdd(key, _ => new Attempts());
lock (throttle)
{
if (DateTimeOffset.UtcNow > throttle.Until)
{
throttle.Count = 0;
throttle.Until = DateTimeOffset.UtcNow.AddMinutes(5);
}
if (++throttle.Count > 8)
{
context.Response.StatusCode = 429;
return;
}
}
string[] parts = data.Username.Replace('.', ' ')
.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length != 2)
{
await ReplyAsync(context.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
return;
}
try
{
var account = _accounts.GetUserAccount(UUID.Zero, parts[0], parts[1]);
if (account is null || !account.LoginAllowed)
{
await ReplyAsync(context.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
return;
}
string hashed = Util.Md5Hash(data.Password);
string loginToken = _auth.Authenticate(account.PrincipalID, hashed, 30);
if (!UUID.TryParse(loginToken, out var session) || session == UUID.Zero)
{
await ReplyAsync(context.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
return;
}
try { _auth.Release(account.PrincipalID, loginToken); }
catch (Exception e) { Log.Warn("[SYS.API] Failed to release one-time auth session", e); }
if (account.UserLevel < 200)
{
await ReplyAsync(context.Response, 403, new { error = "Access Denied – Keine Berechtigung" });
return;
}
lock (throttle) throttle.Count = 0;
string sid = RandomSecret();
AdminSession s = new(account.PrincipalID, account.Name, RandomSecret(),
DateTimeOffset.UtcNow.AddHours(1));
_sessions[sid] = s;
bool secure = context.Request.IsSecureConnection || IsTrustedProxy(context.Request);
context.Response.AppendHeader("Set-Cookie", $"ogl_sysapi={sid}; Path=/; " +
"HttpOnly; SameSite=Strict; Max-Age=3600" + (secure ? "; Secure" : ""));
await ReplyAsync(context.Response, 200, new { name = s.Name, csrf = s.Csrf, minLevel = 200 });
Log.Info("[SYS.API] Web administrator authenticated (UserLevel>=200).");
}
catch (Exception e)
{
Log.Error("[SYS.API] Login validation unavailable", e);
await ReplyAsync(context.Response, 503, new { error = "Authentifizierungsdienst nicht erreichbar" });
}
}
private async Task HandleAsync(HttpListenerContext context)
{
try
{
var req = context.Request;
var response = context.Response;
SecurityHeaders(response);
string path = req.Url?.AbsolutePath ?? "";
bool isGet = req.HttpMethod == "GET";
if (isGet && path is "/" or "/index.html")
{
await AssetAsync(response, "index.html", "text/html; charset=utf-8");
return;
}
if (isGet && path == "/app.js") { await AssetAsync(response, "app.js", "text/javascript; charset=utf-8"); return; }
if (isGet && path == "/style.css") { await AssetAsync(response, "style.css", "text/css; charset=utf-8"); return; }
if (isGet && path == "/ogl-mascot.webp") { await AssetAsync(response, "ogl-mascot.webp", "image/webp"); return; }
if (isGet && path == "/v1/health")
{
await ReplyAsync(response, 200, new { status = "online", module = "sys.api",
port = 8850, version = 1 }); return;
}
if (req.HttpMethod == "POST" && path == "/api/session/login")
{
if (!SameOrigin(req))
{
await ReplyAsync(response, 403, new { error = "Origin rejected" }); return;
}
await LoginAsync(context); return;
}
if (isGet && path is "/api/v1/portal/ping" or "/api/v1/portal/capabilities")
{
if (!HasPortalToken(req))
{
await ReplyAsync(response, 401, new { error = "Invalid portal credential" }); return;
}
await ReplyAsync(response, 200, path.EndsWith("ping")
? new { ok = true, service = "sys.api", apiVersion = "v1" }
: (object)new { apiVersion = "v1", authentication = "single-machine-token", endpoints = new[]
{ "/api/v1/portal/ping", "/api/v1/portal/capabilities" },
legacyWorldApiUnchanged = true });
return;
}
if (!TryAdmin(req, out AdminSession admin))
{
await ReplyAsync(response, 401, new { error = "Access Denied – Keine Berechtigung" }); return;
}
if (!isGet && (!SameOrigin(req) ||
!string.Equals(req.Headers["X-OGL-CSRF"], admin.Csrf, StringComparison.Ordinal)))
{
await ReplyAsync(response, 403, new { error = "CSRF protection denied" }); return;
}
if (isGet && path == "/api/session")
{
await ReplyAsync(response, 200, new { user = admin.Name,
csrf = admin.Csrf, minLevel = 200 }); return;
}
if (req.HttpMethod == "POST" && path == "/api/session/logout")
{
string? sid = req.Cookies["ogl_sysapi"]?.Value;
if (sid != null) _sessions.TryRemove(sid, out _);
response.AppendHeader("Set-Cookie",
"ogl_sysapi=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0");
await ReplyAsync(response, 200, new { ok = true }); return;
}
if (isGet && path == "/api/admin/overview")
{
await ReplyAsync(response, 200, new
{
service = "OpenGenesisLINK System API",
generation = "GEN 1",
api = "v1",
status = "operational",
port = 8850,
internalPort = new Uri(_http.Prefixes.First()).Port,
tlsConfigured = _publicOrigin is not null,
uptimeSeconds = (long)(DateTimeOffset.UtcNow - _startup).TotalSeconds,
portalTokenPresent = true,
session = admin.Name,
minAdminLevel = 200,
oldWorldApiUnchanged = true,
endpoints = new[] { "/v1/health", "/api/v1/portal/ping", "/api/v1/portal/capabilities" }
});
return;
}
await ReplyAsync(response, 404, new { error = "Not found" });
}
catch (Exception e)
{
Log.Error("[SYS.API] Request failed", e);
try { await ReplyAsync(context.Response, 500, new { error = "Internal error" }); }
catch { }
}
finally { try { context.Response.Close(); } catch { } }
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
_stop.Cancel();
_http.Stop();
_http.Close();
_sessions.Clear();
_stop.Dispose();
}
}