App-Sperre mit Passwort und/oder FIDO2-Sicherheitsschlüssel (PRF/hmac-secret): Vault zusätzlich verschlüsselt, Sperrbildschirm, Strg+Shift+L, automatische Sperre
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
// FIDO2/WebAuthn (YubiKey & Co.) für die App-Sperre.
|
||||
// Chromium erlaubt WebAuthn nur auf HTTPS oder http://localhost – nicht unter file://. Deshalb läuft die
|
||||
// Abfrage in einem kleinen eigenen Fenster, dessen http://localhost-Seite über eine eigene Session
|
||||
// abgefangen wird (kein echter Server). rpId ist damit immer "localhost".
|
||||
// Aus dem Schlüssel wird per PRF-Erweiterung (CTAP hmac-secret) ein geheimer Wert abgeleitet, der den
|
||||
// Datenschlüssel des Vaults verpackt. userVerification "discouraged": Berühren genügt (Electron hat keine PIN-Eingabe).
|
||||
const { BrowserWindow, session } = require('electron');
|
||||
const i18n = require('../i18n');
|
||||
|
||||
const PAGE = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>
|
||||
html,body{margin:0;height:100%;background:#1a1d27;color:#e6e8ef;font:14px system-ui,sans-serif;-webkit-app-region:drag}
|
||||
body{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;border:1px solid #2c3142;box-sizing:border-box;text-align:center;padding:16px}
|
||||
.ic{font-size:34px} #t{max-width:340px;line-height:1.4}
|
||||
button{-webkit-app-region:no-drag;background:#2a2f40;color:#e6e8ef;border:1px solid #3a4054;border-radius:8px;padding:7px 16px;font:inherit;cursor:pointer}
|
||||
button:hover{background:#343a4f}
|
||||
</style></head><body><div class="ic">🔑</div><div id="t"></div><button id="c"></button></body></html>`;
|
||||
|
||||
let fidoSession;
|
||||
function getSession() {
|
||||
if (fidoSession) return fidoSession;
|
||||
fidoSession = session.fromPartition('mrterm-fido');
|
||||
fidoSession.protocol.handle('http', () => new Response(PAGE, { headers: { 'content-type': 'text/html; charset=utf-8' } }));
|
||||
return fidoSession;
|
||||
}
|
||||
|
||||
// Gemeinsame Hilfsfunktionen im Fenster (base64url <-> Bytes)
|
||||
const HELPERS = `
|
||||
const b64 = (u) => btoa(String.fromCharCode(...new Uint8Array(u))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');
|
||||
const unb64 = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
|
||||
`;
|
||||
|
||||
async function ceremony(parent, text, script) {
|
||||
const w = new BrowserWindow({
|
||||
parent, modal: !!parent, width: 420, height: 210, frame: false, resizable: false, show: false,
|
||||
backgroundColor: '#1a1d27', webPreferences: { session: getSession(), contextIsolation: true, sandbox: true },
|
||||
});
|
||||
try {
|
||||
await w.loadURL('http://localhost/');
|
||||
await w.webContents.executeJavaScript(`document.getElementById('t').textContent = ${JSON.stringify(text)};
|
||||
const c = document.getElementById('c'); c.textContent = ${JSON.stringify(i18n.t('Cancel'))}; c.onclick = () => window.close(); 0;`);
|
||||
w.show();
|
||||
w.focus();
|
||||
const closed = new Promise((resolve) => w.once('closed', () => resolve({ error: 'cancelled' })));
|
||||
const r = await Promise.race([w.webContents.executeJavaScript(`(async () => { try { ${HELPERS} ${script} } catch (e) { return { error: e.name + ': ' + e.message }; } })()`, true), closed]);
|
||||
if (r?.error === 'cancelled' || /NotAllowedError|AbortError/.test(r?.error || '')) throw new Error(i18n.t('Security key prompt was cancelled or timed out.'));
|
||||
if (r?.error) throw new Error(r.error);
|
||||
return r;
|
||||
} finally {
|
||||
if (!w.isDestroyed()) w.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
// Neuen Schlüssel registrieren; liefert die Credential-ID (base64url)
|
||||
async function register(parent) {
|
||||
const r = await ceremony(parent, i18n.t('Touch your security key to register it.'), `
|
||||
const cred = await navigator.credentials.create({ publicKey: {
|
||||
challenge: crypto.getRandomValues(new Uint8Array(32)),
|
||||
rp: { name: 'MrTerm', id: 'localhost' },
|
||||
user: { id: crypto.getRandomValues(new Uint8Array(16)), name: 'MrTerm', displayName: 'MrTerm' },
|
||||
pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -8 }, { type: 'public-key', alg: -257 }],
|
||||
authenticatorSelection: { userVerification: 'discouraged', residentKey: 'discouraged' },
|
||||
timeout: 60000, extensions: { prf: {} },
|
||||
} });
|
||||
return { credId: b64(cred.rawId), prf: cred.getClientExtensionResults().prf?.enabled };`);
|
||||
if (r.prf === false) throw new Error(i18n.t('This security key does not support the hmac-secret/PRF extension.'));
|
||||
return r.credId;
|
||||
}
|
||||
|
||||
// PRF-Wert für einen der Schlüssel abfragen. creds: [{ credId, prfSalt }] (base64url)
|
||||
// Liefert { credId, secret: Buffer(32) }
|
||||
async function derive(parent, creds, text) {
|
||||
const r = await ceremony(parent, text || i18n.t('Touch your security key to unlock MrTerm.'), `
|
||||
const creds = ${JSON.stringify(creds)};
|
||||
const evalByCredential = Object.fromEntries(creds.map((c) => [c.credId, { first: unb64(c.prfSalt) }]));
|
||||
const a = await navigator.credentials.get({ publicKey: {
|
||||
challenge: crypto.getRandomValues(new Uint8Array(32)), rpId: 'localhost', timeout: 60000, userVerification: 'discouraged',
|
||||
allowCredentials: creds.map((c) => ({ type: 'public-key', id: unb64(c.credId) })),
|
||||
extensions: { prf: { evalByCredential } },
|
||||
} });
|
||||
const first = a.getClientExtensionResults().prf?.results?.first;
|
||||
return { credId: b64(a.rawId), secret: first ? b64(first) : null };`);
|
||||
if (!r.secret) throw new Error(i18n.t('This security key does not support the hmac-secret/PRF extension.'));
|
||||
return { credId: r.credId, secret: Buffer.from(r.secret, 'base64url') };
|
||||
}
|
||||
|
||||
module.exports = { register, derive };
|
||||
+84
-4
@@ -10,6 +10,7 @@ const rdp = require('./rdp');
|
||||
const { Updater } = require('./updater');
|
||||
const { createEmbed, embedSupported } = require('./rdp-embed');
|
||||
const i18n = require('../i18n');
|
||||
const fido = require('./fido');
|
||||
const applyLanguage = () => i18n.setLanguage(store.get().settings.language, app.getLocale());
|
||||
|
||||
let win;
|
||||
@@ -88,9 +89,14 @@ function createWindow() {
|
||||
win.webContents.setWindowOpenHandler(({ url }) => { shell.openExternal(url); return { action: 'deny' }; });
|
||||
}
|
||||
|
||||
// Solange MrTerm gesperrt ist, sind nur die Sperr-Kanäle erreichbar
|
||||
const OPEN_WHILE_LOCKED = new Set(['app:version']);
|
||||
function handle(channel, fn) {
|
||||
ipcMain.handle(channel, async (_e, ...args) => {
|
||||
try { return { ok: true, value: await fn(...args) }; }
|
||||
try {
|
||||
if (store.locked && !channel.startsWith('lock:') && !OPEN_WHILE_LOCKED.has(channel)) throw new Error(i18n.t('MrTerm is locked.'));
|
||||
return { ok: true, value: await fn(...args) };
|
||||
}
|
||||
catch (e) { return { ok: false, error: e.message || String(e) }; }
|
||||
});
|
||||
}
|
||||
@@ -100,6 +106,74 @@ ipcMain.on('win:min', () => win.minimize());
|
||||
ipcMain.on('win:max', () => (win.isMaximized() ? win.unmaximize() : win.maximize()));
|
||||
ipcMain.on('win:close', () => win.close());
|
||||
|
||||
// ---------- App-Sperre (Passwort / FIDO2) ----------
|
||||
const kdf = (pw, salt, N) => new Promise((resolve, reject) =>
|
||||
crypto.scrypt(String(pw), salt, 32, { N, r: 8, p: 1, maxmem: 256 * N * 8 }, (e, k) => (e ? reject(e) : resolve(k))));
|
||||
const fidoKek = (secret) => Buffer.from(crypto.hkdfSync('sha256', secret, Buffer.alloc(0), 'mrterm-fido-kek', 32));
|
||||
function lockStatus() {
|
||||
const { language, appTheme, accent } = store.get().settings;
|
||||
return {
|
||||
enabled: store.lockEnabled, locked: store.locked, hasPassword: !!store.lock?.password,
|
||||
fido: (store.lock?.fido || []).map(({ id, label }) => ({ id, label })), meta: { language, appTheme, accent },
|
||||
};
|
||||
}
|
||||
function requireUnlocked() { if (store.locked) throw new Error(i18n.t('MrTerm is locked.')); }
|
||||
const ensureLock = () => (store.lock = store.lock || { password: null, fido: [] });
|
||||
function afterUnlock() { applyLanguage(); scheduleUpdateCheck(); }
|
||||
|
||||
handle('lock:status', lockStatus);
|
||||
handle('lock:lock', () => { if (store.lockEnabled) store.locked = true; return lockStatus(); });
|
||||
handle('lock:unlockPassword', async (pw) => {
|
||||
const p = store.lock?.password;
|
||||
if (!p) throw new Error(i18n.t('No password set.'));
|
||||
const kek = await kdf(pw, Buffer.from(p.salt, 'base64'), p.N);
|
||||
try { store.unlockWith(kek, p.wrap); } catch { throw new Error(i18n.t('Wrong password.')); }
|
||||
afterUnlock();
|
||||
return true;
|
||||
});
|
||||
handle('lock:unlockFido', async () => {
|
||||
const list = store.lock?.fido || [];
|
||||
if (!list.length) throw new Error(i18n.t('No security key registered.'));
|
||||
const r = await fido.derive(win, list.map(({ credId, prfSalt }) => ({ credId, prfSalt })));
|
||||
const entry = list.find((f) => f.credId === r.credId);
|
||||
if (!entry) throw new Error(i18n.t('Unknown security key.'));
|
||||
try { store.unlockWith(fidoKek(r.secret), entry.wrap); } catch { throw new Error(i18n.t('This security key could not unlock the vault.')); }
|
||||
afterUnlock();
|
||||
return true;
|
||||
});
|
||||
handle('lock:setPassword', async (pw) => {
|
||||
requireUnlocked();
|
||||
if (!pw || String(pw).length < 6) throw new Error(i18n.t('The password must be at least 6 characters long.'));
|
||||
const salt = crypto.randomBytes(16), N = 2 ** 15;
|
||||
const kek = await kdf(pw, salt, N);
|
||||
ensureLock().password = { salt: salt.toString('base64'), N, wrap: store.wrapDek(kek) };
|
||||
store.save();
|
||||
return lockStatus();
|
||||
});
|
||||
handle('lock:removePassword', () => {
|
||||
requireUnlocked();
|
||||
if (store.lock) store.lock.password = null;
|
||||
store.dropLockIfEmpty();
|
||||
store.save();
|
||||
return lockStatus();
|
||||
});
|
||||
handle('lock:addFido', async (label) => {
|
||||
requireUnlocked();
|
||||
const credId = await fido.register(win);
|
||||
const prfSalt = crypto.randomBytes(32).toString('base64url');
|
||||
const r = await fido.derive(win, [{ credId, prfSalt }], i18n.t('Touch your security key again to finish.'));
|
||||
ensureLock().fido.push({ id: crypto.randomUUID(), label: label || i18n.t('Security key'), credId, prfSalt, wrap: store.wrapDek(fidoKek(r.secret)) });
|
||||
store.save();
|
||||
return lockStatus();
|
||||
});
|
||||
handle('lock:removeFido', (id) => {
|
||||
requireUnlocked();
|
||||
if (store.lock) store.lock.fido = store.lock.fido.filter((f) => f.id !== id);
|
||||
store.dropLockIfEmpty();
|
||||
store.save();
|
||||
return lockStatus();
|
||||
});
|
||||
|
||||
// ---------- Vault ----------
|
||||
handle('vault:get', () => ({ ...store.get(), encrypted: store.encrypted, platform: process.platform }));
|
||||
handle('vault:upsert', (col, item) => store.upsert(col, item));
|
||||
@@ -369,10 +443,16 @@ app.whenReady().then(() => {
|
||||
store.load();
|
||||
applyLanguage();
|
||||
createWindow();
|
||||
if (store.get().settings.updateAutoCheck && app.isPackaged) {
|
||||
setTimeout(() => updater.check().then((r) => { if (r.available) send('update:available', r); }).catch(() => {}), 6000);
|
||||
}
|
||||
scheduleUpdateCheck();
|
||||
});
|
||||
|
||||
// Automatische Update-Prüfung – bei gesperrtem Vault erst nach dem Entsperren (Einstellungen sind verschlüsselt)
|
||||
let updateScheduled = false;
|
||||
function scheduleUpdateCheck() {
|
||||
if (updateScheduled || store.sealed || !store.get().settings.updateAutoCheck || !app.isPackaged) return;
|
||||
updateScheduled = true;
|
||||
setTimeout(() => updater.check().then((r) => { if (r.available) send('update:available', r); }).catch(() => {}), 6000);
|
||||
}
|
||||
app.on('window-all-closed', () => { ssh.closeAll(); app.quit(); });
|
||||
|
||||
// Smoke-Test: MRTERM_SMOKE=<pfad.png> startet, loggt Renderer-Meldungen, speichert einen Screenshot und beendet.
|
||||
|
||||
+60
-2
@@ -31,16 +31,63 @@ const DEFAULTS = {
|
||||
updateToken: '',
|
||||
updateAutoCheck: true,
|
||||
updatePrerelease: false,
|
||||
autoLock: 0,
|
||||
language: 'auto',
|
||||
},
|
||||
};
|
||||
|
||||
const merge = (parsed) => ({ ...structuredClone(DEFAULTS), ...parsed, settings: { ...DEFAULTS.settings, ...(parsed.settings || {}) } });
|
||||
|
||||
// AES-256-GCM; Ergebnis als base64-Felder für JSON
|
||||
function box(key, plain) {
|
||||
const iv = crypto.randomBytes(12);
|
||||
const c = crypto.createCipheriv('aes-256-gcm', key, iv);
|
||||
const ct = Buffer.concat([c.update(plain), c.final()]);
|
||||
return { iv: iv.toString('base64'), tag: c.getAuthTag().toString('base64'), ct: ct.toString('base64') };
|
||||
}
|
||||
function unbox(key, b) {
|
||||
const d = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(b.iv, 'base64'));
|
||||
d.setAuthTag(Buffer.from(b.tag, 'base64'));
|
||||
return Buffer.concat([d.update(Buffer.from(b.ct, 'base64')), d.final()]);
|
||||
}
|
||||
|
||||
class Store {
|
||||
constructor() {
|
||||
this.dir = app.getPath('userData');
|
||||
this.file = path.join(this.dir, 'vault.dat');
|
||||
this.data = structuredClone(DEFAULTS);
|
||||
this.encrypted = false;
|
||||
// App-Sperre: Inhalt zusätzlich mit zufälligem Datenschlüssel (DEK, AES-256-GCM) verschlüsselt.
|
||||
// Der DEK liegt je Entsperrmethode verpackt vor: Passwort (scrypt) und/oder FIDO2-Schlüssel (PRF/hmac-secret).
|
||||
this.lock = null; // { password: { salt, N, wrap } | null, fido: [{ id, label, credId, prfSalt, wrap }] }
|
||||
this.dek = null;
|
||||
this.sealed = null; // verschlüsselter Inhalt, solange nach dem Start noch nicht entsperrt
|
||||
this.locked = false;
|
||||
}
|
||||
|
||||
get lockEnabled() { return !!(this.lock && (this.lock.password || this.lock.fido.length)); }
|
||||
|
||||
// Entsperren mit einem Schlüssel, der den DEK verpackt hat (wirft bei falschem Schlüssel)
|
||||
unlockWith(kek, wrap) {
|
||||
const dek = unbox(kek, wrap);
|
||||
if (this.sealed) {
|
||||
const parsed = JSON.parse(unbox(dek, this.sealed).toString('utf8'));
|
||||
this.data = merge(parsed);
|
||||
this.sealed = null;
|
||||
}
|
||||
this.dek = dek;
|
||||
this.locked = false;
|
||||
}
|
||||
|
||||
// Neue Entsperrmethode: verpackt den (ggf. neu erzeugten) DEK mit kek
|
||||
wrapDek(kek) {
|
||||
if (!this.dek) this.dek = crypto.randomBytes(32);
|
||||
return box(kek, this.dek);
|
||||
}
|
||||
|
||||
// Letzte Methode entfernt → Sperre aus, Inhalt wieder nur per Betriebssystem verschlüsselt
|
||||
dropLockIfEmpty() {
|
||||
if (!this.lockEnabled) { this.lock = null; this.dek = null; }
|
||||
}
|
||||
|
||||
canEncrypt() {
|
||||
@@ -64,12 +111,23 @@ class Store {
|
||||
json = raw.toString('utf8');
|
||||
}
|
||||
const parsed = JSON.parse(json);
|
||||
this.data = { ...structuredClone(DEFAULTS), ...parsed, settings: { ...DEFAULTS.settings, ...(parsed.settings || {}) } };
|
||||
if (parsed.mrtermLock) {
|
||||
// Gesperrt: nur Darstellungs-Einstellungen (meta) sind bis zum Entsperren bekannt
|
||||
this.lock = parsed.lock;
|
||||
this.sealed = parsed.data;
|
||||
this.locked = true;
|
||||
this.data = merge({ settings: parsed.meta || {} });
|
||||
} else this.data = merge(parsed);
|
||||
return this.data;
|
||||
}
|
||||
|
||||
save() {
|
||||
const json = JSON.stringify(this.data, null, 2);
|
||||
if (this.sealed) return; // Inhalt noch nicht entschlüsselt – nichts überschreiben
|
||||
let json = JSON.stringify(this.data, null, 2);
|
||||
if (this.lockEnabled && this.dek) {
|
||||
const { language, appTheme, accent } = this.data.settings;
|
||||
json = JSON.stringify({ mrtermLock: 1, meta: { language, appTheme, accent }, lock: this.lock, data: box(this.dek, Buffer.from(json)) });
|
||||
}
|
||||
const tmp = this.file + '.tmp';
|
||||
if (this.canEncrypt()) {
|
||||
fs.writeFileSync(tmp, Buffer.concat([Buffer.from('ENC1'), safeStorage.encryptString(json)]));
|
||||
|
||||
Reference in New Issue
Block a user