Skip to content

LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.

Remote desktop: strict request parsing, IP lockout, address lists and privilege separation

Federico Pereiraadcccb9d5c34
diff --git a/apps/settings/Sharing.jsx b/apps/settings/Sharing.jsx
index 3e8b088..77623d6 100644
--- a/apps/settings/Sharing.jsx
+++ b/apps/settings/Sharing.jsx
@@ -3,7 +3,8 @@
// connections goes through the administration helper (remote-* and ssh-* actions). The SSH
// server is installed, the first time, with the package engine's own pkg-install action.
import {
- View, Text, Button, Toggle, Segmented, useTheme, useLocale, useStore, admin, remote, remoteViewers, sshLogin, statusText, useSystemInfo, spacing, typeScale,
+ View, Text, Button, Toggle, Segmented, TextInput, useTheme, useLocale, useStore, admin, remote, remoteViewers, sshLogin, remoteCidr,
+ remoteMinutesLeft, statusText, useSystemInfo, spacing, typeScale,
} from '@lordos/sdk';
import { useEffect, useState } from 'react';
import { Stack, Section, SettingRow, Note, Message, StatusDot, tint } from './ui.jsx';
@@ -25,6 +26,74 @@ const ago = (sec, tr) => {
return m < 1 ? tr('settings.sharing.justNow') : tr('settings.sharing.minutes', { count: m });
};
+// An address or network field with an action button; the text is checked here for a quick hint
+// and again, strictly, by the admin helper (remote-block, remote-allow).
+function AddressField({ placeholder, label, disabled, onAdd }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const [text, setText] = useState('');
+ const [bad, setBad] = useState(false);
+ const submit = () => {
+ if (disabled) return;
+ const v = remoteCidr(text);
+ if (!v) { setBad(true); return; }
+ setBad(false);
+ Promise.resolve(onAdd(v)).then((ok) => { if (ok !== false) setText(''); });
+ };
+ return (
+ <View style={{ paddingVertical: spacing.s, gap: 4 }}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.s }}>
+ <TextInput value={text} placeholder={placeholder} style={{ flex: 1, direction: 'ltr' }}
+ onChange={(v) => { setText(v.slice(0, 60)); setBad(false); }} onSubmit={submit} />
+ <Button small label={label} disabled={disabled || !text.trim()} onClick={submit} />
+ </View>
+ {bad ? <Text style={{ fontSize: typeScale.caption, color: tint.error, textAlign: 'start' }}>{tr('settings.sharing.badAddress')}</Text> : null}
+ </View>
+ );
+}
+
+// Who may connect and which addresses are blocked (docs/REMOTE.md, "Blocked and allowed addresses").
+function AccessSection({ st, isAdmin, busy, act }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const hint = { lan: 'settings.sharing.netLanHint', list: 'settings.sharing.netListHint', any: 'settings.sharing.netAnyHint' }[st.net] || 'settings.sharing.netLanHint';
+ return (
+ <>
+ <Section title={tr('settings.sharing.access')}>
+ <SettingRow label={tr('settings.sharing.netFrom')} hint={tr(hint)} stack>
+ <Segmented small value={st.net} onChange={(net) => isAdmin && !busy && act('remote-config', `net=${net}`)}
+ options={[['lan', tr('settings.sharing.netLan')], ['list', tr('settings.sharing.netList')], ['any', tr('settings.sharing.netAny')]]} />
+ </SettingRow>
+ {st.net === 'list' && (
+ <>
+ {!st.allowed.length && <SettingRow label={tr('settings.sharing.allowEmpty')} labelStyle={{ color: tint.warn }} />}
+ {st.allowed.map((c) => (
+ <SettingRow key={c} label={c} labelStyle={{ fontFamily: 'monospace', direction: 'ltr' }}>
+ {isAdmin && <Button small label={tr('settings.sharing.remove')} disabled={busy} onClick={() => act('remote-allow', `del ${c}`)} />}
+ </SettingRow>
+ ))}
+ {isAdmin && <AddressField placeholder={tr('settings.sharing.allowPlaceholder')} label={tr('settings.sharing.allowAdd')} disabled={busy}
+ onAdd={(v) => act('remote-allow', `add ${v}`)} />}
+ </>
+ )}
+ </Section>
+ {st.net === 'any' && <Note tone="warn">{tr('settings.sharing.netAnyWarn')}</Note>}
+ <Section title={tr('settings.sharing.blocked')} footer={tr('settings.sharing.blockedFooter')}>
+ {!st.blocked.length ? <SettingRow label={tr('settings.sharing.blockedNone')} labelStyle={{ color: t.textDim }} /> : st.blocked.map((b) => (
+ <SettingRow key={`${b.manual ? 'm' : 'a'}${b.ip}`} icon={<StatusDot color={b.manual ? tint.off : tint.error} />}
+ label={b.ip} labelStyle={{ fontFamily: 'monospace', direction: 'ltr' }}
+ hint={b.manual ? tr('settings.sharing.blockedManual')
+ : tr('settings.sharing.blockedAuto', { minutes: remoteMinutesLeft(b.until) })}>
+ {isAdmin && <Button small label={tr('settings.sharing.unblock')} disabled={busy} onClick={() => act('remote-unblock', b.ip)} />}
+ </SettingRow>
+ ))}
+ {isAdmin && <AddressField placeholder={tr('settings.sharing.blockPlaceholder')} label={tr('settings.sharing.block')} disabled={busy}
+ onAdd={(v) => act('remote-block', v)} />}
+ </Section>
+ </>
+ );
+}
+
// openssh-sftp-server too: scp and sftp need it (a Recommends the package engine skips).
const SSH_PACKAGES = 'openssh-server openssh-sftp-server';
@@ -107,8 +176,8 @@ export function SharingSettings() {
setBusy(true);
setMsg(null);
return admin.run(action, arg).then(
- () => { setMsg(ok ? { ok: true, text: ok } : null); setSt(remote.status()); },
- (e) => setMsg({ ok: false, text: e.message })).finally(() => setBusy(false));
+ (r) => { setMsg({ ok: true, text: ok || statusText(r) }); setTimeout(() => setSt(remote.status()), 300); return true; },
+ (e) => { setMsg({ ok: false, text: e.message }); return false; }).finally(() => setBusy(false));
};
const ips = lanAddresses();
const urls = ips.map((ip) => `https://${ip}:${st.port}`);
@@ -139,6 +208,7 @@ export function SharingSettings() {
{!isAdmin && <Note tone="warn">{tr('settings.admin.unavailable')}</Note>}
{!st.installed && <Note tone="warn">{tr('settings.sharing.notInstalled')}</Note>}
<Message msg={msg} />
+ <AccessSection st={st} isAdmin={isAdmin} busy={busy} act={act} />
<Section title={tr('settings.sharing.connected')} footer={tr('settings.sharing.security')}>
{!st.clients.length ? <SettingRow label={tr('settings.sharing.nobody')} labelStyle={{ color: t.textDim }} /> : st.clients.map((c) => (
<SettingRow key={c.pid} icon={<StatusDot color={tint.ok} />} label={`${c.user} · ${c.ip}`}
diff --git a/assets/locales/en/errors.json b/assets/locales/en/errors.json
index d3923cd..f6df753 100644
--- a/assets/locales/en/errors.json
+++ b/assets/locales/en/errors.json
@@ -564,5 +564,7 @@
"disk.smartFailed": "Could not read the disk health",
"disk.smartTestFailed": "The disk did not start the self-test",
"hw.noKernelLog": "The kernel log could not be read",
- "app.codeRefused": "This app's code was modified and was not loaded"
+ "app.codeRefused": "This app's code was modified and was not loaded",
+ "remote.badAddress": "Not a valid address or network",
+ "remote.listFull": "The list is full (64 entries)"
}
diff --git a/assets/locales/en/settings.json b/assets/locales/en/settings.json
index 462be1a..20c2d25 100644
--- a/assets/locales/en/settings.json
+++ b/assets/locales/en/settings.json
@@ -123,7 +123,7 @@
"sharing.remote": "Remote desktop",
"sharing.remoteHint": "Other computers on your local network sign in from a web browser with a username and password of this computer. With your own user they see and use this same screen; with another user, a desktop of their own.",
"sharing.remoteToggle": "Allow access from the network",
- "sharing.security": "Local network only: the connection is encrypted (TLS) with a certificate of this computer. Failed attempts wait longer each time. To use it from the internet, use a VPN.",
+ "sharing.security": "The connection is encrypted (TLS) with a certificate of this computer. 3 failed sign-ins block the address; the root account can never sign in. To use it from the internet, use a VPN.",
"sharing.thisSession": "viewing this screen",
"sharing.who": "Who can sign in",
"sharing.whoAllHint": "Any user of this computer with a password.",
@@ -279,5 +279,27 @@
"style.hint": "Both styles have the same apps. The change is applied right away, without logging out; open windows come back.",
"dock.taskbarAlign": "Taskbar alignment",
"dock.alignCenter": "Center",
- "dock.alignStart": "Start"
+ "dock.alignStart": "Start",
+ "sharing.access": "Who can connect",
+ "sharing.netFrom": "Allow connections from",
+ "sharing.netLan": "Local network",
+ "sharing.netList": "Only these addresses",
+ "sharing.netAny": "Any address",
+ "sharing.netLanHint": "Private and link-local addresses of your network, and connections that arrive over a VPN of this computer. Public internet addresses are refused.",
+ "sharing.netListHint": "Only the addresses and networks in this list can open the sign-in page.",
+ "sharing.netAnyHint": "Any address that can reach this computer, including the internet if a port is forwarded to it.",
+ "sharing.netAnyWarn": "Connections from any address are allowed. Failed sign-ins still block the address, but a VPN is the safer way to reach this computer from the internet.",
+ "sharing.allowEmpty": "The list is empty: nobody can connect.",
+ "sharing.allowPlaceholder": "Address or network, e.g. 192.168.1.0/24",
+ "sharing.allowAdd": "Add",
+ "sharing.remove": "Remove",
+ "sharing.blocked": "Blocked addresses",
+ "sharing.blockedFooter": "An address is blocked after 3 failed sign-ins: for 15 minutes, then 1 hour, then 24 hours if it happens again within a day. You get a notification when it happens.",
+ "sharing.blockedNone": "No address is blocked.",
+ "sharing.blockedManual": "Blocked by an administrator",
+ "sharing.blockedAuto": "Failed sign-ins · {minutes} min left",
+ "sharing.unblock": "Unblock",
+ "sharing.block": "Block",
+ "sharing.blockPlaceholder": "Address or network to block",
+ "sharing.badAddress": "Write an IPv4 or IPv6 address, or a network such as 192.168.1.0/24 (at least /8; IPv6 at least /16)."
}
diff --git a/assets/locales/en/shell.json b/assets/locales/en/shell.json
index 0f6da07..8f13eff 100644
--- a/assets/locales/en/shell.json
+++ b/assets/locales/en/shell.json
@@ -209,5 +209,8 @@
"classic.snapRight": "Snap to the right half",
"classic.close": "Close",
"classic.personalize": "Personalize",
- "classic.displaySettings": "Display settings"
+ "classic.displaySettings": "Display settings",
+ "remote.blockedTitle": "Remote desktop: address blocked",
+ "remote.blockedBody": "{ip} failed to sign in 3 times and is blocked for {minutes} min.",
+ "remote.blockedOpen": "Open Sharing"
}
diff --git a/assets/locales/en/status.json b/assets/locales/en/status.json
index c5ce8df..514edae 100644
--- a/assets/locales/en/status.json
+++ b/assets/locales/en/status.json
@@ -120,5 +120,7 @@
"ssh.off": "Remote login turned off",
"ssh.on": "Remote login turned on",
"ssh.saved": "Settings saved",
- "hw.firmwareChecked": "Firmware checked"
+ "hw.firmwareChecked": "Firmware checked",
+ "remote.blocked": "{address} blocked",
+ "remote.unblocked": "{address} unblocked"
}
diff --git a/assets/locales/es/errors.json b/assets/locales/es/errors.json
index 8068ecc..dbe9f7e 100644
--- a/assets/locales/es/errors.json
+++ b/assets/locales/es/errors.json
@@ -564,5 +564,7 @@
"disk.smartFailed": "No se pudo leer la salud del disco",
"disk.smartTestFailed": "El disco no inició la autoprueba",
"hw.noKernelLog": "No se pudo leer el registro del kernel",
- "app.codeRefused": "El código de esta app fue modificado y no se cargó"
+ "app.codeRefused": "El código de esta app fue modificado y no se cargó",
+ "remote.badAddress": "No es una dirección o red válida",
+ "remote.listFull": "La lista está llena (64 entradas)"
}
diff --git a/assets/locales/es/settings.json b/assets/locales/es/settings.json
index 18fc054..ada2594 100644
--- a/assets/locales/es/settings.json
+++ b/assets/locales/es/settings.json
@@ -123,7 +123,7 @@
"sharing.remote": "Escritorio remoto",
"sharing.remoteHint": "Otras computadoras de tu red local entran desde un navegador, con un usuario y contraseña de este equipo. Con tu mismo usuario ven y usan esta misma pantalla; con otro usuario, un escritorio propio.",
"sharing.remoteToggle": "Permitir el acceso desde la red",
- "sharing.security": "Solo para la red local: la conexión va cifrada (TLS) con un certificado propio de este equipo. Los intentos fallidos esperan cada vez más. Para usarlo desde internet hace falta una VPN.",
+ "sharing.security": "La conexión va cifrada (TLS) con un certificado propio de este equipo. 3 ingresos fallidos bloquean la dirección; la cuenta root nunca puede entrar. Para usarlo desde internet hace falta una VPN.",
"sharing.thisSession": "mirando esta pantalla",
"sharing.who": "Pueden entrar",
"sharing.whoAllHint": "Cualquier usuario de este equipo con contraseña.",
@@ -279,5 +279,27 @@
"style.hint": "Los dos estilos tienen las mismas apps. El cambio se aplica al instante, sin cerrar sesión; las ventanas abiertas vuelven.",
"dock.taskbarAlign": "Alineación de la barra de tareas",
"dock.alignCenter": "Centro",
- "dock.alignStart": "Inicio"
+ "dock.alignStart": "Inicio",
+ "sharing.access": "Quién puede conectarse",
+ "sharing.netFrom": "Permitir conexiones desde",
+ "sharing.netLan": "Red local",
+ "sharing.netList": "Solo estas direcciones",
+ "sharing.netAny": "Cualquier dirección",
+ "sharing.netLanHint": "Direcciones privadas y de enlace local de tu red, y conexiones que llegan por una VPN de este equipo. Las direcciones públicas de internet se rechazan.",
+ "sharing.netListHint": "Solo las direcciones y redes de esta lista pueden abrir la página de ingreso.",
+ "sharing.netAnyHint": "Cualquier dirección que llegue a este equipo, también internet si se le redirige un puerto.",
+ "sharing.netAnyWarn": "Se aceptan conexiones desde cualquier dirección. Los ingresos fallidos igual bloquean la dirección, pero una VPN es la forma más segura de llegar a este equipo desde internet.",
+ "sharing.allowEmpty": "La lista está vacía: nadie puede conectarse.",
+ "sharing.allowPlaceholder": "Dirección o red, p. ej. 192.168.1.0/24",
+ "sharing.allowAdd": "Agregar",
+ "sharing.remove": "Quitar",
+ "sharing.blocked": "Direcciones bloqueadas",
+ "sharing.blockedFooter": "Una dirección queda bloqueada tras 3 ingresos fallidos: 15 minutos, luego 1 hora y luego 24 horas si se repite en el mismo día. Te llega una notificación cuando pasa.",
+ "sharing.blockedNone": "No hay direcciones bloqueadas.",
+ "sharing.blockedManual": "Bloqueada por un administrador",
+ "sharing.blockedAuto": "Ingresos fallidos · faltan {minutes} min",
+ "sharing.unblock": "Desbloquear",
+ "sharing.block": "Bloquear",
+ "sharing.blockPlaceholder": "Dirección o red para bloquear",
+ "sharing.badAddress": "Escribí una dirección IPv4 o IPv6, o una red como 192.168.1.0/24 (al menos /8; IPv6 al menos /16)."
}
diff --git a/assets/locales/es/shell.json b/assets/locales/es/shell.json
index 2253ad6..b5bfe56 100644
--- a/assets/locales/es/shell.json
+++ b/assets/locales/es/shell.json
@@ -209,5 +209,8 @@
"classic.snapRight": "Acomodar en la mitad derecha",
"classic.close": "Cerrar",
"classic.personalize": "Personalizar",
- "classic.displaySettings": "Ajustes de pantalla"
+ "classic.displaySettings": "Ajustes de pantalla",
+ "remote.blockedTitle": "Escritorio remoto: dirección bloqueada",
+ "remote.blockedBody": "{ip} falló 3 veces al ingresar y quedó bloqueada {minutes} min.",
+ "remote.blockedOpen": "Abrir Compartir"
}
diff --git a/assets/locales/es/status.json b/assets/locales/es/status.json
index 758426b..7d9889b 100644
--- a/assets/locales/es/status.json
+++ b/assets/locales/es/status.json
@@ -120,5 +120,7 @@
"ssh.off": "Inicio de sesión remoto desactivado",
"ssh.on": "Inicio de sesión remoto activado",
"ssh.saved": "Ajustes guardados",
- "hw.firmwareChecked": "Firmware revisado"
+ "hw.firmwareChecked": "Firmware revisado",
+ "remote.blocked": "{address} bloqueada",
+ "remote.unblocked": "{address} desbloqueada"
}
diff --git a/assets/locales/pt/errors.json b/assets/locales/pt/errors.json
index 6c42413..4c53558 100644
--- a/assets/locales/pt/errors.json
+++ b/assets/locales/pt/errors.json
@@ -564,5 +564,7 @@
"disk.smartFailed": "Não foi possível ler a saúde do disco",
"disk.smartTestFailed": "O disco não iniciou o autoteste",
"hw.noKernelLog": "Não foi possível ler o registro do kernel",
- "app.codeRefused": "O código deste app foi modificado e não foi carregado"
+ "app.codeRefused": "O código deste app foi modificado e não foi carregado",
+ "remote.badAddress": "Não é um endereço ou rede válida",
+ "remote.listFull": "A lista está cheia (64 entradas)"
}
diff --git a/assets/locales/pt/settings.json b/assets/locales/pt/settings.json
index df95c7b..da8f5a1 100644
--- a/assets/locales/pt/settings.json
+++ b/assets/locales/pt/settings.json
@@ -123,7 +123,7 @@
"sharing.remote": "Área de trabalho remota",
"sharing.remoteHint": "Outros computadores da sua rede local entram por um navegador, com usuário e senha deste computador. Com o seu mesmo usuário veem e usam esta mesma tela; com outro usuário, uma área de trabalho própria.",
"sharing.remoteToggle": "Permitir o acesso pela rede",
- "sharing.security": "Só para a rede local: a conexão é criptografada (TLS) com um certificado deste computador. Tentativas com erro esperam cada vez mais. Para usar pela internet, use uma VPN.",
+ "sharing.security": "A conexão é criptografada (TLS) com um certificado deste computador. 3 entradas com erro bloqueiam o endereço; a conta root nunca pode entrar. Para usar pela internet, use uma VPN.",
"sharing.thisSession": "vendo esta tela",
"sharing.who": "Quem pode entrar",
"sharing.whoAllHint": "Qualquer usuário deste computador com senha.",
@@ -279,5 +279,27 @@
"style.hint": "Os dois estilos têm os mesmos apps. A mudança é aplicada na hora, sem sair da sessão; as janelas abertas voltam.",
"dock.taskbarAlign": "Alinhamento da barra de tarefas",
"dock.alignCenter": "Centro",
- "dock.alignStart": "Início"
+ "dock.alignStart": "Início",
+ "sharing.access": "Quem pode se conectar",
+ "sharing.netFrom": "Permitir conexões de",
+ "sharing.netLan": "Rede local",
+ "sharing.netList": "Só estes endereços",
+ "sharing.netAny": "Qualquer endereço",
+ "sharing.netLanHint": "Endereços privados e de link local da sua rede, e conexões que chegam por uma VPN deste computador. Endereços públicos da internet são recusados.",
+ "sharing.netListHint": "Só os endereços e redes desta lista podem abrir a página de entrada.",
+ "sharing.netAnyHint": "Qualquer endereço que alcance este computador, inclusive a internet se uma porta for redirecionada para ele.",
+ "sharing.netAnyWarn": "Conexões de qualquer endereço são aceitas. Entradas com erro continuam bloqueando o endereço, mas uma VPN é o jeito mais seguro de chegar a este computador pela internet.",
+ "sharing.allowEmpty": "A lista está vazia: ninguém pode se conectar.",
+ "sharing.allowPlaceholder": "Endereço ou rede, ex.: 192.168.1.0/24",
+ "sharing.allowAdd": "Adicionar",
+ "sharing.remove": "Remover",
+ "sharing.blocked": "Endereços bloqueados",
+ "sharing.blockedFooter": "Um endereço é bloqueado após 3 entradas com erro: 15 minutos, depois 1 hora e depois 24 horas se acontecer de novo no mesmo dia. Você recebe uma notificação quando isso acontece.",
+ "sharing.blockedNone": "Nenhum endereço está bloqueado.",
+ "sharing.blockedManual": "Bloqueado por um administrador",
+ "sharing.blockedAuto": "Entradas com erro · faltam {minutes} min",
+ "sharing.unblock": "Desbloquear",
+ "sharing.block": "Bloquear",
+ "sharing.blockPlaceholder": "Endereço ou rede para bloquear",
+ "sharing.badAddress": "Digite um endereço IPv4 ou IPv6, ou uma rede como 192.168.1.0/24 (pelo menos /8; IPv6 pelo menos /16)."
}
diff --git a/assets/locales/pt/shell.json b/assets/locales/pt/shell.json
index 6989a8b..81adc87 100644
--- a/assets/locales/pt/shell.json
+++ b/assets/locales/pt/shell.json
@@ -209,5 +209,8 @@
"classic.snapRight": "Encaixar na metade direita",
"classic.close": "Fechar",
"classic.personalize": "Personalizar",
- "classic.displaySettings": "Configurações de tela"
+ "classic.displaySettings": "Configurações de tela",
+ "remote.blockedTitle": "Área de trabalho remota: endereço bloqueado",
+ "remote.blockedBody": "{ip} errou a entrada 3 vezes e foi bloqueado por {minutes} min.",
+ "remote.blockedOpen": "Abrir Compartilhar"
}
diff --git a/assets/locales/pt/status.json b/assets/locales/pt/status.json
index a4fac18..d462950 100644
--- a/assets/locales/pt/status.json
+++ b/assets/locales/pt/status.json
@@ -120,5 +120,7 @@
"ssh.off": "Login remoto desativado",
"ssh.on": "Login remoto ativado",
"ssh.saved": "Configurações salvas",
- "hw.firmwareChecked": "Firmware verificado"
+ "hw.firmwareChecked": "Firmware verificado",
+ "remote.blocked": "{address} bloqueado",
+ "remote.unblocked": "{address} desbloqueado"
}
diff --git a/sdk/index.js b/sdk/index.js
index b7e58dc..a8a1a2c 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -20,7 +20,7 @@ import { ImeOverlay } from './ime.js';
import { ClipboardPanel, ClipboardToast, clipboard as clipboardApi } from './clipboard.js';
import { SpotlightPanel } from './spotlight.js';
import { RemoteBadge } from './remote.js';
-export { remote, remoteViewers, sshLogin } from './remote.js';
+export { remote, remoteViewers, sshLogin, remoteCidr, remoteMinutesLeft } from './remote.js';
export { perms, permsRev, requestPermission, markDeviceUse, useIndicators, PrivacyIndicators, PermissionPrompt, registerPrivacySection, privacySections, PERMISSIONS, onPermissionRevoked, micStart, micStop, micLevel } from './privacy.js';
import { PermissionPrompt } from './privacy.js';
import { Powerbox } from './powerbox.jsx';
diff --git a/sdk/remote.js b/sdk/remote.js
index 2e2b6f4..8a25d9e 100644
--- a/sdk/remote.js
+++ b/sdk/remote.js
@@ -5,24 +5,64 @@
// fixed notice at the top right while there are connections, in every theme.
//
// useStore(remoteViewers) → [{ ip, user }]
-// remote.status() → { enabled, installed, port, allow, fingerprint, clients: [...], sessions: [...], monitor }
+// remote.status() → { enabled, installed, port, allow, net: 'lan'|'list'|'any', fingerprint, clients: [...],
+// sessions: [...], monitor, blocked: [{ ip, until, strikes, manual }], allowed: ['cidr'] }
+// remoteCidr(text) → canonical-looking text if it's an address or network the admin actions accept, else ''
+// (lord-sessiond's helper checks again, strictly: server/src/remote/ipnet.c)
+// lord-sessiond's notice "this source was blocked after failed logins" arrives as __lordRemoteNotice and is
+// shown as a notification that opens Settings → Sharing.
// sshLogin.status() → { installed, enabled, running, allow: 'all'|'admins', fingerprint } (remote login, SSH)
import { createElement as h } from 'react';
import { View, Text } from '@lordos/runtime';
import { createStore, useStore } from './store.js';
import { t } from './i18n.js';
+import { notify } from './notify.js';
+import { wm } from './windows.js';
export const remoteViewers = createStore([]);
globalThis.__lordRemote = (json) => {
try { remoteViewers.set(JSON.parse(json)); } catch (e) { remoteViewers.set([]); }
};
+// Mirrors rs_cidr_parse: IPv4 (no leading zeros) with /8../32, or IPv6 with /16../128.
+export function remoteCidr(text) {
+ const s = String(text || '').trim();
+ const m = /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/.exec(s);
+ if (!m || (m[2] && m[2].length > 1 && m[2][0] === '0')) return '';
+ const len = m[2] === undefined ? null : Number(m[2]);
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(m[1])) {
+ if (m[1].split('.').some((o) => Number(o) > 255 || (o.length > 1 && o[0] === '0'))) return '';
+ if (len !== null && (len < 8 || len > 32)) return '';
+ return s;
+ }
+ if (!m[1].includes(':') || m[1].length > 45 || (m[1].match(/::/g) || []).length > 1) return '';
+ const groups = m[1].split(':');
+ if (groups.length > 8 || groups.some((g) => g.length > 4 && !/\./.test(g))) return '';
+ if (len !== null && (len < 16 || len > 128)) return '';
+ return s;
+}
+
+const minutesLeft = (until) => Math.max(1, Math.round((until - Date.now() / 1000) / 60));
+globalThis.__lordRemoteNotice = (n) => {
+ if (!n || n.t !== 'blocked' || typeof n.ip !== 'string' || !/^[0-9a-fA-F:./]{3,48}$/.test(n.ip)) return;
+ const min = Math.max(1, Math.min(1440, Number(n.min) || 15));
+ notify({
+ app: 'settings',
+ title: t('shell.remote.blockedTitle'),
+ body: t('shell.remote.blockedBody', { ip: n.ip, minutes: min }),
+ sticky: true,
+ actions: [{ id: 'open', label: t('shell.remote.blockedOpen'), run: () => wm.open('settings', { args: { section: 'sharing' } }) }],
+ });
+};
+export const remoteMinutesLeft = minutesLeft;
+
function parseConfig(text) {
- const c = { port: 5673, allow: 'all' };
+ const c = { port: 5673, allow: 'all', net: 'lan' };
for (const line of String(text || '').split('\n')) {
const m = /^(\w+)=(.*)$/.exec(line.trim());
if (m && m[1] === 'port') c.port = Number(m[2]) || 5673;
if (m && m[1] === 'allow') c.allow = m[2] === 'group' ? 'group' : 'all';
+ if (m && m[1] === 'net') c.net = ['lan', 'list', 'any'].includes(m[2]) ? m[2] : 'lan';
}
return c;
}
@@ -30,7 +70,7 @@ function parseConfig(text) {
export const remote = {
available: () => typeof lord.remote !== 'undefined',
status() {
- if (typeof lord.remote === 'undefined') return { enabled: false, installed: false, clients: [], sessions: [], monitor: '' };
+ if (typeof lord.remote === 'undefined') return { enabled: false, installed: false, net: 'lan', clients: [], sessions: [], monitor: '', blocked: [], allowed: [] };
const s = lord.remote.status();
const cfg = parseConfig(s.config);
let st = null;
@@ -38,6 +78,7 @@ export const remote = {
return {
installed: !!s.installed, enabled: !!(st && st.running), port: st?.port || cfg.port, allow: st?.allow || cfg.allow,
fingerprint: s.fingerprint || '', clients: st?.clients || [], sessions: st?.sessions || [], monitor: st?.monitor || '',
+ net: st?.net || cfg.net, blocked: Array.isArray(st?.blocked) ? st.blocked : [], allowed: Array.isArray(st?.allowed) ? st.allowed : [],
};
},
};
diff --git a/server/Makefile b/server/Makefile
index be2d721..60de4db 100644
--- a/server/Makefile
+++ b/server/Makefile
@@ -55,7 +55,7 @@ MEDIA_SRC := src/media/media.c src/media/hwdec.c src/media/mview.c src/media/cap
SEC_SRC := src/sec/json.c src/sec/sign.c src/sec/pkgstate.c src/sec/perms.c src/sec/cgroup.c src/sec/sandbox.c src/sec/brokersrv.c src/sec/brokercam.c src/sec/brokerkr.c src/sec/brokermail.c src/sec/restrict.c src/sec/appid.c src/sec/pwguard.c src/sec/codesig.c
# App mode: lord-server --app <id> runs an .lpk app as an isolated Wayland client (src/app)
APP_SRC := src/app/appclient.c src/app/appspawn.c src/ui/js_broker.c src/ui/js_brokercam.c src/ui/js_brokermail.c src/app/apphost_bc.c
-SRC := src/main.c src/kms.c src/gpu/gpu.c src/input.c src/canvas.c src/admin.c src/install/install.c src/apps.c src/lpk.c src/fsops.c src/remote/mirror.c src/remote/remote_admin.c src/remote/ssh_admin.c src/users/users_admin.c src/users/homedirs.c src/keyboard.c src/keylag.c src/ime.c src/wl/wl.c src/wl/x11wire.c src/wl/xwm.c src/wl/xwayland.c \
+SRC := src/main.c src/kms.c src/gpu/gpu.c src/input.c src/canvas.c src/admin.c src/install/install.c src/apps.c src/lpk.c src/fsops.c src/remote/mirror.c src/remote/remote_admin.c src/remote/ipnet.c src/remote/ssh_admin.c src/users/users_admin.c src/users/homedirs.c src/keyboard.c src/keylag.c src/ime.c src/wl/wl.c src/wl/x11wire.c src/wl/xwm.c src/wl/xwayland.c \
src/ui/node.c src/ui/style.c src/ui/layout.c src/ui/transform.c src/ui/text.c src/ui/image.c \
src/ui/paint.c src/ui/js.c src/ui/js_sys.c src/ui/js_term.c src/ui/js_wasm.c src/wasm/wasm.c src/wasm/wasm_run.c src/ui/js_sound.c src/ui/js_net.c src/sound/snd.c src/sound/pulse.c src/ui/otf.c src/ui/fonts.c \
src/ui/unicode.c src/ui/bidi.c src/ui/shape.c src/ui/shape_indic.c src/ui/shape_syl.c src/ui/shape_khmer.c src/ui/shape_myanmar.c src/ui/shape_use.c src/ui/thbrk.c src/ui/textlayout.c \
@@ -233,6 +233,20 @@ build/tzif-test: tests/tzif_test.c src/ui/tzif.c src/ui/tzif.h
@mkdir -p build
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/tzif_test.c src/ui/tzif.c
./$@ || { rm -f $@; exit 1; }
+# remote desktop security (docs/REMOTE.md, "Security analysis (0.8.3)"): the strict HTTP, form,
+# cookie, WebSocket and JSON parsers, addresses and networks, the failed-login lockout and the
+# connection rate; then the same parsers under ASan+UBSan with many random and mutated inputs
+REMOTE_SEC_SRC := src/remote/rsec.c src/remote/ipnet.c src/remote/lockout.c
+test: build/remote-sec-test build/remote-fuzz
+build/remote-sec-test: tests/remote_sec_test.c $(REMOTE_SEC_SRC) src/remote/rsec.h src/remote/ipnet.h src/remote/lockout.h
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/remote_sec_test.c $(REMOTE_SEC_SRC)
+ ./$@ || { rm -f $@; exit 1; }
+build/remote-fuzz: tests/remote_fuzz.c $(REMOTE_SEC_SRC) src/remote/rsec.h src/remote/ipnet.h src/remote/lockout.h
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) -O1 -g $(WARN) -std=c11 -fsanitize=address,undefined -fno-sanitize-recover=all -fno-omit-frame-pointer \
+ -o $@ tests/remote_fuzz.c $(REMOTE_SEC_SRC)
+ ./$@ 100000 || { rm -f $@; exit 1; }
# journal reader (Logs): normal and compact synthetic files, LZ4 and XZ, broken and
# truncated files; `build/journal-test dump <file>` dumps JSON to compare with journalctl
test: build/journal-test
@@ -438,7 +452,8 @@ build/lord-server: $(OBJ) build/obj/ui/stb.o $(QJS_OBJ) $(WL_OBJ)
$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)
SESSIOND_OBJ := build/obj/remote/sessiond.o build/obj/remote/sess.o build/obj/remote/monitor.o build/obj/remote/conn.o \
- build/obj/remote/enc.o build/obj/remote/pages.o build/obj/sec/cgroup.o build/obj/remote/netsup.o build/obj/remote/cgsup.o
+ build/obj/remote/enc.o build/obj/remote/pages.o build/obj/sec/cgroup.o build/obj/remote/netsup.o build/obj/remote/cgsup.o \
+ build/obj/remote/rsec.o build/obj/remote/ipnet.o build/obj/remote/lockout.o
build/obj/remote/pages.o: src/remote/login.html src/remote/client.html
@mkdir -p $(dir $@)
$(LD) -r -b binary -z noexecstack -o $@ src/remote/login.html src/remote/client.html
diff --git a/server/src/main.c b/server/src/main.c
index 8468659..7ef4ce4 100644
--- a/server/src/main.c
+++ b/server/src/main.c
@@ -527,6 +527,7 @@ static void remote_resize(int w, int h) {
}
static void remote_greeter(const char *json) { js_greeter_event(json); }
+static void remote_notice(const char *json) { js_remote_notice(json); }
/* ---- applying the display plan (Settings → Displays, hotplug; hw/display.c) ---- */
@@ -1644,7 +1645,7 @@ int main(int argc, char **argv) {
tp_route_init(&tp_host);
static const MirrorInput mirror_in = { remote_pointer, remote_button, remote_wheel, remote_key, remote_clip, remote_clients,
remote_refresh, remote_resize, remote_greeter, display_attach, display_detach,
- remote_scroll, remote_pinch, remote_input_add };
+ remote_scroll, remote_pinch, remote_input_add, remote_notice };
if (ok && mirror_start(s.W, s.H, &mirror_in)) fprintf(stderr, "lord-server: no remote desktop (socket)\n");
char current[sizeof ui.theme_request];
if (ok) ok = start_theme(theme, s.greeter, current, sizeof current) == 0;
diff --git a/server/src/remote/client.html b/server/src/remote/client.html
index b293a50..fe4b4e8 100644
--- a/server/src/remote/client.html
+++ b/server/src/remote/client.html
@@ -199,7 +199,13 @@ addEventListener('mousemove', (e) => {
if (e.clientY < 8) { $('bar').classList.add('show'); clearTimeout(hideT); hideT = setTimeout(() => $('bar').classList.remove('show'), 2500); }
});
$('fs').onclick = () => (document.fullscreenElement ? document.exitFullscreen() : document.documentElement.requestFullscreen()).then(() => setTimeout(fit, 200));
-$('out').onclick = () => { if (ws) ws.close(); location.href = '/logout'; };
+// logging out is a POST from this page (the server checks its Origin), never a link another site could open
+$('out').onclick = () => {
+ if (ws) ws.close();
+ const f = document.createElement('form');
+ f.method = 'post'; f.action = '/logout';
+ document.body.appendChild(f); f.submit();
+};
$('again').onclick = connect;
$('bar').classList.add('show'); hideT = setTimeout(() => $('bar').classList.remove('show'), 3000);
show(T.conn); connect(); cv.focus();
diff --git a/server/src/remote/conn.c b/server/src/remote/conn.c
index 6565a58..070eeb8 100644
--- a/server/src/remote/conn.c
+++ b/server/src/remote/conn.c
@@ -1,24 +1,29 @@
/* conn.c — one remote desktop connection, in a child process of lord-sessiond.
*
- * 1. TLS (OpenSSL) and one HTTP request: the login page (/), the login itself (POST /login),
- * the desktop (/desk), logout (/logout) or the WebSocket (/ws).
- * 2. Login: system user and password, checked against /etc/shadow with crypt(3). Only regular
- * accounts (uid >= 1000, with a shell, not locked; if the configuration asks for it, in the
- * lordos-remote group). Failures per IP wait longer each time (up to 5 minutes). A random
- * cookie (Secure, HttpOnly, SameSite=Strict) lasts 12 hours.
+ * 1. TLS (OpenSSL) and one HTTP request, parsed strictly (rsec.c) under a deadline: the login
+ * page (GET /), the login itself (POST /login), the desktop (GET /desk), logout (POST /logout)
+ * or the WebSocket (GET /ws). Anything else is refused and the connection closed.
+ * 2. Login: system user and password, checked against /etc/shadow with crypt(3) (sess.c). Only
+ * regular accounts (uid 1000..59999, a shell from /etc/shells, not locked, not expired, never
+ * root; if the configuration asks for it, in the lordos-remote group). Unknown and refused
+ * accounts cost the same time as a wrong password. 3 failures block the source (lockout.c):
+ * 15 min, then 1 h, then 24 h. A random cookie (__Host-, Secure, HttpOnly, SameSite=Strict,
+ * only its SHA-256 is kept) lasts 12 hours.
* 3. WebSocket: finds the user's session (the same one that may be showing on the monitor) or
- * creates it (sess.c, docs/SESSIONS.md).
- * After that this process DROPS root and stays as the user: the rest (TLS, compression,
- * bridge) runs unprivileged.
- * 4. Bridge: session rectangles → PNG/JPEG → browser; mouse, keyboard and clipboard
- * from the browser → session. Flow control: the browser acknowledges each frame ("ack") and
- * only then does the session build the next one, so a slow network gets fewer frames.
- * Browser protocol: docs/REMOTE.md. */
+ * creates it (sess.c, docs/SESSIONS.md). Then this process forks the bridge, which unmaps the
+ * shared state, closes every other descriptor and DROPS root for good: TLS, compression and
+ * the bridge run as the user. This root process only waits, and when the bridge says the
+ * session was locked it ends every cookie of that user.
+ * 4. Bridge: session rectangles → PNG/JPEG → browser; mouse, keyboard and clipboard from the
+ * browser (validated, rsec.c rs_browser_input) → session. Flow control: the browser
+ * acknowledges each frame ("ack") and only then does the session build the next one.
+ * Browser protocol and the security analysis: docs/REMOTE.md. */
#include "sessiond.h"
#include "proto.h"
+#include "rsec.h"
-#include <crypt.h>
#include <ctype.h>
+#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
@@ -30,37 +35,58 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/mman.h>
+#include <sys/prctl.h>
#include <sys/random.h>
+#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
-#include <sys/un.h>
+#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
+#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
extern const char _binary_src_remote_login_html_start[], _binary_src_remote_login_html_end[];
extern const char _binary_src_remote_client_html_start[], _binary_src_remote_client_html_end[];
+#define HEAD_SECONDS 15 /* TLS handshake + request head + body, from accept */
+#define ALARM_SECONDS 90 /* hard limit before the bridge (covers starting a session) */
+#define TOKEN_SECONDS (12 * 3600)
+
static SSL *ssl;
static int sock = -1;
-static char peer[48];
-
+static char peer[48]; /* address as shown */
+static char peer_key[48]; /* lockout key (IPv4, or the IPv6 /64) */
+static double deadline;
+static int lock_fd = -1; /* bridge → root parent: "L" = the session was locked */
+
+static double mono(void) {
+ struct timespec t;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ return (double)t.tv_sec + t.tv_nsec / 1e9;
+}
/* ---- blocking TLS I/O (before the bridge) ---- */
+static int wait_io(int out) {
+ if (!out && SSL_pending(ssl)) return 0;
+ double left = deadline - mono();
+ if (left <= 0) return -1;
+ struct pollfd p = { sock, (short)(out ? POLLOUT : POLLIN), 0 };
+ int ms = left > 10 ? 10000 : (int)(left * 1000) + 1;
+ return poll(&p, 1, ms) > 0 ? 0 : -1;
+}
+
static int tls_write_all(const void *p, size_t n) {
const char *c = p;
while (n) {
int w = SSL_write(ssl, c, n > 1u << 30 ? 1 << 30 : (int)n);
if (w <= 0) {
int e = SSL_get_error(ssl, w);
- if (e == SSL_ERROR_WANT_WRITE || e == SSL_ERROR_WANT_READ) {
- struct pollfd p2 = { sock, (short)(e == SSL_ERROR_WANT_WRITE ? POLLOUT : POLLIN), 0 };
- if (poll(&p2, 1, 10000) <= 0) return -1;
- continue;
- }
+ if ((e == SSL_ERROR_WANT_WRITE || e == SSL_ERROR_WANT_READ) && !wait_io(e == SSL_ERROR_WANT_WRITE)) continue;
return -1;
}
c += w;
@@ -69,198 +95,363 @@ static int tls_write_all(const void *p, size_t n) {
return 0;
}
-static void respond(int code, const char *status, const char *type, const char *extra, const char *body, size_t len) {
- char head[1024];
+/* ---- responses ---- */
+
+/* CSP hashes of the inline <script> and <style> of each page, so nothing else can run there */
+typedef struct { const char *start, *end; char script[64], style[64]; } Page;
+static Page login_page = { _binary_src_remote_login_html_start, _binary_src_remote_login_html_end, "", "" };
+static Page desk_page = { _binary_src_remote_client_html_start, _binary_src_remote_client_html_end, "", "" };
+
+static void hash_block(const char *s, const char *e, const char *open, const char *close, char out[64]) {
+ out[0] = 0;
+ size_t ol = strlen(open);
+ const char *a = NULL;
+ for (const char *p = s; p + ol <= e; p++) if (!memcmp(p, open, ol)) { a = p + ol; break; }
+ if (!a) return;
+ size_t cl = strlen(close);
+ const char *b = NULL;
+ for (const char *p = a; p + cl <= e; p++) if (!memcmp(p, close, cl)) { b = p; break; }
+ if (!b) return;
+ unsigned char md[32];
+ unsigned int ml = 0;
+ if (!EVP_Digest(a, (size_t)(b - a), md, &ml, EVP_sha256(), NULL)) return;
+ EVP_EncodeBlock((unsigned char *)out, md, 32);
+}
+
+static void page_hashes(Page *p) {
+ if (p->script[0]) return;
+ hash_block(p->start, p->end, "<script>", "</script>", p->script);
+ hash_block(p->start, p->end, "<style>", "</style>", p->style);
+}
+
+static const char *status_text(int code) {
+ switch (code) {
+ case 200: return "OK";
+ case 303: return "See Other";
+ case 400: return "Bad Request";
+ case 403: return "Forbidden";
+ case 404: return "Not Found";
+ case 405: return "Method Not Allowed";
+ case 408: return "Request Timeout";
+ case 413: return "Content Too Large";
+ case 414: return "URI Too Long";
+ case 415: return "Unsupported Media Type";
+ case 426: return "Upgrade Required";
+ case 431: return "Request Header Fields Too Large";
+ case 501: return "Not Implemented";
+ case 503: return "Service Unavailable";
+ default: return "Error";
+ }
+}
+
+/* Every answer: no caching, no framing, no referrer, no sniffing, no powerful features, and a CSP
+ * that only lets the page's own inline code run (or nothing, for non-HTML answers). No HSTS: the
+ * certificate is self-signed, and HSTS would make its warning impossible to get past. */
+static void respond_page(int code, const char *type, const char *extra, const char *body, size_t len, const Page *pg, const char *host) {
+ char csp[600];
+ if (pg) {
+ char wss[300] = "";
+ if (rs_valid_host(host)) snprintf(wss, sizeof wss, " wss://%s", host);
+ snprintf(csp, sizeof csp,
+ "default-src 'none'; script-src 'sha256-%s'; style-src 'sha256-%s'; img-src 'self' blob: data:; "
+ "connect-src 'self'%s; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
+ pg->script, pg->style, wss);
+ } else snprintf(csp, sizeof csp, "default-src 'none'; frame-ancestors 'none'; form-action 'none'; base-uri 'none'");
+ char head[2048];
int n = snprintf(head, sizeof head,
- "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\nConnection: close\r\nCache-Control: no-store\r\n"
- "X-Frame-Options: DENY\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: same-origin\r\n"
- "Content-Security-Policy: default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self' wss:; frame-ancestors 'none'\r\n"
- "%s\r\n", code, status, type, len, extra ? extra : "");
+ "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\nConnection: close\r\n"
+ "Cache-Control: no-store, max-age=0\r\nPragma: no-cache\r\n"
+ "X-Frame-Options: DENY\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n"
+ "Cross-Origin-Opener-Policy: same-origin\r\nCross-Origin-Resource-Policy: same-origin\r\n"
+ "Permissions-Policy: camera=(), microphone=(), geolocation=(), usb=(), serial=(), hid=(), bluetooth=(), payment=(), display-capture=()\r\n"
+ "Content-Security-Policy: %s\r\n%s\r\n", code, status_text(code), type, len, csp, extra ? extra : "");
+ if (n < 0 || (size_t)n >= sizeof head) return;
tls_write_all(head, (size_t)n);
if (len) tls_write_all(body, len);
}
+static void respond(int code, const char *extra) {
+ const char *t = status_text(code);
+ respond_page(code, "text/plain; charset=utf-8", extra, t, strlen(t), NULL, NULL);
+}
+
static void redirect(const char *to, const char *extra) {
- char h[512];
+ char h[700];
snprintf(h, sizeof h, "Location: %s\r\n%s", to, extra ? extra : "");
- respond(303, "See Other", "text/plain", h, "", 0);
+ respond_page(303, "text/plain; charset=utf-8", h, "", 0, NULL, NULL);
+}
+
+/* The login page; with an error code e (1 wrong, 2 wait, 4 blocked) marked on <html data-e>, for the
+ * answers that can't be a redirect (a blocked source's next request is refused). */
+static void send_login(int code, int e, const char *host) {
+ page_hashes(&login_page);
+ size_t len = (size_t)(login_page.end - login_page.start);
+ static const char tag[] = "<html lang=\"en\" translate=\"no\">";
+ const char *at = e ? memmem(login_page.start, len, tag, sizeof tag - 1) : NULL;
+ if (!at) { respond_page(code, "text/html; charset=utf-8", NULL, login_page.start, len, &login_page, host); return; }
+ char mark[48];
+ int ml = snprintf(mark, sizeof mark, "<html lang=\"en\" translate=\"no\" data-e=\"%d\">", e);
+ char *b = malloc(len + (size_t)ml);
+ if (!b) return;
+ size_t pre = (size_t)(at - login_page.start);
+ memcpy(b, login_page.start, pre);
+ memcpy(b + pre, mark, (size_t)ml);
+ memcpy(b + pre + (size_t)ml, at + sizeof tag - 1, len - pre - (sizeof tag - 1));
+ respond_page(code, "text/html; charset=utf-8", NULL, b, len - (sizeof tag - 1) + (size_t)ml, &login_page, host);
+ free(b);
}
/* ---- HTTP request ---- */
-typedef struct {
- char method[8], path[256], query[256];
- char cookie[256], upgrade[32], wskey[64], origin[160], host[160];
- long content_length;
- char body[4096];
- size_t body_len;
-} Req;
-
-static void header_val(const char *line, const char *name, char *out, size_t n) {
- size_t l = strlen(name);
- if (strncasecmp(line, name, l) || line[l] != ':') return;
- const char *v = line + l + 1;
- while (*v == ' ') v++;
- snprintf(out, n, "%s", v);
-}
-
-static int read_request(Req *r) {
- memset(r, 0, sizeof *r);
- char buf[16384];
+static char reqbuf[RS_MAX_HEAD + RS_MAX_BODY + 1];
+static char *body;
+static size_t body_len;
+
+/* 0, -status to answer with, or -1 to just close */
+static int read_request(RsReq *r) {
size_t len = 0;
- char *end = NULL;
- while (!end) {
- if (len >= sizeof buf - 1) return -1;
- struct pollfd p = { sock, POLLIN, 0 };
- if (!SSL_pending(ssl) && poll(&p, 1, 15000) <= 0) return -1;
- int n = SSL_read(ssl, buf + len, (int)(sizeof buf - 1 - len));
+ int rc;
+ while ((rc = rs_parse_head(reqbuf, len, r)) == RS_NEED_MORE) {
+ if (len >= RS_MAX_HEAD) return -431;
+ if (wait_io(0)) return len ? -408 : -1;
+ int n = SSL_read(ssl, reqbuf + len, (int)(RS_MAX_HEAD - len));
if (n <= 0) {
int e = SSL_get_error(ssl, n);
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE) continue;
return -1;
}
len += (size_t)n;
- buf[len] = 0;
- end = strstr(buf, "\r\n\r\n");
- }
- *end = 0;
- char *body = end + 4;
- size_t have = len - (size_t)(body - buf);
- char *line = buf, *nl = strstr(line, "\r\n");
- if (nl) *nl = 0;
- char target[512] = "";
- if (sscanf(line, "%7s %511s", r->method, target) != 2) return -1;
- char *q = strchr(target, '?');
- if (q) { *q++ = 0; snprintf(r->query, sizeof r->query, "%s", q); }
- snprintf(r->path, sizeof r->path, "%s", target);
- for (line = nl ? nl + 2 : NULL; line && *line; line = nl ? nl + 2 : NULL) {
- nl = strstr(line, "\r\n");
- if (nl) *nl = 0;
- char cl[24] = "";
- header_val(line, "Cookie", r->cookie, sizeof r->cookie);
- header_val(line, "Upgrade", r->upgrade, sizeof r->upgrade);
- header_val(line, "Sec-WebSocket-Key", r->wskey, sizeof r->wskey);
- header_val(line, "Origin", r->origin, sizeof r->origin);
- header_val(line, "Host", r->host, sizeof r->host);
- header_val(line, "Content-Length", cl, sizeof cl);
- if (cl[0]) r->content_length = atol(cl);
- }
- if (r->content_length < 0 || r->content_length > (long)sizeof r->body - 1) return -1;
- if (have > (size_t)r->content_length) have = (size_t)r->content_length;
- memcpy(r->body, body, have);
- r->body_len = have;
- while (r->body_len < (size_t)r->content_length) {
- int n = SSL_read(ssl, r->body + r->body_len, (int)((size_t)r->content_length - r->body_len));
- if (n <= 0) return -1;
- r->body_len += (size_t)n;
- }
- r->body[r->body_len] = 0;
+ }
+ if (rc < 0) return rc;
+ size_t cl = r->content_length > 0 ? (size_t)r->content_length : 0, have = len - r->head_len;
+ if (have > cl) return -400; /* one request per connection: nothing after it */
+ body = reqbuf + r->head_len;
+ while (have < cl) {
+ if (wait_io(0)) return -408;
+ int n = SSL_read(ssl, body + have, (int)(cl - have));
+ if (n <= 0) {
+ int e = SSL_get_error(ssl, n);
+ if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE) continue;
+ return -1;
+ }
+ have += (size_t)n;
+ }
+ body[cl] = 0;
+ body_len = cl;
return 0;
}
-/* application/x-www-form-urlencoded: value of a key (decoded) */
-static int form_get(const char *body, const char *key, char *out, size_t n) {
+/* "w=1280&h=800": a number of up to 5 digits, or def */
+static int query_num(const char *q, const char *key, int def) {
size_t kl = strlen(key);
- for (const char *p = body; p && *p; p = strchr(p, '&') ? strchr(p, '&') + 1 : NULL) {
- if (strncmp(p, key, kl) || p[kl] != '=') continue;
- const char *v = p + kl + 1;
- size_t o = 0;
- for (; *v && *v != '&' && o + 1 < n; v++) {
- if (*v == '+') out[o++] = ' ';
- else if (*v == '%' && isxdigit((unsigned char)v[1]) && isxdigit((unsigned char)v[2])) {
- char hx[3] = { v[1], v[2], 0 };
- out[o++] = (char)strtol(hx, NULL, 16);
- v += 2;
- } else out[o++] = *v;
+ for (const char *p = q; *p;) {
+ const char *e = strchr(p, '&');
+ size_t l = e ? (size_t)(e - p) : strlen(p);
+ if (l > kl + 1 && l <= kl + 6 && !strncmp(p, key, kl) && p[kl] == '=') {
+ int v = 0, ok = 1;
+ for (size_t i = kl + 1; i < l; i++) { if (!isdigit((unsigned char)p[i])) { ok = 0; break; } v = v * 10 + (p[i] - '0'); }
+ if (ok) return v;
}
- out[o] = 0;
- return 0;
+ p += l;
+ if (*p == '&') p++;
}
- out[0] = 0;
- return -1;
+ return def;
}
-static int query_int(const char *q, const char *key, int def) {
- char v[16];
- return form_get(q, key, v, sizeof v) == 0 && v[0] ? atoi(v) : def;
+/* Same origin, strictly: browsers always send Origin on a POST and on a WebSocket; a request
+ * without it is not from our page. Sec-Fetch-Site, when sent, must agree. */
+static int origin_ok(const RsReq *r) {
+ if (!rs_same_origin(r->origin, r->host)) return 0;
+ if (r->fetch_site[0] && strcmp(r->fetch_site, "same-origin") && strcmp(r->fetch_site, "none")) return 0;
+ return 1;
}
-/* ---- login ---- */
+/* ---- cookies (shared memory; only root processes map it) ---- */
+
+static void sha256(const void *p, size_t n, unsigned char out[32]) {
+ unsigned int l = 0;
+ if (!EVP_Digest(p, n, out, &l, EVP_sha256(), NULL)) memset(out, 0, 32);
+}
-static int ct_equal(const char *a, const char *b) {
- size_t la = strlen(a), lb = strlen(b);
- unsigned char d = (unsigned char)(la != lb);
- for (size_t i = 0; i < la && i < lb; i++) d |= (unsigned char)(a[i] ^ b[i]);
- return d == 0;
+/* a digest of the account's shadow hash: if the password changes or gets locked, cookies end */
+static void pw_digest(const char *user, unsigned char out[16]) {
+ struct spwd *sp = getspnam(user);
+ unsigned char md[32];
+ const char *h = sp && sp->sp_pwdp ? sp->sp_pwdp : "";
+ sha256(h, strlen(h), md);
+ memcpy(out, md, 16);
+ explicit_bzero(md, sizeof md);
}
-static void new_token(uid_t uid, const char *user, char out[65]) {
+static int new_token(uid_t uid, const char *user, char out[65]) {
unsigned char r[32];
- if (getrandom(r, sizeof r, 0) != sizeof r) { out[0] = 0; return; }
+ if (getrandom(r, sizeof r, 0) != sizeof r) { out[0] = 0; return -1; }
for (int i = 0; i < 32; i++) snprintf(out + i * 2, 3, "%02x", r[i]);
+ explicit_bzero(r, sizeof r);
+ RdToken t = { .uid = uid, .expires = rd_now() + TOKEN_SECONDS };
+ sha256(out, 64, t.hash);
+ pw_digest(user, t.pwh);
+ snprintf(t.user, sizeof t.user, "%.32s", user);
double now = rd_now();
rd_lock();
int slot = 0;
- for (int i = 0; i < 64; i++) if (rd_shared->tokens[i].expires < rd_shared->tokens[slot].expires) slot = i;
- RdToken *t = &rd_shared->tokens[slot];
- snprintf(t->tok, sizeof t->tok, "%s", out);
- t->uid = uid;
- snprintf(t->user, sizeof t->user, "%.32s", user);
- t->expires = now + 12 * 3600;
+ for (int i = 0; i < 64; i++) {
+ RdToken *x = &rd_shared->tokens[i];
+ if (x->expires <= now) { slot = i; break; }
+ if (x->expires < rd_shared->tokens[slot].expires) slot = i;
+ }
+ rd_shared->tokens[slot] = t;
rd_unlock();
+ return 0;
}
-static int token_from_cookie(const char *cookie, char out[65]) {
- const char *p = strstr(cookie, "lordos_remote=");
- out[0] = 0;
- if (!p) return -1;
- p += 14;
- size_t n = 0;
- while (n < 64 && isxdigit((unsigned char)p[n])) n++;
- if (n != 64) return -1;
- memcpy(out, p, 64);
- out[64] = 0;
- return 0;
+static void token_drop_hash(const unsigned char h[32]) {
+ rd_lock();
+ for (int i = 0; i < 64; i++)
+ if (!CRYPTO_memcmp(rd_shared->tokens[i].hash, h, 32)) memset(&rd_shared->tokens[i], 0, sizeof rd_shared->tokens[i]);
+ rd_unlock();
+}
+
+void rd_tokens_drop_uid(uid_t uid) {
+ rd_lock();
+ for (int i = 0; i < 64; i++)
+ if (rd_shared->tokens[i].expires > 0 && rd_shared->tokens[i].uid == uid) memset(&rd_shared->tokens[i], 0, sizeof rd_shared->tokens[i]);
+ rd_unlock();
+}
+
+void rd_tokens_clear(void) {
+ rd_lock();
+ memset(rd_shared->tokens, 0, sizeof rd_shared->tokens);
+ rd_unlock();
}
-/* user from the cookie, or -1 */
-static int session_user(const Req *r, char user[33], uid_t *uid) {
+/* user from the cookie, or -1; *hash = the cookie's digest (to drop it on logout) */
+static int session_user(const RsReq *r, char user[33], uid_t *uid, unsigned char hash[32]) {
char tok[65];
- if (token_from_cookie(r->cookie, tok)) return -1;
+ memset(hash, 0, 32);
+ if (rs_cookie_token(r->cookie, RD_COOKIE, tok)) return -1;
+ sha256(tok, 64, hash);
+ explicit_bzero(tok, sizeof tok);
double now = rd_now();
int ok = -1;
+ unsigned char pwh[16];
rd_lock();
for (int i = 0; i < 64; i++) {
RdToken *t = &rd_shared->tokens[i];
- if (t->tok[0] && t->expires > now && ct_equal(t->tok, tok)) { snprintf(user, 33, "%s", t->user); *uid = t->uid; ok = 0; }
+ if (t->expires > now && !CRYPTO_memcmp(t->hash, hash, 32)) {
+ snprintf(user, 33, "%s", t->user);
+ *uid = t->uid;
+ memcpy(pwh, t->pwh, 16);
+ ok = 0;
+ }
}
rd_unlock();
if (ok == 0) { /* the account may have changed since login */
struct passwd *pw = getpwnam(user);
- if (!pw || pw->pw_uid != *uid || !sd_user_allowed(pw, 1)) ok = -1;
+ unsigned char now_pwh[16];
+ pw_digest(user, now_pwh);
+ if (!pw || pw->pw_uid != *uid || !sd_remote_account_ok(user) || CRYPTO_memcmp(now_pwh, pwh, 16)) {
+ token_drop_hash(hash);
+ ok = -1;
+ }
}
return ok;
}
-static void token_drop_tok(const char *tok) {
- if (!tok[0]) return;
- rd_lock();
- for (int i = 0; i < 64; i++) if (ct_equal(rd_shared->tokens[i].tok, tok)) memset(&rd_shared->tokens[i], 0, sizeof rd_shared->tokens[i]);
- rd_unlock();
-}
+#define CLEAR_COOKIES "Set-Cookie: " RD_COOKIE "=; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=0\r\n" \
+ "Set-Cookie: lordos_remote=; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=0\r\n"
+
+/* ---- login ---- */
-/* The login page, with an optional message (?e=1 password, ?e=2 wait). */
-static void send_login(const Req *r) {
- respond(200, "OK", "text/html; charset=utf-8", NULL, _binary_src_remote_login_html_start,
- (size_t)(_binary_src_remote_login_html_end - _binary_src_remote_login_html_start));
- (void)r;
+static void push_notice(const char *key, double until, int strikes) {
+ unsigned i = rd_shared->notice_seq % RD_NOTICES;
+ RdNotice *n = &rd_shared->notices[i];
+ snprintf(n->key, sizeof n->key, "%s", key);
+ n->until = until;
+ n->at = rd_now();
+ n->strikes = strikes;
+ rd_shared->notice_seq++;
}
-/* Same origin (protects the login form from other sites). */
-static int same_origin(const Req *r) {
- if (!r->origin[0]) return 1;
- const char *o = strstr(r->origin, "://");
- return o && !strcmp(o + 3, r->host);
+static void handle_login(const RsReq *r) {
+ if (r->query[0]) { respond(400, NULL); return; } /* credentials never travel in a URL */
+ if (!origin_ok(r)) {
+ char o[64], h[64];
+ rs_log_clean(r->origin, strlen(r->origin), o, sizeof o);
+ rs_log_clean(r->host, strlen(r->host), h, sizeof h);
+ sd_log("login refused: origin \"%s\" is not https://%s", o, h);
+ respond(403, NULL);
+ return;
+ }
+ if (!rs_form_type(r->ctype)) { respond(415, NULL); return; }
+ rd_lock();
+ double left = rl_blocked(&rd_shared->lockout, peer_key, rd_now());
+ rd_unlock();
+ if (left > 0) { send_login(403, 4, r->host); return; }
+ if (sd_fail_wait(peer_key) > 0) { redirect("/?e=2", NULL); return; }
+
+ char user[33], pass[RS_PASS_MAX + 1], raw[33];
+ size_t plen = 0;
+ int fr = rs_parse_login(body, body_len, user, pass, &plen, raw);
+ explicit_bzero(reqbuf, sizeof reqbuf);
+ if (fr == RS_FORM_BAD) {
+ sd_log("login refused: malformed form");
+ respond(400, NULL);
+ return;
+ }
+ int ok = 0;
+ char ukey[40] = "";
+ if (fr == RS_FORM_OK) {
+ snprintf(ukey, sizeof ukey, "u:%s", user);
+ double d = rl_user_delay(sd_fail_count(ukey)); /* per account: slower, never locked */
+ if (d > 0) sleep((unsigned)d);
+ ok = sd_check_password(user, pass, 1);
+ }
+ explicit_bzero(pass, sizeof pass);
+ if (!ok) {
+ sd_fail_note(peer_key, 1);
+ if (ukey[0]) sd_fail_note(ukey, 1);
+ double until = 0;
+ int strikes = 0;
+ rd_lock();
+ int blocked = rl_fail(&rd_shared->lockout, peer_key, rd_now(), &until, &strikes);
+ if (blocked) push_notice(peer_key, until, strikes);
+ rd_shared->lockout_dirty = 1;
+ rd_shared->version++;
+ rd_unlock();
+ sd_log("failed login for \"%s\"%s", raw[0] ? raw : "?", fr == RS_FORM_USER ? " (not a valid user name)" : "");
+ if (blocked) {
+ sd_log("blocked %s for %.0f minutes after %d failed logins (block %d in 24 h)", peer_key, (until - rd_now()) / 60 + 0.5,
+ RL_FAILS, strikes);
+ sleep(1);
+ send_login(403, 4, r->host);
+ return;
+ }
+ sleep(1);
+ redirect("/?e=1", NULL);
+ return;
+ }
+ rd_lock();
+ rl_success(&rd_shared->lockout, peer_key);
+ rd_shared->lockout_dirty = 1;
+ rd_unlock();
+ sd_fail_note(peer_key, 0);
+ sd_fail_note(ukey, 0);
+ struct passwd *pw = getpwnam(user);
+ if (!pw) { respond(503, NULL); return; }
+ /* a cookie the browser already had is never kept (no fixation): it ends here */
+ unsigned char oldh[32];
+ char olduser[33];
+ uid_t olduid;
+ if (session_user(r, olduser, &olduid, oldh) == 0) token_drop_hash(oldh);
+ char tok[65], cookie[400];
+ if (new_token(pw->pw_uid, user, tok)) { respond(503, NULL); return; }
+ snprintf(cookie, sizeof cookie, "Set-Cookie: " RD_COOKIE "=%s; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=%d\r\n"
+ "Set-Cookie: lordos_remote=; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=0\r\n", tok, TOKEN_SECONDS);
+ explicit_bzero(tok, sizeof tok);
+ sd_log("%s logged in", user);
+ redirect("/desk", cookie);
+ explicit_bzero(cookie, sizeof cookie);
}
/* ---- WebSocket ---- */
@@ -293,6 +484,7 @@ static void ws_frame(int opcode, const void *a, size_t an, const void *b, size_t
if (bn) wput(b, bn);
}
+static void ws_text(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void ws_text(const char *fmt, ...) {
char buf[1024];
va_list ap;
@@ -302,8 +494,14 @@ static void ws_text(const char *fmt, ...) {
if (n > 0 && (size_t)n < sizeof buf) ws_frame(1, buf, (size_t)n, NULL, 0);
}
-/* text as a JSON string (for the clipboard) */
+static void ws_close(int code) {
+ unsigned char c[2] = { (unsigned char)(code >> 8), (unsigned char)code };
+ ws_frame(8, c, 2, NULL, 0);
+}
+
+/* text as a JSON string (for the clipboard); invalid UTF-8 from the session is not sent */
static void ws_clip(const char *t, size_t n) {
+ if (n > RS_CLIP_MAX || !rs_utf8_valid((const unsigned char *)t, n)) return;
size_t cap = n * 6 + 32, o = 0;
char *j = malloc(cap);
if (!j) return;
@@ -311,7 +509,7 @@ static void ws_clip(const char *t, size_t n) {
for (size_t i = 0; i < n; i++) {
unsigned char c = (unsigned char)t[i];
if (c == '"' || c == '\\') { j[o++] = '\\'; j[o++] = (char)c; }
- else if (c < 0x20) o += (size_t)snprintf(j + o, cap - o, "\\u%04x", c);
+ else if (c < 0x20 || c == 0x7f) o += (size_t)snprintf(j + o, cap - o, "\\u%04x", c);
else j[o++] = (char)c;
}
o += (size_t)snprintf(j + o, cap - o, "\"}");
@@ -333,7 +531,7 @@ static int ws_flush(void) {
return 0;
}
-static int ws_handshake(const Req *r) {
+static int ws_handshake(const RsReq *r) {
static const char guid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
char k[128];
snprintf(k, sizeof k, "%s%s", r->wskey, guid);
@@ -348,7 +546,7 @@ static int ws_handshake(const Req *r) {
return tls_write_all(head, (size_t)n);
}
-/* ---- bridge ---- */
+/* ---- bridge (runs as the user) ---- */
static int sess = -1; /* session socket */
static uint32_t *fb; /* copy of the screen (to replace with PNG) */
@@ -357,6 +555,7 @@ typedef struct { uint16_t x, y, w, h; } Box16;
static Box16 jpegs[512];
static int njpegs;
static double last_frame;
+static int locked, closing;
static void sess_send(int type, const void *a, size_t an) {
unsigned char h[5];
@@ -367,9 +566,6 @@ static void sess_send(int type, const void *a, size_t an) {
if (an && write(sess, a, an) != (ssize_t)an) return;
}
-static char my_token[65]; /* this connection's cookie (wiped on lock) */
-static int locked; /* the session got locked: cut off */
-
static void send_rect(int x, int y, int w, int h, int allow_jpeg) {
int len = 0, jpeg = 0;
unsigned char *img = rd_encode(fb + (size_t)y * W + x, W, w, h, allow_jpeg, &len, &jpeg);
@@ -389,6 +585,7 @@ static void from_session(int type, const unsigned char *d, uint32_t n) {
{
uint16_t s[2];
memcpy(s, d, 4);
+ if (!s[0] || !s[1] || s[0] > 8192 || s[1] > 8192) break;
W = s[0];
H = s[1];
free(fb);
@@ -419,14 +616,14 @@ static void from_session(int type, const unsigned char *d, uint32_t n) {
int16_t x, y;
memcpy(&x, d, 2);
memcpy(&y, d + 2, 2);
- ws_text("{\"t\":\"cur\",\"x\":%d,\"y\":%d,\"m\":%d}", x, y, d[4]);
+ ws_text("{\"t\":\"cur\",\"x\":%d,\"y\":%d,\"m\":%d}", x, y, d[4] > 2 ? 0 : d[4]);
}
break;
case RP_SHAPE:
if (n >= 8) {
uint16_t s[4];
memcpy(s, d, 8);
- if (n < 8 + (uint32_t)s[0] * s[1] * 4 || !s[0] || !s[1]) break;
+ if (!s[0] || !s[1] || s[0] > 512 || s[1] > 512 || n < 8 + (uint32_t)s[0] * s[1] * 4) break;
uint32_t *px = malloc((size_t)s[0] * s[1] * 4);
if (!px) break;
memcpy(px, d + 8, (size_t)s[0] * s[1] * 4);
@@ -443,9 +640,9 @@ static void from_session(int type, const unsigned char *d, uint32_t n) {
break;
case RP_CLIP: ws_clip((const char *)d, n); break;
case RP_SESSION:
- /* the user locked their session: this browser has to log in again too */
+ /* the user locked their session: every browser of this user has to log in again */
if (n >= 10 && memmem(d, n, "\"lock\"", 6)) {
- token_drop_tok(my_token);
+ if (lock_fd >= 0 && write(lock_fd, "L", 1) != 1) { /* the root parent is gone: the cookie expires anyway */ }
ws_text("{\"t\":\"bye\",\"lock\":1}");
locked = 1;
}
@@ -454,110 +651,64 @@ static void from_session(int type, const unsigned char *d, uint32_t n) {
}
}
-/* Flat JSON from the browser: {"t":"m","x":1,"y":2} — number or string of a key */
-static int jnum(const char *j, const char *key, long *out) {
- char k[24];
- snprintf(k, sizeof k, "\"%s\":", key);
- const char *p = strstr(j, k);
- if (!p) return -1;
- char *e;
- long v = strtol(p + strlen(k), &e, 10);
- if (e == p + strlen(k)) return -1;
- *out = v;
- return 0;
-}
-
-static int jstr(const char *j, const char *key, char *out, size_t n) {
- char k[24];
- snprintf(k, sizeof k, "\"%s\":\"", key);
- const char *p = strstr(j, k);
- if (!p) return -1;
- p += strlen(k);
- size_t o = 0;
- for (; *p && *p != '"' && o + 4 < n; p++) {
- if (*p != '\\') { out[o++] = *p; continue; }
- p++;
- if (*p == 'n') out[o++] = '\n';
- else if (*p == 't') out[o++] = '\t';
- else if (*p == 'r') out[o++] = '\r';
- else if (*p == 'u' && isxdigit((unsigned char)p[1]) && isxdigit((unsigned char)p[2]) && isxdigit((unsigned char)p[3]) && isxdigit((unsigned char)p[4])) {
- char hx[5] = { p[1], p[2], p[3], p[4], 0 };
- unsigned cp = (unsigned)strtol(hx, NULL, 16);
- p += 4;
- if (cp < 0x80) out[o++] = (char)cp;
- else if (cp < 0x800) { out[o++] = (char)(0xc0 | cp >> 6); out[o++] = (char)(0x80 | (cp & 63)); }
- else { out[o++] = (char)(0xe0 | cp >> 12); out[o++] = (char)(0x80 | ((cp >> 6) & 63)); out[o++] = (char)(0x80 | (cp & 63)); }
- } else if (*p) out[o++] = *p;
- else break;
- }
- out[o] = 0;
- return (int)o;
-}
-
+/* One validated browser message → session. */
static void from_browser(const char *j, size_t n) {
- char t[12] = "";
- if (jstr(j, "t", t, sizeof t) < 0) return;
- long a = 0, b = 0;
- if (!strcmp(t, "m") && !jnum(j, "x", &a) && !jnum(j, "y", &b)) {
- if (a < 0) a = 0;
- if (b < 0) b = 0;
- if (a >= W) a = W - 1;
- if (b >= H) b = H - 1;
- int16_t p[2] = { (int16_t)a, (int16_t)b };
- sess_send(RP_PTR, p, 4);
- } else if (!strcmp(t, "b") && !jnum(j, "b", &a) && !jnum(j, "d", &b) && a >= 0 && a <= 2) {
- unsigned char p[2] = { (unsigned char)a, (unsigned char)(b != 0) };
- sess_send(RP_BTN, p, 2);
- } else if (!strcmp(t, "w") && !jnum(j, "d", &a)) {
- signed char d = (signed char)(a > 10 ? 10 : a < -10 ? -10 : a);
- sess_send(RP_WHEEL, &d, 1);
- } else if ((!strcmp(t, "s") || !strcmp(t, "pz")) && !jnum(j, "p", &a) && a >= 1 && a <= 3) {
- /* browser trackpad: fine scroll {t:'s', p, x, y} (1/256 px) or pinch {t:'pz', p, s, r}
- * (scale ×65536, rotation in degrees ×256) */
- long v1 = 0, v2 = 0;
- int sc = !strcmp(t, "s");
- if (jnum(j, sc ? "x" : "s", &v1) || jnum(j, sc ? "y" : "r", &v2)) return;
- long lim = sc ? 4000L * 256 : 20L * 65536;
- if (v1 > lim) v1 = lim;
- if (v1 < -lim) v1 = -lim;
- if (v2 > 360L * 256 * 4) v2 = 360L * 256 * 4;
- if (v2 < -360L * 256 * 4) v2 = -360L * 256 * 4;
- if (sc && (v2 > lim || v2 < -lim)) v2 = v2 > 0 ? lim : -lim;
- unsigned char p[9];
- int32_t w[2] = { (int32_t)v1, (int32_t)v2 };
- p[0] = (unsigned char)a;
- memcpy(p + 1, w, 8);
- sess_send(sc ? RP_SCROLL : RP_PINCH, p, 9);
- } else if (!strcmp(t, "k") && !jnum(j, "c", &a) && !jnum(j, "d", &b) && a > 0 && a < 0x2ff) {
- unsigned char p[3];
- uint16_t c = (uint16_t)a;
- memcpy(p, &c, 2);
- p[2] = (unsigned char)(b != 0);
- sess_send(RP_KEY, p, 3);
- } else if (!strcmp(t, "ack")) sess_send(RP_READY, NULL, 0);
- else if (!strcmp(t, "resize") && !jnum(j, "w", &a) && !jnum(j, "h", &b) && a >= 640 && b >= 480 && a <= 3840 && b <= 2400) {
- uint16_t sz[2] = { (uint16_t)(a & ~1), (uint16_t)(b & ~1) }; /* if the monitor shows it, the monitor wins */
- sess_send(RP_RESIZE, sz, 4);
- }
- else if (!strcmp(t, "ping") && !jnum(j, "ts", &a)) ws_text("{\"t\":\"pong\",\"ts\":%ld}", a);
- else if (!strcmp(t, "clip")) {
- char *txt = malloc(n + 1);
- if (txt) {
- int l = jstr(j, "text", txt, n + 1);
- if (l > 0) sess_send(RP_SETCLIP, txt, (size_t)l);
- free(txt);
+ char *sb = malloc(n + 1);
+ if (!sb) return;
+ RsJson o;
+ RsInput in;
+ if (rs_json_parse(j, n, &o, sb, n + 1) == 0) {
+ switch (rs_browser_input(&o, W, H, &in)) {
+ case RS_IN_PTR: { int16_t p[2] = { (int16_t)in.a, (int16_t)in.b }; sess_send(RP_PTR, p, 4); break; }
+ case RS_IN_BTN: { unsigned char p[2] = { (unsigned char)in.a, (unsigned char)in.b }; sess_send(RP_BTN, p, 2); break; }
+ case RS_IN_WHEEL: { signed char d = (signed char)in.a; sess_send(RP_WHEEL, &d, 1); break; }
+ case RS_IN_SCROLL:
+ case RS_IN_PINCH: {
+ unsigned char p[9];
+ int32_t w[2] = { in.v1, in.v2 };
+ p[0] = (unsigned char)in.a;
+ memcpy(p + 1, w, 8);
+ sess_send(in.type == RS_IN_SCROLL ? RP_SCROLL : RP_PINCH, p, 9);
+ break;
+ }
+ case RS_IN_KEY: {
+ unsigned char p[3];
+ uint16_t c = (uint16_t)in.a;
+ memcpy(p, &c, 2);
+ p[2] = (unsigned char)in.b;
+ sess_send(RP_KEY, p, 3);
+ break;
+ }
+ case RS_IN_ACK: sess_send(RP_READY, NULL, 0); break;
+ case RS_IN_RESIZE: { uint16_t sz[2] = { (uint16_t)in.a, (uint16_t)in.b }; sess_send(RP_RESIZE, sz, 4); break; }
+ case RS_IN_PING: ws_text("{\"t\":\"pong\",\"ts\":%lld}", in.ts); break;
+ case RS_IN_CLIP: sess_send(RP_SETCLIP, in.text, in.tlen); break;
+ default: break;
}
}
+ explicit_bzero(sb, n + 1);
+ free(sb);
+}
+
+static void on_ws(void *ud, int op, unsigned char *data, size_t len) {
+ (void)ud;
+ if (closing) return;
+ if (op == 1) from_browser((const char *)data, len);
+ else if (op == 9) ws_frame(10, data, len, NULL, 0);
+ else if (op == 8) { ws_close(1000); closing = 1; }
+ else if (op == 2) { ws_close(1003); closing = 1; } /* our page never sends binary */
}
-/* Reads frames from the browser (masked). Returns -1 if it closed. */
+/* Reads frames from the browser (rsec.c). Returns -1 if the connection is over. */
static unsigned char *win;
static size_t win_len, win_cap;
+static RsWs wsr;
+
static int ws_read(void) {
for (;;) {
if (win_cap - win_len < 16384) {
size_t cap = win_cap ? win_cap * 2 : 65536;
- if (cap > (4u << 20)) return -1;
+ if (cap > RS_WS_MAX_MSG + 65536) return -1;
unsigned char *nb = realloc(win, cap);
if (!nb) return -1;
win = nb;
@@ -571,30 +722,11 @@ static int ws_read(void) {
}
win_len += (size_t)r;
}
- size_t off = 0;
- while (win_len - off >= 2) {
- unsigned char *f = win + off;
- int op = f[0] & 15, masked = f[1] & 0x80;
- uint64_t len = f[1] & 127;
- size_t hl = 2;
- if (len == 126) { if (win_len - off < 4) break; len = (uint64_t)f[2] << 8 | f[3]; hl = 4; }
- else if (len == 127) { if (win_len - off < 10) break; len = 0; for (int i = 0; i < 8; i++) len = len << 8 | f[2 + i]; hl = 10; }
- if (!masked || len > (2u << 20)) return -1;
- if (win_len - off < hl + 4 + len) break;
- unsigned char *mask = f + hl, *p = f + hl + 4;
- for (uint64_t i = 0; i < len; i++) p[i] ^= mask[i & 3];
- if (op == 8) return -1;
- if (op == 9) ws_frame(10, p, (size_t)len, NULL, 0);
- else if (op == 1 && (f[0] & 0x80)) {
- char save = (char)p[len];
- p[len] = 0;
- from_browser((const char *)p, (size_t)len);
- p[len] = (unsigned char)save;
- }
- off += hl + 4 + (size_t)len;
- }
- memmove(win, win + off, win_len - off);
- win_len -= off;
+ size_t used = 0;
+ int rc = rs_ws_consume(&wsr, win, win_len, &used, on_ws, NULL);
+ memmove(win, win + used, win_len - used);
+ win_len -= used;
+ if (rc) { ws_close(rc); closing = 1; }
return 0;
}
@@ -611,17 +743,30 @@ static void conn_register(const char *user) {
rd_unlock();
}
+static int conns_full(void) {
+ int n = 0;
+ rd_lock();
+ for (int i = 0; i < RD_MAX_CONNS; i++) if (rd_shared->conns[i].pid) n++;
+ rd_unlock();
+ return n >= RD_MAX_CONNS;
+}
+
static void bridge(const struct passwd *pw) {
char hello[96];
snprintf(hello, sizeof hello, "%s %s", peer, pw->pw_name);
sess_send(RP_HELLO, hello, strlen(hello));
fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK);
ws_text("{\"t\":\"hello\",\"user\":\"%s\"}", pw->pw_name);
+ rs_ws_init(&wsr, RS_WS_MAX_MSG);
unsigned char *sin = NULL;
size_t sin_len = 0, sin_cap = 0;
double last_input = rd_now();
for (;;) {
if (ws_flush()) return;
+ if (closing) { /* our close frame went out (or will not): done */
+ for (int i = 0; i < 20 && wout_len; i++) { struct pollfd q = { sock, POLLOUT, 0 }; poll(&q, 1, 100); if (ws_flush()) break; }
+ return;
+ }
struct pollfd p[2] = { { sock, (short)(POLLIN | (wout_len ? POLLOUT : 0)), 0 }, { sess, POLLIN, 0 } };
/* while there is something to send, nothing more is read from the session (flow control) */
if (wout_len > (4u << 20)) p[1].events = 0;
@@ -674,124 +819,202 @@ static void bridge(const struct passwd *pw) {
}
}
+/* ---- privilege drop (in the bridge process) ---- */
+
+static void close_all_but(const int *keep, int nkeep) {
+ int fds[1024], n = 0;
+ DIR *d = opendir("/proc/self/fd");
+ if (d) {
+ struct dirent *e;
+ int dfd = dirfd(d);
+ while ((e = readdir(d)) && n < 1024) {
+ char *end;
+ long fd = strtol(e->d_name, &end, 10);
+ if (*end || fd < 3 || fd == dfd) continue;
+ int k = 0;
+ for (int i = 0; i < nkeep; i++) if (keep[i] == fd) k = 1;
+ if (!k) fds[n++] = (int)fd;
+ }
+ closedir(d);
+ }
+ for (int i = 0; i < n; i++) close(fds[i]);
+}
+
+/* For good: no shared state, no descriptor but the three it needs, no environment, the user's
+ * groups and ids (real, effective and saved), checked; no new privileges, no core dumps, and it dies
+ * with its root parent. */
+static int drop_root(const struct passwd *pw, pid_t parent) {
+ if (rd_shared) munmap(rd_shared, sizeof *rd_shared);
+ rd_shared = NULL;
+ int keep[3] = { sock, sess, lock_fd };
+ close_all_but(keep, 3);
+ clearenv();
+ struct rlimit core = { 0, 0 };
+ setrlimit(RLIMIT_CORE, &core);
+ if (pw->pw_uid == 0 || pw->pw_gid == 0) return -1;
+ if (initgroups(pw->pw_name, pw->pw_gid) || setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
+ setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid)) return -1;
+ uid_t ru, eu, su;
+ gid_t rg, eg, sg;
+ if (getresuid(&ru, &eu, &su) || getresgid(&rg, &eg, &sg)) return -1;
+ if (ru != pw->pw_uid || eu != pw->pw_uid || su != pw->pw_uid || rg != pw->pw_gid || eg != pw->pw_gid || sg != pw->pw_gid) return -1;
+ if (setuid(0) == 0 || seteuid(0) == 0 || setgid(0) == 0 || setegid(0) == 0) return -1;
+ gid_t groups[256];
+ int ng = getgroups(256, groups);
+ for (int i = 0; i < ng; i++) if (groups[i] == 0) return -1;
+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_DUMPABLE, 0, 0, 0, 0)) return -1;
+ if (prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0) || getppid() != parent) return -1;
+ return 0;
+}
+
/* ---- one connection ---- */
-void rd_serve(SSL_CTX *ctx, int fd, const char *ip) {
+static void handle_ws(const RsReq *r, int logged, const char *user, uid_t uid) {
+ if (!logged) { respond(403, NULL); return; }
+ if (!origin_ok(r) || !rs_has_token(r->upgrade, "websocket") || !rs_has_token(r->connection, "upgrade") || !rs_valid_wskey(r->wskey)) {
+ respond(400, NULL);
+ return;
+ }
+ if (strcmp(r->wsversion, "13")) { respond(426, "Sec-WebSocket-Version: 13\r\n"); return; }
+ if (conns_full()) { respond(503, NULL); return; }
+ struct passwd *pw = getpwnam(user);
+ if (!pw || pw->pw_uid != uid) { respond(403, NULL); return; }
+ struct passwd me = *pw;
+ static char name[33], dir[512];
+ snprintf(name, sizeof name, "%s", pw->pw_name);
+ snprintf(dir, sizeof dir, "%s", pw->pw_dir);
+ me.pw_name = name;
+ me.pw_dir = dir;
+ int w = query_num(r->query, "w", 1280), h = query_num(r->query, "h", 800);
+ if (w < 800) w = 800;
+ if (h < 600) h = 600;
+ if (w > 2560) w = 2560;
+ if (h > 1600) h = 1600;
+ sess = sd_session_get(&me, w & ~1, h & ~1);
+ if (sess < 0) { respond(503, NULL); return; }
+ if (ws_handshake(r)) return;
+ conn_register(name);
+ int pp[2];
+ if (pipe2(pp, O_CLOEXEC)) return;
+ pid_t parent = getpid();
+ alarm(0);
+ pid_t b = fork();
+ if (b < 0) return;
+ if (b == 0) {
+ close(pp[0]);
+ lock_fd = pp[1];
+ /* from here on, no root: TLS, compression and bridge as the user */
+ if (drop_root(&me, parent)) { sd_log("could not drop privileges"); _exit(1); }
+ sd_log("connected to %s's session", name);
+ bridge(&me);
+ sd_log("disconnected");
+ _exit(0);
+ }
+ /* the root side keeps nothing of the connection: it only listens for "the session was locked" */
+ close(pp[1]);
+ close(sess);
+ close(sock);
+ for (;;) {
+ char c;
+ ssize_t n = read(pp[0], &c, 1);
+ if (n < 0 && errno == EINTR) continue;
+ if (n <= 0) break;
+ if (c == 'L') { rd_tokens_drop_uid(me.pw_uid); sd_log("%s locked the session: every remote cookie of that user ended", name); }
+ }
+ while (waitpid(b, NULL, 0) < 0 && errno == EINTR) {}
+}
+
+void rd_serve(SSL_CTX *ctx, int fd, const char *ip, const char *key) {
sock = fd;
snprintf(peer, sizeof peer, "%s", ip);
+ snprintf(peer_key, sizeof peer_key, "%s", key);
char prefix[96];
snprintf(prefix, sizeof prefix, "lord-sessiond[%d] %s", (int)getpid(), peer);
sd_log_prefix(prefix);
+ alarm(ALARM_SECONDS); /* backstop: SIGALRM ends a stuck connection */
+ deadline = mono() + HEAD_SECONDS;
ssl = SSL_new(ctx);
if (!ssl) return;
SSL_set_fd(ssl, fd);
SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
- struct timeval tv = { 15, 0 };
- setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
- if (SSL_accept(ssl) <= 0) return;
- Req r;
- if (read_request(&r)) return;
+ fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
+ for (;;) { /* handshake, under the same deadline */
+ int a = SSL_accept(ssl);
+ if (a == 1) break;
+ int e = SSL_get_error(ssl, a);
+ if ((e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE) && !wait_io(e == SSL_ERROR_WANT_WRITE)) continue;
+ return;
+ }
+ RsReq r;
+ int rc = read_request(&r);
+ if (rc == -1) return;
+ if (rc < 0) {
+ if (rc != -408) sd_log("bad request (%d)", -rc);
+ respond(-rc, NULL);
+ return;
+ }
+ deadline = mono() + 30; /* answering (session start is covered by the alarm) */
+ fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
- char user[33];
+ int get = !strcmp(r.method, "GET"), post = !strcmp(r.method, "POST");
+ if (!post && r.content_length > 0) { respond(400, NULL); return; }
+ char user[33] = "";
uid_t uid = 0;
- int logged = session_user(&r, user, &uid) == 0;
+ unsigned char hash[32];
+ int logged = session_user(&r, user, &uid, hash) == 0;
- if (!strcmp(r.method, "POST") && !strcmp(r.path, "/login")) {
- if (!same_origin(&r)) {
- sd_log("login rejected: origin \"%s\" and host \"%s\"", r.origin, r.host);
- respond(403, "Forbidden", "text/plain", NULL, "origin", 6);
- return;
- }
- double wait = sd_fail_wait(peer);
- if (wait > 0) { redirect("/?e=2", NULL); return; }
- char u[64], pass[300];
- form_get(r.body, "user", u, sizeof u);
- form_get(r.body, "pass", pass, sizeof pass);
- int ok = sd_check_password(u, pass, 1);
- explicit_bzero(pass, sizeof pass);
- explicit_bzero(r.body, sizeof r.body);
- if (!ok) {
- sd_fail_note(peer, 1);
- sd_log("failed login for '%s'", sd_valid_username(u) ? u : "?");
- sleep(1);
- char to[64] = "/?e=1";
- if (sd_valid_username(u)) snprintf(to, sizeof to, "/?e=1&u=%.32s", u);
- redirect(to, NULL);
- return;
- }
- sd_fail_note(peer, 0);
- struct passwd *pw = getpwnam(u);
- char tok[65], cookie[160];
- new_token(pw->pw_uid, u, tok);
- snprintf(cookie, sizeof cookie, "Set-Cookie: lordos_remote=%s; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=43200\r\n", tok);
- sd_log("%s logged in", u);
- redirect("/desk", cookie);
+ if (!strcmp(r.path, "/login")) {
+ if (!post) { respond(405, "Allow: POST\r\n"); return; }
+ handle_login(&r);
return;
}
if (!strcmp(r.path, "/logout")) {
- char tok[65];
- if (!token_from_cookie(r.cookie, tok)) token_drop_tok(tok);
- redirect("/", "Set-Cookie: lordos_remote=; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=0\r\n");
+ if (!post) { respond(405, "Allow: POST\r\n"); return; }
+ if (!origin_ok(&r)) { respond(403, NULL); return; }
+ if (logged) { token_drop_hash(hash); sd_log("%s logged out", user); }
+ redirect("/", CLEAR_COOKIES);
return;
}
if (!strcmp(r.path, "/") || !strcmp(r.path, "/index.html")) {
- if (logged) redirect("/desk", NULL); else send_login(&r);
+ if (!get) { respond(405, "Allow: GET\r\n"); return; }
+ if (logged) redirect("/desk", NULL); else send_login(200, 0, r.host);
return;
}
if (!strcmp(r.path, "/bg.jpg")) { /* the login screen background (links to Crystal Crown) */
+ if (!get) { respond(405, "Allow: GET\r\n"); return; }
char p[600];
snprintf(p, sizeof p, "%s", rd_conf.greeter_theme);
char *slash = strrchr(p, '/');
if (slash) snprintf(slash, sizeof p - (size_t)(slash - p), "/assets/background.jpg");
- int fd = open(p, O_RDONLY | O_CLOEXEC);
+ int f = open(p, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
struct stat st;
char *img = NULL;
- if (fd >= 0 && !fstat(fd, &st) && st.st_size > 0 && st.st_size < (8 << 20) && (img = malloc((size_t)st.st_size)) &&
- read(fd, img, (size_t)st.st_size) == st.st_size)
- respond(200, "OK", "image/jpeg", NULL, img, (size_t)st.st_size);
- else respond(404, "Not Found", "text/plain", NULL, "no", 2);
+ size_t got = 0;
+ if (f >= 0 && !fstat(f, &st) && S_ISREG(st.st_mode) && st.st_size > 0 && st.st_size < (8 << 20) && (img = malloc((size_t)st.st_size))) {
+ while (got < (size_t)st.st_size) {
+ ssize_t n = read(f, img + got, (size_t)st.st_size - got);
+ if (n < 0 && errno == EINTR) continue;
+ if (n <= 0) break;
+ got += (size_t)n;
+ }
+ }
+ if (img && got == (size_t)st.st_size) respond_page(200, "image/jpeg", NULL, img, got, NULL, NULL);
+ else respond(404, NULL);
free(img);
- if (fd >= 0) close(fd);
+ if (f >= 0) close(f);
return;
}
if (!strcmp(r.path, "/desk")) {
+ if (!get) { respond(405, "Allow: GET\r\n"); return; }
if (!logged) { redirect("/", NULL); return; }
- respond(200, "OK", "text/html; charset=utf-8", NULL, _binary_src_remote_client_html_start,
- (size_t)(_binary_src_remote_client_html_end - _binary_src_remote_client_html_start));
+ page_hashes(&desk_page);
+ respond_page(200, "text/html; charset=utf-8", NULL, desk_page.start, (size_t)(desk_page.end - desk_page.start), &desk_page, r.host);
return;
}
if (!strcmp(r.path, "/ws")) {
- if (!logged || strcasecmp(r.upgrade, "websocket") || !r.wskey[0] || !same_origin(&r)) {
- respond(403, "Forbidden", "text/plain", NULL, "no", 2);
- return;
- }
- struct passwd *pw = getpwnam(user);
- if (!pw) return;
- struct passwd me = *pw;
- static char name[33], dir[512];
- snprintf(name, sizeof name, "%s", pw->pw_name);
- snprintf(dir, sizeof dir, "%s", pw->pw_dir);
- me.pw_name = name;
- me.pw_dir = dir;
- int w = query_int(r.query, "w", 1280), h = query_int(r.query, "h", 800);
- if (w < 800) w = 800;
- if (h < 600) h = 600;
- if (w > 2560) w = 2560;
- if (h > 1600) h = 1600;
- sess = sd_session_get(&me, w & ~1, h & ~1);
- token_from_cookie(r.cookie, my_token);
- if (sess < 0) { respond(503, "Service Unavailable", "text/plain", NULL, "no session", 10); return; }
- if (ws_handshake(&r)) return;
- conn_register(name);
- /* from here on, no root: TLS, compression and bridge as the user */
- if (initgroups(name, me.pw_gid) || setgid(me.pw_gid) || setuid(me.pw_uid) || setuid(0) == 0) {
- sd_log("could not drop privileges");
- return;
- }
- sd_log("connected to %s's session", name);
- bridge(&me);
- sd_log("disconnected");
+ if (!get) { respond(405, "Allow: GET\r\n"); return; }
+ handle_ws(&r, logged, user, uid);
return;
}
- respond(404, "Not Found", "text/plain", NULL, "no", 2);
+ respond(404, NULL);
}
diff --git a/server/src/remote/ipnet.c b/server/src/remote/ipnet.c
new file mode 100644
index 0000000..ac75695
--- /dev/null
+++ b/server/src/remote/ipnet.c
@@ -0,0 +1,214 @@
+/* ipnet.c — addresses, networks and access rules of the remote desktop (see ipnet.h). */
+#include "ipnet.h"
+
+#include <arpa/inet.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static const unsigned char mapped_prefix[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
+
+int rs_addr_parse(const char *s, RsAddr *a) {
+ memset(a, 0, sizeof *a);
+ size_t n = s ? strlen(s) : 0;
+ if (!n || n > 45) return -1;
+ for (size_t i = 0; i < n; i++) {
+ char ch = s[i];
+ if (!((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') || ch == '.' || ch == ':')) return -1;
+ }
+ unsigned char v4[4];
+ if (!strchr(s, ':')) {
+ /* dotted quad without leading zeros (some libcs read 010 as octal or accept it) */
+ for (size_t i = 0; i < n; i++)
+ if (s[i] == '0' && (i == 0 || s[i - 1] == '.') && i + 1 < n && s[i + 1] != '.') return -1;
+ if (inet_pton(AF_INET, s, v4) != 1) return -1;
+ memcpy(a->a, mapped_prefix, 12);
+ memcpy(a->a + 12, v4, 4);
+ a->v4 = 1;
+ return 0;
+ }
+ if (inet_pton(AF_INET6, s, a->a) != 1) return -1;
+ a->v4 = !memcmp(a->a, mapped_prefix, 12);
+ return 0;
+}
+
+static void mask(RsAddr *a, int prefix) {
+ for (int i = 0; i < 16; i++) {
+ int bits = prefix - i * 8;
+ if (bits >= 8) continue;
+ a->a[i] &= bits <= 0 ? 0 : (unsigned char)(0xff << (8 - bits));
+ }
+}
+
+static int cidr_parse(const char *s, RsCidr *c, int min4, int min6) {
+ memset(c, 0, sizeof *c);
+ if (!s) return -1;
+ char buf[64];
+ size_t n = strlen(s);
+ if (!n || n >= sizeof buf) return -1;
+ memcpy(buf, s, n + 1);
+ char *slash = strchr(buf, '/');
+ int len = -1;
+ if (slash) {
+ *slash = 0;
+ const char *d = slash + 1;
+ size_t dl = strlen(d);
+ if (!dl || dl > 3 || (dl > 1 && d[0] == '0')) return -1;
+ len = 0;
+ for (size_t i = 0; i < dl; i++) {
+ if (d[i] < '0' || d[i] > '9') return -1;
+ len = len * 10 + (d[i] - '0');
+ }
+ }
+ if (rs_addr_parse(buf, &c->net)) return -1;
+ if (c->net.v4) {
+ if (len < 0) len = 32;
+ if (len < min4 || len > 32) return -1;
+ c->prefix = len + 96;
+ } else {
+ if (len < 0) len = 128;
+ if (len < min6 || len > 128) return -1;
+ c->prefix = len;
+ }
+ mask(&c->net, c->prefix);
+ return 0;
+}
+
+int rs_cidr_parse(const char *s, RsCidr *c) { return cidr_parse(s, c, RS_MIN_PREFIX4, RS_MIN_PREFIX6); }
+
+int rs_cidr_contains(const RsCidr *c, const RsAddr *a) {
+ RsAddr m = *a;
+ mask(&m, c->prefix);
+ return !memcmp(m.a, c->net.a, 16);
+}
+
+int rs_cidr_covers(const RsCidr *outer, const RsCidr *inner) {
+ return outer->prefix <= inner->prefix && rs_cidr_contains(outer, &inner->net);
+}
+
+int rs_cidr_equal(const RsCidr *x, const RsCidr *y) { return x->prefix == y->prefix && !memcmp(x->net.a, y->net.a, 16); }
+
+void rs_addr_format(const RsAddr *a, char *out, size_t n) {
+ char t[64] = "";
+ if (a->v4) inet_ntop(AF_INET, a->a + 12, t, sizeof t);
+ else inet_ntop(AF_INET6, a->a, t, sizeof t);
+ snprintf(out, n, "%s", t);
+}
+
+void rs_cidr_format(const RsCidr *c, char *out, size_t n) {
+ char t[64];
+ rs_addr_format(&c->net, t, sizeof t);
+ if (c->prefix == 128) snprintf(out, n, "%s", t);
+ else snprintf(out, n, "%s/%d", t, c->net.v4 ? c->prefix - 96 : c->prefix);
+}
+
+void rs_addr_key(const RsAddr *a, char *out, size_t n) {
+ if (a->v4) { rs_addr_format(a, out, n); return; }
+ RsCidr c = { *a, 64 };
+ mask(&c.net, 64);
+ rs_cidr_format(&c, out, n);
+}
+
+int rs_key_parse(const char *key, RsCidr *c) {
+ if (rs_cidr_parse(key, c)) return -1;
+ if (c->net.v4) return c->prefix == 128 ? 0 : -1;
+ return c->prefix == 64 ? 0 : -1;
+}
+
+int rs_addr_is_local(const RsAddr *a) {
+ static const char *const nets[] = {
+ "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8", "169.254.0.0/16", "100.64.0.0/10",
+ "::1", "fe80::/10", "fc00::/7", NULL,
+ };
+ for (int i = 0; nets[i]; i++) {
+ RsCidr c;
+ if (!cidr_parse(nets[i], &c, 0, 0) && rs_cidr_contains(&c, a)) return 1;
+ }
+ return 0;
+}
+
+void rs_access_parse(const char *text, RsAccess *acc, int *bad) {
+ memset(acc, 0, sizeof *acc);
+ if (bad) *bad = 0;
+ const char *p = text ? text : "";
+ while (*p) {
+ const char *e = strchr(p, '\n');
+ size_t l = e ? (size_t)(e - p) : strlen(p);
+ char line[96];
+ if (l < sizeof line) {
+ memcpy(line, p, l);
+ line[l] = 0;
+ char kind[8], net[64], extra;
+ RsCidr c;
+ if (line[0] == '#' || !line[0]) { /* comment */ }
+ else if (sscanf(line, "%7s %63s %c", kind, net, &extra) == 2 && !rs_cidr_parse(net, &c) && !strcmp(kind, "allow"))
+ { if (rs_access_add(acc->allow, &acc->nallow, &c) < 0 && bad) (*bad)++; }
+ else if (sscanf(line, "%7s %63s %c", kind, net, &extra) == 2 && !rs_cidr_parse(net, &c) && !strcmp(kind, "block"))
+ { if (rs_access_add(acc->block, &acc->nblock, &c) < 0 && bad) (*bad)++; }
+ else if (bad) (*bad)++;
+ } else if (bad) (*bad)++;
+ p += l;
+ if (*p == '\n') p++;
+ }
+}
+
+int rs_access_format(const RsAccess *acc, char *out, size_t n) {
+ size_t o = 0;
+ int k = snprintf(out, n, "# LordOS remote desktop: manual address lists (Settings -> Sharing). See docs/REMOTE.md\n");
+ if (k < 0 || (size_t)k >= n) return -1;
+ o = (size_t)k;
+ for (int pass = 0; pass < 2; pass++) {
+ const RsCidr *l = pass ? acc->block : acc->allow;
+ int cnt = pass ? acc->nblock : acc->nallow;
+ for (int i = 0; i < cnt; i++) {
+ char t[64];
+ rs_cidr_format(&l[i], t, sizeof t);
+ k = snprintf(out + o, n - o, "%s %s\n", pass ? "block" : "allow", t);
+ if (k < 0 || (size_t)k >= n - o) return -1;
+ o += (size_t)k;
+ }
+ }
+ return (int)o;
+}
+
+int rs_access_add(RsCidr *list, int *n, const RsCidr *c) {
+ for (int i = 0; i < *n; i++) if (rs_cidr_equal(&list[i], c)) return 1;
+ if (*n >= RS_ACCESS_MAX) return -1;
+ list[(*n)++] = *c;
+ return 0;
+}
+
+int rs_access_del(RsCidr *list, int *n, const RsCidr *c) {
+ int removed = 0;
+ for (int i = 0; i < *n;) {
+ if (rs_cidr_covers(c, &list[i])) { list[i] = list[--(*n)]; removed++; }
+ else i++;
+ }
+ return removed;
+}
+
+int rs_net_mode(const char *s) {
+ if (!s) return -1;
+ if (!strcmp(s, "lan")) return RS_NET_LAN;
+ if (!strcmp(s, "list")) return RS_NET_LIST;
+ if (!strcmp(s, "any")) return RS_NET_ANY;
+ return -1;
+}
+
+const char *rs_net_name(int mode) { return mode == RS_NET_LIST ? "list" : mode == RS_NET_ANY ? "any" : "lan"; }
+
+int rs_access_decide(const RsAccess *acc, int mode, const RsAddr *peer, int via_vpn) {
+ for (int i = 0; i < acc->nblock; i++) if (rs_cidr_contains(&acc->block[i], peer)) return RS_ACC_BLOCKED;
+ if (mode == RS_NET_ANY) return RS_ACC_OK;
+ if (mode == RS_NET_LIST) {
+ for (int i = 0; i < acc->nallow; i++) if (rs_cidr_contains(&acc->allow[i], peer)) return RS_ACC_OK;
+ return RS_ACC_NOT_ALLOWED;
+ }
+ return rs_addr_is_local(peer) || via_vpn ? RS_ACC_OK : RS_ACC_NOT_ALLOWED;
+}
+
+int rs_vpn_ifname(const char *name) {
+ static const char *const pre[] = { "wg-", "ovpn-", "ips-", "oc-", "fvpn-", "ppp", "tun", "wg", NULL };
+ for (int i = 0; pre[i]; i++) if (!strncmp(name, pre[i], strlen(pre[i]))) return 1;
+ return 0;
+}
diff --git a/server/src/remote/ipnet.h b/server/src/remote/ipnet.h
new file mode 100644
index 0000000..dbe3943
--- /dev/null
+++ b/server/src/remote/ipnet.h
@@ -0,0 +1,63 @@
+/* ipnet.h — addresses, networks (CIDR) and the remote desktop's address rules (docs/REMOTE.md,
+ * "Security analysis (0.8.3)"). Plain libc: shared by lord-sessiond (who may connect) and the
+ * admin helper (the remote-block / remote-unblock / remote-allow actions validate with it).
+ *
+ * An IPv4 address is kept as its IPv4-mapped IPv6 form (::ffff:a.b.c.d), so one comparison covers
+ * both families; prefixes of IPv4 networks are stored +96. */
+#ifndef LORD_REMOTE_IPNET_H
+#define LORD_REMOTE_IPNET_H
+
+#include <stddef.h>
+
+typedef struct { unsigned char a[16]; int v4; } RsAddr;
+typedef struct { RsAddr net; int prefix; } RsCidr; /* prefix 0..128 over the mapped form */
+
+/* Shortest networks the actions accept (a block of 0.0.0.0/0 would shut out everybody). */
+#define RS_MIN_PREFIX4 8
+#define RS_MIN_PREFIX6 16
+
+#define RS_ACCESS_MAX 64 /* manual entries of each kind */
+
+/* Strict textual forms: dotted quad or RFC 4291 text (no zone, no spaces). IPv4-mapped IPv6 is
+ * taken as IPv4. 0 on success. */
+int rs_addr_parse(const char *s, RsAddr *a);
+/* "addr" or "addr/len" (decimal, no leading zeros, v4 8..32, v6 16..128). Host bits are cleared. */
+int rs_cidr_parse(const char *s, RsCidr *c);
+int rs_cidr_contains(const RsCidr *c, const RsAddr *a);
+/* is network `inner` entirely inside `outer`? */
+int rs_cidr_covers(const RsCidr *outer, const RsCidr *inner);
+int rs_cidr_equal(const RsCidr *x, const RsCidr *y);
+void rs_addr_format(const RsAddr *a, char *out, size_t n);
+void rs_cidr_format(const RsCidr *c, char *out, size_t n); /* "a.b.c.d/24", "fd00::/8", single hosts without /len */
+/* Lockout key of an address: IPv4 as is, IPv6 as its /64 ("2001:db8:1:2::/64"). */
+void rs_addr_key(const RsAddr *a, char *out, size_t n);
+int rs_key_parse(const char *key, RsCidr *c); /* the reverse; 0 if it's a valid key */
+/* Private, loopback, link-local, CGNAT and unique-local ranges (never public internet). */
+int rs_addr_is_local(const RsAddr *a);
+
+/* Manual lists (/etc/lordos/remote/access, written only by the admin actions):
+ * allow <cidr> networks for net=list
+ * block <cidr> blocked until removed */
+typedef struct { RsCidr allow[RS_ACCESS_MAX]; int nallow; RsCidr block[RS_ACCESS_MAX]; int nblock; } RsAccess;
+/* Unknown or invalid lines are skipped (counted in *bad if not NULL). */
+void rs_access_parse(const char *text, RsAccess *acc, int *bad);
+/* Text for the file; returns the length or -1 if it doesn't fit. */
+int rs_access_format(const RsAccess *acc, char *out, size_t n);
+/* 0 added, 1 already there, -1 full */
+int rs_access_add(RsCidr *list, int *n, const RsCidr *c);
+/* removes entries equal to c or inside it; returns how many */
+int rs_access_del(RsCidr *list, int *n, const RsCidr *c);
+
+enum { RS_NET_LAN = 0, RS_NET_LIST = 1, RS_NET_ANY = 2 }; /* config net=lan|list|any */
+int rs_net_mode(const char *s); /* -1 if invalid */
+const char *rs_net_name(int mode);
+
+enum { RS_ACC_OK = 0, RS_ACC_BLOCKED = 1, RS_ACC_NOT_ALLOWED = 2 };
+/* Who may open a connection: a manual block always wins; then net=any lets everybody in, net=list
+ * only the listed networks, net=lan (the default) local ranges or a connection that arrived on a
+ * VPN interface (via_vpn). */
+int rs_access_decide(const RsAccess *acc, int mode, const RsAddr *peer, int via_vpn);
+/* Interface names of LordOS VPNs and common tunnel devices (wg-, ovpn-, ips-, ppp, oc-, fvpn-, tun, wg). */
+int rs_vpn_ifname(const char *name);
+
+#endif
diff --git a/server/src/remote/lockout.c b/server/src/remote/lockout.c
new file mode 100644
index 0000000..cbe8058
--- /dev/null
+++ b/server/src/remote/lockout.c
@@ -0,0 +1,167 @@
+/* lockout.c — failed-login lockout and per-source connection rate (see lockout.h). */
+#include "lockout.h"
+#include "ipnet.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static RlEntry *find(RlTable *t, const char *key) {
+ for (int i = 0; i < RL_MAX; i++) if (t->e[i].key[0] && !strcmp(t->e[i].key, key)) return &t->e[i];
+ return NULL;
+}
+
+double rl_blocked(const RlTable *t, const char *key, double now) {
+ for (int i = 0; i < RL_MAX; i++)
+ if (t->e[i].key[0] && !strcmp(t->e[i].key, key)) return t->e[i].until > now ? t->e[i].until - now : 0;
+ return 0;
+}
+
+double rl_duration(int strikes) { return strikes <= 1 ? 15 * 60.0 : strikes == 2 ? 3600.0 : 24 * 3600.0; }
+
+/* A free slot or, with the table full, the least useful one: never a running block if anything
+ * else is left (an attacker cycling addresses must not free their own block), else the block that
+ * ends first. */
+static RlEntry *slot(RlTable *t, double now) {
+ RlEntry *best = NULL;
+ for (int i = 0; i < RL_MAX; i++) {
+ RlEntry *e = &t->e[i];
+ if (!e->key[0]) return e;
+ int blocked = e->until > now;
+ if (!best) { best = e; continue; }
+ int bb = best->until > now;
+ if (bb && !blocked) best = e;
+ else if (bb == blocked && (blocked ? e->until < best->until : e->last_fail < best->last_fail)) best = e;
+ }
+ return best;
+}
+
+int rl_fail(RlTable *t, const char *key, double now, double *until, int *strikes) {
+ RlEntry *e = find(t, key);
+ if (!e) {
+ e = slot(t, now);
+ memset(e, 0, sizeof *e);
+ snprintf(e->key, sizeof e->key, "%s", key);
+ }
+ if (e->fails && now - e->last_fail > RL_WINDOW) e->fails = 0;
+ if (e->strikes && now - e->last_strike > RL_WINDOW) e->strikes = 0;
+ e->fails++;
+ e->last_fail = now;
+ if (e->fails < RL_FAILS) return 0;
+ e->fails = 0;
+ e->strikes++;
+ e->last_strike = now;
+ e->until = now + rl_duration(e->strikes);
+ if (until) *until = e->until;
+ if (strikes) *strikes = e->strikes;
+ return 1;
+}
+
+void rl_success(RlTable *t, const char *key) {
+ RlEntry *e = find(t, key);
+ if (e) e->fails = 0;
+}
+
+int rl_unblock(RlTable *t, const char *cidr) {
+ RsCidr c, k;
+ if (rs_cidr_parse(cidr, &c)) return 0;
+ int n = 0;
+ for (int i = 0; i < RL_MAX; i++) {
+ RlEntry *e = &t->e[i];
+ if (!e->key[0] || rs_key_parse(e->key, &k)) continue;
+ /* the request covers the key, or the key (an IPv6 /64) contains the requested address */
+ if (rs_cidr_covers(&c, &k) || rs_cidr_covers(&k, &c)) { memset(e, 0, sizeof *e); n++; }
+ }
+ return n;
+}
+
+void rl_expire(RlTable *t, double now) {
+ for (int i = 0; i < RL_MAX; i++) {
+ RlEntry *e = &t->e[i];
+ if (!e->key[0]) continue;
+ int live = e->until > now || (e->strikes && now - e->last_strike <= RL_WINDOW) || (e->fails && now - e->last_fail <= RL_WINDOW);
+ if (!live) memset(e, 0, sizeof *e);
+ }
+}
+
+int rl_format(const RlTable *t, double now, char *out, size_t n) {
+ int k = snprintf(out, n, "# lord-sessiond: remote desktop lockout (key fails last_fail strikes last_strike until). Do not edit.\n");
+ if (k < 0 || (size_t)k >= n) return -1;
+ size_t o = (size_t)k;
+ for (int i = 0; i < RL_MAX; i++) {
+ const RlEntry *e = &t->e[i];
+ if (!e->key[0]) continue;
+ int live = e->until > now || (e->strikes && now - e->last_strike <= RL_WINDOW) || (e->fails && now - e->last_fail <= RL_WINDOW);
+ if (!live) continue;
+ k = snprintf(out + o, n - o, "%s %d %.0f %d %.0f %.0f\n", e->key, e->fails, e->last_fail, e->strikes, e->last_strike, e->until);
+ if (k < 0 || (size_t)k >= n - o) return -1;
+ o += (size_t)k;
+ }
+ return (int)o;
+}
+
+void rl_parse(RlTable *t, const char *text, double now) {
+ memset(t, 0, sizeof *t);
+ int used = 0;
+ const char *p = text ? text : "";
+ while (*p && used < RL_MAX) {
+ const char *nl = strchr(p, '\n');
+ size_t l = nl ? (size_t)(nl - p) : strlen(p);
+ char line[160];
+ if (l < sizeof line && p[0] != '#') {
+ memcpy(line, p, l);
+ line[l] = 0;
+ char key[48], extra;
+ int fails, strikes;
+ double lf, ls, until;
+ RsCidr c;
+ if (sscanf(line, "%47s %d %lf %d %lf %lf %c", key, &fails, &lf, &strikes, &ls, &until, &extra) == 6 && !rs_key_parse(key, &c) &&
+ fails >= 0 && fails < RL_FAILS && strikes >= 0 && strikes < 1000 && lf >= 0 && ls >= 0 && until >= 0 &&
+ lf <= now + 60 && ls <= now + 60 && until <= now + 2 * RL_WINDOW) {
+ char canon[48];
+ rs_addr_key(&c.net, canon, sizeof canon); /* only the canonical spelling */
+ if (!strcmp(canon, key) && !find(t, key)) {
+ RlEntry *e = &t->e[used++];
+ snprintf(e->key, sizeof e->key, "%s", key);
+ e->fails = fails;
+ e->strikes = strikes;
+ e->last_fail = lf;
+ e->last_strike = ls;
+ e->until = until;
+ }
+ }
+ }
+ p += l;
+ if (*p == '\n') p++;
+ }
+ rl_expire(t, now);
+}
+
+double rl_user_delay(int fails) {
+ if (fails < 5) return 0;
+ int k = fails - 5;
+ return k >= 3 ? 8 : (double)(1 << k);
+}
+
+int rc_take(RcTable *t, const char *key, double now) {
+ RcEntry *e = NULL, *old = &t->e[0];
+ for (int i = 0; i < RC_MAX; i++) {
+ if (t->e[i].key[0] && !strcmp(t->e[i].key, key)) { e = &t->e[i]; break; }
+ if (!t->e[i].key[0]) { if (old->key[0]) old = &t->e[i]; }
+ else if (old->key[0] && t->e[i].last < old->last) old = &t->e[i];
+ }
+ if (!e) {
+ e = old;
+ memset(e, 0, sizeof *e);
+ snprintf(e->key, sizeof e->key, "%s", key);
+ e->tokens = RC_BURST;
+ e->last = now;
+ }
+ double dt = now - e->last;
+ if (dt > 0) e->tokens += dt * RC_RATE;
+ if (e->tokens > RC_BURST) e->tokens = RC_BURST;
+ e->last = now;
+ if (e->tokens < 1) return 0;
+ e->tokens -= 1;
+ return 1;
+}
diff --git a/server/src/remote/lockout.h b/server/src/remote/lockout.h
new file mode 100644
index 0000000..f9d3bbc
--- /dev/null
+++ b/server/src/remote/lockout.h
@@ -0,0 +1,63 @@
+/* lockout.h — failed-login lockout and connection limits of the remote desktop (docs/REMOTE.md,
+ * "Security analysis (0.8.3)"). Plain libc and no clock of its own (the caller passes `now`), so
+ * the rules are tested in build/remote-sec-test.
+ *
+ * Lockout, per source (an IPv4 address, or the /64 of an IPv6 one; ipnet.h rs_addr_key):
+ * - 3 failed logins without a successful one in between (within 24 h) block the source;
+ * - the block lasts 15 minutes, then 1 hour, then 24 hours for a source blocked again within
+ * 24 hours of its previous block ("strikes");
+ * - a successful login clears the failure count (not the strikes);
+ * - there is no per-account lockout (it would let anybody lock the real user out): accounts only
+ * get a slowdown (rl_user_delay).
+ * The table lives in lord-sessiond's shared memory (root processes only) and is saved to
+ * /var/lib/lordos/remote/blocklist (root, 0600) so blocks survive a restart. */
+#ifndef LORD_REMOTE_LOCKOUT_H
+#define LORD_REMOTE_LOCKOUT_H
+
+#include <stddef.h>
+
+#define RL_MAX 256
+#define RL_FAILS 3 /* failures that block */
+#define RL_WINDOW (24 * 3600.0) /* failures and strikes older than this are forgotten */
+#define RL_FILE_DIR "/var/lib/lordos/remote"
+#define RL_FILE RL_FILE_DIR "/blocklist"
+#define RL_REQUESTS RL_FILE_DIR "/requests" /* "unblock <cidr>" lines from the admin helper */
+
+typedef struct {
+ char key[48];
+ int fails, strikes;
+ double last_fail, last_strike, until;
+} RlEntry;
+
+typedef struct { RlEntry e[RL_MAX]; } RlTable;
+
+/* Seconds the block of that key still lasts (0 = not blocked). */
+double rl_blocked(const RlTable *t, const char *key, double now);
+/* A failed login. Returns 1 if this failure started a block (*until = its end, *strikes = how many
+ * blocks within 24 h, this one included), else 0. */
+int rl_fail(RlTable *t, const char *key, double now, double *until, int *strikes);
+void rl_success(RlTable *t, const char *key);
+/* Block duration for the n-th block (1-based) within 24 h. */
+double rl_duration(int strikes);
+/* Removes the entries whose key lies inside `cidr` (text, ipnet.h); returns how many. */
+int rl_unblock(RlTable *t, const char *cidr);
+void rl_expire(RlTable *t, double now);
+/* Text of the blocklist file (lord-sessiond writes it with an atomic rename, 0600). rl_format
+ * returns the length or -1; rl_parse replaces the table and skips invalid, non-canonical and expired
+ * lines. */
+int rl_format(const RlTable *t, double now, char *out, size_t n);
+void rl_parse(RlTable *t, const char *text, double now);
+
+/* Per-account slowdown, in seconds, before verifying a password after `fails` failures for that
+ * name (from any address): none for the first 4, then 1, 2, 4, 8, at most 8. */
+double rl_user_delay(int fails);
+
+/* New connections per source: a token bucket (burst RC_BURST, then RC_RATE per second). */
+#define RC_MAX 128
+#define RC_BURST 20.0
+#define RC_RATE 2.0
+typedef struct { char key[48]; double tokens, last; } RcEntry;
+typedef struct { RcEntry e[RC_MAX]; } RcTable;
+int rc_take(RcTable *t, const char *key, double now); /* 1 = allowed */
+
+#endif
diff --git a/server/src/remote/login.html b/server/src/remote/login.html
index 0650f35..6a7eff3 100644
--- a/server/src/remote/login.html
+++ b/server/src/remote/login.html
@@ -46,12 +46,12 @@
</head>
<body>
<div class="top"><div class="date" id="date"></div><div class="clock" id="clock"></div></div>
-<form method="post" action="/login" autocomplete="on" id="f">
+<form method="post" action="/login" enctype="application/x-www-form-urlencoded" accept-charset="UTF-8" autocomplete="on" id="f">
<div class="avatar" id="av">👑</div>
<div class="who" id="who"></div>
- <div class="field"><input id="user" name="user" autocomplete="username" autocapitalize="off" spellcheck="false" required autofocus></div>
- <div class="field" id="pf"><input id="pass" name="pass" type="password" autocomplete="current-password" required><button type="submit" id="go" aria-label="→">→</button></div>
- <div class="err" id="err"></div>
+ <div class="field"><input id="user" name="user" type="text" autocomplete="username" autocapitalize="none" autocorrect="off" spellcheck="false" inputmode="text" maxlength="32" pattern="[a-z_][a-z0-9_\-]{0,31}" required autofocus></div>
+ <div class="field" id="pf"><input id="pass" name="pass" type="password" autocomplete="current-password" minlength="1" maxlength="1024" required><button type="submit" id="go" aria-label="→">→</button></div>
+ <div class="err" id="err" role="alert" aria-live="polite"></div>
</form>
<div class="foot" id="foot"></div>
<div class="bl"><i></i><span id="host"></span></div>
@@ -60,18 +60,24 @@
const L = {
en: { user: 'Username', pass: 'Password', e1: 'Wrong username or password.', e2: 'Too many attempts. Wait a while and try again.',
e3: 'The session was locked. Sign in again.',
+ e4: 'Too many failed attempts from this computer: it is blocked for a while. An administrator can unblock it in Settings → Sharing.',
+ e5: 'User names use lowercase letters, digits, - and _ (up to 32).', e6: 'Enter your password.',
foot: 'LordOS remote desktop · encrypted connection. If your browser warns about the certificate, compare its fingerprint with Settings → Sharing.',
days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
date: (w, d, m) => `${w}, ${m} ${d}`, h12: true },
es: { user: 'Usuario', pass: 'Contraseña', e1: 'Usuario o contraseña incorrectos.', e2: 'Demasiados intentos. Esperá un rato y probá de nuevo.',
e3: 'La sesión se bloqueó. Volvé a ingresar.',
+ e4: 'Demasiados intentos fallidos desde esta computadora: quedó bloqueada por un rato. Un administrador puede desbloquearla en Ajustes → Compartir.',
+ e5: 'Los nombres de usuario usan minúsculas, números, - y _ (hasta 32).', e6: 'Escribí tu contraseña.',
foot: 'Escritorio remoto de LordOS · conexión cifrada. Si el navegador avisa del certificado, compará su huella con la de Ajustes → Compartir.',
days: ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],
months: ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'],
date: (w, d, m) => `${w}, ${d} de ${m}`, h12: false },
pt: { user: 'Usuário', pass: 'Senha', e1: 'Usuário ou senha incorretos.', e2: 'Muitas tentativas. Espere um pouco e tente de novo.',
e3: 'A sessão foi bloqueada. Entre de novo.',
+ e4: 'Muitas tentativas falhas deste computador: ele foi bloqueado por um tempo. Um administrador pode desbloqueá-lo em Ajustes → Compartilhar.',
+ e5: 'Nomes de usuário usam letras minúsculas, números, - e _ (até 32).', e6: 'Digite sua senha.',
foot: 'Área de trabalho remota do LordOS · conexão criptografada. Se o navegador avisar do certificado, compare a impressão digital com Ajustes → Compartilhar.',
days: ['domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado'],
months: ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'],
@@ -88,8 +94,11 @@
$('user').placeholder = t.user;
$('pass').placeholder = t.pass;
$('foot').textContent = t.foot;
- const e = new URLSearchParams(location.search).get('e');
- $('err').textContent = e === '1' ? t.e1 : e === '2' ? t.e2 : e === '3' ? t.e3 : '';
+ // the error comes in the URL (?e=1, after a redirect) or, when the server can't redirect (this
+ // computer just got blocked), on <html data-e>; only these fixed codes are shown
+ const e = errCode();
+ $('err').textContent = ['1', '2', '3', '4', '5', '6'].includes(e) ? t['e' + e] : '';
+ if (e === '4') { $('user').disabled = true; $('pass').disabled = true; $('go').disabled = true; }
for (const b of document.querySelectorAll('.pill')) b.setAttribute('aria-pressed', String(b.dataset.l === lang));
tick();
}
@@ -115,12 +124,34 @@
try { localStorage.setItem('lordos-lang', lang); } catch (e) { /* no storage */ }
apply();
});
+ const ERR = document.documentElement.dataset.e || new URLSearchParams(location.search).get('e') || '';
+ function errCode() { return ERR; }
+ const NAME = /^[a-z_][a-z0-9_-]{0,31}$/;
+ // Checked here for a quick answer; the server checks everything again. The user name is kept in
+ // this tab's sessionStorage across the error page (never in the URL), the password never.
+ $('f').addEventListener('submit', (ev) => {
+ const u = $('user').value, p = $('pass').value, enc = new TextEncoder().encode(p).length;
+ let bad = '';
+ if (!NAME.test(u)) bad = '5';
+ else if (!p || enc > 1024 || p.includes('\0')) bad = '6';
+ if (bad) {
+ ev.preventDefault();
+ $('err').textContent = L[lang]['e' + bad];
+ $('pf').classList.remove('shake'); void $('pf').offsetWidth; $('pf').classList.add('shake');
+ (bad === '5' ? $('user') : $('pass')).focus();
+ return;
+ }
+ try { sessionStorage.setItem('lordos-user', u); } catch (e) { /* no storage */ }
+ $('go').disabled = true;
+ });
$('host').textContent = location.hostname;
- const prev = new URLSearchParams(location.search).get('u');
- if (prev && /^[a-z_][a-z0-9_-]{0,31}$/.test(prev)) { $('user').value = prev; $('user').dispatchEvent(new Event('input')); }
+ let prev = '';
+ try { prev = sessionStorage.getItem('lordos-user') || ''; } catch (e) { /* no storage */ }
+ if (errCode() && NAME.test(prev)) { $('user').value = prev; $('user').dispatchEvent(new Event('input')); }
+ if (location.search) history.replaceState(null, '', '/'); // nothing stays in the address bar
apply();
setInterval(tick, 1000);
- if (new URLSearchParams(location.search).get('e')) { $('pf').classList.add('shake'); $('pass').focus(); }
+ if (errCode()) { $('pf').classList.add('shake'); if (!$('pass').disabled) $('pass').focus(); }
</script>
</body>
</html>
diff --git a/server/src/remote/mirror.c b/server/src/remote/mirror.c
index a427264..731a301 100644
--- a/server/src/remote/mirror.c
+++ b/server/src/remote/mirror.c
@@ -263,6 +263,15 @@ static void handle(Client *c, int type, const unsigned char *d, uint32_t n) {
}
explicit_bzero((void *)d, n);
break;
+ case RP_NOTICE:
+ /* only lord-sessiond (root, seat); short and printable ASCII, the JS side validates fields */
+ if (cb.notice && c->uid == 0 && c->seat && n > 0 && n < 512) {
+ char j[512];
+ int ok = 1;
+ for (uint32_t i = 0; i < n; i++) if (d[i] < 0x20 || d[i] > 0x7e) ok = 0;
+ if (ok) { memcpy(j, d, n); j[n] = 0; cb.notice(j); }
+ }
+ break;
case RP_GREETER_IN:
if (cb.greeter && c->seat && n < 65536) {
char *j = malloc(n + 1);
diff --git a/server/src/remote/mirror.h b/server/src/remote/mirror.h
index 54c76be..a576571 100644
--- a/server/src/remote/mirror.h
+++ b/server/src/remote/mirror.h
@@ -27,6 +27,8 @@ typedef struct {
void (*pinch)(int phase, double scale, double rotation);
/* lord-sessiond: input devices plugged in later (the fds now belong to the session) */
void (*input_add)(const int *fds, int n);
+ /* lord-sessiond: a notice for the user (RP_NOTICE, short printable JSON) */
+ void (*notice)(const char *json);
} MirrorInput;
/* After dropping privileges. Creates $XDG_RUNTIME_DIR/lordos/remote.sock. 0 on success. */
diff --git a/server/src/remote/monitor.c b/server/src/remote/monitor.c
index 3f108a7..0920c47 100644
--- a/server/src/remote/monitor.c
+++ b/server/src/remote/monitor.c
@@ -175,6 +175,7 @@ int sd_mon_show(int fd, const char *who, int keep) {
}
void sd_mon_greeter(const char *json) { send_msg(RP_GREETER_IN, json, strlen(json), NULL, 0); }
+void sd_mon_notice(const char *json) { send_msg(RP_NOTICE, json, strlen(json), NULL, 0); }
/* Requests from the session being shown (RP_SESSION, RP_GREETER: JSON up to 4 KB; RP_SHOWN with no
* data). Everything else is discarded without looking at it. -1 if the session closed. */
diff --git a/server/src/remote/proto.h b/server/src/remote/proto.h
index d6ddc09..dca1a9a 100644
--- a/server/src/remote/proto.h
+++ b/server/src/remote/proto.h
@@ -44,6 +44,8 @@ enum {
* session; the session closes unplugged ones when it gets ENODEV). Root only */
RP_KEYRING = 24, /* text: the password just verified on the login screen; the session opens
* its keyring with it (lord-vault, docs/PASSWORDS.md) and wipes it. Root only */
+ RP_NOTICE = 25, /* JSON, from lord-sessiond (root, seat) only: a notice for the user on the monitor,
+ * {"t":"blocked","ip":"…","min":N,"n":N} (a source blocked after failed remote logins) */
RP_SCROLL = 30, /* u8 phase (1 begins, 2 continues, 3 ends), i32 dx, dy in 1/256 pixel: browser trackpad */
RP_PINCH = 31, /* u8 phase, i32 scale ×65536 (relative to the start), i32 rotation in degrees ×256 */
};
diff --git a/server/src/remote/remote_admin.c b/server/src/remote/remote_admin.c
index 309916d..aac7c1c 100644
--- a/server/src/remote/remote_admin.c
+++ b/server/src/remote/remote_admin.c
@@ -2,13 +2,19 @@
*
* remote-enable turns the remote desktop on (enabled=1 and lord-sessiond rereads)
* remote-disable turns it off; sessions stay open (they show on the monitor)
- * remote-config <lines> allow=all|group, port=1024..65535
+ * remote-config <lines> allow=all|group, port=1024..65535, net=lan|list|any
+ * remote-block <cidr> blocks an address or network until removed (/etc/lordos/remote/access)
+ * remote-unblock <cidr> removes manual blocks inside it and asks lord-sessiond to lift the
+ * failed-login blocks inside it (/var/lib/lordos/remote/requests)
+ * remote-allow add|del <cidr> the "only these addresses" list (net=list)
* remote-member <u>\n1|0 adds or removes a user from the lordos-remote group
* remote-kick <pid> cuts a connection (only a pid from lord-sessiond's list)
*
* The remote desktop is part of lord-sessiond (lordos.service, docs/SESSIONS.md): these
* actions only change /etc/lordos/remote/config and notify it with SIGHUP. */
#include "remote_admin.h"
+#include "ipnet.h"
+#include "lockout.h"
#include <errno.h>
#include <fcntl.h>
@@ -19,10 +25,12 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#define CONF_DIR "/etc/lordos/remote"
+#define RD_ACCESS_PATH CONF_DIR "/access"
static int write_file(const char *path, const char *text, mode_t mode) {
char tmp[PATH_MAX];
@@ -35,11 +43,12 @@ static int write_file(const char *path, const char *text, mode_t mode) {
return ok && !rename(tmp, path) ? 0 : -1;
}
-typedef struct { int enabled, port, group_only, insecure_dev; } Conf;
+typedef struct { int enabled, port, group_only, insecure_dev, net; } Conf;
static void conf_read(Conf *c) {
c->port = 5673;
c->enabled = c->group_only = c->insecure_dev = 0;
+ c->net = RS_NET_LAN;
FILE *f = fopen(CONF_DIR "/config", "r");
char line[128], s[32];
int v;
@@ -47,6 +56,7 @@ static void conf_read(Conf *c) {
if (sscanf(line, "enabled=%d", &v) == 1) c->enabled = v == 1;
else if (sscanf(line, "port=%d", &v) == 1 && v >= 1024 && v < 65536) c->port = v;
else if (sscanf(line, "allow=%31s", s) == 1) c->group_only = !strcmp(s, "group");
+ else if (sscanf(line, "net=%31s", s) == 1 && rs_net_mode(s) >= 0) c->net = rs_net_mode(s);
else if (sscanf(line, "insecure_dev=%d", &v) == 1) c->insecure_dev = v == 1;
}
if (f) fclose(f);
@@ -56,8 +66,8 @@ static int conf_write(const Conf *c) {
mkdir("/etc/lordos", 0755);
mkdir(CONF_DIR, 0755);
char text[256];
- snprintf(text, sizeof text, "# LordOS · remote desktop (Settings → Sharing). See docs/REMOTE.md\nenabled=%d\nport=%d\nallow=%s\ninsecure_dev=%d\n",
- c->enabled, c->port, c->group_only ? "group" : "all", c->insecure_dev);
+ snprintf(text, sizeof text, "# LordOS · remote desktop (Settings → Sharing). See docs/REMOTE.md\nenabled=%d\nport=%d\nallow=%s\nnet=%s\ninsecure_dev=%d\n",
+ c->enabled, c->port, c->group_only ? "group" : "all", rs_net_name(c->net), c->insecure_dev);
return write_file(CONF_DIR "/config", text, 0644);
}
@@ -125,6 +135,9 @@ void remote_act_config(const AdminReq *r, const char *arg, size_t len) {
} else if (sscanf(line, "allow=%15s", s) == 1) {
if (strcmp(s, "all") && strcmp(s, "group")) { admin_err("admin.invalidArgument", NULL); return; }
c.group_only = !strcmp(s, "group");
+ } else if (sscanf(line, "net=%15s", s) == 1) {
+ if (rs_net_mode(s) < 0) { admin_err("admin.invalidArgument", NULL); return; }
+ c.net = rs_net_mode(s);
} else { admin_err("admin.invalidArgument", NULL); return; }
}
if (c.group_only && !getgrnam("lordos-remote")) {
@@ -175,3 +188,103 @@ void remote_act_kick(const AdminReq *r, const char *arg, size_t len) {
kill((pid_t)pid, SIGTERM);
admin_ok("remote.disconnected", NULL);
}
+
+/* ---- address lists (docs/REMOTE.md, "Blocked and allowed addresses") ---- */
+
+/* One argument: an address or network, strictly (ipnet.c), nothing else on the line. */
+static int one_cidr(const char *arg, size_t len, RsCidr *c, char canon[64]) {
+ if (!len || len > 60 || memchr(arg, '\n', len) || memchr(arg, ' ', len)) return -1;
+ char buf[64];
+ memcpy(buf, arg, len);
+ buf[len] = 0;
+ if (rs_cidr_parse(buf, c)) return -1;
+ rs_cidr_format(c, canon, 64);
+ return 0;
+}
+
+static void access_read(RsAccess *acc) {
+ char text[16384] = "";
+ int fd = open(RD_ACCESS_PATH, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
+ if (fd >= 0) {
+ struct stat st;
+ if (!fstat(fd, &st) && S_ISREG(st.st_mode) && st.st_uid == 0) {
+ ssize_t n = read(fd, text, sizeof text - 1);
+ if (n > 0) text[n] = 0;
+ }
+ close(fd);
+ }
+ rs_access_parse(text, acc, NULL);
+}
+
+static int access_write(const RsAccess *acc) {
+ char text[16384];
+ if (rs_access_format(acc, text, sizeof text) < 0) return -1;
+ mkdir("/etc/lordos", 0755);
+ mkdir(CONF_DIR, 0755);
+ return write_file(RD_ACCESS_PATH, text, 0600);
+}
+
+static void reload_sessiond(void) {
+ pid_t pid = sessiond_pid();
+ if (pid > 0) kill(pid, SIGHUP);
+}
+
+void remote_act_block(const AdminReq *r, const char *arg, size_t len) {
+ (void)r;
+ RsCidr c;
+ char canon[64];
+ if (one_cidr(arg, len, &c, canon)) { admin_err("remote.badAddress", NULL); return; }
+ RsAccess acc;
+ access_read(&acc);
+ int k = rs_access_add(acc.block, &acc.nblock, &c);
+ if (k < 0) { admin_err("remote.listFull", NULL); return; }
+ if (k == 0 && access_write(&acc)) { admin_err("remote.configFailed", NULL); return; }
+ reload_sessiond();
+ admin_ok("remote.blocked", "address", canon, NULL);
+}
+
+void remote_act_unblock(const AdminReq *r, const char *arg, size_t len) {
+ (void)r;
+ RsCidr c;
+ char canon[64];
+ /* also an IPv6 /64 lockout key, which one_cidr accepts as a network */
+ if (one_cidr(arg, len, &c, canon)) { admin_err("remote.badAddress", NULL); return; }
+ RsAccess acc;
+ access_read(&acc);
+ if (rs_access_del(acc.block, &acc.nblock, &c) && access_write(&acc)) { admin_err("remote.configFailed", NULL); return; }
+ /* the failed-login blocks belong to lord-sessiond: a request it reads on SIGHUP */
+ mkdir("/var/lib/lordos", 0755);
+ mkdir(RL_FILE_DIR, 0700);
+ struct stat st;
+ if (lstat(RL_FILE_DIR, &st) || !S_ISDIR(st.st_mode) || st.st_uid != 0) { admin_err("remote.configFailed", NULL); return; }
+ int fd = open(RL_REQUESTS, O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0600);
+ if (fd < 0) { admin_err("remote.configFailed", NULL); return; }
+ flock(fd, LOCK_EX);
+ char line[96];
+ int n = snprintf(line, sizeof line, "unblock %s\n", canon);
+ int ok = write(fd, line, (size_t)n) == n;
+ close(fd);
+ if (!ok) { admin_err("remote.configFailed", NULL); return; }
+ reload_sessiond();
+ admin_ok("remote.unblocked", "address", canon, NULL);
+}
+
+void remote_act_allow(const AdminReq *r, const char *arg, size_t len) {
+ (void)r;
+ int add;
+ if (len > 4 && !strncmp(arg, "add ", 4)) add = 1;
+ else if (len > 4 && !strncmp(arg, "del ", 4)) add = 0;
+ else { admin_err("admin.invalidArgument", NULL); return; }
+ RsCidr c;
+ char canon[64];
+ if (one_cidr(arg + 4, len - 4, &c, canon)) { admin_err("remote.badAddress", NULL); return; }
+ RsAccess acc;
+ access_read(&acc);
+ if (add) {
+ int k = rs_access_add(acc.allow, &acc.nallow, &c);
+ if (k < 0) { admin_err("remote.listFull", NULL); return; }
+ } else rs_access_del(acc.allow, &acc.nallow, &c);
+ if (access_write(&acc)) { admin_err("remote.configFailed", NULL); return; }
+ reload_sessiond();
+ admin_ok("remote.saved", NULL);
+}
diff --git a/server/src/remote/remote_admin.h b/server/src/remote/remote_admin.h
index 67c726d..26e15a7 100644
--- a/server/src/remote/remote_admin.h
+++ b/server/src/remote/remote_admin.h
@@ -9,12 +9,18 @@ void remote_act_disable(const AdminReq *r, const char *arg, size_t len);
void remote_act_config(const AdminReq *r, const char *arg, size_t len);
void remote_act_member(const AdminReq *r, const char *arg, size_t len);
void remote_act_kick(const AdminReq *r, const char *arg, size_t len);
+void remote_act_block(const AdminReq *r, const char *arg, size_t len);
+void remote_act_unblock(const AdminReq *r, const char *arg, size_t len);
+void remote_act_allow(const AdminReq *r, const char *arg, size_t len);
#define REMOTE_ADMIN_ACTIONS \
{ "remote-enable", remote_act_enable, A_FORK }, \
{ "remote-disable", remote_act_disable, A_FORK }, \
{ "remote-config", remote_act_config, A_FORK }, \
{ "remote-member", remote_act_member, 0 }, \
- { "remote-kick", remote_act_kick, 0 },
+ { "remote-kick", remote_act_kick, 0 }, \
+ { "remote-block", remote_act_block, 0 }, \
+ { "remote-unblock", remote_act_unblock, 0 }, \
+ { "remote-allow", remote_act_allow, 0 },
#endif
diff --git a/server/src/remote/rsec.c b/server/src/remote/rsec.c
new file mode 100644
index 0000000..f9d4588
--- /dev/null
+++ b/server/src/remote/rsec.c
@@ -0,0 +1,594 @@
+/* rsec.c — strict parsers for what the browser sends to the remote desktop (see rsec.h). */
+#include "rsec.h"
+
+#include <arpa/inet.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+
+/* ---- HTTP request head ---- */
+
+static int is_tchar(unsigned char c) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c && strchr("!#$%&'*+-.^_`|~", c));
+}
+
+/* a header value into a fixed field; -431 if it doesn't fit, -400 if repeated */
+static int put_field(char *dst, size_t cap, const char *v, size_t vl, unsigned *seen, unsigned bit) {
+ if (*seen & bit) return -400;
+ *seen |= bit;
+ if (vl >= cap) return -431;
+ memcpy(dst, v, vl);
+ dst[vl] = 0;
+ return 0;
+}
+
+int rs_parse_head(const char *buf, size_t len, RsReq *r) {
+ memset(r, 0, sizeof *r);
+ r->content_length = -1;
+ size_t lim = len < RS_MAX_HEAD ? len : RS_MAX_HEAD, end = 0;
+ int found = 0;
+ /* bytes allowed in a head: visible ASCII, space, tab, and CR only as part of CRLF */
+ for (size_t i = 0; i < lim; i++) {
+ unsigned char c = (unsigned char)buf[i];
+ if (c == '\r') {
+ if (i + 1 < lim && buf[i + 1] != '\n') return -400;
+ if (i + 3 < lim && buf[i + 1] == '\n' && buf[i + 2] == '\r' && buf[i + 3] == '\n') { end = i; found = 1; break; }
+ continue;
+ }
+ if (c == '\n') { if (!i || buf[i - 1] != '\r') return -400; continue; }
+ if (c == '\t') continue;
+ if (c < 0x20 || c > 0x7e) return -400;
+ }
+ if (!found) return len >= RS_MAX_HEAD ? -431 : RS_NEED_MORE;
+ if (end == 0) return -400; /* no request line (leading CRLF) */
+
+ /* request line: METHOD SP /target SP HTTP/1.x */
+ const char *p = buf, *eol = memchr(buf, '\r', end + 1);
+ size_t ml = 0;
+ while (p + ml < eol && p[ml] >= 'A' && p[ml] <= 'Z') ml++;
+ if (!ml || ml >= sizeof r->method || p[ml] != ' ') return -400;
+ memcpy(r->method, p, ml);
+ const char *tg = p + ml + 1, *sp = tg;
+ while (sp < eol && *sp != ' ') sp++;
+ if (sp == tg || sp >= eol || *tg != '/') return -400;
+ size_t tl = (size_t)(sp - tg);
+ if (tl > 400) return -414;
+ const char *q = memchr(tg, '?', tl);
+ if (memchr(tg, '#', tl) || memchr(tg, '\t', tl)) return -400;
+ size_t pl = q ? (size_t)(q - tg) : tl, ql = q ? tl - pl - 1 : 0;
+ if (pl >= sizeof r->path || ql >= sizeof r->query) return -414;
+ memcpy(r->path, tg, pl);
+ if (q) memcpy(r->query, q + 1, ql);
+ const char *ver = sp + 1;
+ int http11;
+ if ((size_t)(eol - ver) == 8 && !memcmp(ver, "HTTP/1.1", 8)) http11 = 1;
+ else if ((size_t)(eol - ver) == 8 && !memcmp(ver, "HTTP/1.0", 8)) http11 = 0;
+ else return -400;
+
+ /* header fields */
+ unsigned seen = 0;
+ int count = 0;
+ for (const char *line = eol + 2; line < buf + end + 2;) {
+ const char *le = memchr(line, '\r', (size_t)(buf + end + 2 - line));
+ if (!le) return -400;
+ if (le == line) break;
+ if (++count > RS_MAX_HEADERS) return -431;
+ if (*line == ' ' || *line == '\t') return -400; /* obsolete line folding */
+ const char *colon = memchr(line, ':', (size_t)(le - line));
+ if (!colon || colon == line) return -400;
+ for (const char *c = line; c < colon; c++) if (!is_tchar((unsigned char)*c)) return -400; /* also no space before ':' */
+ size_t nl = (size_t)(colon - line);
+ const char *v = colon + 1, *ve = le;
+ while (v < ve && (*v == ' ' || *v == '\t')) v++;
+ while (ve > v && (ve[-1] == ' ' || ve[-1] == '\t')) ve--;
+ size_t vl = (size_t)(ve - v);
+ int rc = 0;
+#define HDR(nm) (nl == sizeof(nm) - 1 && !strncasecmp(line, nm, nl))
+ if (HDR("Host")) rc = put_field(r->host, sizeof r->host, v, vl, &seen, 1u << 0);
+ else if (HDR("Origin")) rc = put_field(r->origin, sizeof r->origin, v, vl, &seen, 1u << 1);
+ else if (HDR("Cookie")) rc = put_field(r->cookie, sizeof r->cookie, v, vl, &seen, 1u << 2);
+ else if (HDR("Upgrade")) rc = put_field(r->upgrade, sizeof r->upgrade, v, vl, &seen, 1u << 3);
+ else if (HDR("Connection")) rc = put_field(r->connection, sizeof r->connection, v, vl, &seen, 1u << 4);
+ else if (HDR("Sec-WebSocket-Key")) rc = put_field(r->wskey, sizeof r->wskey, v, vl, &seen, 1u << 5);
+ else if (HDR("Sec-WebSocket-Version")) rc = put_field(r->wsversion, sizeof r->wsversion, v, vl, &seen, 1u << 6);
+ else if (HDR("Content-Type")) rc = put_field(r->ctype, sizeof r->ctype, v, vl, &seen, 1u << 7);
+ else if (HDR("Sec-Fetch-Site")) rc = put_field(r->fetch_site, sizeof r->fetch_site, v, vl, &seen, 1u << 8);
+ else if (HDR("Transfer-Encoding")) return -501;
+ else if (HDR("Content-Length")) {
+ if (seen & (1u << 9)) return -400;
+ seen |= 1u << 9;
+ if (!vl || vl > 9) return vl > 9 ? -413 : -400;
+ long n = 0;
+ for (size_t i = 0; i < vl; i++) {
+ if (v[i] < '0' || v[i] > '9') return -400;
+ n = n * 10 + (v[i] - '0');
+ }
+ if (n > RS_MAX_BODY) return -413;
+ r->content_length = n;
+ }
+#undef HDR
+ if (rc) return rc;
+ line = le + 2;
+ }
+ if (http11 && !r->host[0]) return -400;
+ r->head_len = end + 4;
+ return (int)r->head_len;
+}
+
+int rs_valid_username(const char *u) {
+ size_t n = u ? strlen(u) : 0;
+ if (!n || n > 32 || !((u[0] >= 'a' && u[0] <= 'z') || u[0] == '_')) return 0;
+ for (const char *p = u; *p; p++)
+ if (!((*p >= 'a' && *p <= 'z') || (*p >= '0' && *p <= '9') || *p == '_' || *p == '-')) return 0;
+ return 1;
+}
+
+static int valid_port(const char *p) {
+ size_t n = strlen(p);
+ if (!n || n > 5 || p[0] == '0') return 0;
+ long v = 0;
+ for (size_t i = 0; i < n; i++) { if (p[i] < '0' || p[i] > '9') return 0; v = v * 10 + (p[i] - '0'); }
+ return v > 0 && v < 65536;
+}
+
+int rs_valid_host(const char *h) {
+ size_t n = h ? strlen(h) : 0;
+ if (!n || n > 260) return 0;
+ char buf[264];
+ memcpy(buf, h, n + 1);
+ if (buf[0] == '[') {
+ char *rb = strchr(buf, ']');
+ if (!rb) return 0;
+ *rb = 0;
+ unsigned char a[16];
+ if (inet_pton(AF_INET6, buf + 1, a) != 1) return 0;
+ if (!rb[1]) return 1;
+ return rb[1] == ':' && valid_port(rb + 2);
+ }
+ char *colon = strchr(buf, ':');
+ if (colon) { *colon = 0; if (!valid_port(colon + 1)) return 0; }
+ size_t l = strlen(buf);
+ if (!l || l > 253 || buf[0] == '-' || buf[0] == '.' || buf[l - 1] == '-') return 0;
+ for (size_t i = 0; i < l; i++) {
+ char c = buf[i];
+ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '.')) return 0;
+ if (c == '.' && buf[i + 1] == '.') return 0;
+ }
+ return 1;
+}
+
+int rs_same_origin(const char *origin, const char *host) {
+ if (!origin || !host || !rs_valid_host(host)) return 0;
+ if (strncmp(origin, "https://", 8)) return 0;
+ return !strcasecmp(origin + 8, host);
+}
+
+int rs_has_token(const char *list, const char *token) {
+ size_t tl = strlen(token);
+ for (const char *p = list; p && *p;) {
+ while (*p == ' ' || *p == '\t' || *p == ',') p++;
+ const char *e = p;
+ while (*e && *e != ',') e++;
+ const char *te = e;
+ while (te > p && (te[-1] == ' ' || te[-1] == '\t')) te--;
+ if ((size_t)(te - p) == tl && !strncasecmp(p, token, tl)) return 1;
+ p = e;
+ }
+ return 0;
+}
+
+static int b64c(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/'; }
+
+int rs_valid_wskey(const char *k) {
+ if (!k || strlen(k) != 24 || k[22] != '=' || k[23] != '=') return 0;
+ for (int i = 0; i < 22; i++) if (!b64c(k[i])) return 0;
+ return strchr("AQgw", k[21]) != NULL; /* the last 4 bits must be zero */
+}
+
+int rs_form_type(const char *ct) {
+ static const char base[] = "application/x-www-form-urlencoded";
+ if (!ct || strncasecmp(ct, base, sizeof base - 1)) return 0;
+ const char *p = ct + sizeof base - 1;
+ while (*p == ' ') p++;
+ if (!*p) return 1;
+ if (*p++ != ';') return 0;
+ while (*p == ' ') p++;
+ if (strncasecmp(p, "charset=", 8)) return 0;
+ p += 8;
+ int quoted = *p == '"';
+ if (quoted) p++;
+ if (strncasecmp(p, "utf-8", 5)) return 0;
+ p += 5;
+ if (quoted && *p++ != '"') return 0;
+ while (*p == ' ') p++;
+ return !*p;
+}
+
+int rs_cookie_token(const char *cookie, const char *name, char out[65]) {
+ out[0] = 0;
+ size_t nl = strlen(name);
+ int found = 0;
+ for (const char *p = cookie ? cookie : ""; *p;) {
+ while (*p == ' ' || *p == ';') p++;
+ const char *e = p;
+ while (*e && *e != ';') e++;
+ const char *eq = memchr(p, '=', (size_t)(e - p));
+ if (eq && (size_t)(eq - p) == nl && !memcmp(p, name, nl)) {
+ const char *v = eq + 1, *ve = e;
+ while (ve > v && ve[-1] == ' ') ve--;
+ if (found++ || ve - v != 64) return -2;
+ for (const char *c = v; c < ve; c++) if (!((*c >= '0' && *c <= '9') || (*c >= 'a' && *c <= 'f'))) return -2;
+ memcpy(out, v, 64);
+ out[64] = 0;
+ }
+ p = e;
+ }
+ return found ? 0 : -1;
+}
+
+/* ---- login form ---- */
+
+static int hexv(char c) {
+ return c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
+}
+
+/* decodes v[0..vl) into out (cap bytes); returns the length, -1 malformed, -2 too long */
+static long form_decode(const char *v, size_t vl, char *out, size_t cap) {
+ size_t o = 0;
+ for (size_t i = 0; i < vl; i++) {
+ char c = v[i];
+ if (c == '%') {
+ if (i + 2 >= vl) return -1;
+ int h = hexv(v[i + 1]), l = hexv(v[i + 2]);
+ if (h < 0 || l < 0) return -1;
+ c = (char)(h << 4 | l);
+ i += 2;
+ } else if (c == '+') c = ' ';
+ if (o >= cap) return -2;
+ out[o++] = c;
+ }
+ return (long)o;
+}
+
+void rs_log_clean(const char *in, size_t inlen, char *out, size_t n) {
+ size_t o = 0;
+ for (size_t i = 0; i < inlen && o + 1 < n; i++) {
+ unsigned char c = (unsigned char)in[i];
+ out[o++] = c >= 0x20 && c < 0x7f && c != '"' && c != '\\' ? (char)c : '?';
+ }
+ if (n) out[o] = 0;
+}
+
+int rs_parse_login(const char *body, size_t len, char user[33], char pass[RS_PASS_MAX + 1], size_t *passlen, char rawuser[33]) {
+ user[0] = pass[0] = rawuser[0] = 0;
+ *passlen = 0;
+ if (len > RS_MAX_BODY) return RS_FORM_BAD;
+ for (size_t i = 0; i < len; i++) {
+ unsigned char c = (unsigned char)body[i];
+ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || strchr("-._~*%+=&", c)) || !c) return RS_FORM_BAD;
+ }
+ int have_u = 0, have_p = 0;
+ char ubuf[64];
+ long ul = -1, pl = -1;
+ for (size_t i = 0; i < len;) {
+ size_t e = i;
+ while (e < len && body[e] != '&') e++;
+ const char *f = body + i;
+ size_t fl = e - i;
+ const char *eq = memchr(f, '=', fl);
+ if (!eq) return RS_FORM_BAD;
+ size_t kl = (size_t)(eq - f);
+ if (kl == 4 && !memcmp(f, "user", 4)) {
+ if (have_u++) return RS_FORM_BAD;
+ ul = form_decode(eq + 1, fl - 5, ubuf, sizeof ubuf - 1);
+ if (ul == -1) return RS_FORM_BAD;
+ } else if (kl == 4 && !memcmp(f, "pass", 4)) {
+ if (have_p++) return RS_FORM_BAD;
+ pl = form_decode(eq + 1, fl - 5, pass, RS_PASS_MAX);
+ if (pl == -1) return RS_FORM_BAD;
+ } else return RS_FORM_BAD;
+ i = e + 1;
+ if (e == len - 1 && body[e] == '&') return RS_FORM_BAD; /* trailing '&' */
+ }
+ if (!have_u || !have_p) { explicit_bzero(pass, RS_PASS_MAX + 1); return RS_FORM_BAD; }
+ if (ul >= 0) { ubuf[ul] = 0; rs_log_clean(ubuf, (size_t)ul, rawuser, 33); }
+ else rs_log_clean("(too long)", 10, rawuser, 33);
+ if (ul <= 0 || ul > 32 || memchr(ubuf, 0, (size_t)ul) || !rs_valid_username(ubuf)) { explicit_bzero(pass, RS_PASS_MAX + 1); return RS_FORM_USER; }
+ memcpy(user, ubuf, (size_t)ul + 1);
+ if (pl <= 0 || memchr(pass, 0, (size_t)pl)) { explicit_bzero(pass, RS_PASS_MAX + 1); return RS_FORM_PASS; }
+ pass[pl] = 0;
+ *passlen = (size_t)pl;
+ return RS_FORM_OK;
+}
+
+/* ---- WebSocket ---- */
+
+int rs_utf8_valid(const unsigned char *p, size_t n) {
+ for (size_t i = 0; i < n;) {
+ unsigned char c = p[i];
+ if (c < 0x80) { i++; continue; }
+ size_t k;
+ uint32_t cp, min;
+ if ((c & 0xe0) == 0xc0) { k = 1; cp = c & 0x1f; min = 0x80; }
+ else if ((c & 0xf0) == 0xe0) { k = 2; cp = c & 0x0f; min = 0x800; }
+ else if ((c & 0xf8) == 0xf0) { k = 3; cp = c & 0x07; min = 0x10000; }
+ else return 0;
+ if (n - i <= k) return 0;
+ for (size_t j = 1; j <= k; j++) {
+ if ((p[i + j] & 0xc0) != 0x80) return 0;
+ cp = cp << 6 | (p[i + j] & 0x3f);
+ }
+ if (cp < min || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) return 0;
+ i += k + 1;
+ }
+ return 1;
+}
+
+void rs_ws_init(RsWs *w, size_t max) { memset(w, 0, sizeof *w); w->max = max; }
+
+void rs_ws_free(RsWs *w) {
+ if (w->msg) { explicit_bzero(w->msg, w->msg_cap); free(w->msg); }
+ memset(w, 0, sizeof *w);
+}
+
+int rs_ws_consume(RsWs *w, unsigned char *buf, size_t n, size_t *used, RsWsOn on, void *ud) {
+ size_t off = 0;
+ int rc = 0;
+ while (n - off >= 2) {
+ unsigned char *f = buf + off;
+ size_t avail = n - off;
+ int fin = f[0] & 0x80, op = f[0] & 15;
+ if (f[0] & 0x70) { rc = 1002; break; } /* no extensions were negotiated */
+ if (!(f[1] & 0x80)) { rc = 1002; break; } /* client frames are masked */
+ if ((op > 2 && op < 8) || op > 10) { rc = 1002; break; }
+ uint64_t len = f[1] & 127;
+ size_t hl = 2;
+ if (len == 126) {
+ if (avail < 4) break;
+ len = (uint64_t)f[2] << 8 | f[3];
+ hl = 4;
+ if (len < 126) { rc = 1002; break; } /* not the shortest encoding */
+ } else if (len == 127) {
+ if (avail < 10) break;
+ len = 0;
+ for (int i = 0; i < 8; i++) len = len << 8 | f[2 + i];
+ hl = 10;
+ if (len >> 63 || len < 65536) { rc = 1002; break; }
+ }
+ int control = op >= 8;
+ if (control && (!fin || len > 125)) { rc = 1002; break; }
+ if (len > w->max) { rc = 1009; break; }
+ if (avail - hl < 4 || avail - hl - 4 < len) break; /* frame not complete yet */
+ unsigned char *m = f + hl, *p = f + hl + 4;
+ for (uint64_t i = 0; i < len; i++) p[i] ^= m[i & 3];
+ off += hl + 4 + (size_t)len;
+ if (control) {
+ unsigned char c[126];
+ memcpy(c, p, (size_t)len);
+ c[len] = 0;
+ on(ud, op, c, (size_t)len);
+ if (op == 8) break;
+ continue;
+ }
+ if (op == 0 && !w->frag_op) { rc = 1002; break; } /* continuation of nothing */
+ if (op != 0 && w->frag_op) { rc = 1002; break; } /* new message inside a fragmented one */
+ if (op != 0) { w->frag_op = op; w->msg_len = 0; }
+ if (w->msg_len + len > w->max) { rc = 1009; break; }
+ if (w->msg_len + len + 1 > w->msg_cap) {
+ size_t cap = w->msg_cap ? w->msg_cap : 4096;
+ while (cap < w->msg_len + len + 1) cap *= 2;
+ unsigned char *nb = realloc(w->msg, cap);
+ if (!nb) { rc = 1011; break; }
+ w->msg = nb;
+ w->msg_cap = cap;
+ }
+ memcpy(w->msg + w->msg_len, p, (size_t)len);
+ w->msg_len += (size_t)len;
+ if (!fin) continue;
+ w->msg[w->msg_len] = 0;
+ int mop = w->frag_op;
+ w->frag_op = 0;
+ if (mop == 1 && !rs_utf8_valid(w->msg, w->msg_len)) { rc = 1007; break; }
+ on(ud, mop, w->msg, w->msg_len);
+ w->msg_len = 0;
+ }
+ *used = off;
+ return rc;
+}
+
+/* ---- flat JSON ---- */
+
+static void jws(const char *j, size_t n, size_t *i) { while (*i < n && (j[*i] == ' ' || j[*i] == '\t' || j[*i] == '\n' || j[*i] == '\r')) (*i)++; }
+
+static int hex4(const char *j, size_t n, size_t i, unsigned *v) {
+ if (i + 4 > n) return -1;
+ *v = 0;
+ for (int k = 0; k < 4; k++) { int h = hexv(j[i + k]); if (h < 0) return -1; *v = *v << 4 | (unsigned)h; }
+ return 0;
+}
+
+static int put_utf8(char *sb, size_t cap, size_t *so, unsigned cp) {
+ if (*so + 5 > cap) return -1;
+ if (cp < 0x80) sb[(*so)++] = (char)cp;
+ else if (cp < 0x800) { sb[(*so)++] = (char)(0xc0 | cp >> 6); sb[(*so)++] = (char)(0x80 | (cp & 63)); }
+ else if (cp < 0x10000) { sb[(*so)++] = (char)(0xe0 | cp >> 12); sb[(*so)++] = (char)(0x80 | ((cp >> 6) & 63)); sb[(*so)++] = (char)(0x80 | (cp & 63)); }
+ else { sb[(*so)++] = (char)(0xf0 | cp >> 18); sb[(*so)++] = (char)(0x80 | ((cp >> 12) & 63)); sb[(*so)++] = (char)(0x80 | ((cp >> 6) & 63)); sb[(*so)++] = (char)(0x80 | (cp & 63)); }
+ return 0;
+}
+
+int rs_json_parse(const char *j, size_t n, RsJson *o, char *sb, size_t cap) {
+ memset(o, 0, sizeof *o);
+ size_t i = 0, so = 0;
+ jws(j, n, &i);
+ if (i >= n || j[i++] != '{') return -1;
+ jws(j, n, &i);
+ if (i < n && j[i] == '}') { i++; goto done; }
+ for (;;) {
+ if (o->n >= RS_JMAX) return -1;
+ jws(j, n, &i);
+ if (i >= n || j[i++] != '"') return -1;
+ size_t ks = i;
+ while (i < n && j[i] >= 'a' && j[i] <= 'z') i++;
+ size_t kl = i - ks;
+ if (!kl || kl > 11 || i >= n || j[i++] != '"') return -1;
+ int k = o->n;
+ memcpy(o->key[k], j + ks, kl);
+ o->key[k][kl] = 0;
+ for (int m = 0; m < k; m++) if (!strcmp(o->key[m], o->key[k])) return -1;
+ jws(j, n, &i);
+ if (i >= n || j[i++] != ':') return -1;
+ jws(j, n, &i);
+ if (i >= n) return -1;
+ if (j[i] == '"') {
+ i++;
+ size_t start = so;
+ for (;;) {
+ if (i >= n) return -1;
+ unsigned char c = (unsigned char)j[i];
+ if (c == '"') { i++; break; }
+ if (c < 0x20) return -1;
+ if (c != '\\') { if (so + 2 > cap) return -1; sb[so++] = (char)c; i++; continue; }
+ if (++i >= n) return -1;
+ char e = j[i++];
+ unsigned cp;
+ switch (e) {
+ case '"': cp = '"'; break;
+ case '\\': cp = '\\'; break;
+ case '/': cp = '/'; break;
+ case 'b': cp = 8; break;
+ case 'f': cp = 12; break;
+ case 'n': cp = 10; break;
+ case 'r': cp = 13; break;
+ case 't': cp = 9; break;
+ case 'u':
+ if (hex4(j, n, i, &cp)) return -1;
+ i += 4;
+ if (cp >= 0xdc00 && cp <= 0xdfff) return -1; /* lone low surrogate */
+ if (cp >= 0xd800 && cp <= 0xdbff) {
+ unsigned lo;
+ if (i + 2 > n || j[i] != '\\' || j[i + 1] != 'u' || hex4(j, n, i + 2, &lo) || lo < 0xdc00 || lo > 0xdfff) return -1;
+ i += 6;
+ cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00);
+ }
+ if (!cp) return -1;
+ break;
+ default: return -1;
+ }
+ if (put_utf8(sb, cap, &so, cp)) return -1;
+ }
+ if (so + 1 > cap) return -1;
+ sb[so] = 0;
+ o->is_str[k] = 1;
+ o->str[k] = sb + start;
+ o->slen[k] = so - start;
+ so++;
+ } else {
+ int neg = 0;
+ if (j[i] == '-') { neg = 1; i++; }
+ size_t ds = i;
+ long long v = 0;
+ while (i < n && j[i] >= '0' && j[i] <= '9') {
+ if (i - ds >= 16) return -1;
+ v = v * 10 + (j[i] - '0');
+ i++;
+ }
+ size_t dl = i - ds;
+ if (!dl || (dl > 1 && j[ds] == '0')) return -1;
+ if (i < n && (j[i] == '.' || j[i] == 'e' || j[i] == 'E')) return -1;
+ if (v >= (1LL << 53)) return -1;
+ o->num[k] = neg ? -v : v;
+ }
+ o->n++;
+ jws(j, n, &i);
+ if (i >= n) return -1;
+ if (j[i] == ',') { i++; continue; }
+ if (j[i] == '}') { i++; break; }
+ return -1;
+ }
+done:
+ jws(j, n, &i);
+ return i == n ? 0 : -1;
+}
+
+const char *rs_json_str(const RsJson *o, const char *key, size_t *len) {
+ for (int i = 0; i < o->n; i++)
+ if (o->is_str[i] && !strcmp(o->key[i], key)) { if (len) *len = o->slen[i]; return o->str[i]; }
+ return NULL;
+}
+
+int rs_json_num(const RsJson *o, const char *key, long long *v) {
+ for (int i = 0; i < o->n; i++)
+ if (!o->is_str[i] && !strcmp(o->key[i], key)) { *v = o->num[i]; return 0; }
+ return -1;
+}
+
+static long long clampll(long long v, long long lo, long long hi) { return v < lo ? lo : v > hi ? hi : v; }
+
+int rs_browser_input(const RsJson *j, int W, int H, RsInput *in) {
+ memset(in, 0, sizeof *in);
+ size_t tl = 0;
+ const char *t = rs_json_str(j, "t", &tl);
+ long long a, b;
+ if (!t || tl > 6) return RS_IN_NONE;
+ if (!strcmp(t, "m")) {
+ if (W <= 0 || H <= 0 || rs_json_num(j, "x", &a) || rs_json_num(j, "y", &b)) return RS_IN_NONE;
+ in->a = (int)clampll(a, 0, W - 1);
+ in->b = (int)clampll(b, 0, H - 1);
+ return in->type = RS_IN_PTR;
+ }
+ if (!strcmp(t, "b")) {
+ if (rs_json_num(j, "b", &a) || rs_json_num(j, "d", &b) || a < 0 || a > 2) return RS_IN_NONE;
+ in->a = (int)a;
+ in->b = b != 0;
+ return in->type = RS_IN_BTN;
+ }
+ if (!strcmp(t, "w")) {
+ if (rs_json_num(j, "d", &a) || !a) return RS_IN_NONE;
+ in->a = (int)clampll(a, -10, 10);
+ return in->type = RS_IN_WHEEL;
+ }
+ if (!strcmp(t, "s") || !strcmp(t, "pz")) {
+ int sc = t[0] == 's';
+ long long v1, v2;
+ if (rs_json_num(j, "p", &a) || a < 1 || a > 3) return RS_IN_NONE;
+ if (rs_json_num(j, sc ? "x" : "s", &v1) || rs_json_num(j, sc ? "y" : "r", &v2)) return RS_IN_NONE;
+ in->a = (int)a;
+ if (sc) {
+ in->v1 = (int32_t)clampll(v1, -4000LL * 256, 4000LL * 256);
+ in->v2 = (int32_t)clampll(v2, -4000LL * 256, 4000LL * 256);
+ return in->type = RS_IN_SCROLL;
+ }
+ in->v1 = (int32_t)clampll(v1, 3277, 20LL * 65536); /* scale 0.05 .. 20 */
+ in->v2 = (int32_t)clampll(v2, -360LL * 256 * 4, 360LL * 256 * 4);
+ return in->type = RS_IN_PINCH;
+ }
+ if (!strcmp(t, "k")) {
+ /* keyboard keys only (KEY_ESC .. KEY_MICMUTE): no BTN_* codes */
+ if (rs_json_num(j, "c", &a) || rs_json_num(j, "d", &b) || a < 1 || a > 248) return RS_IN_NONE;
+ in->a = (int)a;
+ in->b = b != 0;
+ return in->type = RS_IN_KEY;
+ }
+ if (!strcmp(t, "ack")) return in->type = RS_IN_ACK;
+ if (!strcmp(t, "resize")) {
+ if (rs_json_num(j, "w", &a) || rs_json_num(j, "h", &b) || a < 640 || b < 480 || a > 3840 || b > 2400) return RS_IN_NONE;
+ in->a = (int)(a & ~1LL);
+ in->b = (int)(b & ~1LL);
+ return in->type = RS_IN_RESIZE;
+ }
+ if (!strcmp(t, "ping")) {
+ if (rs_json_num(j, "ts", &a) || a < 0) return RS_IN_NONE;
+ in->ts = a;
+ return in->type = RS_IN_PING;
+ }
+ if (!strcmp(t, "clip")) {
+ size_t l = 0;
+ const char *x = rs_json_str(j, "text", &l);
+ if (!x || !l || l > RS_CLIP_MAX) return RS_IN_NONE;
+ in->text = x;
+ in->tlen = l;
+ return in->type = RS_IN_CLIP;
+ }
+ return RS_IN_NONE;
+}
diff --git a/server/src/remote/rsec.h b/server/src/remote/rsec.h
new file mode 100644
index 0000000..2115eb2
--- /dev/null
+++ b/server/src/remote/rsec.h
@@ -0,0 +1,118 @@
+/* rsec.h — strict parsers of everything a browser sends to the remote desktop (docs/REMOTE.md,
+ * "Security analysis (0.8.3)"): the HTTP request head, the login form, the cookie, WebSocket
+ * frames and the JSON input messages. Plain libc, no I/O and no OpenSSL, so they are unit-tested
+ * and fuzzed with ASan+UBSan (build/remote-sec-test, build/remote-fuzz).
+ *
+ * Every function rejects instead of guessing: a request that is not exactly what our own pages
+ * send gets an error status and the connection is closed. */
+#ifndef LORD_REMOTE_RSEC_H
+#define LORD_REMOTE_RSEC_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+/* ---- HTTP/1.1 request head ---- */
+
+#define RS_MAX_HEAD 8192 /* request line + headers + blank line */
+#define RS_MAX_HEADERS 40
+#define RS_MAX_BODY 4096 /* only POST /login has a body */
+
+typedef struct {
+ char method[8];
+ char path[128];
+ char query[256];
+ char host[256], origin[256], cookie[1024], upgrade[32], connection[128];
+ char wskey[32], wsversion[8], ctype[96], fetch_site[24];
+ long content_length; /* -1: no Content-Length */
+ size_t head_len; /* bytes of the head, CRLFCRLF included */
+} RsReq;
+
+/* Results < 0 are HTTP statuses to answer with (negated). */
+enum { RS_NEED_MORE = 0 };
+/* Parses the head at the start of buf[0..len). Returns the head length (> 0), RS_NEED_MORE (0) if
+ * it isn't complete yet, or -status: -400 malformed, -405 unknown method, -414 target too long,
+ * -431 head or a header too large, -413 body too large, -501 Transfer-Encoding. */
+int rs_parse_head(const char *buf, size_t len, RsReq *r);
+
+int rs_valid_username(const char *u); /* ^[a-z_][a-z0-9_-]{0,31}$ */
+int rs_valid_host(const char *h); /* host[:port]: name, IPv4 or [IPv6] */
+/* Origin must be exactly "https://" + Host (the host part case-insensitive). */
+int rs_same_origin(const char *origin, const char *host);
+/* comma-separated list contains this token (case-insensitive) */
+int rs_has_token(const char *list, const char *token);
+int rs_valid_wskey(const char *k); /* base64 of 16 bytes */
+/* Content-Type of the login form: application/x-www-form-urlencoded, optionally ;charset=UTF-8 */
+int rs_form_type(const char *ctype);
+
+/* The session cookie: exactly one `name` pair with 64 lowercase hex digits.
+ * 0 found, -1 absent, -2 malformed or present twice. */
+int rs_cookie_token(const char *cookie, const char *name, char out[65]);
+
+/* ---- login form (application/x-www-form-urlencoded) ---- */
+
+#define RS_PASS_MAX 1024
+enum { RS_FORM_OK = 0, RS_FORM_BAD = -1, RS_FORM_USER = -2, RS_FORM_PASS = -3 };
+/* Exactly the fields "user" and "pass", once each, nothing else; strict %XX decoding; the user a
+ * valid login name; the password 1..1024 bytes without NUL. *ulen_raw gets the decoded length of
+ * the user field even if invalid (for logging a sanitized copy into rawuser). */
+int rs_parse_login(const char *body, size_t len, char user[33], char pass[RS_PASS_MAX + 1], size_t *passlen,
+ char rawuser[33]);
+
+/* Printable ASCII copy for the journal (anything else becomes '?'), at most n-1 bytes. */
+void rs_log_clean(const char *in, size_t inlen, char *out, size_t n);
+
+/* ---- WebSocket (RFC 6455, server side: client frames must be masked) ---- */
+
+#define RS_WS_MAX_MSG (2u << 20) /* largest message from the browser (a clipboard) */
+
+int rs_utf8_valid(const unsigned char *p, size_t n);
+
+typedef struct {
+ int frag_op; /* opcode of a fragmented message in progress, 0 if none */
+ unsigned char *msg;
+ size_t msg_len, msg_cap, max;
+} RsWs;
+
+/* op: 1 text (valid UTF-8), 2 binary, 8 close, 9 ping, 10 pong. data is writable and NUL-terminated. */
+typedef void (*RsWsOn)(void *ud, int op, unsigned char *data, size_t len);
+
+void rs_ws_init(RsWs *w, size_t max);
+void rs_ws_free(RsWs *w);
+/* Consumes complete frames from buf[0..n) (unmasking in place) and calls `on` for every complete
+ * message. *used = bytes consumed. Returns 0, or a close code: 1002 protocol error, 1007 invalid
+ * UTF-8, 1009 too big, 1011 out of memory. */
+int rs_ws_consume(RsWs *w, unsigned char *buf, size_t n, size_t *used, RsWsOn on, void *ud);
+
+/* ---- flat JSON objects from the browser: {"t":"m","x":1,"y":2} ---- */
+
+#define RS_JMAX 8
+typedef struct {
+ int n;
+ char key[RS_JMAX][12];
+ int is_str[RS_JMAX];
+ long long num[RS_JMAX];
+ const char *str[RS_JMAX]; /* decoded, NUL-terminated, inside the caller's buffer */
+ size_t slen[RS_JMAX];
+} RsJson;
+
+/* Strict: one object, keys [a-z]{1,11} without duplicates, values integers (|v| < 2^53) or strings
+ * (escapes decoded, surrogate pairs joined, no lone surrogates, no NUL). strbuf must hold n+1 bytes. */
+int rs_json_parse(const char *j, size_t n, RsJson *o, char *strbuf, size_t strcap);
+const char *rs_json_str(const RsJson *o, const char *key, size_t *len);
+int rs_json_num(const RsJson *o, const char *key, long long *v);
+
+/* A browser message, validated and clamped against a W×H screen. */
+enum { RS_IN_NONE = 0, RS_IN_PTR, RS_IN_BTN, RS_IN_WHEEL, RS_IN_SCROLL, RS_IN_PINCH, RS_IN_KEY, RS_IN_ACK, RS_IN_RESIZE,
+ RS_IN_PING, RS_IN_CLIP };
+#define RS_CLIP_MAX (1u << 20)
+typedef struct {
+ int type;
+ int a, b; /* PTR x,y · BTN button,down · WHEEL steps · KEY code,down · RESIZE w,h · SCROLL/PINCH phase */
+ int32_t v1, v2; /* SCROLL dx,dy (1/256 px) · PINCH scale ×65536, rotation ×256 */
+ long long ts; /* PING */
+ const char *text; /* CLIP (inside the RsJson buffer) */
+ size_t tlen;
+} RsInput;
+int rs_browser_input(const RsJson *j, int W, int H, RsInput *in);
+
+#endif
diff --git a/server/src/remote/sess.c b/server/src/remote/sess.c
index 7615af0..ecdbef8 100644
--- a/server/src/remote/sess.c
+++ b/server/src/remote/sess.c
@@ -8,6 +8,7 @@
* per-user lock (/run/lordos/spawn-<uid>.lock). */
#include "sessiond.h"
#include "../sec/cgroup.h"
+#include "rsec.h"
#include <crypt.h>
#include <ctype.h>
@@ -57,17 +58,25 @@ static int ct_equal(const char *a, const char *b) {
return d == 0;
}
-int sd_valid_username(const char *u) {
- size_t n = strlen(u);
- if (!n || n > 32 || !((u[0] >= 'a' && u[0] <= 'z') || u[0] == '_')) return 0;
- for (const char *p = u; *p; p++) if (!((*p >= 'a' && *p <= 'z') || (*p >= '0' && *p <= '9') || *p == '_' || *p == '-')) return 0;
- return 1;
+int sd_valid_username(const char *u) { return rs_valid_username(u); }
+
+/* is the shell a real login shell? (listed in /etc/shells, and not nologin/false) */
+static int login_shell(const char *sh) {
+ if (!sh || !sh[0] || strstr(sh, "nologin") || strstr(sh, "/false")) return 0;
+ int ok = 0;
+ setusershell();
+ for (char *s; (s = getusershell());) if (!strcmp(s, sh)) { ok = 1; break; }
+ endusershell();
+ return ok;
}
int sd_user_allowed(const struct passwd *pw, int remote) {
if (!pw || pw->pw_uid < 1000 || pw->pw_uid >= 60000) return 0;
if (!pw->pw_shell || strstr(pw->pw_shell, "nologin") || strstr(pw->pw_shell, "/false")) return 0;
- if (!remote || !rd_conf.group_only) return 1;
+ if (!remote) return 1;
+ /* from the network, stricter: never root's name or group, and a shell from /etc/shells */
+ if (!strcmp(pw->pw_name, "root") || pw->pw_gid == 0 || !login_shell(pw->pw_shell)) return 0;
+ if (!rd_conf.group_only) return 1;
struct group *g = getgrnam("lordos-remote");
if (!g) return 0;
gid_t groups[256];
@@ -86,16 +95,64 @@ static int is_autologin(const char *user) {
return u[0] && !strcmp(u, user);
}
+/* A hash setting with the cost of a real one, to spend the same time on unknown or refused
+ * accounts as on a wrong password (no user enumeration by timing). Taken once at startup from the
+ * first hash in /etc/shadow (only its "$id$params$salt" part), or libxcrypt's default. */
+static char dummy[128];
+
+void sd_dummy_init(void) {
+ dummy[0] = 0;
+ setspent();
+ for (struct spwd *sp; (sp = getspent());) {
+ const char *h = sp->sp_pwdp, *last = h ? strrchr(h, '$') : NULL;
+ if (!h || h[0] != '$' || !last || last == h || (size_t)(last - h) >= sizeof dummy) continue;
+ memcpy(dummy, h, (size_t)(last - h));
+ dummy[last - h] = 0;
+ break;
+ }
+ endspent();
+ if (!dummy[0] && !crypt_gensalt_rn(NULL, 0, NULL, 0, dummy, sizeof dummy)) snprintf(dummy, sizeof dummy, "$6$lordos.dummy");
+}
+
+static void waste(const char *pass) {
+ struct crypt_data cd;
+ memset(&cd, 0, sizeof cd);
+ const char *h = crypt_r(pass, dummy[0] ? dummy : "$6$lordos.dummy", &cd);
+ volatile int x = h ? ct_equal(h, "*") : 0;
+ (void)x;
+ explicit_bzero(&cd, sizeof cd);
+}
+
+/* Shadow restrictions for logins from the network: no /etc/nologin, password set and not locked,
+ * not forced to change (last change 0), not expired (max days) and the account not expired. */
+static int shadow_ok_remote(const struct spwd *sp) {
+ struct stat st;
+ if (!stat("/etc/nologin", &st)) return 0;
+ if (!sp || !sp->sp_pwdp || !sp->sp_pwdp[0] || sp->sp_pwdp[0] == '!' || sp->sp_pwdp[0] == '*') return 0;
+ long today = (long)(time(NULL) / 86400);
+ if (sp->sp_lstchg == 0) return 0;
+ if (sp->sp_lstchg > 0 && sp->sp_max >= 0 && sp->sp_max < 99999 && today > sp->sp_lstchg + sp->sp_max) return 0;
+ if (sp->sp_expire > 0 && sp->sp_expire <= today) return 0;
+ return 1;
+}
+
+int sd_remote_account_ok(const char *user) {
+ struct passwd *pw = sd_valid_username(user) ? getpwnam(user) : NULL;
+ if (!sd_user_allowed(pw, 1)) return 0;
+ return shadow_ok_remote(getspnam(user));
+}
+
int sd_check_password(const char *user, const char *pass, int remote) {
- if (!sd_valid_username(user) || strlen(pass) > 256) return 0;
+ if (!sd_valid_username(user) || strlen(pass) > 1024) return 0;
struct passwd *pw = getpwnam(user);
- if (!sd_user_allowed(pw, remote)) return 0;
- struct spwd *sp = getspnam(user);
+ struct spwd *sp = sd_user_allowed(pw, remote) ? getspnam(user) : NULL;
/* account without a password (the live ISO user): only on the monitor, only if it's the autologin
* user and with the field empty (to come back after locking). Never from the network. */
if (!remote && sp && sp->sp_pwdp && !sp->sp_pwdp[0] && !pass[0] && is_autologin(user)) return 1;
- if (!sp || !sp->sp_pwdp || !sp->sp_pwdp[0] || sp->sp_pwdp[0] == '!' || sp->sp_pwdp[0] == '*') return 0;
- if (sp->sp_expire > 0 && sp->sp_expire <= (long)(time(NULL) / 86400)) return 0;
+ int usable = sp && sp->sp_pwdp && sp->sp_pwdp[0] && sp->sp_pwdp[0] != '!' && sp->sp_pwdp[0] != '*' &&
+ !(sp->sp_expire > 0 && sp->sp_expire <= (long)(time(NULL) / 86400));
+ if (usable && remote) usable = shadow_ok_remote(sp);
+ if (!usable) { waste(pass); return 0; } /* same work as a wrong password */
struct crypt_data cd;
memset(&cd, 0, sizeof cd);
const char *h = crypt_r(pass, sp->sp_pwdp, &cd);
@@ -109,17 +166,25 @@ int sd_check_password(const char *user, const char *pass, int remote) {
double sd_fail_wait(const char *key) {
double w = 0, now = rd_now();
rd_lock();
- for (int i = 0; i < 64; i++)
+ for (int i = 0; i < 128; i++)
if (!strcmp(rd_shared->fails[i].key, key) && rd_shared->fails[i].until > now) w = rd_shared->fails[i].until - now;
rd_unlock();
return w;
}
+int sd_fail_count(const char *key) {
+ int n = 0;
+ rd_lock();
+ for (int i = 0; i < 128; i++) if (!strcmp(rd_shared->fails[i].key, key)) n = rd_shared->fails[i].fails;
+ rd_unlock();
+ return n;
+}
+
void sd_fail_note(const char *key, int failed) {
double now = rd_now();
rd_lock();
int slot = -1, oldest = 0;
- for (int i = 0; i < 64; i++) {
+ for (int i = 0; i < 128; i++) {
if (!strcmp(rd_shared->fails[i].key, key)) { slot = i; break; }
if (rd_shared->fails[i].until < rd_shared->fails[oldest].until) oldest = i;
}
diff --git a/server/src/remote/sessiond.c b/server/src/remote/sessiond.c
index b7a28cf..7c54792 100644
--- a/server/src/remote/sessiond.c
+++ b/server/src/remote/sessiond.c
@@ -14,7 +14,10 @@
* one child per connection that drops root as soon as it knows whose session it is.
*
* /etc/lordos/session.conf AUTOLOGIN=user (empty or missing line: login screen)
- * /etc/lordos/remote/config enabled=0|1, port=5673, allow=all|group, insecure_dev=0 (0644)
+ * /etc/lordos/remote/config enabled=0|1, port=5673, allow=all|group, net=lan|list|any, insecure_dev=0 (0644)
+ * /etc/lordos/remote/access manual "allow <cidr>" / "block <cidr>" lists (root 0600, admin actions)
+ * /var/lib/lordos/remote/blocklist sources blocked after failed logins (root 0600, survives restarts)
+ * /var/lib/lordos/remote/requests "unblock <cidr>" lines from the admin helper (read on SIGHUP)
* /etc/lordos/remote/cert.pem self-signed certificate (created when remote is turned on)
* /etc/lordos/remote/key.pem its key (0600)
* /etc/lordos/remote/fingerprint SHA-256 fingerprint of the certificate (shown by Settings)
@@ -40,6 +43,8 @@
#include <stdlib.h>
#include <string.h>
#include <grp.h>
+#include <ifaddrs.h>
+#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/syscall.h>
@@ -97,9 +102,34 @@ static void find_paths(void) {
SP(rd_conf.workdir, "%s", exe);
}
+/* A small root-owned file that nobody else can write (else it's ignored): its text, or NULL. */
+static char *read_root_file(const char *path, size_t max) {
+ int fd = open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
+ if (fd < 0) return NULL;
+ struct stat st;
+ char *t = NULL;
+ if (!fstat(fd, &st) && S_ISREG(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 022) && (size_t)st.st_size <= max &&
+ (t = malloc((size_t)st.st_size + 1))) {
+ ssize_t n = read(fd, t, (size_t)st.st_size);
+ if (n < 0) n = 0;
+ t[n] = 0;
+ } else if (!fstat(fd, &st) && (st.st_uid != 0 || (st.st_mode & 022))) sd_log("%s ignored: not owned by root or writable by others", path);
+ close(fd);
+ return t;
+}
+
+static void load_access(void) {
+ char *t = read_root_file(RD_ACCESS, 16384);
+ int bad = 0;
+ rs_access_parse(t, &rd_conf.access, &bad);
+ if (bad) sd_log("%s: %d invalid line(s) skipped", RD_ACCESS, bad);
+ free(t);
+}
+
static void load_config(void) {
rd_conf.port = RD_DEFAULT_PORT;
rd_conf.enabled = rd_conf.group_only = rd_conf.insecure_dev = 0;
+ rd_conf.net_mode = RS_NET_LAN;
FILE *f = fopen(RD_CONF_DIR "/config", "r");
char line[256];
while (f && fgets(line, sizeof line, f)) {
@@ -108,9 +138,11 @@ static void load_config(void) {
if (sscanf(line, "enabled=%d", &v) == 1) rd_conf.enabled = v == 1;
else if (sscanf(line, "port=%d", &v) == 1 && v > 0 && v < 65536) rd_conf.port = v;
else if (sscanf(line, "allow=%31s", s) == 1) rd_conf.group_only = !strcmp(s, "group");
+ else if (sscanf(line, "net=%31s", s) == 1 && rs_net_mode(s) >= 0) rd_conf.net_mode = rs_net_mode(s);
else if (sscanf(line, "insecure_dev=%d", &v) == 1) rd_conf.insecure_dev = v == 1;
}
if (f) fclose(f);
+ load_access();
}
/* Self-signed P-256 certificate for 10 years (CN = host name). */
@@ -244,6 +276,27 @@ static void write_status(void) {
sput(&s, "%s{\"pid\":%d,\"ip\":\"%s\",\"user\":\"%s\",\"since\":%.0f}", first ? "" : ",", (int)c->pid, c->ip, c->user, c->since);
first = 0;
}
+ sput(&s, "],\"net\":\"%s\",\"blocked\":[", rs_net_name(rd_conf.net_mode));
+ first = 1;
+ double now = rd_now();
+ for (int i = 0; i < RL_MAX; i++) {
+ RlEntry *e = &rd_shared->lockout.e[i];
+ if (!e->key[0] || e->until <= now) continue;
+ sput(&s, "%s{\"ip\":\"%s\",\"until\":%.0f,\"strikes\":%d,\"manual\":false}", first ? "" : ",", e->key, e->until, e->strikes);
+ first = 0;
+ }
+ for (int i = 0; i < rd_conf.access.nblock; i++) {
+ char c[64];
+ rs_cidr_format(&rd_conf.access.block[i], c, sizeof c);
+ sput(&s, "%s{\"ip\":\"%s\",\"until\":0,\"strikes\":0,\"manual\":true}", first ? "" : ",", c);
+ first = 0;
+ }
+ sput(&s, "],\"allowed\":[");
+ for (int i = 0; i < rd_conf.access.nallow; i++) {
+ char c[64];
+ rs_cidr_format(&rd_conf.access.allow[i], c, sizeof c);
+ sput(&s, "%s\"%s\"", i ? "," : "", c);
+ }
sput(&s, "],\"monitor\":\"%s\",\"sessions\":[", rd_shared->monitor);
first = 1;
for (int i = 0; i < SD_MAX_SESSIONS; i++) {
@@ -666,7 +719,12 @@ static void from_shown(int type, const char *j) {
char a[16] = "";
jstr(j, "a", a, sizeof a);
if (!strcmp(a, "power")) { session_power(j); return; }
- if (strstr(j, "\"lock\"")) { sd_log("%s locked the screen", shown_user); show_greeter("lock", shown_user); }
+ if (strstr(j, "\"lock\"")) {
+ sd_log("%s locked the screen", shown_user);
+ struct passwd *lp = sd_valid_username(shown_user) ? getpwnam(shown_user) : NULL;
+ if (lp) rd_tokens_drop_uid(lp->pw_uid); /* locking also signs that user's browsers out */
+ show_greeter("lock", shown_user);
+ }
else if (strstr(j, "\"switch\"")) { sd_log("%s is switching user", shown_user); show_greeter("switch", shown_user); }
return;
}
@@ -700,14 +758,16 @@ static void monitor_event(void) {
/* ---- remote desktop ---- */
static SSL_CTX *tls;
+/* this process's connection children (the only pids it ever signals) */
+static struct { pid_t pid; char key[48]; } kids[RD_MAX_CHILDREN];
static void stop_remote(void) {
if (lfd >= 0) close(lfd);
lfd = -1;
listening = 0;
- rd_lock();
- for (int i = 0; i < RD_MAX_CONNS; i++) if (rd_shared->conns[i].pid) kill(rd_shared->conns[i].pid, SIGTERM);
- rd_unlock();
+ /* only our own children (never a pid read back from shared memory) */
+ for (int i = 0; i < RD_MAX_CHILDREN; i++) if (kids[i].pid > 1) kill(kids[i].pid, SIGTERM);
+ rd_tokens_clear(); /* turning remote off signs every browser out */
if (tls) SSL_CTX_free(tls);
tls = NULL;
}
@@ -715,8 +775,19 @@ static void stop_remote(void) {
static void start_remote(void) {
if (ensure_cert()) { sd_log("could not create the certificate"); return; }
write_fingerprint();
+ /* the private key: root's, 0600 (fixed if it isn't) */
+ struct stat ks;
+ if (!stat(RD_CONF_DIR "/key.pem", &ks) && (ks.st_uid != 0 || (ks.st_mode & 077))) {
+ sd_log("%s had owner %u and mode %o: set to root 0600", RD_CONF_DIR "/key.pem", (unsigned)ks.st_uid, (unsigned)(ks.st_mode & 0777));
+ if (chown(RD_CONF_DIR "/key.pem", 0, 0) || chmod(RD_CONF_DIR "/key.pem", 0600)) { sd_log("could not fix the key's permissions"); return; }
+ }
tls = SSL_CTX_new(TLS_server_method());
+ /* TLS 1.2 and 1.3, AEAD suites with forward secrecy only (the key is P-256: ECDSA), no
+ * compression, no renegotiation, the server's order */
if (!tls || SSL_CTX_set_min_proto_version(tls, TLS1_2_VERSION) != 1 ||
+ SSL_CTX_set_cipher_list(tls, "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305") != 1 ||
+ SSL_CTX_set_ciphersuites(tls, "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256") != 1 ||
+ SSL_CTX_set1_groups_list(tls, "X25519:P-256:P-384") != 1 ||
SSL_CTX_use_certificate_file(tls, RD_CONF_DIR "/cert.pem", SSL_FILETYPE_PEM) != 1 ||
SSL_CTX_use_PrivateKey_file(tls, RD_CONF_DIR "/key.pem", SSL_FILETYPE_PEM) != 1) {
ERR_print_errors_fp(stderr);
@@ -724,12 +795,13 @@ static void start_remote(void) {
tls = NULL;
return;
}
+ SSL_CTX_set_options(tls, SSL_OP_NO_COMPRESSION | SSL_OP_NO_RENEGOTIATION | SSL_OP_CIPHER_SERVER_PREFERENCE);
lfd = socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
int one = 1, zero = 0;
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
setsockopt(lfd, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof zero);
struct sockaddr_in6 a = { .sin6_family = AF_INET6, .sin6_port = htons((uint16_t)rd_conf.port), .sin6_addr = in6addr_any };
- if (lfd < 0 || bind(lfd, (struct sockaddr *)&a, sizeof a) || listen(lfd, 16)) {
+ if (lfd < 0 || bind(lfd, (struct sockaddr *)&a, sizeof a) || listen(lfd, 64)) {
sd_log("could not listen on port %d: %s", rd_conf.port, strerror(errno));
if (lfd >= 0) close(lfd);
lfd = -1;
@@ -739,6 +811,47 @@ static void start_remote(void) {
sd_log("remote desktop on https://*:%d", rd_conf.port);
}
+/* Did this connection arrive on a VPN interface? (its local address belongs to one) */
+static int via_vpn(int fd) {
+ struct sockaddr_in6 me;
+ socklen_t ml = sizeof me;
+ if (getsockname(fd, (struct sockaddr *)&me, &ml)) return 0;
+ RsAddr local = { 0 };
+ memcpy(local.a, &me.sin6_addr, 16);
+ struct ifaddrs *ifs = NULL, *i;
+ if (getifaddrs(&ifs)) return 0;
+ int vpn = 0;
+ for (i = ifs; i && !vpn; i = i->ifa_next) {
+ if (!i->ifa_addr || !i->ifa_name || !rs_vpn_ifname(i->ifa_name)) continue;
+ RsAddr x = { 0 };
+ if (i->ifa_addr->sa_family == AF_INET) {
+ static const unsigned char pre[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
+ memcpy(x.a, pre, 12);
+ memcpy(x.a + 12, &((struct sockaddr_in *)i->ifa_addr)->sin_addr, 4);
+ } else if (i->ifa_addr->sa_family == AF_INET6) memcpy(x.a, &((struct sockaddr_in6 *)i->ifa_addr)->sin6_addr, 16);
+ else continue;
+ if (!memcmp(x.a, local.a, 16)) vpn = 1;
+ }
+ freeifaddrs(ifs);
+ return vpn;
+}
+
+/* Refusals are logged at most once a minute per source (a flood must not flood the journal). */
+static void refuse_log(const char *key, const char *why) {
+ static struct { char key[48]; double at; } seen[32];
+ double now = rd_now();
+ int slot = 0;
+ for (int i = 0; i < 32; i++) {
+ if (!strcmp(seen[i].key, key)) { if (now - seen[i].at < 60) return; slot = i; break; }
+ if (seen[i].at < seen[slot].at) slot = i;
+ }
+ snprintf(seen[slot].key, sizeof seen[slot].key, "%s", key);
+ seen[slot].at = now;
+ sd_log("remote connection from %s refused: %s", key, why);
+}
+
+static RcTable rate;
+
static void accept_remote(void) {
struct sockaddr_in6 peer;
socklen_t pl = sizeof peer;
@@ -747,11 +860,45 @@ static void accept_remote(void) {
char ip[64];
inet_ntop(AF_INET6, &peer.sin6_addr, ip, sizeof ip);
const char *shown_ip = !strncmp(ip, "::ffff:", 7) ? ip + 7 : ip;
- int busy = 0;
+ RsAddr a = { 0 };
+ memcpy(a.a, &peer.sin6_addr, 16);
+ static const unsigned char mapped[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
+ a.v4 = !memcmp(a.a, mapped, 12);
+ char key[48];
+ rs_addr_key(&a, key, sizeof key);
+ /* everything here is cheap and happens before any TLS work: refused sources are just closed */
+ int vpn = rd_conf.net_mode == RS_NET_LAN && !rs_addr_is_local(&a) ? via_vpn(fd) : 0;
+ int acc = rs_access_decide(&rd_conf.access, rd_conf.net_mode, &a, vpn);
+ if (acc != RS_ACC_OK) {
+ refuse_log(key, acc == RS_ACC_BLOCKED ? "blocked in Settings" :
+ rd_conf.net_mode == RS_NET_LIST ? "not in the allowed list" : "not a local network address (Settings -> Sharing)");
+ close(fd);
+ return;
+ }
rd_lock();
- for (int i = 0; i < RD_MAX_CONNS; i++) if (rd_shared->conns[i].pid) busy++;
+ double left = rl_blocked(&rd_shared->lockout, key, rd_now());
rd_unlock();
- if (busy >= RD_MAX_CONNS) { close(fd); return; }
+ if (left > 0) {
+ char why[96];
+ snprintf(why, sizeof why, "blocked after failed logins, %.0f min left", left / 60 + 0.5);
+ refuse_log(key, why);
+ close(fd);
+ return;
+ }
+ struct timespec mt;
+ clock_gettime(CLOCK_MONOTONIC, &mt);
+ if (!rc_take(&rate, key, (double)mt.tv_sec + mt.tv_nsec / 1e9)) { refuse_log(key, "too many new connections"); close(fd); return; }
+ int total = 0, mine = 0, free_slot = -1;
+ for (int i = 0; i < RD_MAX_CHILDREN; i++) {
+ if (!kids[i].pid) { if (free_slot < 0) free_slot = i; continue; }
+ total++;
+ if (!strcmp(kids[i].key, key)) mine++;
+ }
+ if (free_slot < 0 || total >= RD_MAX_CHILDREN || mine >= RD_MAX_PER_SOURCE) {
+ refuse_log(key, mine >= RD_MAX_PER_SOURCE ? "too many open connections from it" : "too many open connections");
+ close(fd);
+ return;
+ }
pid_t c = fork();
if (c == 0) {
close(lfd);
@@ -761,10 +908,104 @@ static void accept_remote(void) {
prctl(PR_SET_PDEATHSIG, SIGTERM);
signal(SIGTERM, SIG_DFL);
signal(SIGHUP, SIG_DFL);
- rd_serve(tls, fd, shown_ip);
+ signal(SIGALRM, SIG_DFL);
+ rd_serve(tls, fd, shown_ip, key);
_exit(0);
}
+ if (c > 0) {
+ kids[free_slot].pid = c;
+ snprintf(kids[free_slot].key, sizeof kids[free_slot].key, "%s", key);
+ }
+ close(fd);
+}
+
+/* ---- lockout: persistence, unblock requests from Settings, notices ---- */
+
+static void save_lockout(void) {
+ rd_lock();
+ rd_shared->lockout_dirty = 0;
+ RlTable copy = rd_shared->lockout;
+ rd_unlock();
+ char *t = malloc(RL_MAX * 128 + 256);
+ if (!t) return;
+ int n = rl_format(&copy, rd_now(), t, RL_MAX * 128 + 256);
+ mkdir("/var/lib/lordos", 0755);
+ mkdir(RL_FILE_DIR, 0700);
+ struct stat st;
+ if (n < 0 || lstat(RL_FILE_DIR, &st) || !S_ISDIR(st.st_mode) || st.st_uid != 0) { free(t); return; }
+ if (st.st_mode & 077) chmod(RL_FILE_DIR, 0700);
+ unlink(RL_FILE ".new");
+ int fd = open(RL_FILE ".new", O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
+ if (fd < 0) { free(t); return; }
+ int ok = write(fd, t, (size_t)n) == n && !fsync(fd);
close(fd);
+ free(t);
+ if (!ok || rename(RL_FILE ".new", RL_FILE)) { unlink(RL_FILE ".new"); sd_log("could not save %s", RL_FILE); }
+}
+
+static void load_lockout(void) {
+ char *t = read_root_file(RL_FILE, RL_MAX * 160);
+ RlTable tab;
+ rl_parse(&tab, t, rd_now());
+ free(t);
+ int n = 0;
+ for (int i = 0; i < RL_MAX; i++) if (tab.e[i].key[0] && tab.e[i].until > rd_now()) n++;
+ rd_lock();
+ rd_shared->lockout = tab;
+ rd_unlock();
+ if (n) sd_log("remote desktop: %d source(s) still blocked after failed logins (%s)", n, RL_FILE);
+}
+
+/* "unblock <cidr>" lines the admin helper appended (remote-unblock), under flock */
+static void unblock_requests(void) {
+ int fd = open(RL_REQUESTS, O_RDWR | O_NOFOLLOW | O_CLOEXEC);
+ if (fd < 0) return;
+ struct stat st;
+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_uid != 0 || (st.st_mode & 077)) { close(fd); unlink(RL_REQUESTS); return; }
+ flock(fd, LOCK_EX);
+ char buf[4096];
+ ssize_t n = read(fd, buf, sizeof buf - 1);
+ if (ftruncate(fd, 0)) { /* read again next time */ }
+ close(fd);
+ if (n <= 0) return;
+ buf[n] = 0;
+ for (char *line = strtok(buf, "\n"); line; line = strtok(NULL, "\n")) {
+ char net[64], extra;
+ if (sscanf(line, "unblock %63s %c", net, &extra) != 1) continue;
+ rd_lock();
+ int k = rl_unblock(&rd_shared->lockout, net);
+ if (k) { rd_shared->lockout_dirty = 1; rd_shared->version++; }
+ rd_unlock();
+ char clean[64];
+ rs_log_clean(net, strlen(net), clean, sizeof clean);
+ sd_log("remote desktop: %s unblocked from Settings (%d entr%s)", clean, k, k == 1 ? "y" : "ies");
+ }
+}
+
+/* Blocks the connection processes reported: to the session on the monitor (a notification). They
+ * wait (up to an hour) while the monitor shows the login screen. */
+static unsigned notices_done;
+
+static void deliver_notices(void) {
+ unsigned seq;
+ RdNotice ring[RD_NOTICES];
+ rd_lock();
+ seq = rd_shared->notice_seq;
+ memcpy(ring, rd_shared->notices, sizeof ring);
+ rd_unlock();
+ if (seq == notices_done) return;
+ if (shown != 'u' || sd_mon_fd() < 0) return;
+ if (seq - notices_done > RD_NOTICES) notices_done = seq - RD_NOTICES;
+ for (; notices_done != seq; notices_done++) {
+ RdNotice *n = &ring[notices_done % RD_NOTICES];
+ if (rd_now() - n->at > 3600 || !n->key[0]) continue;
+ RsCidr c;
+ if (rs_key_parse(n->key, &c)) continue; /* only a valid address goes out */
+ char json[160];
+ snprintf(json, sizeof json, "{\"t\":\"blocked\",\"ip\":\"%s\",\"min\":%.0f,\"n\":%d}", n->key,
+ (n->until - n->at) / 60 + 0.5, n->strikes);
+ sd_mon_notice(json);
+ }
}
/* ---- login screen processes ----
@@ -858,6 +1099,9 @@ int main(int argc, char **argv) {
pthread_mutexattr_setpshared(&ma, PTHREAD_PROCESS_SHARED);
pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST);
pthread_mutex_init(&rd_shared->lock, &ma);
+ sd_dummy_init();
+ load_lockout();
+ unblock_requests();
/* sessions that stayed alive from before a service restart */
for (uid_t u = 1000; u < 1100; u++) {
int fd = sd_session_connect(u);
@@ -914,7 +1158,8 @@ int main(int argc, char **argv) {
reload = 0;
int was = rd_conf.enabled, port = rd_conf.port;
load_config();
- sd_log("configuration: remote %s, port %d", rd_conf.enabled ? "on" : "off", rd_conf.port);
+ unblock_requests();
+ sd_log("configuration: remote %s, port %d, from %s", rd_conf.enabled ? "on" : "off", rd_conf.port, rs_net_name(rd_conf.net_mode));
if (listening && (!rd_conf.enabled || port != rd_conf.port)) stop_remote();
if (rd_conf.enabled && (!listening || !was)) start_remote();
bump();
@@ -935,6 +1180,7 @@ int main(int argc, char **argv) {
else if (k == W_AUTOLOGIN && start_worker(W_AUTOLOGIN, pending_user, NULL)) pending = k;
else if (WIFEXITED(st) && WEXITSTATUS(st) && shown != 'u' && shown != 'g') show_greeter("login", NULL);
} else {
+ for (int i = 0; i < RD_MAX_CHILDREN; i++) if (kids[i].pid == pid) memset(&kids[i], 0, sizeof kids[i]);
rd_lock();
for (int i = 0; i < RD_MAX_CONNS; i++)
if (rd_shared->conns[i].pid == pid) { memset(&rd_shared->conns[i], 0, sizeof rd_shared->conns[i]); rd_shared->version++; }
@@ -948,6 +1194,8 @@ int main(int argc, char **argv) {
if (r > 0 && lfd >= 0 && (p[1].revents & POLLIN)) accept_remote();
if (r > 0 && p[2].fd >= 0 && p[2].fd == sd_mon_fd() && p[2].revents) monitor_event();
if (r > 0 && p[3].fd >= 0 && (p[3].revents & POLLIN)) sd_mon_hotplug(); /* hotplug */
+ if (rd_shared->lockout_dirty) save_lockout();
+ deliver_notices();
if (rd_shared->version != seen) { seen = rd_shared->version; write_status(); }
else {
static double last;
@@ -957,6 +1205,7 @@ int main(int argc, char **argv) {
/* on shutdown: cuts remote and releases the monitor; sessions stay alive (on return
* you log in again through the login screen) */
stop_remote();
+ save_lockout();
if (has_monitor) sd_mon_close();
if (worker_pid > 0) kill(worker_pid, SIGTERM);
stop_greeters("lord-sessiond is stopping");
diff --git a/server/src/remote/sessiond.h b/server/src/remote/sessiond.h
index 6ce3c9c..46cf676 100644
--- a/server/src/remote/sessiond.h
+++ b/server/src/remote/sessiond.h
@@ -13,6 +13,9 @@
#include <sys/types.h>
#include <openssl/ssl.h>
+#include "ipnet.h"
+#include "lockout.h"
+
#define RD_CONF_DIR "/etc/lordos/remote"
#define SD_RUN_DIR "/run/lordos"
#define SD_STATUS SD_RUN_DIR "/status.json"
@@ -24,18 +27,32 @@
#define SD_USERS_DIR "/var/lib/lordos/users" /* avatars: <user>.json and <user>.png */
#define SD_GREETER_USER "lordos-greeter"
#define RD_DEFAULT_PORT 5673 /* "LORD" on a phone keypad */
-#define RD_MAX_CONNS 32
+#define RD_MAX_CONNS 32 /* signed-in browsers (bridges) */
+#define RD_MAX_CHILDREN 48 /* connection processes in all, signing in or not */
+#define RD_MAX_PER_SOURCE 8 /* of those, from one address (IPv6: one /64) */
+#define RD_ACCESS RD_CONF_DIR "/access" /* manual allow/block lists (admin actions, root 0600) */
+#define RD_COOKIE "__Host-lordos_remote"
#define SD_MAX_SESSIONS 32
/* State shared between the main process and its children. */
-typedef struct { char key[56]; int fails; double until; } RdFail; /* key: IP or "monitor:<user>" */
-typedef struct { char tok[65]; uid_t uid; char user[33]; double expires; } RdToken;
+typedef struct { char key[56]; int fails; double until; } RdFail; /* key: source, "monitor:<user>" or "u:<user>" */
+/* A signed-in browser. Only the SHA-256 of the cookie is kept, and a digest of the account's shadow
+ * hash at sign-in: changing or locking the password ends the cookie. */
+typedef struct { unsigned char hash[32], pwh[16]; uid_t uid; char user[33]; double expires; } RdToken;
+/* "source blocked" notices from the connection processes; the main process shows them on the
+ * monitor's session (RP_NOTICE) */
+typedef struct { char key[48]; double until, at; int strikes; } RdNotice;
+#define RD_NOTICES 8
typedef struct { pid_t pid; char ip[48]; char user[33]; double since; } RdConn;
typedef struct { pid_t pid; uid_t uid; char user[33]; double since; } SdSession; /* a user's lord-server */
typedef struct {
pthread_mutex_t lock;
- RdFail fails[64];
+ RdFail fails[128];
RdToken tokens[64];
+ RlTable lockout; /* failed-login blocks per source (lockout.h) */
+ int lockout_dirty; /* changed: the main process saves RL_FILE */
+ RdNotice notices[RD_NOTICES];
+ unsigned notice_seq;
RdConn conns[RD_MAX_CONNS];
SdSession sessions[SD_MAX_SESSIONS];
char monitor[33]; /* user shown on the monitor ("" = login screen) */
@@ -47,6 +64,8 @@ typedef struct {
int port;
int group_only; /* only the lordos-remote group */
int insecure_dev; /* allows binaries not owned by root (development VMs only) */
+ int net_mode; /* RS_NET_LAN (default) | RS_NET_LIST | RS_NET_ANY: who may connect */
+ RsAccess access; /* RD_ACCESS */
char server[512], theme[512], greeter_theme[512], fonts[512], shell[512], workdir[512];
} RdConfig;
@@ -62,11 +81,14 @@ void rd_unlock(void);
void sd_log_prefix(const char *prefix); /* "lord-sessiond[pid] 1.2.3.4" */
void sd_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
int sd_valid_username(const char *u);
+void sd_dummy_init(void); /* hash setting for unknown users (same timing) */
/* A person's regular account: uid 1000..59999, with a shell, and (remote + allow=group) in the group. */
int sd_user_allowed(const struct passwd *pw, int remote);
int sd_check_password(const char *user, const char *pass, int remote);
+int sd_remote_account_ok(const char *user); /* still allowed from the network (cookies) */
double sd_fail_wait(const char *key); /* seconds to wait for that key */
void sd_fail_note(const char *key, int failed);
+int sd_fail_count(const char *key);
int sd_run_wait(const char *const argv[]);
/* Socket of that user's session if it's already running (lord-server --headless), or -1. */
int sd_session_connect(uid_t uid);
@@ -96,7 +118,9 @@ extern char sd_gpu_env[24];
extern int sd_input_debug; /* LORD_INPUT_DEBUG=1 for user sessions (keylag.h) */
/* ---- conn.c: one remote desktop connection (in a child process) ---- */
-void rd_serve(SSL_CTX *ctx, int fd, const char *ip);
+void rd_serve(SSL_CTX *ctx, int fd, const char *ip, const char *key);
+void rd_tokens_drop_uid(uid_t uid); /* every cookie of that user (lock) */
+void rd_tokens_clear(void); /* every cookie (remote turned off) */
/* ---- enc.c: rectangle (0xAARRGGBB) → PNG or JPEG. Returns malloc'd memory; *jpeg = 1 if it chose JPEG. */
unsigned char *rd_encode(const uint32_t *px, int stride, int w, int h, int allow_jpeg, int *len, int *jpeg);
@@ -110,6 +134,7 @@ int sd_mon_show(int session_fd, const char *who, int keep); /* gives it the ca
int sd_mon_fd(void); /* socket of the session being shown, or -1 */
int sd_mon_read(void (*fn)(int type, const char *json)); /* -1 if the session closed */
void sd_mon_greeter(const char *json); /* RP_GREETER_IN to the login screen */
+void sd_mon_notice(const char *json); /* RP_NOTICE to the session on the monitor */
void sd_mon_lost(void); /* takes it away (revokes) */
void sd_mon_child(void); /* in a child: closes the copies without revoking */
int sd_mon_hotplug_fd(void); /* inotify on /dev/input, or -1 */
diff --git a/server/src/ui/js.c b/server/src/ui/js.c
index 22ed94f..def7e1a 100644
--- a/server/src/ui/js.c
+++ b/server/src/ui/js.c
@@ -827,6 +827,18 @@ void js_remote_event(const char *json) {
drain_jobs();
}
+/* Remote desktop: lord-sessiond's notice for the user on the monitor (RP_NOTICE, e.g. a source blocked
+ * after failed logins) → __lordRemoteNotice(object). sdk/remote.js shows it as a notification. */
+void js_remote_notice(const char *json) {
+ if (!ctx) return;
+ JSValue v = JS_ParseJSON(ctx, json, strlen(json), "<remote-notice>");
+ if (JS_IsException(v)) { JS_FreeValue(ctx, JS_GetException(ctx)); return; }
+ JSValueConst args[1] = { v };
+ JS_FreeValue(ctx, call_global("__lordRemoteNotice", 1, args));
+ JS_FreeValue(ctx, v);
+ drain_jobs();
+}
+
/* Broker of isolated .lpk apps: "prompt" (ask for a permission) or "device" (indicator) →
* __lordBroker(kind, json). The theme handles it in sdk/privacy.js. */
void js_broker_event(const char *kind, const char *json) {
diff --git a/server/src/ui/js.h b/server/src/ui/js.h
index 87848c0..2b1a83d 100644
--- a/server/src/ui/js.h
+++ b/server/src/ui/js.h
@@ -31,6 +31,7 @@ void js_admin_event(int id, const char *kind, const char *text);
void js_logs_event(const char *kind, int id, const char *name); /* app Registros */
void js_clipboard_poll(void);
void js_remote_event(const char *json);
+void js_remote_notice(const char *json); /* RP_NOTICE from lord-sessiond → __lordRemoteNotice */
void js_greeter_event(const char *json);
void js_screen_resized(void);
/* lord.screen.displays / .mirror: {"mirror":…,"displays":[{id,name,x,y,w,h,pw,ph,scale,main}]} (main.c) */
diff --git a/server/tests/remote_fuzz.c b/server/tests/remote_fuzz.c
new file mode 100644
index 0000000..e34312d
--- /dev/null
+++ b/server/tests/remote_fuzz.c
@@ -0,0 +1,149 @@
+/* remote_fuzz.c — the remote desktop's parsers under ASan+UBSan with random and mutated inputs
+ * (HTTP heads, login forms, cookies, WebSocket streams, JSON messages, addresses, the lockout file).
+ * Built by `make -C server test` with -fsanitize=address,undefined; any memory error or undefined
+ * behaviour aborts. Usage: remote-fuzz [iterations] [seed]. */
+#include "remote/rsec.h"
+#include "remote/ipnet.h"
+#include "remote/lockout.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static unsigned long long st = 88172645463325252ULL;
+static unsigned rnd(void) { st ^= st << 13; st ^= st >> 7; st ^= st << 17; return (unsigned)(st >> 11); }
+
+static const char *const seeds[] = {
+ "GET / HTTP/1.1\r\nHost: 10.0.0.5:5673\r\n\r\n",
+ "POST /login HTTP/1.1\r\nHost: a:5673\r\nOrigin: https://a:5673\r\nContent-Type: application/x-www-form-urlencoded\r\n"
+ "Content-Length: 20\r\nCookie: __Host-lordos_remote=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n\r\nuser=lord&pass=x",
+ "GET /ws?w=1280&h=800 HTTP/1.1\r\nHost: [fe80::1]:5673\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
+ "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\nSec-Fetch-Site: same-origin\r\n\r\n",
+ "user=lord&pass=a%20b+c%26",
+ "{\"t\":\"m\",\"x\":10,\"y\":20}",
+ "{\"t\":\"clip\",\"text\":\"h\\u00e9\\ud83d\\udc51\\n\"}",
+ "{\"t\":\"pz\",\"p\":2,\"s\":65536,\"r\":-90}",
+ "192.168.1.0/24", "2001:db8::/32", "::ffff:10.0.0.1",
+ "10.0.0.1 2 1000 0 0 0\n2001:db8:1:2::/64 0 1990 1 1990 2500\n",
+ "allow 203.0.113.0/24\nblock 192.168.1.66\n",
+};
+static const char alphabet[] = "\r\n :%&=+/?#\"\\{}[],.-_0123456789abcdefABCDEFghijkluvwxyzGETPOSTHosUpgrade\x00\x01\x7f\x80\xc3\xa9\xed\xff";
+
+static size_t mutate(char *b, size_t n, size_t cap) {
+ int k = 1 + (int)(rnd() % 8);
+ while (k--) {
+ unsigned op = rnd() % 6;
+ if (op == 0 && n) b[rnd() % n] = alphabet[rnd() % (sizeof alphabet - 1)];
+ else if (op == 1 && n) b[rnd() % n] ^= (char)(1 << (rnd() % 8));
+ else if (op == 2 && n + 1 < cap) { size_t p = n ? rnd() % n : 0; memmove(b + p + 1, b + p, n - p); b[p] = alphabet[rnd() % (sizeof alphabet - 1)]; n++; }
+ else if (op == 3 && n) { size_t p = rnd() % n; memmove(b + p, b + p + 1, n - p - 1); n--; }
+ else if (op == 4 && n && n * 2 < cap) { size_t p = rnd() % n, l = 1 + rnd() % (n - p); memcpy(b + n, b + p, l); n += l; }
+ else if (op == 5) n = n ? rnd() % n : 0;
+ }
+ return n;
+}
+
+static void on(void *ud, int op, unsigned char *d, size_t l) {
+ (void)ud;
+ if (op == 1) {
+ char *sb = malloc(l + 1);
+ RsJson o;
+ RsInput in;
+ if (sb && !rs_json_parse((const char *)d, l, &o, sb, l + 1)) rs_browser_input(&o, 1280, 800, &in);
+ free(sb);
+ }
+}
+
+static void one(const char *b, size_t n) {
+ /* each parser gets an exact-size heap copy, so ASan sees any byte read past the end */
+ char *c = malloc(n + 1);
+ memcpy(c, b, n);
+ RsReq r;
+ rs_parse_head(c, n, &r);
+ char u[33], p[RS_PASS_MAX + 1], raw[33], tok[65];
+ size_t pl;
+ rs_parse_login(c, n, u, p, &pl, raw);
+ {
+ RsJson o;
+ RsInput in;
+ char *sb = malloc(n + 1);
+ if (!rs_json_parse(c, n, &o, sb, n + 1)) rs_browser_input(&o, (int)(rnd() % 3000), (int)(rnd() % 3000), &in);
+ free(sb);
+ }
+ rs_utf8_valid((unsigned char *)c, n);
+ {
+ RsWs w;
+ rs_ws_init(&w, 1 + rnd() % 70000);
+ unsigned char *m = malloc(n ? n : 1);
+ memcpy(m, c, n);
+ size_t pos = 0, end = 0, used = 0;
+ while (end < n) { /* the stream arrives in random pieces, as TLS records do */
+ end += 1 + rnd() % (n - end);
+ if (rs_ws_consume(&w, m + pos, end - pos, &used, on, NULL)) break;
+ pos += used;
+ }
+ free(m);
+ rs_ws_free(&w);
+ }
+ c[n] = 0; /* the string functions get a C string */
+ rs_cookie_token(c, "__Host-lordos_remote", tok);
+ rs_valid_host(c);
+ rs_same_origin(c, "a:5673");
+ rs_form_type(c);
+ rs_has_token(c, "upgrade");
+ rs_valid_wskey(c);
+ rs_valid_username(c);
+ RsCidr cd;
+ RsAddr ad;
+ if (!rs_cidr_parse(c, &cd)) { char t[64]; rs_cidr_format(&cd, t, sizeof t); RsCidr back; if (rs_cidr_parse(t, &back) || !rs_cidr_equal(&back, &cd)) abort(); }
+ if (!rs_addr_parse(c, &ad)) { char t[64]; rs_addr_key(&ad, t, sizeof t); rs_addr_is_local(&ad); }
+ static RlTable t;
+ rl_parse(&t, c, 1e9);
+ char out[RL_MAX * 128 + 256];
+ rl_format(&t, 1e9, out, sizeof out);
+ rl_unblock(&t, c);
+ RsAccess acc;
+ rs_access_parse(c, &acc, NULL);
+ char at[8192];
+ rs_access_format(&acc, at, sizeof at);
+ free(c);
+}
+
+/* random WebSocket stream: well-formed frames with random flags, lengths and payloads */
+static size_t ws_stream(unsigned char *b, size_t cap) {
+ size_t o = 0;
+ while (o + 200 < cap && rnd() % 8) {
+ size_t len = rnd() % 4 == 0 ? rnd() % 70000 : rnd() % 130;
+ if (o + len + 14 >= cap) break;
+ int op = (int)(rnd() % 11);
+ b[o++] = (unsigned char)((rnd() % 4 ? 0x80 : 0) | op | (rnd() % 50 == 0 ? 0x40 : 0));
+ if (len < 126) b[o++] = (unsigned char)(0x80 | len);
+ else if (len < 65536) { b[o++] = 0x80 | 126; b[o++] = (unsigned char)(len >> 8); b[o++] = (unsigned char)len; }
+ else { b[o++] = 0x80 | 127; for (int i = 0; i < 8; i++) b[o++] = (unsigned char)((unsigned long long)len >> (56 - 8 * i)); }
+ for (int i = 0; i < 4; i++) b[o++] = (unsigned char)rnd();
+ for (size_t i = 0; i < len; i++) b[o++] = (unsigned char)(rnd() % 3 ? "{\"t\":\"m\",\"x\":1}"[i % 15] : rnd());
+ }
+ return o;
+}
+
+int main(int argc, char **argv) {
+ long iters = argc > 1 ? atol(argv[1]) : 100000;
+ if (argc > 2) st = strtoull(argv[2], NULL, 10) | 1;
+ static char b[200000];
+ for (long i = 0; i < iters; i++) {
+ size_t n;
+ unsigned kind = rnd() % 10;
+ if (kind < 6) {
+ const char *s = seeds[rnd() % (sizeof seeds / sizeof *seeds)];
+ n = strlen(s);
+ memcpy(b, s, n);
+ n = mutate(b, n, 16384);
+ } else if (kind < 8) {
+ n = rnd() % 2048;
+ for (size_t k = 0; k < n; k++) b[k] = (char)rnd();
+ } else n = ws_stream((unsigned char *)b, sizeof b);
+ one(b, n);
+ }
+ printf("remote-fuzz: %ld inputs, no memory errors or undefined behaviour\n", iters);
+ return 0;
+}
diff --git a/server/tests/remote_sec_test.c b/server/tests/remote_sec_test.c
new file mode 100644
index 0000000..c4deafe
--- /dev/null
+++ b/server/tests/remote_sec_test.c
@@ -0,0 +1,429 @@
+/* remote_sec_test.c — the remote desktop's strict parsers and rules (src/remote/rsec.c, ipnet.c,
+ * lockout.c; docs/REMOTE.md, "Security analysis (0.8.3)"). Every case is a request, a form, a frame
+ * or an address our own pages would (or would never) send. */
+#include "remote/rsec.h"
+#include "remote/ipnet.h"
+#include "remote/lockout.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int fails, checks;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0)
+
+static int head(const char *s, RsReq *r) { return rs_parse_head(s, strlen(s), r); }
+
+static void test_head(void) {
+ RsReq r;
+ CHECK(head("GET / HTTP/1.1\r\nHost: 10.0.0.5:5673\r\n\r\n", &r) > 0);
+ CHECK(!strcmp(r.method, "GET") && !strcmp(r.path, "/") && !strcmp(r.host, "10.0.0.5:5673") && r.content_length == -1);
+ CHECK(head("GET /?e=1 HTTP/1.1\r\nHost: a\r\n\r\n", &r) > 0 && !strcmp(r.query, "e=1"));
+ CHECK(head("POST /login HTTP/1.1\r\nHost: a\r\nContent-Length: 20\r\nContent-Type: application/x-www-form-urlencoded\r\n"
+ "Origin: https://a\r\nCookie: x=1\r\n\r\n", &r) > 0 && r.content_length == 20 && !strcmp(r.origin, "https://a"));
+ CHECK(head("GET / HTTP/1.1\r\nHost: a\r\n", &r) == RS_NEED_MORE); /* not complete */
+ CHECK(head("GET / HTTP/1.1\r\n", &r) == RS_NEED_MORE);
+ CHECK(head("GET / HTTP/1.1\r\n\r\n", &r) == -400); /* 1.1 without Host */
+ CHECK(head("GET / HTTP/1.0\r\n\r\n", &r) > 0);
+ CHECK(head("GET / HTTP/2.0\r\nHost: a\r\n\r\n", &r) == -400);
+ CHECK(head("GET / HTTP/1.1\r\nHost: a\r\n\r\n", &r) == -400); /* double space */
+ CHECK(head("get / HTTP/1.1\r\nHost: a\r\n\r\n", &r) == -400);
+ CHECK(head("GET http://x/ HTTP/1.1\r\nHost: a\r\n\r\n", &r) == -400); /* absolute form */
+ CHECK(head("GET /#x HTTP/1.1\r\nHost: a\r\n\r\n", &r) == -400);
+ CHECK(head("GET / HTTP/1.1\nHost: a\r\n\r\n", &r) == -400); /* bare LF */
+ CHECK(head("GET / HTTP/1.1\r\nHost: a\rb\r\n\r\n", &r) == -400); /* bare CR */
+ CHECK(head("GET / HTTP/1.1\r\nHost: a\r\nX: \x01\r\n\r\n", &r) == -400); /* control byte */
+ CHECK(head("GET / HTTP/1.1\r\nHost: \xc3\xa1\r\n\r\n", &r) == -400); /* non-ASCII */
+ CHECK(head("GET / HTTP/1.1\r\nHost: a\r\nHost: b\r\n\r\n", &r) == -400); /* duplicate Host */
+ CHECK(head("GET / HTTP/1.1\r\nHost: a\r\nCookie: a=1\r\nCookie: b=2\r\n\r\n", &r) == -400);
+ CHECK(head("POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 5\r\nContent-Length: 5\r\n\r\n", &r) == -400);
+ CHECK(head("POST / HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\n\r\n", &r) == -501); /* smuggling */
+ CHECK(head("POST / HTTP/1.1\r\nHost: a\r\nContent-Length: -1\r\n\r\n", &r) == -400);
+ CHECK(head("POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 1e3\r\n\r\n", &r) == -400);
+ CHECK(head("POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 4097\r\n\r\n", &r) == -413);
+ CHECK(head("POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 99999999999\r\n\r\n", &r) == -413);
+ CHECK(head("GET / HTTP/1.1\r\nHost : a\r\n\r\n", &r) == -400); /* space before the colon */
+ CHECK(head("GET / HTTP/1.1\r\nHost: a\r\n folded\r\n\r\n", &r) == -400); /* obs-fold */
+ CHECK(head("GET / HTTP/1.1\r\nHost: a\r\nNoColon\r\n\r\n", &r) == -400);
+ CHECK(head("\r\nGET / HTTP/1.1\r\nHost: a\r\n\r\n", &r) == -400);
+ { /* too many headers, a too-long field, a too-long head, a too-long path */
+ char b[9000];
+ int o = sprintf(b, "GET / HTTP/1.1\r\nHost: a\r\n");
+ for (int i = 0; i < 41; i++) o += sprintf(b + o, "X-%d: 1\r\n", i);
+ strcpy(b + o, "\r\n");
+ CHECK(head(b, &r) == -431);
+ o = sprintf(b, "GET / HTTP/1.1\r\nHost: a\r\nCookie: ");
+ memset(b + o, 'a', 1100);
+ strcpy(b + o + 1100, "\r\n\r\n");
+ CHECK(head(b, &r) == -431);
+ memset(b, 'a', sizeof b);
+ memcpy(b, "GET / HTTP/1.1\r\nX: ", 19);
+ CHECK(rs_parse_head(b, sizeof b, &r) == -431);
+ o = sprintf(b, "GET /");
+ memset(b + o, 'p', 200);
+ strcpy(b + o + 200, " HTTP/1.1\r\nHost: a\r\n\r\n");
+ CHECK(head(b, &r) == -414);
+ }
+ CHECK(head("GET / HTTP/1.1\r\nhOsT: x\r\nsec-websocket-key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n", &r) > 0 &&
+ !strcmp(r.host, "x") && !strcmp(r.wskey, "dGhlIHNhbXBsZSBub25jZQ==") && !strcmp(r.wsversion, "13"));
+}
+
+static void test_small(void) {
+ CHECK(rs_valid_username("lord") && rs_valid_username("_x") && rs_valid_username("a-b_9"));
+ CHECK(!rs_valid_username("") && !rs_valid_username("Lord") && !rs_valid_username("9a") && !rs_valid_username("-a"));
+ CHECK(!rs_valid_username("a b") && !rs_valid_username("a$") && !rs_valid_username("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
+ CHECK(rs_valid_username("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); /* 32 */
+ CHECK(rs_valid_host("192.168.1.5:5673") && rs_valid_host("lordos.local") && rs_valid_host("[fe80::1]:5673") && rs_valid_host("[::1]"));
+ CHECK(!rs_valid_host("") && !rs_valid_host("a b") && !rs_valid_host("a:0") && !rs_valid_host("a:65536") && !rs_valid_host("[zz]"));
+ CHECK(!rs_valid_host("a..b") && !rs_valid_host("-a") && !rs_valid_host("a:5673x") && !rs_valid_host("a/b"));
+ CHECK(rs_same_origin("https://10.0.0.5:5673", "10.0.0.5:5673"));
+ CHECK(rs_same_origin("https://LordOS.local:5673", "lordos.local:5673"));
+ CHECK(!rs_same_origin("http://10.0.0.5:5673", "10.0.0.5:5673"));
+ CHECK(!rs_same_origin("https://evil.example", "10.0.0.5:5673"));
+ CHECK(!rs_same_origin("https://10.0.0.5:5673.evil", "10.0.0.5:5673"));
+ CHECK(!rs_same_origin("", "10.0.0.5:5673") && !rs_same_origin("null", "10.0.0.5:5673"));
+ CHECK(rs_has_token("keep-alive, Upgrade", "upgrade") && rs_has_token("Upgrade", "upgrade"));
+ CHECK(!rs_has_token("keep-alive", "upgrade") && !rs_has_token("upgraded", "upgrade"));
+ CHECK(rs_valid_wskey("dGhlIHNhbXBsZSBub25jZQ==") && !rs_valid_wskey("dGhlIHNhbXBsZSBub25jZR==") && !rs_valid_wskey("abc"));
+ CHECK(rs_form_type("application/x-www-form-urlencoded") && rs_form_type("application/x-www-form-urlencoded;charset=UTF-8"));
+ CHECK(rs_form_type("application/x-www-form-urlencoded; charset=\"utf-8\""));
+ CHECK(!rs_form_type("multipart/form-data") && !rs_form_type("application/x-www-form-urlencodedX") && !rs_form_type("text/plain"));
+ CHECK(!rs_form_type("application/x-www-form-urlencoded; charset=latin1"));
+ char tok[65], hex[65];
+ memset(hex, 'a', 64);
+ hex[64] = 0;
+ char c[300];
+ snprintf(c, sizeof c, "theme=dark; __Host-lordos_remote=%s; x=y", hex);
+ CHECK(rs_cookie_token(c, "__Host-lordos_remote", tok) == 0 && !strcmp(tok, hex));
+ snprintf(c, sizeof c, "x__Host-lordos_remote=%s", hex);
+ CHECK(rs_cookie_token(c, "__Host-lordos_remote", tok) == -1); /* suffix match is not a match */
+ snprintf(c, sizeof c, "__Host-lordos_remote=%s; __Host-lordos_remote=%s", hex, hex);
+ CHECK(rs_cookie_token(c, "__Host-lordos_remote", tok) == -2); /* cookie tossing */
+ CHECK(rs_cookie_token("__Host-lordos_remote=ABC", "__Host-lordos_remote", tok) == -2);
+ hex[10] = 'G';
+ snprintf(c, sizeof c, "__Host-lordos_remote=%s", hex);
+ CHECK(rs_cookie_token(c, "__Host-lordos_remote", tok) == -2);
+ CHECK(rs_cookie_token("", "__Host-lordos_remote", tok) == -1);
+ char clean[33];
+ rs_log_clean("a\nb\"c\\d\x1b", 8, clean, sizeof clean);
+ CHECK(!strcmp(clean, "a?b?c?d?"));
+}
+
+static int login(const char *body, char *user, char *pass, size_t *pl) {
+ char raw[33];
+ return rs_parse_login(body, strlen(body), user, pass, pl, raw);
+}
+
+static void test_login(void) {
+ char u[33], p[RS_PASS_MAX + 1], raw[33];
+ size_t pl;
+ CHECK(login("user=lord&pass=s3cret", u, p, &pl) == RS_FORM_OK && !strcmp(u, "lord") && !strcmp(p, "s3cret") && pl == 6);
+ CHECK(login("pass=a+b%26c%3D&user=bob", u, p, &pl) == RS_FORM_OK && !strcmp(u, "bob") && !strcmp(p, "a b&c="));
+ CHECK(login("user=lord&pass=%C3%B1", u, p, &pl) == RS_FORM_OK && pl == 2);
+ CHECK(login("user=lord", u, p, &pl) == RS_FORM_BAD);
+ CHECK(login("pass=x", u, p, &pl) == RS_FORM_BAD);
+ CHECK(login("user=lord&pass=x&x=1", u, p, &pl) == RS_FORM_BAD); /* unknown field */
+ CHECK(login("user=lord&user=root&pass=x", u, p, &pl) == RS_FORM_BAD); /* duplicate */
+ CHECK(login("user=lord&pass=x&pass=y", u, p, &pl) == RS_FORM_BAD);
+ CHECK(login("user=lord&pass=x&", u, p, &pl) == RS_FORM_BAD);
+ CHECK(login("&user=lord&pass=x", u, p, &pl) == RS_FORM_BAD);
+ CHECK(login("user=lord&pass=%4", u, p, &pl) == RS_FORM_BAD); /* truncated escape */
+ CHECK(login("user=lord&pass=%zz", u, p, &pl) == RS_FORM_BAD);
+ CHECK(login("user=lord&pass=a b", u, p, &pl) == RS_FORM_BAD); /* raw space */
+ CHECK(login("user=lord&pass=a\"", u, p, &pl) == RS_FORM_BAD);
+ CHECK(login("user=lord&pass", u, p, &pl) == RS_FORM_BAD);
+ CHECK(login("user=Lord&pass=x", u, p, &pl) == RS_FORM_USER);
+ CHECK(login("user=lord%00x&pass=x", u, p, &pl) == RS_FORM_USER); /* NUL in the name */
+ CHECK(login("user=&pass=x", u, p, &pl) == RS_FORM_USER);
+ CHECK(login("user=lo%20rd&pass=x", u, p, &pl) == RS_FORM_USER);
+ CHECK(login("user=lord&pass=", u, p, &pl) == RS_FORM_PASS);
+ CHECK(login("user=lord&pass=ab%00cd", u, p, &pl) == RS_FORM_PASS); /* NUL in the password */
+ char big[4200];
+ int o = sprintf(big, "user=lord&pass=");
+ memset(big + o, 'x', 1024);
+ big[o + 1024] = 0;
+ CHECK(login(big, u, p, &pl) == RS_FORM_OK && pl == 1024);
+ big[o + 1024] = 'x';
+ big[o + 1025] = 0;
+ CHECK(login(big, u, p, &pl) == RS_FORM_PASS); /* 1025 bytes */
+ o = sprintf(big, "user=");
+ memset(big + o, 'a', 40);
+ strcpy(big + o + 40, "&pass=x");
+ CHECK(login(big, u, p, &pl) == RS_FORM_USER);
+ CHECK(rs_parse_login("user=root\n&pass=x", 17, u, p, &pl, raw) == RS_FORM_BAD);
+ CHECK(login("user=x%0Ay&pass=x", u, p, &pl) == RS_FORM_USER);
+ rs_parse_login("user=x%0Ay&pass=x", 17, u, p, &pl, raw);
+ CHECK(!strcmp(raw, "x?y")); /* sanitized for the journal */
+}
+
+typedef struct { int n, op[8]; char data[8][256]; size_t len[8]; } Got;
+
+static void on(void *ud, int op, unsigned char *d, size_t l) {
+ Got *g = ud;
+ if (g->n >= 8) return;
+ g->op[g->n] = op;
+ memcpy(g->data[g->n], d, l < 255 ? l : 255);
+ g->data[g->n][l < 255 ? l : 255] = 0;
+ g->len[g->n++] = l;
+}
+
+/* a masked client frame */
+static size_t frame(unsigned char *out, int fin, int op, const char *p, size_t n) {
+ static const unsigned char m[4] = { 0x12, 0x34, 0x56, 0x78 };
+ size_t o = 0;
+ out[o++] = (unsigned char)((fin ? 0x80 : 0) | op);
+ if (n < 126) out[o++] = (unsigned char)(0x80 | n);
+ else if (n < 65536) { out[o++] = 0x80 | 126; out[o++] = (unsigned char)(n >> 8); out[o++] = (unsigned char)n; }
+ else { out[o++] = 0x80 | 127; for (int i = 0; i < 8; i++) out[o++] = (unsigned char)((uint64_t)n >> (56 - 8 * i)); }
+ memcpy(out + o, m, 4);
+ o += 4;
+ for (size_t i = 0; i < n; i++) out[o + i] = (unsigned char)p[i] ^ m[i & 3];
+ return o + n;
+}
+
+static int ws(unsigned char *b, size_t n, Got *g, size_t *used) {
+ RsWs w;
+ rs_ws_init(&w, 70000);
+ memset(g, 0, sizeof *g);
+ int rc = rs_ws_consume(&w, b, n, used, on, g);
+ rs_ws_free(&w);
+ return rc;
+}
+
+static void test_ws(void) {
+ unsigned char b[200000];
+ Got g;
+ size_t used, n;
+ n = frame(b, 1, 1, "{\"t\":\"ack\"}", 11);
+ CHECK(ws(b, n, &g, &used) == 0 && g.n == 1 && g.op[0] == 1 && !strcmp(g.data[0], "{\"t\":\"ack\"}") && used == n);
+ CHECK(ws(b, n - 1, &g, &used) == 0 && g.n == 0 && used == 0); /* incomplete: waits */
+ n = frame(b, 0, 1, "ab", 2);
+ n += frame(b + n, 1, 9, "p", 1); /* ping between fragments */
+ n += frame(b + n, 1, 0, "cd", 2);
+ CHECK(ws(b, n, &g, &used) == 0 && g.n == 2 && g.op[0] == 9 && g.op[1] == 1 && !strcmp(g.data[1], "abcd"));
+ n = frame(b, 1, 0, "x", 1);
+ CHECK(ws(b, n, &g, &used) == 1002); /* continuation of nothing */
+ n = frame(b, 0, 1, "a", 1);
+ n += frame(b + n, 1, 1, "b", 1);
+ CHECK(ws(b, n, &g, &used) == 1002); /* new message inside one */
+ n = frame(b, 1, 1, "x", 1);
+ b[1] &= 0x7f;
+ CHECK(ws(b, n, &g, &used) == 1002); /* unmasked */
+ n = frame(b, 1, 1, "x", 1);
+ b[0] |= 0x40;
+ CHECK(ws(b, n, &g, &used) == 1002); /* RSV bit */
+ n = frame(b, 1, 3, "x", 1);
+ CHECK(ws(b, n, &g, &used) == 1002); /* reserved opcode */
+ n = frame(b, 0, 9, "x", 1);
+ CHECK(ws(b, n, &g, &used) == 1002); /* fragmented control */
+ char big[70001];
+ memset(big, 'a', sizeof big);
+ n = frame(b, 1, 9, big, 126);
+ CHECK(ws(b, n, &g, &used) == 1002); /* control > 125 */
+ n = frame(b, 1, 1, big, 70001);
+ CHECK(ws(b, n, &g, &used) == 1009); /* message too big */
+ n = frame(b, 0, 1, big, 40000);
+ n += frame(b + n, 1, 0, big, 40000);
+ CHECK(ws(b, n, &g, &used) == 1009); /* too big in pieces */
+ n = frame(b, 1, 1, "\xc3\x28", 2);
+ CHECK(ws(b, n, &g, &used) == 1007); /* invalid UTF-8 */
+ n = frame(b, 1, 1, "\xed\xa0\x80", 3);
+ CHECK(ws(b, n, &g, &used) == 1007); /* surrogate */
+ n = frame(b, 1, 2, "\xff", 1);
+ CHECK(ws(b, n, &g, &used) == 0 && g.op[0] == 2); /* binary is passed up */
+ n = frame(b, 1, 8, "\x03\xe8", 2);
+ n += frame(b + n, 1, 1, "late", 4);
+ CHECK(ws(b, n, &g, &used) == 0 && g.n == 1 && g.op[0] == 8); /* nothing after close */
+ /* non-minimal length encoding */
+ unsigned char nm[16] = { 0x81, 0x80 | 126, 0, 5, 1, 2, 3, 4, 'a', 'b', 'c', 'd', 'e' };
+ CHECK(ws(nm, 13, &g, &used) == 1002);
+ unsigned char huge[14] = { 0x81, 0x80 | 127, 0x80, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 };
+ CHECK(ws(huge, 14, &g, &used) == 1002);
+ CHECK(rs_utf8_valid((const unsigned char *)"\xf0\x9f\x91\x91", 4) && !rs_utf8_valid((const unsigned char *)"\xf4\x90\x80\x80", 4));
+ CHECK(!rs_utf8_valid((const unsigned char *)"\xc0\xaf", 2) && !rs_utf8_valid((const unsigned char *)"\xe2\x82", 2));
+}
+
+static int jin(const char *j, int W, int H, RsInput *in) {
+ static char sb[4096];
+ RsJson o;
+ if (rs_json_parse(j, strlen(j), &o, sb, sizeof sb)) return -1;
+ return rs_browser_input(&o, W, H, in);
+}
+
+static void test_json(void) {
+ RsInput in;
+ CHECK(jin("{\"t\":\"m\",\"x\":10,\"y\":20}", 1280, 800, &in) == RS_IN_PTR && in.a == 10 && in.b == 20);
+ CHECK(jin("{\"t\":\"m\",\"x\":-5,\"y\":99999}", 1280, 800, &in) == RS_IN_PTR && in.a == 0 && in.b == 799);
+ CHECK(jin(" { \"y\" : 1 , \"t\" : \"m\" , \"x\" : 2 } ", 1280, 800, &in) == RS_IN_PTR);
+ CHECK(jin("{\"t\":\"m\",\"x\":1}", 1280, 800, &in) == RS_IN_NONE);
+ CHECK(jin("{\"t\":\"m\",\"x\":1,\"y\":2}", 0, 0, &in) == RS_IN_NONE); /* no screen yet */
+ CHECK(jin("{\"t\":\"m\",\"x\":\"\\\"y\\\":5\",\"y\":2}", 1280, 800, &in) == RS_IN_NONE); /* key confusion */
+ CHECK(jin("{\"t\":\"m\",\"t\":\"k\",\"x\":1,\"y\":2}", 1280, 800, &in) == -1); /* duplicate key */
+ CHECK(jin("{\"t\":\"m\",\"x\":1.5,\"y\":2}", 1280, 800, &in) == -1);
+ CHECK(jin("{\"t\":\"m\",\"x\":01,\"y\":2}", 1280, 800, &in) == -1);
+ CHECK(jin("{\"t\":\"m\",\"x\":9007199254740992,\"y\":2}", 1280, 800, &in) == -1);
+ CHECK(jin("{\"t\":\"m\",\"x\":1,\"y\":2}x", 1280, 800, &in) == -1); /* trailing bytes */
+ CHECK(jin("{\"t\":\"m\",\"x\":{\"a\":1},\"y\":2}", 1280, 800, &in) == -1); /* nested */
+ CHECK(jin("[1]", 1280, 800, &in) == -1 && jin("", 1280, 800, &in) == -1 && jin("{", 1280, 800, &in) == -1);
+ CHECK(jin("{\"T\":\"m\"}", 1280, 800, &in) == -1);
+ CHECK(jin("{\"t\":\"b\",\"b\":0,\"d\":1}", 1280, 800, &in) == RS_IN_BTN && in.a == 0 && in.b == 1);
+ CHECK(jin("{\"t\":\"b\",\"b\":3,\"d\":1}", 1280, 800, &in) == RS_IN_NONE);
+ CHECK(jin("{\"t\":\"w\",\"d\":-500}", 1280, 800, &in) == RS_IN_WHEEL && in.a == -10);
+ CHECK(jin("{\"t\":\"k\",\"c\":30,\"d\":1}", 1280, 800, &in) == RS_IN_KEY && in.a == 30);
+ CHECK(jin("{\"t\":\"k\",\"c\":272,\"d\":1}", 1280, 800, &in) == RS_IN_NONE); /* BTN_LEFT is not a key */
+ CHECK(jin("{\"t\":\"k\",\"c\":0,\"d\":1}", 1280, 800, &in) == RS_IN_NONE);
+ CHECK(jin("{\"t\":\"s\",\"p\":2,\"x\":99999999,\"y\":-99999999}", 1280, 800, &in) == RS_IN_SCROLL && in.v1 == 4000 * 256 && in.v2 == -4000 * 256);
+ CHECK(jin("{\"t\":\"s\",\"p\":4,\"x\":1,\"y\":1}", 1280, 800, &in) == RS_IN_NONE);
+ CHECK(jin("{\"t\":\"pz\",\"p\":1,\"s\":65536,\"r\":0}", 1280, 800, &in) == RS_IN_PINCH && in.v1 == 65536);
+ CHECK(jin("{\"t\":\"pz\",\"p\":2,\"s\":0,\"r\":0}", 1280, 800, &in) == RS_IN_PINCH && in.v1 == 3277);
+ CHECK(jin("{\"t\":\"resize\",\"w\":1921,\"h\":1080}", 1280, 800, &in) == RS_IN_RESIZE && in.a == 1920);
+ CHECK(jin("{\"t\":\"resize\",\"w\":100000,\"h\":1080}", 1280, 800, &in) == RS_IN_NONE);
+ CHECK(jin("{\"t\":\"resize\",\"w\":100,\"h\":100}", 1280, 800, &in) == RS_IN_NONE);
+ CHECK(jin("{\"t\":\"ping\",\"ts\":123}", 1280, 800, &in) == RS_IN_PING && in.ts == 123);
+ CHECK(jin("{\"t\":\"ack\"}", 1280, 800, &in) == RS_IN_ACK);
+ CHECK(jin("{\"t\":\"clip\",\"text\":\"h\\u00e9\\ud83d\\udc51\\n\"}", 1280, 800, &in) == RS_IN_CLIP && in.tlen == 8 &&
+ !memcmp(in.text, "h\xc3\xa9\xf0\x9f\x91\x91\n", 8));
+ CHECK(jin("{\"t\":\"clip\",\"text\":\"\\ud83d\"}", 1280, 800, &in) == -1); /* lone surrogate */
+ CHECK(jin("{\"t\":\"clip\",\"text\":\"\\udc51\"}", 1280, 800, &in) == -1);
+ CHECK(jin("{\"t\":\"clip\",\"text\":\"\\u0000\"}", 1280, 800, &in) == -1); /* NUL */
+ CHECK(jin("{\"t\":\"clip\",\"text\":\"a\\x\"}", 1280, 800, &in) == -1);
+ CHECK(jin("{\"t\":\"clip\",\"text\":\"\"}", 1280, 800, &in) == RS_IN_NONE);
+ CHECK(jin("{\"t\":\"clip\",\"text\":\"a\x01\"}", 1280, 800, &in) == -1); /* raw control */
+ CHECK(jin("{\"t\":\"nope\"}", 1280, 800, &in) == RS_IN_NONE);
+}
+
+static void test_ipnet(void) {
+ RsAddr a;
+ RsCidr c;
+ char t[64];
+ CHECK(!rs_addr_parse("192.168.1.10", &a) && a.v4);
+ CHECK(!rs_addr_parse("::ffff:192.168.1.10", &a) && a.v4);
+ CHECK(!rs_addr_parse("2001:db8::1", &a) && !a.v4);
+ CHECK(rs_addr_parse("192.168.01.10", &a) && rs_addr_parse("1.2.3", &a) && rs_addr_parse("fe80::1%eth0", &a) && rs_addr_parse(" 1.2.3.4", &a));
+ CHECK(rs_addr_parse("256.1.1.1", &a) && rs_addr_parse("", &a));
+ CHECK(!rs_cidr_parse("192.168.1.77/24", &c));
+ rs_cidr_format(&c, t, sizeof t);
+ CHECK(!strcmp(t, "192.168.1.0/24")); /* host bits cleared */
+ CHECK(!rs_cidr_parse("10.0.0.1", &c) && c.prefix == 128);
+ rs_cidr_format(&c, t, sizeof t);
+ CHECK(!strcmp(t, "10.0.0.1"));
+ CHECK(rs_cidr_parse("0.0.0.0/0", &c) && rs_cidr_parse("10.0.0.0/7", &c) && rs_cidr_parse("10.0.0.0/33", &c));
+ CHECK(rs_cidr_parse("10.0.0.0/024", &c) && rs_cidr_parse("10.0.0.0/", &c) && rs_cidr_parse("10.0.0.0/2a", &c) && rs_cidr_parse("::/0", &c));
+ CHECK(!rs_cidr_parse("2001:db8::/32", &c) && !rs_cidr_parse("10.0.0.0/8", &c));
+ CHECK(!rs_addr_parse("10.200.3.4", &a) && rs_cidr_contains(&c, &a));
+ CHECK(!rs_addr_parse("11.0.0.1", &a) && !rs_cidr_contains(&c, &a));
+ CHECK(!rs_addr_parse("2001:db8:1:2:3:4:5:6", &a));
+ rs_addr_key(&a, t, sizeof t);
+ CHECK(!strcmp(t, "2001:db8:1:2::/64"));
+ CHECK(!rs_key_parse("2001:db8:1:2::/64", &c) && rs_cidr_contains(&c, &a));
+ CHECK(!rs_key_parse("10.0.0.1", &c) && rs_key_parse("10.0.0.0/24", &c) && rs_key_parse("2001:db8::/48", &c));
+ CHECK(!rs_addr_parse("192.168.1.1", &a) && rs_addr_is_local(&a));
+ CHECK(!rs_addr_parse("172.20.0.1", &a) && rs_addr_is_local(&a));
+ CHECK(!rs_addr_parse("172.32.0.1", &a) && !rs_addr_is_local(&a));
+ CHECK(!rs_addr_parse("8.8.8.8", &a) && !rs_addr_is_local(&a));
+ CHECK(!rs_addr_parse("fe80::5", &a) && rs_addr_is_local(&a));
+ CHECK(!rs_addr_parse("fd12::5", &a) && rs_addr_is_local(&a));
+ CHECK(!rs_addr_parse("2a00::5", &a) && !rs_addr_is_local(&a));
+ CHECK(!rs_addr_parse("::ffff:8.8.8.8", &a) && !rs_addr_is_local(&a));
+
+ RsAccess acc;
+ int bad;
+ rs_access_parse("# x\nallow 203.0.113.0/24\nblock 192.168.1.66\nblock nope\nallow 1.2.3.4 extra\nweird line\n", &acc, &bad);
+ CHECK(acc.nallow == 1 && acc.nblock == 1 && bad == 3);
+ char text[4096];
+ CHECK(rs_access_format(&acc, text, sizeof text) > 0 && strstr(text, "allow 203.0.113.0/24\n") && strstr(text, "block 192.168.1.66\n"));
+ RsAccess back;
+ rs_access_parse(text, &back, &bad);
+ CHECK(back.nallow == 1 && back.nblock == 1 && bad == 0);
+ rs_addr_parse("192.168.1.66", &a);
+ CHECK(rs_access_decide(&acc, RS_NET_ANY, &a, 0) == RS_ACC_BLOCKED); /* manual block always wins */
+ rs_addr_parse("192.168.1.67", &a);
+ CHECK(rs_access_decide(&acc, RS_NET_LAN, &a, 0) == RS_ACC_OK);
+ CHECK(rs_access_decide(&acc, RS_NET_LIST, &a, 0) == RS_ACC_NOT_ALLOWED);
+ rs_addr_parse("203.0.113.9", &a);
+ CHECK(rs_access_decide(&acc, RS_NET_LAN, &a, 0) == RS_ACC_NOT_ALLOWED); /* public, default */
+ CHECK(rs_access_decide(&acc, RS_NET_LAN, &a, 1) == RS_ACC_OK); /* ...unless over a VPN */
+ CHECK(rs_access_decide(&acc, RS_NET_LIST, &a, 0) == RS_ACC_OK);
+ CHECK(rs_access_decide(&acc, RS_NET_ANY, &a, 0) == RS_ACC_OK);
+ rs_cidr_parse("192.168.1.0/24", &c);
+ CHECK(rs_access_add(acc.block, &acc.nblock, &c) == 0 && rs_access_add(acc.block, &acc.nblock, &c) == 1);
+ CHECK(rs_access_del(acc.block, &acc.nblock, &c) == 2 && acc.nblock == 0); /* the /24 and the host inside */
+ for (int i = 0; i < RS_ACCESS_MAX; i++) { char s[32]; snprintf(s, sizeof s, "10.0.%d.0/24", i); rs_cidr_parse(s, &c); rs_access_add(acc.block, &acc.nblock, &c); }
+ rs_cidr_parse("10.9.9.9", &c);
+ CHECK(rs_access_add(acc.block, &acc.nblock, &c) == -1);
+ CHECK(rs_net_mode("lan") == RS_NET_LAN && rs_net_mode("any") == RS_NET_ANY && rs_net_mode("list") == RS_NET_LIST && rs_net_mode("all") < 0);
+ CHECK(rs_vpn_ifname("wg-home") && rs_vpn_ifname("ovpn-work") && rs_vpn_ifname("tun0") && !rs_vpn_ifname("eth0") && !rs_vpn_ifname("wlan0"));
+}
+
+static void test_lockout(void) {
+ static RlTable t;
+ memset(&t, 0, sizeof t);
+ double now = 1e9, until = 0;
+ int strikes = 0;
+ const char *k = "192.168.1.50";
+ CHECK(!rl_fail(&t, k, now, &until, &strikes) && !rl_fail(&t, k, now + 1, &until, &strikes));
+ CHECK(rl_blocked(&t, k, now + 2) == 0);
+ CHECK(rl_fail(&t, k, now + 2, &until, &strikes) && strikes == 1 && until == now + 2 + 900); /* 3rd: 15 min */
+ CHECK(rl_blocked(&t, k, now + 3) > 890 && rl_blocked(&t, k, now + 903) == 0);
+ rl_fail(&t, k, now + 1000, &until, &strikes);
+ rl_fail(&t, k, now + 1001, &until, &strikes);
+ CHECK(rl_fail(&t, k, now + 1002, &until, &strikes) && strikes == 2 && until == now + 1002 + 3600); /* 1 h */
+ rl_fail(&t, k, now + 5000, &until, &strikes);
+ rl_fail(&t, k, now + 5001, &until, &strikes);
+ CHECK(rl_fail(&t, k, now + 5002, &until, &strikes) && strikes == 3 && until == now + 5002 + 86400); /* 24 h */
+ /* a day later the strikes are forgotten: 15 min again */
+ double later = now + 5002 + 86400 + RL_WINDOW + 10;
+ rl_fail(&t, k, later, &until, &strikes);
+ rl_fail(&t, k, later + 1, &until, &strikes);
+ CHECK(rl_fail(&t, k, later + 2, &until, &strikes) && strikes == 1 && until == later + 2 + 900);
+ /* a success clears the count */
+ const char *k2 = "192.168.1.51";
+ rl_fail(&t, k2, now, &until, &strikes);
+ rl_fail(&t, k2, now, &until, &strikes);
+ rl_success(&t, k2);
+ CHECK(!rl_fail(&t, k2, now, &until, &strikes) && !rl_fail(&t, k2, now, &until, &strikes) && rl_fail(&t, k2, now, &until, &strikes));
+ /* persistence */
+ char text[RL_MAX * 128 + 256];
+ CHECK(rl_format(&t, later + 3, text, sizeof text) > 0);
+ static RlTable back;
+ rl_parse(&back, text, later + 3);
+ CHECK(rl_blocked(&back, k, later + 3) > 800);
+ rl_parse(&back, "2001:db8:1:2::/64 1 1000 1 1000 9999999999\n10.0.0.1 2 1000 0 0 0\nbad\n10.0.0.01 1 1 1 1 1\n"
+ "10.0.0.2 7 1000 0 0 0\n10.0.0.3 1 1000 0 0 1e300\n", 2000);
+ CHECK(rl_blocked(&back, "2001:db8:1:2::/64", 2000) == 0); /* until too far: refused */
+ int n = 0;
+ for (int i = 0; i < RL_MAX; i++) if (back.e[i].key[0]) n++;
+ CHECK(n == 1); /* only 10.0.0.1 is valid */
+ rl_parse(&back, "2001:db8:1:2::/64 0 1990 1 1990 2500\n", 2000);
+ CHECK(rl_blocked(&back, "2001:db8:1:2::/64", 2000) == 500);
+ CHECK(rl_unblock(&back, "2001:db8:1:2:aaaa::1") == 1 && rl_blocked(&back, "2001:db8:1:2::/64", 2000) == 0);
+ rl_fail(&t, "10.1.1.1", now, NULL, NULL);
+ rl_fail(&t, "10.1.1.1", now, NULL, NULL);
+ rl_fail(&t, "10.1.1.1", now, NULL, NULL);
+ CHECK(rl_unblock(&t, "10.1.0.0/16") == 1 && rl_blocked(&t, "10.1.1.1", now) == 0);
+ CHECK(rl_unblock(&t, "garbage") == 0);
+ /* a flood of other addresses doesn't evict a running block */
+ memset(&t, 0, sizeof t);
+ for (int i = 0; i < 3; i++) rl_fail(&t, "192.168.9.9", now, NULL, NULL);
+ for (int i = 0; i < 5000; i++) { char s[32]; snprintf(s, sizeof s, "10.%d.%d.%d", i >> 16 & 255, i >> 8 & 255, i & 255); rl_fail(&t, s, now + 1, NULL, NULL); }
+ CHECK(rl_blocked(&t, "192.168.9.9", now + 2) > 0);
+ CHECK(rl_user_delay(0) == 0 && rl_user_delay(4) == 0 && rl_user_delay(5) == 1 && rl_user_delay(7) == 4 && rl_user_delay(100) == 8);
+ static RcTable rc;
+ int ok = 0;
+ for (int i = 0; i < 100; i++) ok += rc_take(&rc, "1.2.3.4", 10.0);
+ CHECK(ok == 20); /* the burst */
+ CHECK(rc_take(&rc, "1.2.3.4", 10.6) == 1 && rc_take(&rc, "1.2.3.4", 10.6) == 0); /* 2 per second */
+ CHECK(rc_take(&rc, "1.2.3.5", 10.6) == 1); /* others are not affected */
+}
+
+int main(void) {
+ test_head();
+ test_small();
+ test_login();
+ test_ws();
+ test_json();
+ test_ipnet();
+ test_lockout();
+ printf("remote-sec-test: %d checks, %d failed\n", checks, fails);
+ return fails ? 1 : 0;
+}