fix(gen1): secure explicit HTTPS reverse-proxy origin for simulator UI

This commit is contained in:
OpenGenesis (MPL 2.0) committed 2026-11-17 17:05:53 +01:00
1 parent cb6006ade4
commit 58772f54cc
7 files changed
+74 -14

No files matched your search

+30 -9
View File
@@ -30,11 +30,23 @@ internal sealed class AdminHttpServer : IDisposable
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<UUID, Scene> scenes, string storage, int port, int retention, List<(string Name, Uri Uri)> services, LiveUpdateBridge liveUpdate)
public AdminHttpServer(ConcurrentDictionary<UUID, Scene> 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;
@@ -97,17 +109,27 @@ internal sealed class AdminHttpServer : IDisposable
"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 static bool SameOrigin(HttpListenerRequest request)
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)
{
// No CORS: browsers sending cross-site requests may not perform mutations.
// 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;
string? host = request.Headers["Host"];
if (string.IsNullOrWhiteSpace(host)) return false;
return string.Equals(parsed.Authority, host, StringComparison.OrdinalIgnoreCase) &&
(parsed.Scheme == "https" || parsed.Scheme == "http");
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";
@@ -197,8 +219,7 @@ internal sealed class AdminHttpServer : IDisposable
string sid = Token();
var session = new Session(account.PrincipalID, account.Name, Token(), DateTimeOffset.UtcNow.AddHours(1));
_sessions[sid] = session;
bool secure = ctx.Request.IsSecureConnection ||
string.Equals(ctx.Request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase);
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 });
@@ -76,7 +76,8 @@ public sealed class OSWebInterfaceModule : ISharedRegionModule
string liveUrl = node?.GetString("LiveUpdateServiceUrl", "http://127.0.0.1:19090") ?? "";
string liveToken = Environment.GetEnvironmentVariable("OGL_NODE_UPDATER_TOKEN") ?? "";
var bridge = new LiveUpdateBridge(liveAllowed, nodeId, liveUrl, liveToken);
_server = new AdminHttpServer(_scenes, _storage, _port, retention, services, bridge);
string publicOrigin = c?.GetString("PublicOrigin", "")?.Trim() ?? "";
_server = new AdminHttpServer(_scenes, _storage, _port, retention, services, bridge, publicOrigin);
_server.Start();
Log.Info($"[OS WEBINTERFACE] Enabled on http://127.0.0.1:{_port}/ (loopback only). Configure an HTTPS reverse proxy for remote access.");
}
+2
View File
@@ -593,3 +593,5 @@
DataDirectory = "os-webinterface-data"
BackupRetention = 5
AllowLiveUpdates = false
; Optional HTTPS-Origin of your reverse proxy, e.g. https://sim-admin.example.org
PublicOrigin = ""
+2
View File
@@ -476,3 +476,5 @@
DataDirectory = "os-webinterface-data"
BackupRetention = 5
AllowLiveUpdates = false
; Optional HTTPS-Origin of your reverse proxy, e.g. https://sim-admin.example.org
PublicOrigin = ""
+13 -1
View File
@@ -6,7 +6,18 @@
os_webinterface.dll is a .NET 10 Mono.Addins ISharedRegionModule, loaded by the simulator's existing region-module manager. No additional web administration handlers are added to OpenSim.dll. Each simulator has its own panel and own port.
The HTTP listener binds ONLY to 127.0.0.1. For remote usage, configure an HTTPS reverse proxy with host firewall, certificate, forwarded Host header, and X-Forwarded-Proto set to https. Do not publish the raw HTTP port via a public Fritz!Box port forward.
The HTTP listener binds ONLY to 127.0.0.1. For remote access use an HTTPS reverse proxy with firewall and certificate, never expose the raw port through Fritz!Box. Because HttpListener matches the local Host header, the reverse proxy MUST overwrite Host to 127.0.0.1:9847 and explicitly set X-Forwarded-Host to the public domain plus X-Forwarded-Proto=https. Configure PublicOrigin as that exact public HTTPS origin (https://sim-admin.example.org); without this option external browser login is intentionally rejected.
Example Nginx location block (in an existing HTTPS virtual host for sim-admin.example.org):
location / {
proxy_pass http://127.0.0.1:9847;
proxy_set_header Host 127.0.0.1:9847;
proxy_set_header X-Forwarded-Host sim-admin.example.org;
proxy_set_header X-Forwarded-Proto https;
}
Configure PublicOrigin = "https://sim-admin.example.org" and ensure Nginx never forwards client-supplied Forwarded headers unmodified. You must configure real TLS certificates and outside firewall separately.
## Configuration (simulator bin/OpenSim.ini)
@@ -16,6 +27,7 @@ The HTTP listener binds ONLY to 127.0.0.1. For remote usage, configure an HTTPS
DataDirectory = "os-webinterface-data"
BackupRetention = 5
AllowLiveUpdates = false
PublicOrigin = ""
Default Enabled=false; activating requires ONE planned simulator restart. Every simulator process must use a distinct port.
+23 -1
View File
@@ -16,6 +16,7 @@ IConfig entry = config.Configs.Add("OSWebInterface");
entry.Set("Enabled", "true");
entry.Set("Port", port.ToString());
entry.Set("DataDirectory", "os-webinterface-smoke-test");
entry.Set("PublicOrigin", "https://admin.example.test");
var module = new OSWebInterfaceModule();
module.Initialise(config);
try
@@ -42,6 +43,27 @@ try
using var deniedUpdate = await client.GetAsync("/api/updates/live-status");
if (deniedUpdate.StatusCode != HttpStatusCode.Unauthorized)
throw new Exception("Unauthenticated live-updater status not denied");
using var foreignHostRequest = new HttpRequestMessage(HttpMethod.Get, "/");
foreignHostRequest.Headers.Host = "admin.example.test";
using var foreignHostResponse = await client.SendAsync(foreignHostRequest);
if (foreignHostResponse.StatusCode != HttpStatusCode.NotFound)
throw new Exception("Listener unexpectedly accepted foreign Host header");
using var proxyLogin = new HttpRequestMessage(HttpMethod.Post, "/api/login");
proxyLogin.Headers.Add("Origin", "https://admin.example.test");
proxyLogin.Headers.Add("X-Forwarded-Host", "admin.example.test");
proxyLogin.Headers.Add("X-Forwarded-Proto", "https");
proxyLogin.Content = new StringContent("{\"username\":\"Test User\",\"password\":\"123\"}", Encoding.UTF8, "application/json");
using var trusted = await client.SendAsync(proxyLogin);
if (trusted.StatusCode != HttpStatusCode.ServiceUnavailable)
throw new Exception("Trusted reverse proxy login did not reach authentication layer");
using var fakeProxyLogin = new HttpRequestMessage(HttpMethod.Post, "/api/login");
fakeProxyLogin.Headers.Add("Origin", "https://attacker.example");
fakeProxyLogin.Headers.Add("X-Forwarded-Host", "admin.example.test");
fakeProxyLogin.Headers.Add("X-Forwarded-Proto", "https");
fakeProxyLogin.Content = new StringContent("{\"username\":\"Test User\",\"password\":\"123\"}", Encoding.UTF8, "application/json");
using var fakeProxy = await client.SendAsync(fakeProxyLogin);
if (fakeProxy.StatusCode != HttpStatusCode.Forbidden)
throw new Exception("Forged reverse-proxy Origin was not rejected");
using var denied = await client.GetAsync("/api/overview");
if (denied.StatusCode != HttpStatusCode.Unauthorized)
throw new Exception("Unauthenticated overview not denied");
@@ -57,6 +79,6 @@ try
"application/json"));
if (noBackends.StatusCode != HttpStatusCode.ServiceUnavailable)
throw new Exception("Missing authentication service did not fail closed");
Console.WriteLine("OSWebInterface HTTP smoke PASS: UI, static resources, CSP, 401, CSRF-origin and fail-closed login");
Console.WriteLine("OSWebInterface HTTP smoke PASS: UI, CSP, 401, CSRF, fail-closed login and trusted HTTPS reverse proxy");
}
finally { module.Close(); }
+2 -2
View File
@@ -16,7 +16,7 @@ js = text("addons/OSWebInterface/www/app.js")
ini_paths = ("bin/OpenSim.ini", "bin/OpenSim.ini.example")
for ini in ini_paths:
c = text(ini).split("[OSWebInterface]", 1)
assert len(c) == 2 and "Enabled = false" in c[1] and "AllowLiveUpdates = false" in c[1], ini
assert len(c) == 2 and "Enabled = false" in c[1] and "AllowLiveUpdates = false" in c[1] and 'PublicOrigin = ""' in c[1], ini
for part in (
"<AssemblyName>os_webinterface</AssemblyName>",
@@ -38,7 +38,7 @@ for part in (
"Access Denied – Keine Berechtigung.",
"_liveUpdate.StatusAsync", "_liveUpdate.StartAsync",
"HttpOnly; SameSite=Strict", "X-OGL-CSRF", "SameOrigin(",
"Content-Security-Policy", "TrySession(request",
"Content-Security-Policy", "TrySession(request", "IsTrustedProxyRequest", "PublicOrigin",
'"/api/regions/restart"', '"/api/oar/import"', '"/api/oar/export"',
'"/api/oar/download"', '"/api/updates/check"', '"/api/updates/stage"',
):