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.
C cdebiandesktop-environmentebpffirewalllandlocklinuxlinux-distributionopen-sourceprivacyquickjsraspberry-pi-5reactsecuritywaylandwayland-compositor
Verified system code: signed manifest of LordOS's bundles, checked by lord-server at load time
Federico Pereira6878a374a872
diff --git a/.gitignore b/.gitignoreindex 2bc114e..24fc4c0 100644--- a/.gitignore+++ b/.gitignore@@ -16,3 +16,5 @@ assets/app-host.bundle.jsassets/sysapps/assets/locales/*.tgzlogs/+/code-manifest.json+/code-manifest.sigdiff --git a/apps/about/index.jsx b/apps/about/index.jsxindex 63cedd1..412f4de 100644--- a/apps/about/index.jsx+++ b/apps/about/index.jsx@@ -1,6 +1,7 @@// About LordOS: real system data (/proc) and display server stats.import { version as reactVersion } from 'react';-import { View, Text, LordOSLogo, LordOSWordmark, Lumo, screen, lordosVersion, useTheme, useSystemInfo, useServerStats, formatBytes, formatDuration, formatNumber, typeScale, t as tr } from '@lordos/sdk';+import { useMemo } from 'react';+import { View, Text, LordOSLogo, LordOSWordmark, Lumo, screen, lordosVersion, useTheme, useSystemInfo, useServerStats, formatBytes, formatDuration, formatNumber, typeScale, codeStatus, isSystemApp, t as tr } from '@lordos/sdk';export function Icon({ size }) {return <LordOSLogo size={size} />;@@ -20,18 +21,46 @@ function InfoRow({ k, v }) {);}+// A small pill: a colored dot and a label (System app, Verified, Development build).+function Badge({ color, label }) {+ const t = useTheme();+ return (+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 5, paddingHorizontal: 8, paddingVertical: 2, borderRadius: 10,+ backgroundColor: t.mode === 'dark' ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)' }}>+ <View style={{ width: 7, height: 7, borderRadius: 4, backgroundColor: color }} />+ <Text style={{ fontSize: typeScale.caption, color: t.text, whiteSpace: 'nowrap' }}>{label}</Text>+ </View>+ );+}++// The state of LordOS's own code, as lord-server checked it (docs/SIGNING.md, "Verified system code").+const CODE = {+ verified: { color: '#30d158', key: 'about.codeVerified' },+ development: { color: '#ff9f0a', key: 'about.codeDevelopment' },+ invalid: { color: '#ff453a', key: 'about.codeInvalid' },+};+export default function About() {const t = useTheme();const info = useSystemInfo(5000);const st = useServerStats(2000);const cpu = info.cpu.replace(/\(R\)|\(TM\)|CPU|Processor/g, '').replace(/\s+/g, ' ').trim();const ver = lordosVersion(info);+ const code = useMemo(() => codeStatus(), []);+ const cs = CODE[code.refused?.length ? 'invalid' : code.state] || CODE.development;+ const codeNote = code.state === 'verified' && !code.refused?.length ? tr('about.codeVerifiedNote', { count: code.files })+ : code.state === 'development' ? tr('about.codeDevNote') : null;return (<View style={{ flex: 1, alignItems: 'center', paddingHorizontal: 20, paddingTop: 20, paddingBottom: 16 }}><Icon size={64} /><View style={{ marginTop: 12 }}><LordOSWordmark size={typeScale.largeTitle} crown={false} /></View><Text style={{ fontSize: typeScale.callout, color: t.textDim, marginTop: 2 }}>{ver.channel ? tr('about.versionChannel', { v: ver.version, channel: ver.channel }) : tr('about.version', { v: ver.version })}</Text>{ver.build ? <Text style={{ fontSize: typeScale.caption, color: t.textDim, marginTop: 1 }}>{tr('about.build', { b: ver.build })}</Text> : null}+ <View style={{ flexDirection: 'row', gap: 6, marginTop: 8 }}>+ {isSystemApp('about') ? <Badge color="#0a84ff" label={tr('about.systemApp')} /> : null}+ <Badge color={cs.color} label={tr(cs.key)} />+ </View>+ {codeNote ? <Text style={{ fontSize: typeScale.caption, color: code.state === 'development' ? '#ff9f0a' : t.textDim, marginTop: 4, textAlign: 'center' }}>{codeNote}</Text> : null}<Text style={{ fontSize: typeScale.callout, color: t.textDim, marginTop: 10, maxWidth: 320, textAlign: 'center', lineHeight: 17 }}>{tr('about.tagline')}</Text><View style={{ alignSelf: 'stretch', marginTop: 16, gap: 2 }}><InfoRow k={tr('about.os')} v={info.os} />@@ -43,6 +72,7 @@ export default function About() {<View style={{ height: 1, backgroundColor: t.separator, marginVertical: 8, marginHorizontal: 24 }} /><InfoRow k={tr('about.server')} v="lord-server (C · DRM/KMS · evdev)" /><InfoRow k={tr('about.engine')} v={`QuickJS + React ${reactVersion}`} />+ <InfoRow k={tr('about.codeLabel')} v={tr(cs.key)} /><InfoRow k={tr('about.display')} v={`${screen.width} × ${screen.height}`} /><InfoRow k={tr('about.ram')} v={`${formatNumber(st.rssKB / 1024, 1)} MB (JS ${formatNumber(st.jsKB / 1024, 1)} MB)`} /><InfoRow k={tr('about.render')} v={tr('about.renderValue', { ms: formatNumber(st.layoutMs + st.paintMs, 1), count: st.nodes })} />diff --git a/apps/about/manifest.json b/apps/about/manifest.jsonindex bfec9af..6ed1b81 100644--- a/apps/about/manifest.json+++ b/apps/about/manifest.json@@ -4,7 +4,7 @@"description": "System and graphics server information","size": [440,- 572+ 650],"dock": true,"permissions": [diff --git a/apps/store/index.jsx b/apps/store/index.jsxindex 9206ef9..d6b3b52 100644--- a/apps/store/index.jsx+++ b/apps/store/index.jsx@@ -2,7 +2,7 @@// server/src/pkg; install and remove go through the administration helper).import {View, Text, Image, useTheme, useLocale, useAppWindow, useStore, Button, ScrollView, SidebarItem, SectionTitle, SearchField, Hairline, EmptyState, GroupBox,- packages, packageList, refreshPackages, useLauncherApps, launchApp, fs, formatBytes, wm, direction, typeScale, spacing,+ packages, packageList, refreshPackages, useLauncherApps, launchApp, fs, formatBytes, wm, direction, typeScale, spacing, isSystemApp,} from '@lordos/sdk';import { useEffect, useMemo, useState } from 'react';import { debian, useDebian } from './debian.js';@@ -286,6 +286,8 @@ function InstalledPage({ query }) {<List count={null} empty={tr('store.debian.none')}>{shown.map((a) => (<AppRow key={a.id} icon={<a.Icon size={32} />} name={a.name} detail={a.comment || a.genericName || ''} extra={kind(a)}>+ {/* a system app is part of LordOS: never removable here (docs/SIGNING.md, "Verified system code") */}+ {a.kind === 'lordos' && isSystemApp(a.id) && <Text style={{ fontSize: typeScale.caption, color: t.textDim, whiteSpace: 'nowrap' }}>{tr('store.systemApp')}</Text>}{a.kind === 'linux' && debian.canRemove(a) && <Button small label={tr('store.remove')} onClick={() => debian.removeApp(a)} />}<Button small label={tr('store.open')} onClick={() => launchApp(a.id)} /></AppRow>diff --git a/assets/locales/en/about.json b/assets/locales/en/about.jsonindex 7352ac8..060d0c4 100644--- a/assets/locales/en/about.json+++ b/assets/locales/en/about.json@@ -5,6 +5,12 @@"channelBeta": "Beta","channelDev": "Development","channelRc": "Release candidate",+ "codeDevNote": "Development build: the system code is not signed by LordOS.",+ "codeDevelopment": "Development build",+ "codeInvalid": "Modified — not loaded",+ "codeLabel": "System code",+ "codeVerified": "Verified",+ "codeVerifiedNote": "Signed by LordOS · {count} components","cpu": "Processor","cpuUnknown": "Unknown","cpuValue": {@@ -26,6 +32,7 @@"other": "{ms} ms · {count} nodes"},"server": "Display server",+ "systemApp": "System app","tagline": "A free, fast and secure GNU/Linux desktop, built on Debian and Wayland.","uptime": "Uptime","version": "Version {v}",diff --git a/assets/locales/en/errors.json b/assets/locales/en/errors.jsonindex c1886e6..f6b7760 100644--- a/assets/locales/en/errors.json+++ b/assets/locales/en/errors.json@@ -558,5 +558,6 @@"proc.denied": "Not allowed to stop this process","proc.failed": "Could not stop the process","proc.badArgument": "Invalid process request",- "proc.notOwn": "This process belongs to another user"+ "proc.notOwn": "This process belongs to another user",+ "app.codeRefused": "This app's code was modified and was not loaded"}diff --git a/assets/locales/en/shell.json b/assets/locales/en/shell.jsonindex 876f38c..60fef63 100644--- a/assets/locales/en/shell.json+++ b/assets/locales/en/shell.json@@ -158,5 +158,15 @@"power.shuttingDown": "Shutting down…","power.restart": "Restart","power.shutdown": "Shut Down",- "power.cancel": "Cancel"+ "power.cancel": "Cancel",+ "code.modifiedTitle": "This LordOS component was modified and was not loaded",+ "code.modifiedBody": "It no longer matches the signed copy of LordOS: {list}. Reinstall LordOS to repair it.",+ "code.details": "Details",+ "code.recovery.title": "This LordOS component was modified and was not loaded",+ "code.recovery.session": "LordOS checks its own code before running it. A part of the desktop no longer matches the signed copy, so it was not started. Your files were not touched.",+ "code.recovery.greeter": "LordOS checks its own code before running it. The login screen no longer matches the signed copy, so it was not started. Your files were not touched.",+ "code.recovery.app": "LordOS checks its own code before running it. This app no longer matches the signed copy, so it was not started.",+ "code.recovery.fix": "To repair it, reinstall LordOS: sudo apt install --reinstall lordos",+ "code.recovery.details": "Not loaded:",+ "code.recovery.logout": "Log Out"}diff --git a/assets/locales/en/store.json b/assets/locales/en/store.jsonindex 77d26b9..8dc356c 100644--- a/assets/locales/en/store.json+++ b/assets/locales/en/store.json@@ -148,5 +148,6 @@"other": "Debian updates ({count})"},"updates.auto": "Check for updates automatically",- "updates.autoHint": "Once a day, and only to tell you. Nothing is installed without asking."+ "updates.autoHint": "Once a day, and only to tell you. Nothing is installed without asking.",+ "systemApp": "System app — part of LordOS"}diff --git a/assets/locales/es/about.json b/assets/locales/es/about.jsonindex 73a4112..30821a4 100644--- a/assets/locales/es/about.json+++ b/assets/locales/es/about.json@@ -5,6 +5,12 @@"channelBeta": "Beta","channelDev": "Desarrollo","channelRc": "Versión candidata",+ "codeDevNote": "Compilación de desarrollo: el código del sistema no está firmado por LordOS.",+ "codeDevelopment": "Compilación de desarrollo",+ "codeInvalid": "Modificado — no se cargó",+ "codeLabel": "Código del sistema",+ "codeVerified": "Verificado",+ "codeVerifiedNote": "Firmado por LordOS · {count} componentes","cpu": "Procesador","cpuUnknown": "Desconocido","cpuValue": {@@ -26,6 +32,7 @@"other": "{ms} ms · {count} nodos"},"server": "Servidor gráfico",+ "systemApp": "App del sistema","tagline": "Un escritorio GNU/Linux libre, rápido y seguro, construido sobre Debian y Wayland.","uptime": "Encendido hace","version": "Versión {v}",diff --git a/assets/locales/es/errors.json b/assets/locales/es/errors.jsonindex 51eb699..6956d67 100644--- a/assets/locales/es/errors.json+++ b/assets/locales/es/errors.json@@ -558,5 +558,6 @@"proc.denied": "No tenés permiso para detener este proceso","proc.failed": "No se pudo detener el proceso","proc.badArgument": "Pedido de proceso no válido",- "proc.notOwn": "Este proceso es de otro usuario"+ "proc.notOwn": "Este proceso es de otro usuario",+ "app.codeRefused": "El código de esta app fue modificado y no se cargó"}diff --git a/assets/locales/es/shell.json b/assets/locales/es/shell.jsonindex 12c054e..5a329bb 100644--- a/assets/locales/es/shell.json+++ b/assets/locales/es/shell.json@@ -158,5 +158,15 @@"power.shuttingDown": "Apagando…","power.restart": "Reiniciar","power.shutdown": "Apagar",- "power.cancel": "Cancelar"+ "power.cancel": "Cancelar",+ "code.modifiedTitle": "Este componente de LordOS fue modificado y no se cargó",+ "code.modifiedBody": "Ya no coincide con la copia firmada de LordOS: {list}. Reinstalá LordOS para repararlo.",+ "code.details": "Detalles",+ "code.recovery.title": "Este componente de LordOS fue modificado y no se cargó",+ "code.recovery.session": "LordOS verifica su propio código antes de ejecutarlo. Una parte del escritorio ya no coincide con la copia firmada, así que no se inició. Tus archivos no se tocaron.",+ "code.recovery.greeter": "LordOS verifica su propio código antes de ejecutarlo. La pantalla de ingreso ya no coincide con la copia firmada, así que no se inició. Tus archivos no se tocaron.",+ "code.recovery.app": "LordOS verifica su propio código antes de ejecutarlo. Esta app ya no coincide con la copia firmada, así que no se inició.",+ "code.recovery.fix": "Para repararlo, reinstalá LordOS: sudo apt install --reinstall lordos",+ "code.recovery.details": "No se cargó:",+ "code.recovery.logout": "Cerrar sesión"}diff --git a/assets/locales/es/store.json b/assets/locales/es/store.jsonindex d84d6b8..2a5d0d7 100644--- a/assets/locales/es/store.json+++ b/assets/locales/es/store.json@@ -148,5 +148,6 @@"other": "Actualizaciones de Debian ({count})"},"updates.auto": "Buscar actualizaciones automáticamente",- "updates.autoHint": "Una vez por día, y solo para avisarte. No se instala nada sin preguntar."+ "updates.autoHint": "Una vez por día, y solo para avisarte. No se instala nada sin preguntar.",+ "systemApp": "App del sistema — parte de LordOS"}diff --git a/assets/locales/pt/about.json b/assets/locales/pt/about.jsonindex 33fc9c8..9e68713 100644--- a/assets/locales/pt/about.json+++ b/assets/locales/pt/about.json@@ -5,6 +5,12 @@"channelBeta": "Beta","channelDev": "Desenvolvimento","channelRc": "Versão candidata",+ "codeDevNote": "Compilação de desenvolvimento: o código do sistema não é assinado pelo LordOS.",+ "codeDevelopment": "Compilação de desenvolvimento",+ "codeInvalid": "Modificado — não carregado",+ "codeLabel": "Código do sistema",+ "codeVerified": "Verificado",+ "codeVerifiedNote": "Assinado pelo LordOS · {count} componentes","cpu": "Processador","cpuUnknown": "Desconhecido","cpuValue": {@@ -26,6 +32,7 @@"other": "{ms} ms · {count} nós"},"server": "Servidor gráfico",+ "systemApp": "App do sistema","tagline": "Um desktop GNU/Linux livre, rápido e seguro, construído sobre Debian e Wayland.","uptime": "Ligado há","version": "Versão {v}",diff --git a/assets/locales/pt/errors.json b/assets/locales/pt/errors.jsonindex 0543704..9c2e380 100644--- a/assets/locales/pt/errors.json+++ b/assets/locales/pt/errors.json@@ -558,5 +558,6 @@"proc.denied": "Sem permissão para parar este processo","proc.failed": "Não foi possível parar o processo","proc.badArgument": "Pedido de processo inválido",- "proc.notOwn": "Este processo pertence a outro usuário"+ "proc.notOwn": "Este processo pertence a outro usuário",+ "app.codeRefused": "O código deste app foi modificado e não foi carregado"}diff --git a/assets/locales/pt/shell.json b/assets/locales/pt/shell.jsonindex 019b067..8509066 100644--- a/assets/locales/pt/shell.json+++ b/assets/locales/pt/shell.json@@ -158,5 +158,15 @@"power.shuttingDown": "Desligando…","power.restart": "Reiniciar","power.shutdown": "Desligar",- "power.cancel": "Cancelar"+ "power.cancel": "Cancelar",+ "code.modifiedTitle": "Este componente do LordOS foi modificado e não foi carregado",+ "code.modifiedBody": "Ele não corresponde mais à cópia assinada do LordOS: {list}. Reinstale o LordOS para repará-lo.",+ "code.details": "Detalhes",+ "code.recovery.title": "Este componente do LordOS foi modificado e não foi carregado",+ "code.recovery.session": "O LordOS verifica o próprio código antes de executá-lo. Uma parte da área de trabalho não corresponde mais à cópia assinada, então não foi iniciada. Seus arquivos não foram tocados.",+ "code.recovery.greeter": "O LordOS verifica o próprio código antes de executá-lo. A tela de login não corresponde mais à cópia assinada, então não foi iniciada. Seus arquivos não foram tocados.",+ "code.recovery.app": "O LordOS verifica o próprio código antes de executá-lo. Este app não corresponde mais à cópia assinada, então não foi iniciado.",+ "code.recovery.fix": "Para reparar, reinstale o LordOS: sudo apt install --reinstall lordos",+ "code.recovery.details": "Não carregado:",+ "code.recovery.logout": "Encerrar sessão"}diff --git a/assets/locales/pt/store.json b/assets/locales/pt/store.jsonindex a873f35..dcbcbf4 100644--- a/assets/locales/pt/store.json+++ b/assets/locales/pt/store.json@@ -148,5 +148,6 @@"other": "Atualizações do Debian ({count})"},"updates.auto": "Procurar atualizações automaticamente",- "updates.autoHint": "Uma vez por dia, e só para avisar. Nada é instalado sem perguntar."+ "updates.autoHint": "Uma vez por dia, e só para avisar. Nada é instalado sem perguntar.",+ "systemApp": "App do sistema — parte do LordOS"}diff --git a/sdk/codesig.js b/sdk/codesig.jsnew file mode 100644index 0000000..2c9253a--- /dev/null+++ b/sdk/codesig.js@@ -0,0 +1,30 @@+// codesig.js — verified system code (docs/SIGNING.md, "Verified system code").+//+// codeStatus() → { state: 'verified' | 'development' | 'invalid' | 'unchecked', signed, release,+// version, files, ms, reason, refused: [{ path, reason }] }+// reportRefusedCode() one notification for each LordOS component that lord-server refused to load+// because it no longer matches the signed manifest (called by startShell)+//+// lord-server does the checking (server/src/sec/codesig.c); this only shows the result.+import { notify } from './notify.js';+import { t } from './i18n.js';+import { wm } from './windows.js';++export function codeStatus() {+ try { if (typeof lord.code?.status === 'function') return lord.code.status(); } catch (e) { /* app mode */ }+ return { state: 'unchecked', signed: false, release: false, version: '', files: 0, ms: 0, reason: '', refused: [] };+}++export function reportRefusedCode() {+ if (typeof lord.code?.takeRefused !== 'function') return;+ const list = lord.code.takeRefused();+ if (!list.length) return;+ console.warn(`code: not loaded (modified): ${list.map((r) => `${r.path} (${r.reason})`).join(', ')}`);+ notify({+ app: 'about',+ title: t('shell.code.modifiedTitle'),+ body: t('shell.code.modifiedBody', { list: list.map((r) => r.path).join(', ') }),+ sticky: true,+ actions: [{ id: 'about', label: t('shell.code.details'), run: () => wm.open('about') }],+ });+}diff --git a/sdk/index.js b/sdk/index.jsindex 8827657..573c7ff 100644--- a/sdk/index.js+++ b/sdk/index.js@@ -54,8 +54,10 @@ export { packages, packageList, refreshPackages, packageFile, loadWasm } from '.import { refreshPackages } from './packages.js';export {windows, wm, useWindows, configureWindows, getApp, listApps, isLiveSystem, appIdOf, workArea, workAreaOf, pointerWorkArea, appMenus, useAppMenus, windowTitle, appRegistry, appMenuClick,- registerBuiltinApp,+ registerBuiltinApp, isSystemApp,} from './windows.js';+export { codeStatus } from './codesig.js';+import { reportRefusedCode } from './codesig.js';export { WindowShell, WINDOW_EDGE } from './windowshell.jsx';export { term } from './terminal.js';export { clipboard, clipboardHistory, clipboardPanel, clipboardKind } from './clipboard.js';@@ -172,6 +174,7 @@ export function startShell(element) {startReminders(); // calendar and reminder alarms, with the apps closedmaybeStartTour(); // "Welcome to LordOS", the first timestartHardware(); // Night Light, idle timers, battery in the menu bar (hardware.jsx)+ setTimeout(reportRefusedCode, 800); // "This LordOS component was modified and was not loaded" (docs/SIGNING.md)}// Changing the language remounts the whole interface (windows, tabs anddiff --git a/sdk/windows.js b/sdk/windows.jsindex c671490..b47a8f0 100644--- a/sdk/windows.js+++ b/sdk/windows.js@@ -83,13 +83,17 @@ export function registerBuiltinApp(app) {}// Apps installed as a package (packages.js). They don't override the theme's.export function setPackageApps(list) {- packageApps = list.filter((a) => !themeApps.some((t) => t.id === a.id));+ // a package is never a system app, whatever its manifest says (only apps/ built into the theme)+ packageApps = list.filter((a) => !themeApps.some((t) => t.id === a.id)).map((a) => ({ ...a, system: false }));rebuild();}export const windowChrome = () => chrome;export const appIdOf = (id) => String(id ?? '').split('#')[0];export const getApp = (id) => registry.get(appIdOf(id));+// A system app: built into LordOS (apps/), verified with it and not removable (docs/SIGNING.md,+// "Verified system code"). Packages (.lpk) and Linux apps never are.+export const isSystemApp = (id) => { const a = getApp(id); return !!(a && a.system && !a.package); };// Live system (ISO): apps with "live": true in their manifest (the installer) only exist there.let live = null;export const isLiveSystem = () => {diff --git a/server/Makefile b/server/Makefileindex 832ff4f..0566685 100644--- a/server/Makefile+++ b/server/Makefile@@ -51,7 +51,7 @@ QJS_OBJ := $(patsubst %,build/qjs/%.o,quickjs libregexp libunicode cutils dtoa)MON_SRC := src/monitor/mon.c src/monitor/conn.c src/monitor/procctl.c src/monitor/proc_admin.c src/monitor/mmdb.c src/monitor/map.c src/ui/js_monitor.c# Media (src/media, docs/MEDIA.md): only the lord-server side. Only lord-media links FFmpeg.MEDIA_SRC := src/media/media.c src/media/mview.c src/media/capture.c src/media/annot.c src/media/maudio.c src/media/mpulse.c src/media/proto.c src/ui/js_media.c-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/restrict.c src/sec/appid.c src/sec/pwguard.c+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/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.cSRC := 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 \@@ -214,6 +214,12 @@ build/sandbox-test: tests/sandbox_test.c src/sec/sandbox.c src/sec/cgroup.c src/$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -D_GNU_SOURCE -o $@ tests/sandbox_test.c src/sec/sandbox.c src/sec/cgroup.c -lpthreadbuild/sign-test: tests/sign_test.c src/sec/json.c src/sec/sign.c src/lpk.c src/pkg/crypto.c build/obj/ui/stb.o $(wildcard src/sec/*.h) src/lpk.h src/pkg/crypto.h$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -DLORD_SIGN_TEST -o $@ tests/sign_test.c src/sec/json.c src/sec/sign.c src/lpk.c src/pkg/crypto.c build/obj/ui/stb.o -lm+# Verified system code: manifest parser, signature, per-file check, reading under the root (docs/SIGNING.md)+test: build/codesig-test+build/codesig-test: tests/codesig_test.c src/sec/codesig.c src/sec/json.c src/pkg/crypto.c src/sec/codesig.h src/sec/json.h src/pkg/crypto.h build/gen/codesig_build.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/codesig_test.c src/sec/codesig.c src/sec/json.c src/pkg/crypto.c+ ./$@ ../tools/release/lordos-release.pub.pem || { rm -f $@; exit 1; }# Clock time zones: TZif and POSIX rules against glibc (docs/SYSTEM.md)test: build/tzif-testbuild/tzif-test: tests/tzif_test.c src/ui/tzif.c src/ui/tzif.h@@ -431,6 +437,20 @@ build/gen/lord_version.h: FORCE'$(or $(LORD_VERSION),0.0.0)' '$(LORD_CHANNEL)' '$(shell printf %s '$(LORD_BUILD)' | tr -cd 'A-Za-z0-9.+~-')' > [email protected]build/obj/ui/js.o build/obj/ui/js_sys.o build/obj/term/pty.o: build/gen/lord_version.h+# Verified system code (src/sec/codesig.c, docs/SIGNING.md "Verified system code"). RELEASE=1: a+# release build, which only runs a manifest signed with the LordOS release key (no development mode).+# CODE_PUBKEY=<64 hex>: a TEST build that trusts a throwaway key instead of the release key (VM tests+# only; never for a release, and refused together with RELEASE=1).+RELEASE ?= 0+CODE_PUBKEY ?=+ifneq ($(and $(filter 1,$(RELEASE)),$(CODE_PUBKEY)),)+$(error CODE_PUBKEY is for test builds only, not with RELEASE=1)+endif+build/gen/codesig_build.h: FORCE+ @mkdir -p build/gen+ @{ [ '$(RELEASE)' = 1 ] && echo '#define LORD_CODE_RELEASE 1'; k=$$(printf %s '$(CODE_PUBKEY)' | tr -cd '0-9a-f'); [ -n "$$k" ] && printf '#define LORD_CODE_PUBKEY_HEX "%s"\n' "$$k"; true; } > [email protected]+build/obj/sec/codesig.o: build/gen/codesig_build.h.PHONY: FORCEFORCE:diff --git a/server/src/app/appclient.c b/server/src/app/appclient.cindex 7f64c15..5b13011 100644--- a/server/src/app/appclient.c+++ b/server/src/app/appclient.c@@ -11,6 +11,7 @@* Lo lanza lord-server (tercera excepción acotada a «el servidor no ejecuta comandos», ver* AGENTS.md): el único argumento es un id validado de un paquete instalado. */#include "app.h"+#include "../sec/codesig.h"#include "../ui/ui.h"#include "../ui/js.h"#include "../ui/js_sys.h"@@ -254,6 +255,9 @@ static JSValue f_win_close(JSContext *c, JSValueConst t, int argc, JSValueConst(void)t;int32_t key = -1;if (argc > 0) JS_ToInt32(c, &key, argv[0]);+ /* the app's code was refused (verified code): React tears its windows down, but the main one+ * stays to show the recovery screen */+ if (js_broker_code_refused() && key == 0) return JS_UNDEFINED;win_destroy(win_by_key(key));return JS_UNDEFINED;}@@ -459,13 +463,16 @@ static int manifest_pair(const char *dir, const char *key, int *w, int *h) {int app_main(const char *id, const char *theme_bundle, const char *fonts) {if (!lpk_valid_id(id)) { fprintf(stderr, "lord-server --app: invalid id\n"); return 2; }char dir[PATH_MAX];+ int sys;{/* <assets> = the parent of the fonts folder; a system app there wins over a user .lpk */char assets[PATH_MAX];snprintf(assets, sizeof assets, "%s", fonts);char *sl = strrchr(assets, '/');if (sl) *sl = 0;- if (app_package_dir(id, assets, dir, sizeof dir) < 0) {+ /* verified system code (sec/codesig.c): the manifest is read and checked before the sandbox */+ codesig_init(assets);+ if ((sys = app_package_dir(id, assets, dir, sizeof dir)) < 0) {fprintf(stderr, "lord-server --app: app '%s' is not installed\n", id);return 2;}@@ -498,7 +505,7 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {wl_display_roundtrip(dpy); /* first configure *//* Caja de arena: después de conectar Wayland y abrir el broker, antes de cargar la app. */- js_broker_set_pkgdir(dir); /* la carpeta del paquete, antes de la caja de arena */+ js_broker_set_pkgdir(dir, sys); /* the package folder, before the sandbox */int net = js_broker_wants_network(); /* del manifest + el permiso *//* el «app host» (React + SDK) es código del SO; su carpeta es de solo lectura */char hostdir[PATH_MAX];@@ -511,7 +518,10 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {SandboxConfig sb = { .id = id, .pkg_dir = dir, .data_dir = data, .runtime_dir = getenv("XDG_RUNTIME_DIR"), .ro_extra = ro, .network = net };sandbox_apply(&sb);- if (js_init_app(theme_bundle, id)) { fprintf(stderr, "lord-server --app: could not load the app\n"); return 1; }+ int jr = js_init_app(theme_bundle, id);+ if (jr == JS_REFUSED) fprintf(stderr, "lord-server --app: the app host was modified and was not loaded (recovery screen)\n");+ else if (jr) { fprintf(stderr, "lord-server --app: could not load the app\n"); return 1; }+ int recovered = jr == JS_REFUSED;int wfd = wl_display_get_fd(dpy);double start = now_ms();@@ -520,6 +530,13 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {double delay = -1;for (int i = 0; i < 64; i++) { delay = js_tick(now_ms()); if (delay != 0) break; }if (js_wants_frame()) { js_frame(now_ms()); }+ /* the system app's own code was refused while the host loaded it: show why (outside JS) */+ if (!recovered && js_broker_code_refused()) {+ recovered = 1;+ js_app_recovery();+ for (int i = 0; i < MAX_WINS; i++) if (wins[i].used) { if (wins[i].key == 0) wins[i].node = 0; wins[i].need_render = 1; }+ continue;+ }/* one node tree for all windows: any change repaints every window (cheap: apps are small) */if (ui.dirty) { for (int i = 0; i < MAX_WINS; i++) if (wins[i].used) wins[i].need_render = 1; ui.dirty = 0; }/* a window waiting for its frame callback or a free buffer renders when those arrive */diff --git a/server/src/main.c b/server/src/main.cindex cb1502f..637b746 100644--- a/server/src/main.c+++ b/server/src/main.c@@ -48,6 +48,10 @@#include "hw/hw.h"#include "hw/modes.h"#include "outputs.h"+#include "sec/codesig.h"++#include <libgen.h>+#include <limits.h>#include <errno.h>#include <fcntl.h>@@ -1329,6 +1333,77 @@ static void render_frame(Server *s) {}/* Cambio de tema pedido desde JS (lord.themes.use): se descarta el contexto JS y el árbol. */+/* Loads the first theme that passes the verified-code check (sec/codesig.c): the one asked for,+ * then the default and the classic theme next to it; if none can be loaded because the system code+ * was modified, the built-in recovery screen (never a blank screen). The login screen goes straight+ * to the recovery screen. `used` gets the bundle that is running. 0 if something is on screen. */+static int start_theme(const char *theme, int greeter, char *used, size_t n) {+ snprintf(used, n, "%s", theme);+ int r = js_init(theme);+ if (r == 0) return 0;+ if (r != JS_REFUSED && codesig_state() != CODE_INVALID) return -1;+ if (r == JS_REFUSED) snprintf(ui.theme_failed, sizeof ui.theme_failed, "%s", theme); /* lord.themes.use won't go back to it */+ if (!greeter && codesig_state() != CODE_INVALID) {+ char root[PATH_MAX], tmp[PATH_MAX];+ snprintf(tmp, sizeof tmp, "%s", theme);+ char *d = dirname(tmp); /* .../themes/<id> */+ snprintf(root, sizeof root, "%s", d);+ snprintf(tmp, sizeof tmp, "%s", root);+ snprintf(root, sizeof root, "%s", dirname(tmp)); /* .../themes */+ static const char *const fallback[] = { "default", "classic" };+ for (size_t i = 0; i < sizeof fallback / sizeof fallback[0]; i++) {+ char alt[sizeof ui.theme_request];+ if ((size_t)snprintf(alt, sizeof alt, "%.*s/%s/theme.bundle.js", (int)(sizeof alt - 32), root, fallback[i]) >= sizeof alt) continue;+ if (!strcmp(alt, theme) || access(alt, R_OK)) continue;+ js_shutdown();+ ui_reset();+ fprintf(stderr, "lord-server: theme %s was not loaded, trying %s\n", theme, alt);+ if (js_init(alt) == 0) { snprintf(used, n, "%s", alt); return 0; }+ }+ }+ js_shutdown();+ ui_reset();+ return js_init_recovery(greeter);+}++/* lord-server --check-code [root]: checks the signed manifest and every file it lists, the way a+ * session would load them (docs/SIGNING.md, "Verified system code"). Used by tools/iso/mkdeb.sh+ * and for troubleshooting. Exit 0 when everything matches; 1 otherwise; with --require-signed, a+ * development (unsigned) manifest also fails. */+static int check_code(int argc, char **argv) {+ const char *root = NULL;+ int need_signed = codesig_release_build();+ for (int i = 2; i < argc; i++) {+ if (!strcmp(argv[i], "--require-signed")) need_signed = 1;+ else root = argv[i];+ }+ char exe[PATH_MAX], def[PATH_MAX];+ if (!root) { /* next to this binary: <root>/bin/lord-server */+ ssize_t k = readlink("/proc/self/exe", exe, sizeof exe - 1);+ if (k <= 0) return 1;+ exe[k] = 0;+ char *bin = dirname(exe); /* <root>/bin (dirname writes into exe) */+ snprintf(def, sizeof def, "%s/..", bin);+ root = def;+ }+ CodeState st = codesig_init_root(root, codesig_key(), need_signed);+ const CodeManifest *m = codesig_manifest();+ printf("root: %s\nstate: %s%s%s\nbuild: %s\n", codesig_root(), codesig_state_name(st), codesig_reason()[0] ? " — " : "",+ codesig_reason(), codesig_release_build() ? "release" : "development");+ int bad = st == CODE_INVALID || !m;+ for (int i = 0; m && i < m->nfiles; i++) {+ char path[PATH_MAX * 2], why[160];+ snprintf(path, sizeof path, "%s/%s", codesig_root(), m->files[i].path);+ size_t len;+ char *b = codesig_load(path, CODE_FILE_MAX, &len, why, sizeof why);+ printf("%-8s %s%s%s\n", b ? "ok" : "FAILED", m->files[i].path, b ? "" : ": ", b ? "" : why);+ if (!b) bad = 1;+ free(b);+ }+ printf("%s: %d file(s), %.1f ms\n", bad ? "FAILED" : "ok", m ? m->nfiles : 0, codesig_ms());+ return bad ? 1 : 0;+}+static void switch_theme(const char *current) {char path[sizeof ui.theme_request];snprintf(path, sizeof path, "%s", ui.theme_request);@@ -1376,6 +1451,7 @@ int main(int argc, char **argv) {sigaction(SIGPIPE, &pipe_sa, NULL);/* guardián de una sesión de terminal (ver term/hold.c): no abre pantalla ni input */if (argc > 1 && !strcmp(argv[1], "--term-holder")) return hold_main(argc, argv);+ if (argc > 1 && !strcmp(argv[1], "--check-code")) return check_code(argc, argv);/* «modo app»: lord-server --app <id> corre una app .lpk como cliente Wayland aislado* (app/appclient.c). El id ya viene validado del propio lord-server (no de JS). */if (argc >= 3 && !strcmp(argv[1], "--app")) {@@ -1502,11 +1578,8 @@ int main(int argc, char **argv) {remote_refresh, remote_resize, remote_greeter, display_attach, display_detach,remote_scroll, remote_pinch, remote_input_add };if (ok && mirror_start(s.W, s.H, &mirror_in)) fprintf(stderr, "lord-server: no remote desktop (socket)\n");- if (ok) {- char path[1024];- snprintf(path, sizeof path, "%s", theme);- ok = js_init(path) == 0;- }+ char current[sizeof ui.theme_request];+ if (ok) ok = start_theme(theme, s.greeter, current, sizeof current) == 0;if (!ok) {input_close(&s.input);if (!s.headless) kms_close(K0(&s));@@ -1522,8 +1595,6 @@ int main(int argc, char **argv) {keylag_init(s.greeter); /* key latency trace, only with LORD_INPUT_DEBUG=1 (keylag.h) */int sfd = signalfd(-1, &mask, SFD_CLOEXEC);- char current[sizeof ui.theme_request];- snprintf(current, sizeof current, "%s", theme);double start = now_ms();while (!s.quit && !ui.quit_requested) {if (ui.theme_request[0]) {diff --git a/server/src/pkg/crypto.c b/server/src/pkg/crypto.cindex 4c5e95c..b27fb76 100644--- a/server/src/pkg/crypto.c+++ b/server/src/pkg/crypto.c@@ -6,6 +6,7 @@* no secrets, so it doesn't need to be constant-time. */#include "crypto.h"+#include <stdlib.h>#include <string.h>/* ---- SHA-256 ---- */@@ -31,22 +32,96 @@ static const uint32_t K256[64] = {#define ROR32(x, n) (((x) >> (n)) | ((x) << (32 - (n))))-static void sha256_block(Sha256 *s, const uint8_t *p) {- uint32_t w[64];+/* Portable C: the 64 rounds unrolled 8 at a time (the variables rotate instead of being moved),+ * the message schedule kept in 16 words. */+#define S256_CH(x, y, z) (((x) & (y)) ^ (~(x) & (z)))+#define S256_MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))+#define S256_E0(x) (ROR32(x, 2) ^ ROR32(x, 13) ^ ROR32(x, 22))+#define S256_E1(x) (ROR32(x, 6) ^ ROR32(x, 11) ^ ROR32(x, 25))+#define S256_S0(x) (ROR32(x, 7) ^ ROR32(x, 18) ^ ((x) >> 3))+#define S256_S1(x) (ROR32(x, 17) ^ ROR32(x, 19) ^ ((x) >> 10))+#define S256_R(a, b, c, d, e, f, g, h, i) do { \+ uint32_t t1_ = h + S256_E1(e) + S256_CH(e, f, g) + K256[i] + w[(i) & 15]; \+ d += t1_; h = t1_ + S256_E0(a) + S256_MAJ(a, b, c); } while (0)++static void sha256_block_c(uint32_t st[8], const uint8_t *p) {+ uint32_t w[16];for (int i = 0; i < 16; i++) w[i] = (uint32_t)p[4 * i] << 24 | (uint32_t)p[4 * i + 1] << 16 | (uint32_t)p[4 * i + 2] << 8 | p[4 * i + 3];- for (int i = 16; i < 64; i++) {- uint32_t s0 = ROR32(w[i - 15], 7) ^ ROR32(w[i - 15], 18) ^ (w[i - 15] >> 3);- uint32_t s1 = ROR32(w[i - 2], 17) ^ ROR32(w[i - 2], 19) ^ (w[i - 2] >> 10);- w[i] = w[i - 16] + s0 + w[i - 7] + s1;+ uint32_t a = st[0], b = st[1], c = st[2], d = st[3], e = st[4], f = st[5], g = st[6], h = st[7];+ for (int i = 0; i < 64; i += 8) {+ if (i >= 16)+ for (int j = i; j < i + 8; j++)+ w[j & 15] += S256_S1(w[(j - 2) & 15]) + w[(j - 7) & 15] + S256_S0(w[(j - 15) & 15]);+ S256_R(a, b, c, d, e, f, g, h, i);+ S256_R(h, a, b, c, d, e, f, g, i + 1);+ S256_R(g, h, a, b, c, d, e, f, i + 2);+ S256_R(f, g, h, a, b, c, d, e, i + 3);+ S256_R(e, f, g, h, a, b, c, d, i + 4);+ S256_R(d, e, f, g, h, a, b, c, i + 5);+ S256_R(c, d, e, f, g, h, a, b, i + 6);+ S256_R(b, c, d, e, f, g, h, a, i + 7);}- uint32_t a = s->h[0], b = s->h[1], c = s->h[2], d = s->h[3], e = s->h[4], f = s->h[5], g = s->h[6], h = s->h[7];- for (int i = 0; i < 64; i++) {- uint32_t t1 = h + (ROR32(e, 6) ^ ROR32(e, 11) ^ ROR32(e, 25)) + ((e & f) ^ (~e & g)) + K256[i] + w[i];- uint32_t t2 = (ROR32(a, 2) ^ ROR32(a, 13) ^ ROR32(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));- h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;+ st[0] += a; st[1] += b; st[2] += c; st[3] += d;+ st[4] += e; st[5] += f; st[6] += g; st[7] += h;+}++/* The CPU's own SHA-256 instructions on aarch64, when it has them (checked once at run time: the+ * ARMv8 cryptography extension of the Raspberry Pi 5's Cortex-A76; the Pi 4 has none). Same results+ * bit for bit: sign_test and codesig_test run the NIST vectors through the path the machine takes,+ * and LORD_SHA256_C=1 forces the C one to compare. x86-64 uses the C code: its SHA extensions are+ * not used until they can be tested on such a CPU. */+typedef void (*Sha256Blocks)(uint32_t st[8], const uint8_t *p, size_t n);+static void sha256_blocks_c(uint32_t st[8], const uint8_t *p, size_t n) { for (; n; n--, p += 64) sha256_block_c(st, p); }++#if defined(__aarch64__) && (defined(__GNUC__) || defined(__clang__))+#include <arm_neon.h>+#include <sys/auxv.h>+#ifndef HWCAP_SHA2+#define HWCAP_SHA2 (1 << 6)+#endif+__attribute__((target("+crypto")))+static void sha256_blocks_arm(uint32_t st[8], const uint8_t *p, size_t n) {+ uint32x4_t s0 = vld1q_u32(&st[0]), s1 = vld1q_u32(&st[4]);+ for (; n; n--, p += 64) {+ uint32x4_t abcd = s0, efgh = s1, m[4];+ for (int i = 0; i < 4; i++) m[i] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(p + 16 * i)));+ for (int g = 0; g < 16; g++) {+ uint32x4_t w = vaddq_u32(m[g & 3], vld1q_u32(&K256[4 * g]));+ if (g < 12) m[g & 3] = vsha256su1q_u32(vsha256su0q_u32(m[g & 3], m[(g + 1) & 3]), m[(g + 2) & 3], m[(g + 3) & 3]);+ uint32x4_t t = s0;+ s0 = vsha256hq_u32(s0, s1, w);+ s1 = vsha256h2q_u32(s1, t, w);+ }+ s0 = vaddq_u32(s0, abcd);+ s1 = vaddq_u32(s1, efgh);}- s->h[0] += a; s->h[1] += b; s->h[2] += c; s->h[3] += d;- s->h[4] += e; s->h[5] += f; s->h[6] += g; s->h[7] += h;+ vst1q_u32(&st[0], s0);+ vst1q_u32(&st[4], s1);+}+static int sha256_hw(void) { return (getauxval(AT_HWCAP) & HWCAP_SHA2) != 0; }+#define SHA256_HW sha256_blocks_arm+#endif++static Sha256Blocks sha256_blocks;+static void sha256_pick(void) {+ sha256_blocks = sha256_blocks_c;+#ifdef SHA256_HW+ if (sha256_hw() && !getenv("LORD_SHA256_C")) sha256_blocks = SHA256_HW; /* LORD_SHA256_C=1: tests */+#endif+}+static void sha256_block(Sha256 *s, const uint8_t *p) {+ if (!sha256_blocks) sha256_pick();+ sha256_blocks(s->h, p, 1);+}+/* Tests: 0 forces the C code, 1 goes back to the best path for this CPU. */+void sha256_select(int hw) {+ sha256_pick();+ if (!hw) sha256_blocks = sha256_blocks_c;+}+/* 1 if the CPU's SHA-256 instructions are in use (for the measurements in docs/SIGNING.md). */+int sha256_accelerated(void) {+ if (!sha256_blocks) sha256_pick();+ return sha256_blocks != sha256_blocks_c;}void sha256_init(Sha256 *s) {@@ -70,7 +145,12 @@ void sha256_update(Sha256 *s, const void *data, size_t len) {sha256_block(s, s->buf);s->n = 0;}- for (; len >= 64; p += 64, len -= 64) sha256_block(s, p);+ if (len >= 64) {+ if (!sha256_blocks) sha256_pick();+ sha256_blocks(s->h, p, len / 64);+ p += len & ~(size_t)63;+ len &= 63;+ }memcpy(s->buf, p, len);s->n = len;}diff --git a/server/src/pkg/crypto.h b/server/src/pkg/crypto.hindex 5cbbc11..383504b 100644--- a/server/src/pkg/crypto.h+++ b/server/src/pkg/crypto.h@@ -14,6 +14,8 @@ void sha256_init(Sha256 *s);void sha256_update(Sha256 *s, const void *data, size_t len);void sha256_final(Sha256 *s, uint8_t out[32]);void sha256(const void *data, size_t len, uint8_t out[32]);+void sha256_select(int hw); /* tests: 0 = C code only, 1 = best for this CPU */+int sha256_accelerated(void); /* 1: the CPU's SHA-256 instructions are used (x86 SHA, ARMv8 crypto) */void sha512_init(Sha512 *s);void sha512_update(Sha512 *s, const void *data, size_t len);void sha512_final(Sha512 *s, uint8_t out[64]);diff --git a/server/src/sec/codesig.c b/server/src/sec/codesig.cnew file mode 100644index 0000000..3b0c8cc--- /dev/null+++ b/server/src/sec/codesig.c@@ -0,0 +1,374 @@+/* codesig.c — verified system code: the signed manifest of LordOS's own JavaScript and the+ * check of each file at load time (see codesig.h and docs/SIGNING.md, "Verified system code"). */+#include "codesig.h"+#include "json.h"+#include "../pkg/crypto.h"+#include "codesig_build.h" /* build/gen: RELEASE=1 and CODE_PUBKEY (Makefile) */++#include <errno.h>+#include <fcntl.h>+#include <limits.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <sys/syscall.h>+#include <time.h>+#include <unistd.h>+#ifdef SYS_openat2+#include <linux/openat2.h>+#endif++/* tools/release/lordos-release.pub.pem: the last 32 bytes of its DER (SubjectPublicKeyInfo).+ * codesig_test checks that they match the PEM file. */+const uint8_t codesig_release_key[32] = {+ 0xf1, 0xca, 0xb0, 0x0f, 0x31, 0xfe, 0x65, 0x53, 0x1d, 0x06, 0xa3, 0x63, 0x0b, 0x7d, 0x78, 0xd5,+ 0xd9, 0xa8, 0xde, 0x07, 0x07, 0xf0, 0xf5, 0xad, 0xf3, 0xc2, 0x3e, 0x44, 0x4f, 0x5d, 0x39, 0xa0,+};++static void seterr(char *err, size_t n, const char *fmt, const char *a) {+ if (err && n) snprintf(err, n, fmt, a ? a : "");+}++/* ---- base64 ---- */++static int b64v(int c) {+ if (c >= 'A' && c <= 'Z') return c - 'A';+ if (c >= 'a' && c <= 'z') return c - 'a' + 26;+ if (c >= '0' && c <= '9') return c - '0' + 52;+ if (c == '+') return 62;+ if (c == '/') return 63;+ return -1;+}++int codesig_sig_decode(const char *text, size_t len, uint8_t out[64]) {+ while (len && (text[len - 1] == '\n' || text[len - 1] == '\r')) len--;+ /* 64 bytes = 86 characters + "==" */+ if (len != 88 || text[86] != '=' || text[87] != '=') return -1;+ uint32_t acc = 0;+ int bits = 0;+ size_t o = 0;+ for (size_t i = 0; i < 86; i++) {+ int v = b64v((unsigned char)text[i]);+ if (v < 0) return -1;+ acc = (acc << 6) | (uint32_t)v;+ bits += 6;+ if (bits >= 8) {+ bits -= 8;+ if (o >= 64) return -1;+ out[o++] = (uint8_t)(acc >> bits);+ }+ }+ /* the 4 leftover bits must be zero (one encoding per signature) */+ if (o != 64 || bits != 4 || (acc & 0xf)) return -1;+ return 0;+}++/* ---- the manifest ---- */++static int valid_rel(const char *p) {+ size_t n = strlen(p);+ if (!n || n > CODE_PATH_MAX || p[0] == '/' || p[n - 1] == '/') return 0;+ const char *seg = p;+ for (size_t i = 0; i <= n; i++) {+ char c = p[i];+ if (c == '/' || c == 0) {+ size_t sl = (size_t)(p + i - seg);+ if (sl == 0 || (sl == 1 && seg[0] == '.') || (sl == 2 && seg[0] == '.' && seg[1] == '.')) return 0;+ seg = p + i + 1;+ continue;+ }+ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||+ c == '.' || c == '_' || c == '-' || c == '+')) return 0;+ }+ return 1;+}++static int lower_hex64(const char *s) {+ if (!s || strlen(s) != 64) return 0;+ for (int i = 0; i < 64; i++)+ if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return 0;+ return 1;+}++void codesig_free(CodeManifest *m) {+ if (!m) return;+ free(m->files);+ memset(m, 0, sizeof *m);+}++int codesig_parse(const char *json, size_t len, const char *sig, size_t siglen, const uint8_t pub[32],+ CodeManifest *out, char *err, size_t errlen) {+ memset(out, 0, sizeof *out);+ if (!json || len == 0 || len > CODE_MANIFEST_MAX) { seterr(err, errlen, "manifest size%s", NULL); return -1; }+ /* the signature first: nothing of an unsigned text is parsed when a signature is expected */+ if (sig) {+ uint8_t s[64];+ if (codesig_sig_decode(sig, siglen, s)) { seterr(err, errlen, "signature is not 64 bytes of base64%s", NULL); return -1; }+ if (!ed25519_verify(pub, s, (const uint8_t *)json, len)) { seterr(err, errlen, "bad signature%s", NULL); return -1; }+ out->signed_ok = 1;+ }+ JDoc d;+ char jerr[96];+ if (json_parse(json, len, &d, jerr, sizeof jerr)) { seterr(err, errlen, "manifest: %s", jerr); return -1; }+ int rc = -1;+ const JVal *r = d.root;+ const JVal *files = json_get(r, "files");+ const char *kind = json_str(r, "kind"), *ver = json_str(r, "version");+ if (!r || r->type != J_OBJ || json_num(r, "format", 0) != 1) { seterr(err, errlen, "manifest: format is not 1%s", NULL); goto out; }+ if (!kind || strcmp(kind, CODE_KIND)) { seterr(err, errlen, "manifest: kind is not " CODE_KIND "%s", NULL); goto out; }+ if (!ver || strlen(ver) >= sizeof out->version) { seterr(err, errlen, "manifest: bad version%s", NULL); goto out; }+ if (!files || files->type != J_ARR || files->len > CODE_FILES_MAX) { seterr(err, errlen, "manifest: bad file list%s", NULL); goto out; }+ snprintf(out->version, sizeof out->version, "%s", ver);+ out->files = calloc(files->len ? files->len : 1, sizeof *out->files);+ if (!out->files) { seterr(err, errlen, "out of memory%s", NULL); goto out; }+ for (const JVal *f = files->kid; f; f = f->next) {+ const char *p = json_str(f, "path"), *h = json_str(f, "sha256");+ const JVal *sz = json_get(f, "size");+ if (f->type != J_OBJ || !p || !valid_rel(p)) { seterr(err, errlen, "manifest: bad path %s", p); goto out; }+ if (!sz || sz->type != J_NUM || sz->num < 0 || sz->num > CODE_FILE_MAX || sz->num != (double)(uint64_t)sz->num) {+ seterr(err, errlen, "manifest: bad size for %s", p); goto out;+ }+ if (!lower_hex64(h)) { seterr(err, errlen, "manifest: bad sha256 for %s", p); goto out; }+ if (out->nfiles && strcmp(out->files[out->nfiles - 1].path, p) >= 0) { seterr(err, errlen, "manifest: paths not sorted or repeated at %s", p); goto out; }+ CodeFile *cf = &out->files[out->nfiles++];+ snprintf(cf->path, sizeof cf->path, "%s", p);+ cf->size = (uint64_t)sz->num;+ hex_decode(h, cf->sha256, 32);+ }+ rc = 0;+out:+ json_free(&d);+ if (rc) codesig_free(out);+ return rc;+}++const CodeFile *codesig_find(const CodeManifest *m, const char *rel) {+ int lo = 0, hi = m ? m->nfiles - 1 : -1;+ while (lo <= hi) {+ int mid = (lo + hi) / 2, c = strcmp(m->files[mid].path, rel);+ if (!c) return &m->files[mid];+ if (c < 0) lo = mid + 1; else hi = mid - 1;+ }+ return NULL;+}++int codesig_check_buf(const CodeManifest *m, const char *rel, const void *buf, size_t len, char *why, size_t n) {+ const CodeFile *f = codesig_find(m, rel);+ if (!f) { seterr(why, n, "not listed in the manifest%s", NULL); return -1; }+ if (f->size != (uint64_t)len) { seterr(why, n, "size differs from the manifest%s", NULL); return -1; }+ uint8_t h[32];+ sha256(buf, len, h);+ if (memcmp(h, f->sha256, 32)) { seterr(why, n, "SHA-256 differs from the manifest%s", NULL); return -1; }+ return 0;+}++/* ---- the process's state ---- */++static struct {+ CodeState state;+ char root[PATH_MAX];+ int rootfd;+ int release;+ int have_manifest;+ CodeManifest m;+ char reason[160];+ double ms;+ CodeRefusal refused[16];+ int nrefused;+} cs = { .state = CODE_UNCHECKED, .rootfd = -1 };++static double now_ms(void) {+ struct timespec t;+ clock_gettime(CLOCK_MONOTONIC, &t);+ return t.tv_sec * 1000.0 + t.tv_nsec / 1e6;+}++int codesig_release_build(void) {+#ifdef LORD_CODE_RELEASE+ return 1;+#else+ return 0;+#endif+}++/* Reads a whole regular file from fd: at most max bytes; NULL if bigger, not regular or unreadable. */+static char *read_fd(int fd, size_t max, size_t *len) {+ struct stat st;+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size < 0 || (uint64_t)st.st_size > max) return NULL;+ size_t cap = (size_t)st.st_size + 1, n = 0;+ char *buf = malloc(cap + 1);+ if (!buf) return NULL;+ for (;;) {+ ssize_t r = read(fd, buf + n, cap - n);+ if (r < 0) { if (errno == EINTR) continue; free(buf); return NULL; }+ if (r == 0) break;+ n += (size_t)r;+ if (n == cap) { free(buf); return NULL; } /* it grew while being read */+ }+ buf[n] = 0;+ *len = n;+ return buf;+}++/* Opens rel under the root without leaving it (no "..", no absolute links, no /proc magic). */+static int open_beneath(const char *rel) {+#ifdef SYS_openat2+ struct open_how how = { .flags = O_RDONLY | O_CLOEXEC | O_NOCTTY, .resolve = RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS };+ int fd = (int)syscall(SYS_openat2, cs.rootfd, rel, &how, sizeof how);+ if (fd >= 0 || errno != ENOSYS) return fd;+#endif+ /* kernels before 5.6: rel is already validated (no ".."); no links at the last step */+ return openat(cs.rootfd, rel, O_RDONLY | O_CLOEXEC | O_NOCTTY | O_NOFOLLOW);+}++static char *read_beneath(const char *rel, size_t max, size_t *len) {+ int fd = open_beneath(rel);+ if (fd < 0) return NULL;+ char *b = read_fd(fd, max, len);+ close(fd);+ return b;+}++static void reset(void) {+ codesig_free(&cs.m);+ if (cs.rootfd >= 0) close(cs.rootfd);+ cs.rootfd = -1;+ cs.have_manifest = 0;+ cs.root[0] = cs.reason[0] = 0;+ cs.nrefused = 0;+ cs.ms = 0;+ cs.state = CODE_UNCHECKED;+}++CodeState codesig_init_root(const char *root, const uint8_t pub[32], int release) {+ reset();+ double t0 = now_ms();+ cs.release = release;+ if (!root || !realpath(root, cs.root) || (cs.rootfd = open(cs.root, O_RDONLY | O_DIRECTORY | O_CLOEXEC)) < 0) {+ snprintf(cs.reason, sizeof cs.reason, "no LordOS folder");+ cs.root[0] = 0;+ cs.state = release ? CODE_INVALID : CODE_DEVELOPMENT;+ goto done;+ }+ size_t mlen = 0, slen = 0;+ char *mtext = read_beneath(CODE_MANIFEST, CODE_MANIFEST_MAX, &mlen);+ char *stext = read_beneath(CODE_SIGNATURE, 4096, &slen);+ if (!mtext) {+ snprintf(cs.reason, sizeof cs.reason, "no %s", CODE_MANIFEST);+ cs.state = release ? CODE_INVALID : CODE_DEVELOPMENT;+ } else if (!stext && release) {+ snprintf(cs.reason, sizeof cs.reason, "unsigned manifest in a release build");+ cs.state = CODE_INVALID;+ } else {+ char err[128];+ if (codesig_parse(mtext, mlen, stext, slen, pub, &cs.m, err, sizeof err)) {+ snprintf(cs.reason, sizeof cs.reason, "%s", err);+ cs.state = CODE_INVALID;+ } else {+ cs.have_manifest = 1;+ cs.state = cs.m.signed_ok ? CODE_VERIFIED : CODE_DEVELOPMENT;+ if (!cs.m.signed_ok) snprintf(cs.reason, sizeof cs.reason, "unsigned manifest");+ }+ }+ free(mtext);+ free(stext);+done:+ cs.ms += now_ms() - t0;+ fprintf(stderr, "code: %s (%s%s%s) in %.2f ms, %d files listed\n", codesig_state_name(cs.state), cs.root[0] ? cs.root : "-",+ cs.reason[0] ? ": " : "", cs.reason, cs.ms, cs.have_manifest ? cs.m.nfiles : 0);+ return cs.state;+}++const uint8_t *codesig_key(void) {+#ifdef LORD_CODE_PUBKEY_HEX+ /* a test build with a throwaway key (make CODE_PUBKEY=<hex>, docs/SIGNING.md); never a release */+ static uint8_t k[32];+ static int done;+ if (!done) { done = 1; if (hex_decode(LORD_CODE_PUBKEY_HEX, k, 32)) memset(k, 0, 32); }+ return k;+#else+ return codesig_release_key;+#endif+}++CodeState codesig_init(const char *assets_dir) {+ if (cs.state != CODE_UNCHECKED) return cs.state;+ char root[PATH_MAX];+ if (!assets_dir || (size_t)snprintf(root, sizeof root, "%s/..", assets_dir) >= sizeof root) root[0] = 0;+ return codesig_init_root(root[0] ? root : NULL, codesig_key(), codesig_release_build());+}++CodeState codesig_state(void) { return cs.state; }+const char *codesig_root(void) { return cs.root; }+const char *codesig_reason(void) { return cs.reason; }+const CodeManifest *codesig_manifest(void) { return cs.have_manifest ? &cs.m : NULL; }+double codesig_ms(void) { return cs.ms; }+int codesig_refused_count(void) { return cs.nrefused; }+CodeRefusal *codesig_refused(int i) { return i >= 0 && i < cs.nrefused ? &cs.refused[i] : NULL; }++const char *codesig_state_name(CodeState s) {+ switch (s) {+ case CODE_VERIFIED: return "verified";+ case CODE_DEVELOPMENT: return "development";+ case CODE_INVALID: return "invalid";+ default: return "unchecked";+ }+}++static void refuse(const char *rel, const char *why) {+ fprintf(stderr, "code: REFUSED %s: %s — this LordOS component was modified and was not loaded\n", rel, why);+ for (int i = 0; i < cs.nrefused; i++) if (!strcmp(cs.refused[i].path, rel)) return;+ if (cs.nrefused >= (int)(sizeof cs.refused / sizeof cs.refused[0])) return;+ CodeRefusal *r = &cs.refused[cs.nrefused++];+ snprintf(r->path, sizeof r->path, "%s", rel);+ snprintf(r->reason, sizeof r->reason, "%s", why);+ r->reported = 0;+}++char *codesig_load(const char *path, size_t max, size_t *len, char *why, size_t whylen) {+ char wbuf[128];+ if (!why) { why = wbuf; whylen = sizeof wbuf; }+ why[0] = 0;+ if (cs.state == CODE_UNCHECKED) codesig_init(NULL);+ double t0 = now_ms();+ char real[PATH_MAX];+ const char *rel = NULL;+ size_t rl = strlen(cs.root);+ if (cs.root[0] && realpath(path, real) && !strncmp(real, cs.root, rl) && real[rl] == '/') rel = real + rl + 1;+ char *buf = NULL;+ size_t n = 0;+ if (cs.state == CODE_INVALID) {+ snprintf(why, whylen, "the system code manifest is not valid (%s)", cs.reason);+ refuse(rel ? rel : path, why);+ return NULL;+ }+ if (!rel || !valid_rel(rel)) {+ /* outside LordOS's folder: only a development build without a signed manifest runs it */+ if (cs.state != CODE_DEVELOPMENT) { snprintf(why, whylen, "not part of LordOS's system code"); refuse(path, why); return NULL; }+ int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOCTTY);+ if (fd >= 0) { buf = read_fd(fd, max, &n); close(fd); }+ if (!buf) { snprintf(why, whylen, "cannot read it"); return NULL; }+ fprintf(stderr, "code: %s loaded unchecked (outside %s, development build)\n", path, cs.root[0] ? cs.root : "the LordOS folder");+ *len = n;+ return buf;+ }+ buf = read_beneath(rel, max, &n);+ if (!buf) { snprintf(why, whylen, "cannot read it"); return NULL; } /* missing: not a modification */+ if (!cs.have_manifest) {+ /* development build without a manifest: runs, flagged in About */+ cs.ms += now_ms() - t0;+ *len = n;+ return buf;+ }+ if (codesig_check_buf(&cs.m, rel, buf, n, why, whylen)) {+ free(buf);+ refuse(rel, why);+ return NULL;+ }+ double dt = now_ms() - t0;+ cs.ms += dt;+ fprintf(stderr, "code: %s %s (%zu KB) checked in %.2f ms\n", cs.state == CODE_VERIFIED ? "verified" : "hash ok", rel, n / 1024, dt);+ *len = n;+ return buf;+}diff --git a/server/src/sec/codesig.h b/server/src/sec/codesig.hnew file mode 100644index 0000000..02f1259--- /dev/null+++ b/server/src/sec/codesig.h@@ -0,0 +1,98 @@+/* codesig.h — verified system code (0.8.2, "System apps immutable", phase 1; see docs/SIGNING.md,+ * "Verified system code").+ *+ * The JavaScript that LordOS runs as its own code — the theme bundles (the shell, the SDK, the+ * runtime and every native app), the login screen, the app host of isolated apps and the system+ * apps in assets/sysapps — is listed with its size and SHA-256 in <root>/code-manifest.json, and+ * that file is signed with the LordOS release key (Ed25519) in <root>/code-manifest.sig (base64 of+ * the 64-byte signature over the exact bytes of the manifest). <root> is the folder that holds+ * assets/ and themes/ (/usr/lib/lordos when installed).+ *+ * lord-server checks the signature once per process, with the public key compiled in, and the hash+ * of every file before it runs it: codesig_load() reads the file from one descriptor (opened under+ * <root>, never following a link out of it), hashes exactly the bytes it read and returns those same+ * bytes, so what is checked is what runs (no TOCTOU).+ *+ * States:+ * VERIFIED signed manifest, signature good: only listed files with the right hash load.+ * DEVELOPMENT unsigned manifest (or none) in a development build: hashes are still checked when+ * there is a manifest; About shows "Development build". A release build+ * (make RELEASE=1, LORD_CODE_RELEASE) never accepts this state.+ * INVALID bad signature, broken manifest, or an unsigned/missing one in a release build:+ * nothing loads and the session shows the recovery screen. */+#ifndef LORD_SEC_CODESIG_H+#define LORD_SEC_CODESIG_H++#include <stddef.h>+#include <stdint.h>++#define CODE_MANIFEST "code-manifest.json"+#define CODE_SIGNATURE "code-manifest.sig"+#define CODE_KIND "lordos-system-code"+#define CODE_MANIFEST_MAX (1u << 20) /* bytes */+#define CODE_FILES_MAX 4096+#define CODE_FILE_MAX (64u << 20) /* one bundle */+#define CODE_PATH_MAX 200++typedef enum { CODE_UNCHECKED, CODE_VERIFIED, CODE_DEVELOPMENT, CODE_INVALID } CodeState;++typedef struct {+ char path[CODE_PATH_MAX + 1];+ uint64_t size;+ uint8_t sha256[32];+} CodeFile;++typedef struct {+ CodeFile *files; /* sorted by path (the manifest must already be sorted) */+ int nfiles;+ char version[32];+ int signed_ok; /* 1 if the signature was checked and is good */+} CodeManifest;++/* ---- pure functions (server/tests/codesig_test.c) ---- */++/* Parses and checks a manifest. sig/siglen: the text of code-manifest.sig, or NULL when there is none+ * (then signed_ok = 0). With a signature, it must verify with pub over json[0..len). 0 on success;+ * err gets the reason. Strict: format 1, kind "lordos-system-code", relative paths of+ * [A-Za-z0-9._+-/] without "." or ".." parts, strictly sorted, sizes ≤ CODE_FILE_MAX, 64 lowercase+ * hex digits, at most CODE_FILES_MAX files. */+int codesig_parse(const char *json, size_t len, const char *sig, size_t siglen, const uint8_t pub[32],+ CodeManifest *out, char *err, size_t errlen);+void codesig_free(CodeManifest *m);+const CodeFile *codesig_find(const CodeManifest *m, const char *rel);+/* 0 if buf is exactly the listed file rel; otherwise why ("not listed", "size", "hash"). */+int codesig_check_buf(const CodeManifest *m, const char *rel, const void *buf, size_t len, char *why, size_t n);+/* Base64 (standard alphabet, padding, optional trailing newline) of exactly 64 bytes. 0 ok. */+int codesig_sig_decode(const char *text, size_t len, uint8_t out[64]);++/* ---- the process's state ---- */++/* Loads <assets_dir>/../code-manifest.json once (later calls do nothing). Returns the state. */+CodeState codesig_init(const char *assets_dir);+/* For tests and --check-code: the same with an explicit root, key and policy (release = 1 refuses+ * DEVELOPMENT). Replaces any previous state. */+CodeState codesig_init_root(const char *root, const uint8_t pub[32], int release);+CodeState codesig_state(void);+const char *codesig_state_name(CodeState s); /* "verified", "development", "invalid", "unchecked" */+const char *codesig_root(void);+const char *codesig_reason(void); /* why INVALID (or a DEVELOPMENT detail) */+const CodeManifest *codesig_manifest(void); /* NULL without a manifest */+int codesig_release_build(void); /* 1 if built with RELEASE=1 */+double codesig_ms(void); /* time spent verifying in this process */++/* Reads one file of LordOS's code. On success returns a malloc'd, NUL-terminated buffer with exactly+ * the bytes that were hashed (len set). On refusal returns NULL, records the refusal (see below),+ * logs it and fills why. max: largest size accepted. */+char *codesig_load(const char *path, size_t max, size_t *len, char *why, size_t whylen);++/* Refusals of this process, for the "This LordOS component was modified" notification. */+typedef struct { char path[CODE_PATH_MAX + 1]; char reason[96]; int reported; } CodeRefusal;+int codesig_refused_count(void);+CodeRefusal *codesig_refused(int i);++/* The LordOS release key (tools/release/lordos-release.pub.pem), raw 32 bytes. */+extern const uint8_t codesig_release_key[32];+/* The key this build trusts: the release key, or a test build's CODE_PUBKEY. */+const uint8_t *codesig_key(void);++#endifdiff --git a/server/src/ui/js.c b/server/src/ui/js.cindex dc71889..aec63fb 100644--- a/server/src/ui/js.c+++ b/server/src/ui/js.c@@ -27,6 +27,7 @@#include "js_help.h"#include "js_hw.h"#include "../media/media.h"+#include "../sec/codesig.h"#include "ui.h"#include "../term/term.h"#include "lord_version.h" /* build/gen: version, channel and build (Makefile) */@@ -373,21 +374,22 @@ static JSValue call_global(const char *name, int argc, JSValueConst *argv) {return r;}-int js_init(const char *bundle_path) {- char dir[1024];- snprintf(dir, sizeof dir, "%s", bundle_path);- snprintf(ui.theme_dir, sizeof ui.theme_dir, "%s", dirname(dir));-- FILE *f = fopen(bundle_path, "rb");- if (!f) { perror(bundle_path); return -1; }- fseek(f, 0, SEEK_END);- long len = ftell(f);- fseek(f, 0, SEEK_SET);- char *src = malloc((size_t)len + 1);- if (!src || fread(src, 1, (size_t)len, f) != (size_t)len) { fclose(f); free(src); return -1; }- src[len] = 0;- fclose(f);+/* Reads a bundle of LordOS's own code through the verified-code check (sec/codesig.c): the bytes+ * returned are exactly the ones that were hashed. NULL (and *refused = 1) if it was refused. */+static char *load_code(const char *path, size_t *len, int *refused) {+ codesig_init(js_sys_assets());+ char why[160];+ int before = codesig_refused_count();+ char *src = codesig_load(path, CODE_FILE_MAX, len, why, sizeof why);+ if (!src) {+ *refused = codesig_refused_count() > before || codesig_state() == CODE_INVALID;+ fprintf(stderr, "js: %s not loaded: %s\n", path, why);+ }+ return src;+}+/* A new context with the whole `lord` object of a session (or of the login screen). */+static void session_context(void) {rt = JS_NewRuntime();JS_SetMemoryLimit(rt, 256u << 20);JS_SetMaxStackSize(rt, 4u << 20);@@ -410,7 +412,7 @@ int js_init(const char *bundle_path) {js_wasm_register(ctx, g); /* the WebAssembly global (our own interpreter, src/wasm) */js_net_register(ctx, lord);js_monitor_register(ctx, lord, js_sys_assets()); /* lord.monitor (app Monitor) */- js_sec_register(ctx, lord); /* lord.perms and lord.sign (privacy and signing) */+ js_sec_register(ctx, lord); /* lord.perms, lord.sign and lord.code (privacy, signing, verified code) */js_media_register(ctx, lord); /* lord.media (video, photos, screenshots, camera, recorder) */js_doc_register(ctx, lord); /* lord.doc: PDF, archives and fonts through the lord-doc helper */js_print_register(ctx, lord); /* lord.print: CUPS over IPP and eSCL scanners */@@ -426,32 +428,116 @@ int js_init(const char *bundle_path) {js_hw_register(ctx, lord); /* lord.display/power/bt/mime/timedate (Settings, src/hw) */JS_SetPropertyStr(ctx, g, "lord", lord);JS_FreeValue(ctx, g);+}+int js_init(const char *bundle_path) {+ char dir[1024];+ snprintf(dir, sizeof dir, "%s", bundle_path);+ snprintf(ui.theme_dir, sizeof ui.theme_dir, "%s", dirname(dir));++ size_t len = 0;+ int refused = 0;+ char *src = load_code(bundle_path, &len, &refused);+ if (!src) return refused ? JS_REFUSED : -1;++ session_context();double t0 = now_ms();int r = eval(prelude, sizeof prelude - 1, "<prelude>");- if (!r) r = eval(src, (size_t)len, bundle_path);- fprintf(stderr, "js: theme %s loaded in %.1f ms (%ld KB)\n", bundle_path, now_ms() - t0, len / 1024);+ if (!r) r = eval(src, len, bundle_path);+ fprintf(stderr, "js: theme %s loaded in %.1f ms (%zu KB)\n", bundle_path, now_ms() - t0, len / 1024);free(src);return r;}+/* ---- the recovery screen ----+ * When the theme (or the login screen, or an isolated app's code) was refused, lord-server shows+ * this instead of a blank screen. It is compiled into the binary, so it is as trusted as+ * lord-server itself. Texts: the "shell" catalog (code.recovery.*) when it can be read, English+ * otherwise. */+static const char recovery_js[] =+ "(function(){\n"+ "const R = globalThis.__lordRecovery || {};\n"+ "const EN = {\n"+ " 'code.recovery.title': 'This LordOS component was modified and was not loaded',\n"+ " 'code.recovery.session': 'LordOS checks its own code before running it. A part of the desktop no longer matches the signed copy, so it was not started. Your files were not touched.',\n"+ " 'code.recovery.greeter': 'LordOS checks its own code before running it. The login screen no longer matches the signed copy, so it was not started. Your files were not touched.',\n"+ " 'code.recovery.app': 'LordOS checks its own code before running it. This app no longer matches the signed copy, so it was not started.',\n"+ " 'code.recovery.fix': 'To repair it, reinstall LordOS: sudo apt install --reinstall lordos',\n"+ " 'code.recovery.details': 'Not loaded:',\n"+ " 'code.recovery.logout': 'Log Out',\n"+ "};\n"+ "let cat = {};\n"+ "let lang = R.lang || 'en';\n"+ "try { const s = lord.settings && lord.settings.load && lord.settings.load(); const o = typeof s === 'string' ? JSON.parse(s) : s;\n"+ " if (o && typeof o.language === 'string' && /^[a-z]{2,3}(-[A-Za-z0-9]+)?$/.test(o.language)) lang = o.language; } catch (e) { /* no settings */ }\n"+ "try { const l = String(lang); const txt = lord.locale && lord.locale.catalog && (lord.locale.catalog(l, 'shell') || lord.locale.catalog(l.split('-')[0], 'shell'));\n"+ " if (txt) cat = JSON.parse(txt); } catch (e) { cat = {}; }\n"+ "const t = k => (typeof cat[k] === 'string' && cat[k]) || EN[k];\n"+ "const W = (lord.screen && lord.screen.width) || 800, H = (lord.screen && lord.screen.height) || 600;\n"+ "/* colors are ARGB numbers, as runtime/style.js sends them */\n"+ "const view = (style, parent) => { const id = lord.createNode('view'); for (const k in style) lord.setStyle(id, k, style[k]); if (parent) lord.appendChild(parent, id); return id; };\n"+ "let lastRaw = 0;\n"+ "const text = (s, style, parent) => { const id = lord.createNode('text'); for (const k in style) lord.setStyle(id, k, style[k]);\n"+ " const raw = lord.createNode('raw'); lord.setText(raw, s); lord.appendChild(id, raw); lastRaw = raw; lord.appendChild(parent, id); return id; };\n"+ "const ds = (lord.screen && lord.screen.displays) || [];\n"+ "const d = ds.find(x => x && x.main) || ds[0] || { x: 0, y: 0, w: W, h: H };\n"+ "const app = R.kind === 'app'; /* an app window: fill it; a session: the main display */\n"+ "const root = view(app ? { flex: 1, backgroundColor: 0xff1c1c1e } : { width: W, height: H, backgroundColor: 0xff1c1c1e });\n"+ "const area = view(app ? { flex: 1, alignItems: 'stretch', justifyContent: 'center', paddingLeft: 16, paddingRight: 16 }\n"+ " : { position: 'absolute', left: d.x, top: d.y, width: d.w, height: d.h, alignItems: 'center', justifyContent: 'center' }, root);\n"+ "const card = view({ ...(app ? {} : { width: Math.min(560, d.w - 40) }), paddingTop: 28, paddingBottom: 28, paddingLeft: 32, paddingRight: 32, borderRadius: 14,\n"+ " backgroundColor: 0xff2c2c2e, gap: 12 }, area);\n"+ "const mark = view({ width: 44, height: 44, borderRadius: 22, backgroundColor: 0xffff9f0a, alignItems: 'center', justifyContent: 'center' }, card);\n"+ "text('!', { color: 0xffffffff, fontSize: 26, fontWeight: 700 }, mark);\n"+ "text(t('code.recovery.title'), { color: 0xffffffff, fontSize: 18, fontWeight: 600, textAlign: 'start' }, card);\n"+ "text(t('code.recovery.' + (R.kind || 'session')), { color: 0xffd1d1d6, fontSize: 14, lineHeight: 20, textAlign: 'start' }, card);\n"+ "const list = (R.refused || []).slice(0, 6);\n"+ "if (list.length) { text(t('code.recovery.details'), { color: 0xff98989d, fontSize: 12, textAlign: 'start' }, card);\n"+ " for (const p of list) text(p, { color: 0xff98989d, fontSize: 12, fontFamily: 'monospace', direction: 'ltr', textAlign: 'start' }, card); }\n"+ "text(t('code.recovery.fix'), { color: 0xffd1d1d6, fontSize: 13, lineHeight: 19, textAlign: 'start' }, card);\n"+ "let btn = 0; const hits = new Set();\n"+ "if (R.kind === 'session' && typeof lord.quit === 'function') {\n"+ " btn = view({ alignSelf: 'flex-end', paddingTop: 6, paddingBottom: 6, paddingLeft: 16, paddingRight: 16, borderRadius: 7, backgroundColor: 0xff0a84ff, cursor: 'pointer' }, card);\n"+ " hits.add(btn); hits.add(text(t('code.recovery.logout'), { color: 0xffffffff, fontSize: 13, fontWeight: 600 }, btn)); hits.add(lastRaw);\n"+ "}\n"+ "globalThis.__lordEvent = (type, id) => { if (type === 'up' && hits.has(id)) lord.quit(); };\n"+ "globalThis.__lordKey = () => {};\n"+ "lord.setRoot(root);\n"+ "})();\n";++/* Fills __lordRecovery = { kind, lang, refused: [paths] } and runs the recovery screen: in a fresh+ * context (with the prelude), or in place over a running one (an isolated app whose own code was+ * refused after its host started), where the old timers and frames are stopped first. */+static int run_recovery(const char *kind, int inplace) {+ JSValue g = JS_GetGlobalObject(ctx);+ JSValue o = JS_NewObject(ctx), arr = JS_NewArray(ctx);+ for (int i = 0; i < codesig_refused_count(); i++) JS_SetPropertyUint32(ctx, arr, (uint32_t)i, JS_NewString(ctx, codesig_refused(i)->path));+ const char *lang = getenv("LANGUAGE");+ if (!lang || !lang[0]) lang = getenv("LANG");+ if (text_language()[0]) lang = text_language(); /* what the SDK showed until now (an app) */+ char l[16] = "en";+ if (lang && lang[0]) { snprintf(l, sizeof l, "%s", lang); l[strcspn(l, "_.:@")] = 0; }+ JS_SetPropertyStr(ctx, o, "kind", JS_NewString(ctx, kind));+ JS_SetPropertyStr(ctx, o, "lang", JS_NewString(ctx, l));+ JS_SetPropertyStr(ctx, o, "refused", arr);+ JS_SetPropertyStr(ctx, g, "__lordRecovery", o);+ JS_FreeValue(ctx, g);+ static const char stop[] = "globalThis.__lordTick = () => -1; globalThis.__lordWantsFrame = () => false; globalThis.__lordFrame = () => {};";+ int r = inplace ? eval(stop, sizeof stop - 1, "<recovery>") : eval(prelude, sizeof prelude - 1, "<prelude>");+ if (!r) r = eval(recovery_js, sizeof recovery_js - 1, "<recovery>");+ fprintf(stderr, "js: recovery screen (%s): %d component(s) refused\n", kind, codesig_refused_count());+ return r;+}++int js_init_recovery(int greeter) {+ session_context();+ return run_recovery(greeter ? "greeter" : "session", 0);+}+/* "App mode" (lord-server --app <id>): the same JS engine, but the `lord` object only has the* drawing primitives (local) plus the broker (fs/clipboard/perms through lord-server, which checks* the permissions). Loads the "app host" (React + SDK + the app), see app/appclient.c. */-int js_init_app(const char *host_bundle, const char *app_id) {- char dir[1024];- snprintf(dir, sizeof dir, "%s", host_bundle);- snprintf(ui.theme_dir, sizeof ui.theme_dir, "%s", dirname(dir));- FILE *f = fopen(host_bundle, "rb");- if (!f) { perror(host_bundle); return -1; }- fseek(f, 0, SEEK_END);- long len = ftell(f);- fseek(f, 0, SEEK_SET);- char *src = malloc((size_t)len + 1);- if (!src || fread(src, 1, (size_t)len, f) != (size_t)len) { fclose(f); free(src); return -1; }- src[len] = 0;- fclose(f);-+static void app_context(const char *app_id) {rt = JS_NewRuntime();JS_SetMemoryLimit(rt, 256u << 20);JS_SetMaxStackSize(rt, 4u << 20);@@ -470,15 +556,38 @@ int js_init_app(const char *host_bundle, const char *app_id) {js_wasm_register(ctx, g); /* WebAssembly for the app's loadWasm */JS_SetPropertyStr(ctx, g, "lord", lord);JS_FreeValue(ctx, g);+}+int js_init_app(const char *host_bundle, const char *app_id) {+ char dir[1024];+ snprintf(dir, sizeof dir, "%s", host_bundle);+ snprintf(ui.theme_dir, sizeof ui.theme_dir, "%s", dirname(dir));+ size_t len = 0;+ int refused = 0;+ char *src = load_code(host_bundle, &len, &refused);+ if (!src) {+ if (!refused) return -1;+ app_context(app_id); /* the window shows why instead of closing */+ run_recovery("app", 0);+ return JS_REFUSED;+ }+ app_context(app_id);double t0 = now_ms();int r = eval(prelude, sizeof prelude - 1, "<prelude>");- if (!r) r = eval(src, (size_t)len, host_bundle);+ if (!r) r = eval(src, len, host_bundle);fprintf(stderr, "js: app %s loaded in %.1f ms\n", app_id, now_ms() - t0);free(src);return r;}+/* The app's own code was refused after the host loaded (assets/sysapps/<id>/app.js): the same+ * recovery screen in the app's window, drawn over the running context (freeing it from here would+ * leave the broker's and the windows' references dangling). */+int js_app_recovery(void) {+ if (!ctx) return -1;+ return run_recovery("app", 1);+}+void js_shutdown(void) {media_shutdown(); /* the lord-media helpers belong to this context */if (ctx) js_wasm_shutdown(ctx);diff --git a/server/src/ui/js.h b/server/src/ui/js.hindex c538e9c..87848c0 100644--- a/server/src/ui/js.h+++ b/server/src/ui/js.h@@ -5,7 +5,12 @@#include <stddef.h>int js_init(const char *bundle_path);+/* js_init/js_init_app return JS_REFUSED when the code was refused by the verified-code check+ * (sec/codesig.h): the caller falls back to another theme or to js_init_recovery(). */+#define JS_REFUSED (-2)int js_init_app(const char *host_bundle, const char *app_id); /* lord-server --app <id> */+int js_init_recovery(int greeter); /* the built-in "component was modified" screen */+int js_app_recovery(void); /* the same in an isolated app's window */void js_shutdown(void);double js_tick(double now); /* runs expired timers; ms until the next one or -1 */int js_wants_frame(void); /* there are pending requestAnimationFrame callbacks */diff --git a/server/src/ui/js_broker.c b/server/src/ui/js_broker.cindex 484ee0f..56bd9dd 100644--- a/server/src/ui/js_broker.c+++ b/server/src/ui/js_broker.c@@ -17,6 +17,8 @@#include <errno.h>#include <fcntl.h>+#include "../sec/codesig.h"+#include <limits.h>#include <stdio.h>#include <stdlib.h>@@ -31,7 +33,11 @@ static uint32_t next_req = 1;static char app_id[48];static char pkg_dir[PATH_MAX]; /* carpeta del paquete (solo lectura); se fija antes de la caja de arena */-void js_broker_set_pkgdir(const char *dir) { snprintf(pkg_dir, sizeof pkg_dir, "%s", dir); }+static int pkg_system; /* 1: a system app (assets/sysapps): its app.js is LordOS code, checked */+static int code_refused; /* its app.js was refused by the verified-code check */++void js_broker_set_pkgdir(const char *dir, int system) { snprintf(pkg_dir, sizeof pkg_dir, "%s", dir); pkg_system = system == 1; }+int js_broker_code_refused(void) { return code_refused; }static char *pkg_read(const char *rel, size_t max, size_t *len);@@ -620,7 +626,19 @@ static JSValue f_pkg_file(JSContext *c, JSValueConst t, int argc, JSValueConst *static JSValue f_load_app(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t; (void)argc; (void)argv;size_t len = 0;- char *src = pkg_read("app.js", 16u * 1024 * 1024, &len);+ char *src;+ if (pkg_system && code_refused) return js_throw_code(c, "app.codeRefused", NULL);+ if (pkg_system) {+ /* a system app: the same check as the theme (sec/codesig.c), from one descriptor */+ char path[PATH_MAX + 16];+ snprintf(path, sizeof path, "%s/app.js", pkg_dir);+ int before = codesig_refused_count();+ src = codesig_load(path, 16u * 1024 * 1024, &len, NULL, 0);+ if (!src && (codesig_refused_count() > before || codesig_state() == CODE_INVALID)) {+ code_refused = 1; /* appclient.c shows the recovery screen */+ return js_throw_code(c, "app.codeRefused", NULL);+ }+ } else src = pkg_read("app.js", 16u * 1024 * 1024, &len);if (!src) return js_throw_code(c, "app.loadFailed", NULL);JSValue r = JS_Eval(c, src, len, "app.js", JS_EVAL_TYPE_GLOBAL);free(src);diff --git a/server/src/ui/js_broker.h b/server/src/ui/js_broker.hindex ad04725..826e3f2 100644--- a/server/src/ui/js_broker.h+++ b/server/src/ui/js_broker.h@@ -9,7 +9,8 @@int js_broker_fd(void); /* fd del broker para poll; -1 si no hay */void js_broker_poll(void); /* mensajes del servidor sin pedir (indicadores, tema) */int js_broker_pending(void); /* events queued during an RPC, not dispatched yet */-void js_broker_set_pkgdir(const char *dir); /* antes de la caja de arena */+void js_broker_set_pkgdir(const char *dir, int system); /* before the sandbox; system: assets/sysapps */+int js_broker_code_refused(void); /* the system app's app.js was refused (verified code) */int js_broker_wants_network(void); /* la app declaró `network` y lo tiene permitido */void js_broker_register(JSContext *c, JSValue lord, const char *app_id);/* lord.appWindows: the app's own windows (app/appclient.c, docs/PRIVACY.md) */diff --git a/server/src/ui/js_sec.c b/server/src/ui/js_sec.cindex 6452537..1569332 100644--- a/server/src/ui/js_sec.c+++ b/server/src/ui/js_sec.c@@ -8,6 +8,7 @@#include "../sec/pkgstate.h"#include "../lpk.h"#include "../sec/broker.h"+#include "../sec/codesig.h"#include <string.h>@@ -221,7 +222,57 @@ static const JSCFunctionListEntry broker_funcs[] = {JS_CFUNC_DEF("quit", 1, f_broker_quit),};+/* ---- lord.code: verified system code (sec/codesig.c, docs/SIGNING.md "Verified system code") ----+ * lord.code.status() → { state: 'verified'|'development'|'invalid'|'unchecked', signed, release,+ * version, files, ms, reason, refused: [{ path, reason }] }+ * lord.code.takeRefused() → the refusals not reported yet ([{ path, reason }]); each is returned once+ * per session, for the "This LordOS component was modified" notification. */+static JSValue refusal_obj(JSContext *c, const CodeRefusal *r) {+ JSValue o = JS_NewObject(c);+ JS_SetPropertyStr(c, o, "path", JS_NewString(c, r->path));+ JS_SetPropertyStr(c, o, "reason", JS_NewString(c, r->reason));+ return o;+}++static JSValue f_code_status(JSContext *c, JSValueConst this_val, int argc, JSValueConst *argv) {+ (void)this_val; (void)argc; (void)argv;+ codesig_init(js_sys_assets());+ const CodeManifest *m = codesig_manifest();+ JSValue o = JS_NewObject(c), arr = JS_NewArray(c);+ JS_SetPropertyStr(c, o, "state", JS_NewString(c, codesig_state_name(codesig_state())));+ JS_SetPropertyStr(c, o, "signed", JS_NewBool(c, m && m->signed_ok));+ JS_SetPropertyStr(c, o, "release", JS_NewBool(c, codesig_release_build()));+ JS_SetPropertyStr(c, o, "version", JS_NewString(c, m ? m->version : ""));+ JS_SetPropertyStr(c, o, "files", JS_NewInt32(c, m ? m->nfiles : 0));+ JS_SetPropertyStr(c, o, "ms", JS_NewFloat64(c, codesig_ms()));+ JS_SetPropertyStr(c, o, "reason", JS_NewString(c, codesig_reason()));+ for (int i = 0; i < codesig_refused_count(); i++) JS_SetPropertyUint32(c, arr, (uint32_t)i, refusal_obj(c, codesig_refused(i)));+ JS_SetPropertyStr(c, o, "refused", arr);+ return o;+}++static JSValue f_code_take(JSContext *c, JSValueConst this_val, int argc, JSValueConst *argv) {+ (void)this_val; (void)argc; (void)argv;+ JSValue arr = JS_NewArray(c);+ uint32_t n = 0;+ for (int i = 0; i < codesig_refused_count(); i++) {+ CodeRefusal *r = codesig_refused(i);+ if (r->reported) continue;+ r->reported = 1;+ JS_SetPropertyUint32(c, arr, n++, refusal_obj(c, r));+ }+ return arr;+}++static const JSCFunctionListEntry code_funcs[] = {+ JS_CFUNC_DEF("status", 0, f_code_status),+ JS_CFUNC_DEF("takeRefused", 0, f_code_take),+};+void js_sec_register(JSContext *c, JSValue lord) {+ JSValue code = JS_NewObject(c);+ JS_SetPropertyFunctionList(c, code, code_funcs, sizeof code_funcs / sizeof code_funcs[0]);+ JS_SetPropertyStr(c, lord, "code", code);JSValue perms = JS_NewObject(c);JS_SetPropertyFunctionList(c, perms, perms_funcs, sizeof perms_funcs / sizeof perms_funcs[0]);JS_SetPropertyStr(c, lord, "perms", perms);diff --git a/server/src/ui/textlayout.c b/server/src/ui/textlayout.cindex ddcec41..9fd9f90 100644--- a/server/src/ui/textlayout.c+++ b/server/src/ui/textlayout.c@@ -121,7 +121,11 @@ static int emoji_font(void) {static int mono_cjk[2] = { -2, -2 };+static int lang_set; /* the SDK has set it (text_language) */+const char *text_language(void) { return lang_set ? lang : ""; }+void text_set_language(const char *l) {+ if (l) lang_set = 1;if (!l || !strcmp(l, lang)) return;snprintf(lang, sizeof lang, "%s", l);init_fonts();diff --git a/server/src/ui/ui.h b/server/src/ui/ui.hindex 7004882..5d60e8f 100644--- a/server/src/ui/ui.h+++ b/server/src/ui/ui.h@@ -247,6 +247,7 @@ void text_layout_draw_n(Canvas *c, const char *s, int font, float size, float lint text_layout_line_bytes(const char *s, int font, float size, float max_w, int nowrap, int *bs, int *be, int max);int text_ellipsis_join(char *out, int out_size, const char *s, int len); /* prefix + "…" */void text_set_language(const char *lang); /* picks the CJK font (ja/ko/zh) */+const char *text_language(void); /* the UI language the SDK set ("" before) */int text_script_fallback(uint32_t cp, int bold); /* terminal: font per script */int text_direction(const char *s); /* 1 if the first strong character is RTL */diff --git a/server/tests/codesig_test.c b/server/tests/codesig_test.cnew file mode 100644index 0000000..f71362e--- /dev/null+++ b/server/tests/codesig_test.c@@ -0,0 +1,348 @@+/* codesig_test.c — verified system code (src/sec/codesig.c, docs/SIGNING.md "Verified system code"):+ * the manifest parser, the signature, the per-file check, reading under the root, the development+ * and release policies, and that the compiled-in key is tools/release/lordos-release.pub.pem.+ *+ * build/codesig-test [path to lordos-release.pub.pem] (make test passes it) */+#include "sec/codesig.h"+#include "pkg/crypto.h"++#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <time.h>+#include <unistd.h>++static int pass, fail;+#define CHECK(cond, name) do { if (cond) pass++; else { fail++; printf("FAILED: %s (line %d)\n", name, __LINE__); } } while (0)++static const uint8_t SEED[32] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,+ 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 };+static uint8_t pub[32], other_pub[32];++static void b64(const uint8_t *in, size_t n, char *out) {+ static const char a[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ size_t o = 0;+ for (size_t i = 0; i < n; i += 3) {+ uint32_t v = (uint32_t)in[i] << 16 | (i + 1 < n ? (uint32_t)in[i + 1] << 8 : 0) | (i + 2 < n ? in[i + 2] : 0);+ out[o++] = a[v >> 18 & 63];+ out[o++] = a[v >> 12 & 63];+ out[o++] = i + 1 < n ? a[v >> 6 & 63] : '=';+ out[o++] = i + 2 < n ? a[v & 63] : '=';+ }+ out[o] = 0;+}++static void sign_text(const char *text, char sig[100]) {+ uint8_t s[64];+ ed25519_sign(SEED, (const uint8_t *)text, strlen(text), s);+ b64(s, 64, sig);+ strcat(sig, "\n");+}++static void hexsha(const char *data, size_t n, char out[65]) {+ uint8_t h[32];+ sha256(data, n, h);+ hex_encode(h, 32, out);+}++/* a manifest with two files: "a/one.js" = A, "b.js" = B */+static const char A[] = "console.log('one');\n", B[] = "globalThis.x = 2;\n";+static void manifest(char *out, size_t n, const char *kind) {+ char ha[65], hb[65];+ hexsha(A, strlen(A), ha);+ hexsha(B, strlen(B), hb);+ snprintf(out, n, "{\n \"format\": 1,\n \"kind\": \"%s\",\n \"version\": \"0.8.2\",\n \"files\": [\n"+ " { \"path\": \"a/one.js\", \"size\": %zu, \"sha256\": \"%s\" },\n"+ " { \"path\": \"b.js\", \"size\": %zu, \"sha256\": \"%s\" }\n ]\n}\n",+ kind, strlen(A), ha, strlen(B), hb);+}++static int parse(const char *json, const char *sig, CodeManifest *m) {+ char err[160];+ int r = codesig_parse(json, strlen(json), sig, sig ? strlen(sig) : 0, pub, m, err, sizeof err);+ return r;+}++static void test_parser(void) {+ char j[2048], sig[100];+ CodeManifest m;+ manifest(j, sizeof j, CODE_KIND);+ sign_text(j, sig);+ CHECK(parse(j, sig, &m) == 0 && m.signed_ok && m.nfiles == 2 && !strcmp(m.version, "0.8.2"), "signed manifest parses");+ CHECK(codesig_find(&m, "b.js") && codesig_find(&m, "a/one.js") && !codesig_find(&m, "c.js"), "find");+ CHECK(codesig_check_buf(&m, "a/one.js", A, strlen(A), NULL, 0) == 0, "right bytes pass");+ char bad[64];+ snprintf(bad, sizeof bad, "%s", A);+ bad[3] ^= 1; /* one modified byte */+ char why[96];+ CHECK(codesig_check_buf(&m, "a/one.js", bad, strlen(bad), why, sizeof why) != 0 && strstr(why, "SHA-256"), "one modified byte is refused");+ CHECK(codesig_check_buf(&m, "a/one.js", A, strlen(A) - 1, why, sizeof why) != 0 && strstr(why, "size"), "truncated file is refused");+ CHECK(codesig_check_buf(&m, "evil.js", A, strlen(A), why, sizeof why) != 0 && strstr(why, "not listed"), "unlisted file is refused");+ codesig_free(&m);++ CHECK(parse(j, NULL, &m) == 0 && !m.signed_ok && m.nfiles == 2, "unsigned manifest parses as development");+ codesig_free(&m);++ /* the signature covers every byte */+ char j2[2100];+ snprintf(j2, sizeof j2, "%s", j);+ char *p = strstr(j2, "0.8.2");+ p[4] = '3';+ CHECK(parse(j2, sig, &m) != 0, "altered manifest: bad signature");+ snprintf(j2, sizeof j2, "%s ", j);+ CHECK(parse(j2, sig, &m) != 0, "one extra byte: bad signature");+ /* another key */+ {+ char err[96];+ CHECK(codesig_parse(j, strlen(j), sig, strlen(sig), other_pub, &m, err, sizeof err) != 0 && strstr(err, "signature"), "other key: refused");+ }+ /* broken signature encodings */+ char s2[100];+ snprintf(s2, sizeof s2, "%s", sig);+ s2[10] = s2[10] == 'A' ? 'B' : 'A';+ CHECK(parse(j, s2, &m) != 0, "flipped signature character");+ CHECK(parse(j, "AAAA\n", &m) != 0, "short signature");+ snprintf(s2, sizeof s2, "%s", sig);+ s2[3] = '*';+ CHECK(parse(j, s2, &m) != 0, "signature with a non-base64 character");+ uint8_t raw[64];+ CHECK(codesig_sig_decode(sig, strlen(sig), raw) == 0, "signature decodes");+ snprintf(s2, sizeof s2, "%s", sig);+ s2[85] = s2[85] == 'B' ? 'C' : 'B'; /* leftover bits not zero → refused or different */+ CHECK(codesig_sig_decode(s2, 88, raw) != 0 || memcmp(s2, sig, 88), "non-canonical base64");++ /* wrong kind (a signature for something else must not pass as this) */+ manifest(j2, sizeof j2, "something-else");+ sign_text(j2, s2);+ CHECK(parse(j2, s2, &m) != 0, "wrong kind is refused");++ /* strict structure (unsigned, to reach the parser) */+ const char *bad_manifests[] = {+ "{\"format\":2,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"files\":[]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":{}}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"../etc/passwd\",\"size\":1,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"/abs.js\",\"size\":1,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"a/./b.js\",\"size\":1,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"a//b.js\",\"size\":1,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"a b.js\",\"size\":1,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"a.js\",\"size\":-1,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"a.js\",\"size\":1.5,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"a.js\",\"size\":1,\"sha256\":\"00000000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"a.js\",\"size\":1,\"sha256\":\"ABCDEF0000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"b.js\",\"size\":1,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"},"+ "{\"path\":\"a.js\",\"size\":1,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[{\"path\":\"a.js\",\"size\":1,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"},"+ "{\"path\":\"a.js\",\"size\":1,\"sha256\":\"0000000000000000000000000000000000000000000000000000000000000000\"}]}",+ "{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[]} trailing",+ "not json",+ };+ for (size_t i = 0; i < sizeof bad_manifests / sizeof bad_manifests[0]; i++) {+ char name[64];+ snprintf(name, sizeof name, "strict manifest #%zu refused", i);+ CHECK(parse(bad_manifests[i], NULL, &m) != 0, name);+ }+ CHECK(parse("{\"format\":1,\"kind\":\"lordos-system-code\",\"version\":\"1\",\"files\":[]}", NULL, &m) == 0 && m.nfiles == 0, "empty list is fine");+ codesig_free(&m);+}++/* ---- the process state against a real folder ---- */++static char root[256];+static void put(const char *rel, const char *data) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", root, rel);+ FILE *f = fopen(p, "wb");+ if (f) { fputs(data, f); fclose(f); }+}++static int loads(const char *rel, const char *want) {+ char p[512], why[160];+ snprintf(p, sizeof p, "%s/%s", root, rel);+ size_t n = 0;+ char *b = codesig_load(p, CODE_FILE_MAX, &n, why, sizeof why);+ int ok = b && n == strlen(want) && !memcmp(b, want, n) && b[n] == 0;+ free(b);+ return ok;+}++static void test_root(void) {+ snprintf(root, sizeof root, "%s/codesig-test.XXXXXX", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp");+ if (!mkdtemp(root)) { fail++; printf("FAILED: mkdtemp\n"); return; }+ char p[512];+ snprintf(p, sizeof p, "%s/a", root);+ mkdir(p, 0755);+ put("a/one.js", A);+ put("b.js", B);+ put("evil.js", "steal();\n");+ char j[2048], sig[100];+ manifest(j, sizeof j, CODE_KIND);+ sign_text(j, sig);++ /* no manifest: development (everything loads, flagged) / release: nothing */+ CHECK(codesig_init_root(root, pub, 0) == CODE_DEVELOPMENT && !codesig_manifest(), "no manifest: development");+ CHECK(loads("b.js", B) && loads("evil.js", "steal();\n"), "development without manifest loads");+ CHECK(codesig_init_root(root, pub, 1) == CODE_INVALID, "no manifest in a release build: invalid");+ CHECK(!loads("b.js", B) && codesig_refused_count() == 1, "release without manifest refuses");++ /* unsigned manifest: development with hashes; release: invalid */+ put(CODE_MANIFEST, j);+ CHECK(codesig_init_root(root, pub, 0) == CODE_DEVELOPMENT && codesig_manifest(), "unsigned: development");+ CHECK(loads("a/one.js", A) && loads("b.js", B), "development checks and loads listed files");+ CHECK(!loads("evil.js", "steal();\n"), "development refuses an unlisted file");+ CHECK(codesig_init_root(root, pub, 1) == CODE_INVALID, "unsigned in a release build: invalid");++ /* signed */+ put(CODE_SIGNATURE, sig);+ CHECK(codesig_init_root(root, pub, 1) == CODE_VERIFIED, "signed: verified (release)");+ CHECK(codesig_init_root(root, pub, 0) == CODE_VERIFIED, "signed: verified (development build)");+ CHECK(loads("a/one.js", A) && loads("b.js", B), "verified files load");+ CHECK(codesig_refused_count() == 0, "no refusals yet");++ /* one modified byte in a bundle */+ char mod[64];+ snprintf(mod, sizeof mod, "%s", B);+ mod[0] = 'G';+ put("b.js", mod);+ CHECK(!loads("b.js", mod), "modified bundle is refused");+ CHECK(codesig_refused_count() == 1 && !strcmp(codesig_refused(0)->path, "b.js") && !codesig_refused(0)->reported, "refusal recorded");+ CHECK(!loads("b.js", mod) && codesig_refused_count() == 1, "same refusal recorded once");+ put("b.js", B);+ CHECK(loads("b.js", B), "restored bundle loads again");++ /* a link that leaves the root, and a file outside it */+ snprintf(p, sizeof p, "%s/a/one.js", root);+ unlink(p);+ char target[512];+ snprintf(target, sizeof target, "%s/../codesig-outside.js", root);+ FILE *f = fopen(target, "wb");+ if (f) { fputs(A, f); fclose(f); }+ if (symlink(target, p) == 0) CHECK(!loads("a/one.js", A), "link out of the root is refused");+ char why[160];+ size_t n;+ char *b = codesig_load(target, CODE_FILE_MAX, &n, why, sizeof why);+ CHECK(!b && strstr(why, "not part"), "file outside the root is refused when verified");+ free(b);+ unlink(p);+ unlink(target);+ put("a/one.js", A);++ /* a forged signature next to a modified manifest */+ char j2[2048];+ snprintf(j2, sizeof j2, "%s", j);+ char hx[65];+ hexsha("steal();\n", 9, hx);+ char *at = strstr(j2, "\"sha256\": \"") + 11; /* a/one.js's hash */+ memcpy(at, hx, 64);+ put(CODE_MANIFEST, j2);+ CHECK(codesig_init_root(root, pub, 0) == CODE_INVALID, "modified manifest with the old signature: invalid");+ CHECK(!loads("b.js", B), "nothing loads with an invalid manifest");+ CHECK(codesig_init_root(root, other_pub, 0) == CODE_INVALID, "manifest signed by another key: invalid");++ /* clean up */+ const char *rm[] = { "a/one.js", "b.js", "evil.js", CODE_MANIFEST, CODE_SIGNATURE };+ for (size_t i = 0; i < sizeof rm / sizeof rm[0]; i++) { snprintf(p, sizeof p, "%s/%s", root, rm[i]); unlink(p); }+ snprintf(p, sizeof p, "%s/a", root);+ rmdir(p);+ rmdir(root);+}++/* The compiled-in key is the last 32 bytes of the PEM's DER. */+static void test_release_key(const char *pem) {+ FILE *f = pem ? fopen(pem, "r") : NULL;+ if (!f) { printf("skipped: release key check (no PEM path)\n"); return; }+ char line[256], b[256] = "";+ while (fgets(line, sizeof line, f)) {+ if (line[0] == '-') continue;+ line[strcspn(line, "\r\n")] = 0;+ strncat(b, line, sizeof b - strlen(b) - 1);+ }+ fclose(f);+ /* decode base64 (44 bytes of DER for Ed25519) */+ uint8_t der[64];+ size_t o = 0;+ uint32_t acc = 0;+ int bits = 0;+ for (const char *c = b; *c && *c != '='; c++) {+ const char *a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ const char *q = strchr(a, *c);+ if (!q) break;+ acc = acc << 6 | (uint32_t)(q - a);+ bits += 6;+ if (bits >= 8 && o < sizeof der) { bits -= 8; der[o++] = (uint8_t)(acc >> bits); }+ }+ CHECK(o == 44 && !memcmp(der + 12, codesig_release_key, 32), "compiled-in key matches lordos-release.pub.pem");+}++/* SHA-256: NIST vectors and the CPU's instructions (aarch64) against the C code, every length. */+static void test_sha256(void) {+ static const struct { const char *in; const char *hex; } v[] = {+ { "", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" },+ { "abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" },+ { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" },+ { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",+ "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1" },+ };+ for (int hw = 0; hw <= 1; hw++) {+ sha256_select(hw);+ for (size_t i = 0; i < sizeof v / sizeof v[0]; i++) {+ char hx[65];+ hexsha(v[i].in, strlen(v[i].in), hx);+ CHECK(!strcmp(hx, v[i].hex), hw ? "SHA-256 NIST vector (best path)" : "SHA-256 NIST vector (C)");+ }+ }+ size_t big = 3u << 20;+ uint8_t *buf = malloc(big);+ if (!buf) return;+ uint32_t x = 2463534242u;+ for (size_t i = 0; i < big; i++) { x ^= x << 13; x ^= x >> 17; x ^= x << 5; buf[i] = (uint8_t)x; }+ int same = 1;+ for (size_t n = 0; n <= 300 && same; n++) {+ uint8_t a[32], b[32];+ sha256_select(0); sha256(buf + n, n, a);+ sha256_select(1); sha256(buf + n, n, b);+ same = !memcmp(a, b, 32);+ }+ uint8_t a[32], b[32];+ sha256_select(0); sha256(buf, big, a);+ sha256_select(1); sha256(buf, big, b);+ CHECK(same && !memcmp(a, b, 32), "SHA-256: the CPU's instructions match the C code");+ /* speed of what lord-server uses here (docs/SIGNING.md, "Startup cost") */+ struct timespec t0, t1;+ clock_gettime(CLOCK_MONOTONIC, &t0);+ sha256(buf, big, a);+ clock_gettime(CLOCK_MONOTONIC, &t1);+ double ms = (t1.tv_sec - t0.tv_sec) * 1e3 + (t1.tv_nsec - t0.tv_nsec) / 1e6;+ sha256_select(0);+ clock_gettime(CLOCK_MONOTONIC, &t0);+ sha256(buf, big, a);+ clock_gettime(CLOCK_MONOTONIC, &t1);+ double msc = (t1.tv_sec - t0.tv_sec) * 1e3 + (t1.tv_nsec - t0.tv_nsec) / 1e6;+ sha256_select(1);+ printf("sha256: %.0f MB/s (%s), C code %.0f MB/s\n", 3.0 / (ms / 1e3), sha256_accelerated() ? "CPU instructions" : "C code", 3.0 / (msc / 1e3));+ uint8_t s[64];+ clock_gettime(CLOCK_MONOTONIC, &t0);+ ed25519_sign(SEED, buf, 1000, s);+ clock_gettime(CLOCK_MONOTONIC, &t1);+ clock_gettime(CLOCK_MONOTONIC, &t0);+ int ok = ed25519_verify(pub, s, buf, 1000);+ clock_gettime(CLOCK_MONOTONIC, &t1);+ CHECK(ok, "ed25519 verify");+ printf("ed25519 verify: %.2f ms\n", (t1.tv_sec - t0.tv_sec) * 1e3 + (t1.tv_nsec - t0.tv_nsec) / 1e6);+ free(buf);+}++int main(int argc, char **argv) {+ ed25519_public(SEED, pub);+ uint8_t s2[32];+ memcpy(s2, SEED, 32);+ s2[0] ^= 0xff;+ ed25519_public(s2, other_pub);+ test_sha256();+ test_parser();+ test_root();+ test_release_key(argc > 1 ? argv[1] : NULL);+ printf("codesig: %d/%d\n", pass, pass + fail);+ return fail ? 1 : 0;+}diff --git a/tools/build-theme.mjs b/tools/build-theme.mjsindex 3c2f5b5..3efd3e6 100644--- a/tools/build-theme.mjs+++ b/tools/build-theme.mjs@@ -5,6 +5,7 @@ import { build } from 'esbuild';import { fileURLToPath } from 'node:url';import fs from 'node:fs';import path from 'node:path';+import { writeManifest } from './code-manifest.mjs';const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));@@ -24,9 +25,11 @@ const appsPlugin = {// "process": "isolated": a built-in app that runs as its own sandboxed process (its window in// the theme only starts it; see sdk/packages.js isolatedApp and buildSysApps below)const iso = ids.map((id) => JSON.parse(fs.readFileSync(path.join(dir, id, 'manifest.json'), 'utf8')).process === 'isolated');+ // every app in apps/ is a system app (system: true): part of LordOS, verified with it and never+ // removable from the Store (docs/SIGNING.md, "Verified system code")const list = ids.map((_, i) => (iso[i]- ? `{ ...M${i}, isolated: true, Component: isolatedApp(M${i}.id, A${i}.default), Icon: A${i}.Icon }`- : `{ ...M${i}, Component: A${i}.default, Icon: A${i}.Icon }`)).join(',\n ');+ ? `{ ...M${i}, system: true, isolated: true, Component: isolatedApp(M${i}.id, A${i}.default), Icon: A${i}.Icon }`+ : `{ ...M${i}, system: true, Component: A${i}.default, Icon: A${i}.Icon }`)).join(',\n ');const head = iso.some(Boolean) ? `import { isolatedApp } from ${JSON.stringify(path.join(root, 'sdk', 'packages.js'))};\n` : '';return { contents: `${head}${lines.join('\n')}\nexport const apps = [\n ${list}\n];\n`, resolveDir: root, loader: 'js' };});@@ -118,3 +121,7 @@ const all = fs.readdirSync(path.join(root, 'themes'))for (const name of (names.length ? names : all).filter((n) => n !== 'app-host' && n !== 'sysapps')) await buildTheme(name);if (!names.length || names.includes('app-host')) await buildAppHost();if (!names.length || names.includes('sysapps')) await buildSysApps();+// the verified-code manifest of what was just built (unsigned: a development build until+// tools/release/sign-code.sh signs it on the maintainer's machine)+const cm = writeManifest(root);+console.log(`code-manifest.json: ${cm.files} files${cm.changed ? '' : ' (unchanged)'}`);diff --git a/tools/code-manifest.mjs b/tools/code-manifest.mjsnew file mode 100644index 0000000..f75d541--- /dev/null+++ b/tools/code-manifest.mjs@@ -0,0 +1,63 @@+// Writes code-manifest.json: the size and SHA-256 of every file LordOS runs as its own code (see+// docs/SIGNING.md, "Verified system code"). lord-server checks each file against it before loading+// it (server/src/sec/codesig.c); tools/release/sign-code.sh signs it with the LordOS release key.+//+// node tools/code-manifest.mjs [--root <dir>] [--check]+//+// <dir> (default: the repository) holds themes/ and assets/ as installed (/usr/lib/lordos has the+// same layout). The output is deterministic: the same files give the same bytes, so a signature+// made on the maintainer's machine stays valid for the .deb, the ISO and the Raspberry Pi image.+// If the manifest changes, a code-manifest.sig next to it no longer matches and is removed.+// --check: only compare with the existing manifest (exit 1 if it would change).+//+// Listed: themes/*/theme.bundle.js (the shell, the SDK, the runtime and every native app),+// assets/app-host.bundle.js (React + SDK of isolated apps) and assets/sysapps/*/app.js (system apps+// that run as their own process). Not listed (data, not code): fonts, locales, icons, images,+// help articles, theme.json and the sysapps' manifest.json (window size only).+import { createHash } from 'node:crypto';+import { fileURLToPath } from 'node:url';+import fs from 'node:fs';+import path from 'node:path';++const repo = path.dirname(path.dirname(fileURLToPath(import.meta.url)));+const args = process.argv.slice(2);+const at = args.indexOf('--root');+const root = at >= 0 ? path.resolve(args[at + 1]) : repo;+const check = args.includes('--check');++export function codeFiles(dir) {+ const out = [];+ const add = (rel) => { try { if (fs.lstatSync(path.join(dir, rel)).isFile()) out.push(rel); } catch { /* not built */ } };+ const list = (rel) => { try { return fs.readdirSync(path.join(dir, rel)).sort(); } catch { return []; } };+ for (const t of list('themes')) add(`themes/${t}/theme.bundle.js`);+ add('assets/app-host.bundle.js');+ for (const a of list('assets/sysapps')) add(`assets/sysapps/${a}/app.js`);+ // byte order, as lord-server compares paths with strcmp+ return out.sort((a, b) => (Buffer.compare(Buffer.from(a), Buffer.from(b))));+}++export function manifestText(dir, version) {+ const files = codeFiles(dir).map((rel) => {+ const data = fs.readFileSync(path.join(dir, rel));+ return ` { "path": ${JSON.stringify(rel)}, "size": ${data.length}, "sha256": "${createHash('sha256').update(data).digest('hex')}" }`;+ });+ return `{\n "format": 1,\n "kind": "lordos-system-code",\n "version": ${JSON.stringify(version)},\n "files": [\n${files.join(',\n')}\n ]\n}\n`;+}++export function writeManifest(dir = root) {+ const version = JSON.parse(fs.readFileSync(path.join(repo, 'package.json'), 'utf8')).version;+ const text = manifestText(dir, version);+ const file = path.join(dir, 'code-manifest.json'), sig = path.join(dir, 'code-manifest.sig');+ const old = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;+ if (old === text) return { changed: false, files: (text.match(/"path"/g) || []).length };+ if (check) return { changed: true };+ fs.writeFileSync(file, text);+ if (fs.existsSync(sig)) fs.rmSync(sig); // signed a different manifest+ return { changed: true, files: (text.match(/"path"/g) || []).length };+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const r = writeManifest(root);+ if (check) { console.log(r.changed ? 'code-manifest.json is out of date' : 'code-manifest.json is up to date'); process.exit(r.changed ? 1 : 0); }+ console.log(`code-manifest.json: ${r.files} files${r.changed ? '' : ' (unchanged)'}`);+}diff --git a/tools/iso/mkdeb.sh b/tools/iso/mkdeb.shindex 4541b9e..dfda3a0 100755--- a/tools/iso/mkdeb.sh+++ b/tools/iso/mkdeb.sh@@ -11,6 +11,8 @@# /usr/lib/lordos/themes/<theme>/ theme.json, theme.bundle.js and their resources (greeter: the# login screen)# /usr/lib/lordos/assets/ fonts, texts (locales), icons, shell integration+# /usr/lib/lordos/code-manifest.json SHA-256 of every bundle LordOS runs as its own code, and+# /usr/lib/lordos/code-manifest.sig its Ed25519 signature (release key; docs/SIGNING.md)# /usr/lib/lordos/lordos-live-prep live preparation (grub language, folders)# /usr/lib/systemd/system/lordos.service lord-sessiond on tty1# /usr/lib/lordos/lordos-splash boot splash hand-off (Plymouth → LordOS, docs/SESSIONS.md)@@ -75,6 +77,18 @@ cp -r assets/fonts assets/locales assets/shell assets/icons assets/mascot assetsinstall -m 644 assets/app-host.bundle.js "$L/assets/app-host.bundle.js"# system apps that run as their own sandboxed process (manifest "process": "isolated"; e.g. Passwords)[ -d assets/sysapps ] && cp -r assets/sysapps "$L/assets/"+# verified system code (docs/SIGNING.md): the manifest of every bundle above and, for a release, its+# signature made on the maintainer's machine (tools/release/sign-code.sh). lord-server checks the+# staged tree exactly as a session will; a release build (RELEASE=1) needs the signature.+[ -f code-manifest.json ] || { echo "missing code-manifest.json (npm run build writes it)" >&2; exit 1; }+install -m 644 code-manifest.json "$L/code-manifest.json"+[ -f code-manifest.sig ] && install -m 644 code-manifest.sig "$L/code-manifest.sig"+if [ "${REQUIRE_SIGNED_CODE:-0}" = 1 ] && [ ! -f "$L/code-manifest.sig" ]; then+ echo "missing code-manifest.sig: sign the manifest on the maintainer's machine (tools/release/sign-code.sh)" >&2; exit 1+fi+server/build/lord-server --check-code "$L" > "$PKG/code-check.log" 2>&1 || {+ tail -20 "$PKG/code-check.log" >&2; echo "the staged system code does not match code-manifest.json" >&2; exit 1; }+tail -1 "$PKG/code-check.log"; rm -f "$PKG/code-check.log"install -m 755 tools/iso/rootfs/usr/lib/lordos/lordos-live-prep "$L/lordos-live-prep"# updates in place (docs/UPDATES.md): the repository, its key, the migrations and the restart noticeinstall -D -m 644 packaging/apt/lordos.sources "$L/apt/lordos.sources"@@ -192,6 +206,7 @@ Depends: libc6 (>= 2.38), libwayland-server0 (>= 1.22), libwayland-client0 (>= 1Recommends: pipewire-pulse, wireplumber, wpasupplicant, openvpn, fonts-noto-core, locales, tzdata, sudo, cups, cups-client, avahi-daemon, mesa-va-drivers, bluez, libspa-0.2-bluetooth, power-profiles-daemon, systemd-timesyncd, shared-mime-info, gsettings-desktop-schemasSection: x11Priority: optional+Protected: yesHomepage: https://github.com/lordbasex/LordOSDescription: desktop environment for Debian GNU/Linux, built from scratchLordOS is a desktop environment for Debian GNU/Linux with its own displaydiff --git a/tools/release/sign-code.sh b/tools/release/sign-code.shnew file mode 100755index 0000000..28f023d--- /dev/null+++ b/tools/release/sign-code.sh@@ -0,0 +1,32 @@+#!/bin/sh+# Signs the verified-system-code manifest (docs/SIGNING.md, "Verified system code"): regenerates+# code-manifest.json from the built bundles (themes/*/theme.bundle.js, assets/app-host.bundle.js,+# assets/sysapps/*/app.js) and writes code-manifest.sig = base64 of the Ed25519 signature over its+# exact bytes, then checks it against tools/release/lordos-release.pub.pem.+#+# npm run build && tools/release/sign-code.sh [root] [private-key.pem]+#+# Run on the maintainer's machine, after `npm run build` and before the tree travels to the build+# VMs: the bundles are architecture-independent, so one signature serves the amd64 and arm64 .debs,+# the ISO and the Raspberry Pi image. The private key never leaves this machine. Default key:+# ~/.config/lordos-release/release-ed25519.key.pem (mode 0600). A different key (a throwaway one for+# a test build made with `make -C server CODE_PUBKEY=<hex>`) can be passed with its public key in+# CODE_PUB=<public.pem>.+set -eu+here=$(cd "$(dirname "$0")" && pwd)+repo=$(cd "$here/../.." && pwd)+root=${1:-$repo}+key=${2:-$HOME/.config/lordos-release/release-ed25519.key.pem}+pub=${CODE_PUB:-$here/lordos-release.pub.pem}+[ -r "$key" ] || { echo "no private key at $key" >&2; exit 1; }+command -v openssl >/dev/null || { echo "openssl is needed" >&2; exit 1; }+command -v node >/dev/null || { echo "node is needed" >&2; exit 1; }+node "$repo/tools/code-manifest.mjs" --root "$root"+cd "$root"+rm -f code-manifest.sig+openssl pkeyutl -sign -rawin -inkey "$key" -in code-manifest.json | base64 | tr -d '\n' > code-manifest.sig+echo >> code-manifest.sig+base64 -d < code-manifest.sig > code-manifest.sig.bin 2>/dev/null || base64 -D < code-manifest.sig > code-manifest.sig.bin+openssl pkeyutl -verify -pubin -inkey "$pub" -rawin -in code-manifest.json -sigfile code-manifest.sig.bin >/dev/null+rm -f code-manifest.sig.bin+echo "signed code-manifest.json ($(grep -c '"path"' code-manifest.json) files) in $root, signature verified"diff --git a/tools/rpi/build-img.sh b/tools/rpi/build-img.shindex 157c627..863180f 100755--- a/tools/rpi/build-img.sh+++ b/tools/rpi/build-img.sh@@ -174,16 +174,18 @@ elsemount_ch "$BR"firm -rf "$BR/src/LordOS"; mkdir -p "$BR/src/LordOS"+ # code-manifest.json (+ .sig for a release): the verified system code (docs/SIGNING.md)tar -C "$ROOT" --exclude=server/build --exclude=node_modules -cf - \- package.json README.md server third_party assets themes tools | tar -C "$BR/src/LordOS" -xf -+ package.json README.md server third_party assets themes tools \+ $(cd "$ROOT" && ls code-manifest.json code-manifest.sig 2>/dev/null) | tar -C "$BR/src/LordOS" -xf -J=$(nproc)- in_root "$BR" sh -c "cd /src/LordOS && make -C server -j$J GPU=1 && make -C server build/canvas-test" > "$WORK/build.log" 2>&1 || {+ in_root "$BR" sh -c "cd /src/LordOS && make -C server -j$J GPU=1 RELEASE=${RELEASE:-0} && make -C server build/canvas-test" > "$WORK/build.log" 2>&1 || {tail -40 "$WORK/build.log"; exit 1; }is_aarch64 "$BR/src/LordOS/server/build/lord-server" || { echo "build-img.sh: the binary is not aarch64" >&2; exit 1; }# canvas-test: NEON against C, bit for bit (under qemu it measures nothing, but it checks)in_root "$BR" /src/LordOS/server/build/canvas-test > "$WORK/canvas-test.log" 2>&1 || {cat "$WORK/canvas-test.log"; echo "build-img.sh: canvas-test failed (NEON ≠ C); build with NEON=0" >&2; exit 1; }- in_root "$BR" sh -c "cd /src/LordOS && DEB_ARCH=$ARCH sh tools/iso/mkdeb.sh /tmp/lordos.deb" >> "$WORK/build.log" 2>&1 || {+ in_root "$BR" sh -c "cd /src/LordOS && DEB_ARCH=$ARCH REQUIRE_SIGNED_CODE=${REQUIRE_SIGNED_CODE:-0} sh tools/iso/mkdeb.sh /tmp/lordos.deb" >> "$WORK/build.log" 2>&1 || {tail -20 "$WORK/build.log"; exit 1; }cp "$BR/tmp/lordos.deb" "$DEB"umount_ch "$BR"