Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 511c6026ac | |||
| 85b401d05e | |||
| b54ff1b002 | |||
| a59a095691 | |||
| d32e851b74 | |||
| e3e6d04955 | |||
| 2c1b4a399a | |||
| 0a8dc8f7af | |||
| 6570611ed8 | |||
| ea13593925 |
@@ -40,19 +40,6 @@ dependencies on the server: the binary installs, updates and removes itself.
|
|||||||
- **HTTPS built in:** Let's Encrypt, a self-signed certificate, your own
|
- **HTTPS built in:** Let's Encrypt, a self-signed certificate, your own
|
||||||
certificate files, or plain HTTP behind a reverse proxy.
|
certificate files, or plain HTTP behind a reverse proxy.
|
||||||
|
|
||||||
## Screenshots
|
|
||||||
|
|
||||||
| | |
|
|
||||||
|---|---|
|
|
||||||
|  |  |
|
|
||||||
| **Peers:** status, endpoint, latency and traffic at a glance | **Peer:** traffic, latency, connection history and settings |
|
|
||||||
|  |  |
|
|
||||||
| **Server:** health, address plan, client defaults and firewall | **Settings:** users, web interface and API tokens |
|
|
||||||
|  |  |
|
|
||||||
| **My account:** profile, password and your app tokens | **Sign-in** |
|
|
||||||
|
|
||||||
The screenshots show sample data from the built-in simulator.
|
|
||||||
|
|
||||||
## Security
|
## Security
|
||||||
|
|
||||||
- **Client private keys are never stored.** A config is shown once, as a
|
- **Client private keys are never stored.** A config is shown once, as a
|
||||||
@@ -65,16 +52,19 @@ The screenshots show sample data from the built-in simulator.
|
|||||||
`CAP_NET_ADMIN` and `CAP_NET_BIND_SERVICE`, and can write only to
|
`CAP_NET_ADMIN` and `CAP_NET_BIND_SERVICE`, and can write only to
|
||||||
`/opt/ghostwire`.
|
`/opt/ghostwire`.
|
||||||
- **Sign-in:** one or more users, all admins. Passwords are stored as argon2id hashes.
|
- **Sign-in:** one or more users, all admins. Passwords are stored as argon2id hashes.
|
||||||
After 5 failed attempts, sign-in is locked for 15 minutes. Sessions use an
|
After 5 failed attempts from one IP address, sign-in from it is locked for 15
|
||||||
|
minutes; wrong two-step codes count too. Sessions use an
|
||||||
HttpOnly, SameSite=Strict cookie and last 12 hours by default.
|
HttpOnly, SameSite=Strict cookie and last 12 hours by default.
|
||||||
- **Two-step sign-in:** each user can add an authenticator app (TOTP), security
|
- **Two-step sign-in:** each user can add an authenticator app (TOTP) and
|
||||||
keys such as a YubiKey, and passkeys that sign in without a password, under
|
passkeys under My account. A passkey signs in on its own, without username
|
||||||
My account. Turning it on gives 10 one-time recovery codes. An admin can
|
and password, and also works as the second step after a password. It can live
|
||||||
require it for everyone (Settings → Sign-in) and reset it for a user who lost
|
on the device (Touch ID, Face ID, Windows Hello), in a password manager, or on
|
||||||
their phone or key. Security keys and passkeys use WebAuthn and need the
|
a YubiKey with a PIN set. Turning it on gives 10 one-time recovery codes. An
|
||||||
server's domain name with a trusted certificate (Let's Encrypt, certificate
|
admin can require it for everyone (Settings → Sign-in) and reset it for a user
|
||||||
files, or a reverse proxy); on a self-signed certificate or an IP address,
|
who lost their phone or key. Passkeys use WebAuthn and need the server's
|
||||||
only the authenticator app is offered. API tokens never need a second step.
|
domain name with a trusted certificate (Let's Encrypt, certificate files, or a
|
||||||
|
reverse proxy); on a self-signed certificate or an IP address, only the
|
||||||
|
authenticator app is offered. API tokens never need a second step.
|
||||||
- **API tokens** are stored only as hashes and can be read-only or full access.
|
- **API tokens** are stored only as hashes and can be read-only or full access.
|
||||||
- `config.json` holds the server private key and is readable only by the
|
- `config.json` holds the server private key and is readable only by the
|
||||||
service (0600).
|
service (0600).
|
||||||
@@ -227,7 +217,7 @@ After editing `config.json` by hand, run `sudo systemctl reload ghostwire`.
|
|||||||
| File | Content |
|
| File | Content |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `GHOSTWIRE` | the program |
|
| `GHOSTWIRE` | the program |
|
||||||
| `config.json` | all settings, server key, peers, token hashes (0600) |
|
| `config.json` | all settings, server key, peers, pending setup links with their PINs, user password hashes, authenticator app secrets, passkeys, recovery code and token hashes (0600) |
|
||||||
| `stats.json` | traffic and connection history per peer |
|
| `stats.json` | traffic and connection history per peer |
|
||||||
| `geo-country.mmdb`, `geo-asn.mmdb` | DB-IP Lite databases for country and network lookups |
|
| `geo-country.mmdb`, `geo-asn.mmdb` | DB-IP Lite databases for country and network lookups |
|
||||||
| `GHOSTWIRE.jsonl` | log, one JSON object per line. Changes carry `"audit":true` |
|
| `GHOSTWIRE.jsonl` | log, one JSON object per line. Changes carry `"audit":true` |
|
||||||
@@ -237,7 +227,8 @@ After editing `config.json` by hand, run `sudo systemctl reload ghostwire`.
|
|||||||
|
|
||||||
Base path `/api/v1`. The web interface signs in with a session cookie; every
|
Base path `/api/v1`. The web interface signs in with a session cookie; every
|
||||||
user is an admin. Apps and scripts use `Authorization: Bearer <token>`; create
|
user is an admin. Apps and scripts use `Authorization: Bearer <token>`; create
|
||||||
the token under Settings → Pair iOS app. A token belongs to the user who made
|
the token under Settings → Pair iOS app, or in the iOS app under Settings →
|
||||||
|
Access → API tokens. A token belongs to the user who made
|
||||||
it and is revoked when that user is deleted. A read-only token may only use
|
it and is revoked when that user is deleted. A read-only token may only use
|
||||||
GET. Full-access tokens can do everything the web interface does except backup
|
GET. Full-access tokens can do everything the web interface does except backup
|
||||||
and restore. Users, passwords and API tokens need a full-access token even for
|
and restore. Users, passwords and API tokens need a full-access token even for
|
||||||
@@ -262,7 +253,7 @@ POST /auth/login/totp · /auth/login/recovery {"ticket", "code"}
|
|||||||
POST /auth/login/key/begin {"ticket"} · /auth/login/key/finish?ticket= (body: the WebAuthn credential)
|
POST /auth/login/key/begin {"ticket"} · /auth/login/key/finish?ticket= (body: the WebAuthn credential)
|
||||||
POST /auth/login/passkey/begin · /auth/login/passkey/finish?id=
|
POST /auth/login/passkey/begin · /auth/login/passkey/finish?id=
|
||||||
signed in: GET /auth/mfa · POST /auth/mfa/totp/setup · /auth/mfa/totp/confirm · DELETE /auth/mfa/totp
|
signed in: GET /auth/mfa · POST /auth/mfa/totp/setup · /auth/mfa/totp/confirm · DELETE /auth/mfa/totp
|
||||||
signed in: POST /auth/mfa/keys/begin {"passkey"} · /auth/mfa/keys/finish?name= · PATCH|DELETE /auth/mfa/keys/{id}
|
signed in: POST /auth/mfa/keys/begin · /auth/mfa/keys/finish?name= · PATCH|DELETE /auth/mfa/keys/{id}
|
||||||
signed in: POST /auth/mfa/recovery-codes
|
signed in: POST /auth/mfa/recovery-codes
|
||||||
GET /status GET /stats?range=24h|7d|30d|90d
|
GET /status GET /stats?range=24h|7d|30d|90d
|
||||||
GET /server PATCH /server POST /server/rotate-key GET /server/detect-ip
|
GET /server PATCH /server POST /server/rotate-key GET /server/detect-ip
|
||||||
@@ -306,7 +297,8 @@ override a drop in another table, so if ufw or firewalld is active, allow UDP
|
|||||||
|
|
||||||
The native iPhone app (SwiftUI, iOS 17+) lives in its own project,
|
The native iPhone app (SwiftUI, iOS 17+) lives in its own project,
|
||||||
GHOSTWIRE-Companion. It does everything the web interface does except
|
GHOSTWIRE-Companion. It does everything the web interface does except
|
||||||
password, API tokens and backups. Pair it in the web interface under
|
backup and restore, and adding an authenticator app or passkeys for two-step
|
||||||
|
sign-in. Pair it in the web interface under
|
||||||
Settings → Pair iOS app: scan the QR code, or tap "Copy pairing code" and paste
|
Settings → Pair iOS app: scan the QR code, or tap "Copy pairing code" and paste
|
||||||
it into the app's "Enter manually". Self-signed certificates are pinned during
|
it into the app's "Enter manually". Self-signed certificates are pinned during
|
||||||
pairing.
|
pairing.
|
||||||
|
|||||||
@@ -232,7 +232,7 @@ func (a *App) login(w http.ResponseWriter, r *http.Request) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Warn("login failed", "user", in.Username, "remote", ip, "reason", err.Error())
|
slog.Warn("login failed", "user", in.Username, "remote", ip, "reason", err.Error())
|
||||||
code := http.StatusUnauthorized
|
code := http.StatusUnauthorized
|
||||||
if errors.Is(err, errLocked) {
|
if errors.Is(err, errLocked) || errors.Is(err, errBusy) {
|
||||||
code = http.StatusTooManyRequests
|
code = http.StatusTooManyRequests
|
||||||
}
|
}
|
||||||
writeJSON(w, code, map[string]string{"error": err.Error()})
|
writeJSON(w, code, map[string]string{"error": err.Error()})
|
||||||
|
|||||||
@@ -144,6 +144,8 @@ td { padding: 12px; border-bottom: 1px solid var(--line-2); vertical-align: midd
|
|||||||
tr:last-child td { border-bottom: 0; }
|
tr:last-child td { border-bottom: 0; }
|
||||||
.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||||
td .note { font-size: 12px; color: var(--ink-3); }
|
td .note { font-size: 12px; color: var(--ink-3); }
|
||||||
|
a.pname { color: var(--ink); font-weight: 600; text-decoration: none; }
|
||||||
|
a.pname:hover, a.pname:focus-visible { color: var(--ink); text-decoration: underline; text-underline-offset: 3px; }
|
||||||
.empty { padding: 24px 12px; margin: 0; text-align: center; color: var(--ink-3); }
|
.empty { padding: 24px 12px; margin: 0; text-align: center; color: var(--ink-3); }
|
||||||
|
|
||||||
/* forms */
|
/* forms */
|
||||||
|
|||||||
@@ -144,7 +144,6 @@
|
|||||||
if (!m) return '';
|
if (!m) return '';
|
||||||
const parts = [];
|
const parts = [];
|
||||||
if (m.totp) parts.push('App');
|
if (m.totp) parts.push('App');
|
||||||
if (m.keys) parts.push(m.keys === 1 ? '1 key' : m.keys + ' keys');
|
|
||||||
if (m.passkeys) parts.push(m.passkeys === 1 ? '1 passkey' : m.passkeys + ' passkeys');
|
if (m.passkeys) parts.push(m.passkeys === 1 ? '1 passkey' : m.passkeys + ' passkeys');
|
||||||
return parts.join(', ');
|
return parts.join(', ');
|
||||||
}
|
}
|
||||||
@@ -258,13 +257,26 @@
|
|||||||
else if (okMsg) toast(okMsg);
|
else if (okMsg) toast(okMsg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// dialog shows a modal dialog. Extensions such as Bitwarden move elements
|
||||||
|
// around in <body>; a moved dialog stays open but drops out of the top
|
||||||
|
// layer to the bottom of the page, so it is shown as a modal again. That
|
||||||
|
// goes through close(), whose close event arrives after the dialog is open
|
||||||
|
// again and is kept from the listeners added by callers.
|
||||||
function dialog(build) {
|
function dialog(build) {
|
||||||
const d = h('dialog');
|
const d = h('dialog');
|
||||||
const close = () => d.close();
|
const close = () => d.close();
|
||||||
d.addEventListener('close', () => d.remove());
|
const moved = new MutationObserver(() => {
|
||||||
|
if (d.open && d.isConnected && !d.matches(':modal')) { d.close(); d.showModal(); }
|
||||||
|
});
|
||||||
|
d.addEventListener('close', (e) => {
|
||||||
|
if (d.open) { e.stopImmediatePropagation(); return; }
|
||||||
|
moved.disconnect();
|
||||||
|
d.remove();
|
||||||
|
});
|
||||||
d.append(build(close));
|
d.append(build(close));
|
||||||
document.body.append(d);
|
document.body.append(d);
|
||||||
d.showModal();
|
d.showModal();
|
||||||
|
moved.observe(document.body, { childList: true, subtree: true });
|
||||||
return d;
|
return d;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -636,7 +648,7 @@
|
|||||||
// allows it.
|
// allows it.
|
||||||
const passkeyRow = h('div', { class: 'loginalt', hidden: true },
|
const passkeyRow = h('div', { class: 'loginalt', hidden: true },
|
||||||
h('div', { class: 'or' }, 'or'),
|
h('div', { class: 'or' }, 'or'),
|
||||||
h('button', { type: 'button', class: 'btn altbtn', onClick: async () => {
|
h('button', { type: 'button', class: 'btn altbtn signin', onClick: async () => {
|
||||||
err.textContent = '';
|
err.textContent = '';
|
||||||
try {
|
try {
|
||||||
const b = await api('POST', '/auth/login/passkey/begin');
|
const b = await api('POST', '/auth/login/passkey/begin');
|
||||||
@@ -644,7 +656,7 @@
|
|||||||
await api('POST', '/auth/login/passkey/finish?id=' + encodeURIComponent(b.id), cred);
|
await api('POST', '/auth/login/passkey/finish?id=' + encodeURIComponent(b.id), cred);
|
||||||
await signedIn();
|
await signedIn();
|
||||||
} catch (x) { err.textContent = keyError(x); }
|
} catch (x) { err.textContent = keyError(x); }
|
||||||
} }, icon('key', 18), 'Sign in with a passkey'));
|
} }, icon('key', 18), h('span', { class: 'en' }, 'Sign in with a passkey'), h('span', { class: 'ja', lang: 'ja', 'aria-hidden': 'true' }, 'パスキーでサインイン')));
|
||||||
if (window.PublicKeyCredential) {
|
if (window.PublicKeyCredential) {
|
||||||
api('GET', '/auth/options').then((o) => { passkeyRow.hidden = !o.passkeys; }).catch(() => {});
|
api('GET', '/auth/options').then((o) => { passkeyRow.hidden = !o.passkeys; }).catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -706,7 +718,7 @@
|
|||||||
function keyError(x) {
|
function keyError(x) {
|
||||||
if (x && x.name === 'NotAllowedError') return 'Cancelled or timed out. Try again.';
|
if (x && x.name === 'NotAllowedError') return 'Cancelled or timed out. Try again.';
|
||||||
if (x && x.name === 'InvalidStateError') return 'This key is already set up for your account.';
|
if (x && x.name === 'InvalidStateError') return 'This key is already set up for your account.';
|
||||||
if (x && x.name === 'SecurityError') return 'Security keys need this site on its domain name with a trusted certificate.';
|
if (x && x.name === 'SecurityError') return 'Passkeys need this site on its domain name with a trusted certificate.';
|
||||||
return x.message;
|
return x.message;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -720,11 +732,11 @@
|
|||||||
let mode = canKey ? 'key' : methods.includes('totp') ? 'totp' : 'recovery';
|
let mode = canKey ? 'key' : methods.includes('totp') ? 'totp' : 'recovery';
|
||||||
const box = h('div', { class: 'loginform' });
|
const box = h('div', { class: 'loginform' });
|
||||||
const TITLES = {
|
const TITLES = {
|
||||||
key: ['Use your security key', 'Insert your key and touch it, or use the passkey on this device.'],
|
key: ['Use your passkey', 'Confirm with Touch ID, Face ID, Windows Hello or your password manager, or insert your YubiKey and touch it.'],
|
||||||
totp: ['Enter the code', 'The 6-digit code from your authenticator app.'],
|
totp: ['Enter the code', 'The 6-digit code from your authenticator app.'],
|
||||||
recovery: ['Use a recovery code', 'One of the codes you saved when you set up two-step sign-in. Each works once.'],
|
recovery: ['Use a recovery code', 'One of the codes you saved when you set up two-step sign-in. Each works once.'],
|
||||||
};
|
};
|
||||||
const LINKS = { key: 'Use a security key instead', totp: 'Use an authenticator code instead', recovery: 'Use a recovery code' };
|
const LINKS = { key: 'Use a passkey instead', totp: 'Use an authenticator code instead', recovery: 'Use a recovery code' };
|
||||||
const head = h('div', { class: 'logintext' });
|
const head = h('div', { class: 'logintext' });
|
||||||
const draw = () => {
|
const draw = () => {
|
||||||
const err = h('p', { class: 'err-text', role: 'alert' });
|
const err = h('p', { class: 'err-text', role: 'alert' });
|
||||||
@@ -733,7 +745,7 @@
|
|||||||
.map((m) => h('button', { type: 'button', class: 'linkbtn', onClick: () => { mode = m; draw(); } }, LINKS[m]));
|
.map((m) => h('button', { type: 'button', class: 'linkbtn', onClick: () => { mode = m; draw(); } }, LINKS[m]));
|
||||||
const foot = h('div', { class: 'loginlinks' }, others, h('button', { type: 'button', class: 'linkbtn', onClick: showLogin }, 'Start over'));
|
const foot = h('div', { class: 'loginlinks' }, others, h('button', { type: 'button', class: 'linkbtn', onClick: showLogin }, 'Start over'));
|
||||||
if (mode === 'key') {
|
if (mode === 'key') {
|
||||||
const btn = h('button', { type: 'button', class: 'btn primary' }, 'Use security key');
|
const btn = h('button', { type: 'button', class: 'btn primary' }, 'Use passkey');
|
||||||
const go = async () => {
|
const go = async () => {
|
||||||
err.textContent = '';
|
err.textContent = '';
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
@@ -788,8 +800,7 @@
|
|||||||
h('p', null, 'This server asks for a second step after the password. Add one to continue.')),
|
h('p', null, 'This server asks for a second step after the password. Add one to continue.')),
|
||||||
h('div', { class: 'loginform' },
|
h('div', { class: 'loginform' },
|
||||||
h('button', { type: 'button', class: 'btn primary', onClick: () => addTOTP(done) }, 'Use an authenticator app'),
|
h('button', { type: 'button', class: 'btn primary', onClick: () => addTOTP(done) }, 'Use an authenticator app'),
|
||||||
keys ? h('button', { type: 'button', class: 'btn altbtn', onClick: () => addKey(false, done) }, 'Use a security key') : null,
|
keys ? h('button', { type: 'button', class: 'btn altbtn', onClick: () => addPasskey(done) }, 'Use a passkey') : null,
|
||||||
keys ? h('button', { type: 'button', class: 'btn altbtn', onClick: () => addKey(true, done) }, 'Use a passkey') : null,
|
|
||||||
h('div', { class: 'loginlinks' }, h('button', { type: 'button', class: 'linkbtn', onClick: logout }, 'Sign out'))))));
|
h('div', { class: 'loginlinks' }, h('button', { type: 'button', class: 'linkbtn', onClick: logout }, 'Sign out'))))));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -841,30 +852,28 @@
|
|||||||
code.focus();
|
code.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
// addKey adds a security key, or with passkey a passkey that also signs
|
// addPasskey adds a passkey. It signs in on its own, and also serves as
|
||||||
// in without a password.
|
// the second step after a password.
|
||||||
function addKey(passkey, onDone) {
|
function addPasskey(onDone) {
|
||||||
const nm = h('input', { id: 'kn', value: passkey ? 'Passkey' : 'YubiKey', autocomplete: 'off', maxLength: 64 });
|
const nm = h('input', { id: 'kn', value: 'Passkey', autocomplete: 'off', maxLength: 64 });
|
||||||
const e = h('p', { class: 'err-text', role: 'alert' });
|
const e = h('p', { class: 'err-text', role: 'alert' });
|
||||||
const btn = h('button', { type: 'submit', class: 'btn primary' }, passkey ? 'Add passkey' : 'Add security key');
|
const btn = h('button', { type: 'submit', class: 'btn primary' }, 'Add passkey');
|
||||||
dialog((close) => h('form', { class: 'dlg', onSubmit: async (ev) => {
|
dialog((close) => h('form', { class: 'dlg', onSubmit: async (ev) => {
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
e.textContent = '';
|
e.textContent = '';
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
try {
|
try {
|
||||||
const opts = await api('POST', '/auth/mfa/keys/begin', { passkey });
|
const opts = await api('POST', '/auth/mfa/keys/begin');
|
||||||
const cred = await webauthnCreate(opts);
|
const cred = await webauthnCreate(opts);
|
||||||
const res = await api('POST', '/auth/mfa/keys/finish?name=' + encodeURIComponent(nm.value.trim()), cred);
|
const res = await api('POST', '/auth/mfa/keys/finish?name=' + encodeURIComponent(nm.value.trim()), cred);
|
||||||
close();
|
close();
|
||||||
toast((passkey ? 'Passkey' : 'Security key') + ' added');
|
toast('Passkey added');
|
||||||
afterAdd(res, onDone);
|
afterAdd(res, onDone);
|
||||||
} catch (x) { e.textContent = keyError(x); btn.disabled = false; }
|
} catch (x) { e.textContent = keyError(x); btn.disabled = false; }
|
||||||
} },
|
} },
|
||||||
h('h2', null, passkey ? 'Add a passkey' : 'Add a security key'),
|
h('h2', null, 'Add a passkey'),
|
||||||
h('p', null, passkey
|
h('p', null, 'A passkey signs you in on its own, without username and password, and also works as the second step after your password. It can live on this device (Touch ID, Face ID, Windows Hello), in your password manager, or on a YubiKey with a PIN set.'),
|
||||||
? 'A passkey signs you in on its own, without username and password. It can live in your password manager, on this device (Touch ID, Face ID, Windows Hello) or on a YubiKey.'
|
h('div', { class: 'field' }, h('label', { htmlFor: 'kn' }, 'Name'), nm, h('span', { class: 'hint' }, 'So you can tell your passkeys apart, for example "MacBook" or "YubiKey"')),
|
||||||
: 'A YubiKey or other FIDO2 key, asked for after your password. Have it ready: your browser asks you to insert and touch it.'),
|
|
||||||
h('div', { class: 'field' }, h('label', { htmlFor: 'kn' }, 'Name'), nm, h('span', { class: 'hint' }, 'So you can tell your keys apart')),
|
|
||||||
e,
|
e,
|
||||||
h('div', { class: 'foot' }, h('button', { type: 'button', class: 'btn', onClick: close }, 'Cancel'), btn)));
|
h('div', { class: 'foot' }, h('button', { type: 'button', class: 'btn', onClick: close }, 'Cancel'), btn)));
|
||||||
nm.select();
|
nm.select();
|
||||||
@@ -910,7 +919,7 @@
|
|||||||
}
|
}
|
||||||
for (const k of s.keys) {
|
for (const k of s.keys) {
|
||||||
rows.push(h('div', { class: 'mfarow' }, h('div', { class: 'grow' }, h('strong', null, k.name),
|
rows.push(h('div', { class: 'mfarow' }, h('div', { class: 'grow' }, h('strong', null, k.name),
|
||||||
h('div', { class: 'hint' }, (k.passkey ? 'Passkey' : 'Security key') + ' · added ' + fmtDate(k.created) + ' · ' + (k.lastUsed ? 'last used ' + ago(k.lastUsed) : 'not used yet'))),
|
h('div', { class: 'hint' }, 'Added ' + fmtDate(k.created) + ' · ' + (k.lastUsed ? 'last used ' + ago(k.lastUsed) : 'not used yet'))),
|
||||||
h('button', { type: 'button', class: 'btn small', onClick: () => renameKey(k) }, 'Rename'),
|
h('button', { type: 'button', class: 'btn small', onClick: () => renameKey(k) }, 'Rename'),
|
||||||
h('button', { type: 'button', class: 'btn danger small', onClick: () => removeKey(k) }, 'Remove')));
|
h('button', { type: 'button', class: 'btn danger small', onClick: () => removeKey(k) }, 'Remove')));
|
||||||
}
|
}
|
||||||
@@ -922,9 +931,8 @@
|
|||||||
rows.length ? h('div', { class: 'mfalist' }, rows) : h('div', { class: 'notice' }, s.required ? 'Two-step sign-in is required on this server.' : 'Two-step sign-in is off for your account.'),
|
rows.length ? h('div', { class: 'mfalist' }, rows) : h('div', { class: 'notice' }, s.required ? 'Two-step sign-in is required on this server.' : 'Two-step sign-in is off for your account.'),
|
||||||
h('div', { class: 'actions section' },
|
h('div', { class: 'actions section' },
|
||||||
s.totp ? null : h('button', { type: 'button', class: 'btn primary', onClick: () => addTOTP(draw) }, 'Add authenticator app'),
|
s.totp ? null : h('button', { type: 'button', class: 'btn primary', onClick: () => addTOTP(draw) }, 'Add authenticator app'),
|
||||||
keys ? h('button', { type: 'button', class: 'btn', onClick: () => addKey(false, draw) }, 'Add security key') : null,
|
keys ? h('button', { type: 'button', class: 'btn', onClick: () => addPasskey(draw) }, 'Add passkey') : null),
|
||||||
keys ? h('button', { type: 'button', class: 'btn', onClick: () => addKey(true, draw) }, 'Add passkey') : null),
|
keys ? null : h('p', { class: 'hint section' }, 'Passkeys need this site on its domain name with a trusted certificate (Let\'s Encrypt or certificate files).'),
|
||||||
keys ? null : h('p', { class: 'hint section' }, 'Security keys and passkeys need this site on its domain name with a trusted certificate (Let\'s Encrypt or certificate files).'),
|
|
||||||
].filter(Boolean));
|
].filter(Boolean));
|
||||||
};
|
};
|
||||||
draw();
|
draw();
|
||||||
@@ -1116,7 +1124,7 @@
|
|||||||
return hit && keep;
|
return hit && keep;
|
||||||
});
|
});
|
||||||
tbody.replaceChildren(...sorted(rows).map((p) => h('tr', null,
|
tbody.replaceChildren(...sorted(rows).map((p) => h('tr', null,
|
||||||
h('td', null, h('a', { href: '#/peers/' + p.id }, h('strong', null, p.name)), p.note ? h('div', { class: 'note' }, p.note) : null),
|
h('td', null, h('a', { class: 'pname', href: '#/peers/' + p.id }, p.name), p.note ? h('div', { class: 'note' }, p.note) : null),
|
||||||
h('td', { class: 'mono' }, p.ipv4),
|
h('td', { class: 'mono' }, p.ipv4),
|
||||||
h('td', null, badge(peerState(p))),
|
h('td', null, badge(peerState(p))),
|
||||||
h('td', { class: 'mono muted' }, p.stats.endpoint || '–',
|
h('td', { class: 'mono muted' }, p.stats.endpoint || '–',
|
||||||
@@ -1839,7 +1847,7 @@
|
|||||||
h('div', { class: 'foot' }, h('button', { type: 'button', class: 'btn', onClick: close }, 'Cancel'), h('button', { type: 'submit', class: 'btn primary' }, 'Reset password'))));
|
h('div', { class: 'foot' }, h('button', { type: 'button', class: 'btn', onClick: close }, 'Cancel'), h('button', { type: 'submit', class: 'btn primary' }, 'Reset password'))));
|
||||||
};
|
};
|
||||||
const resetMFA = async (u) => {
|
const resetMFA = async (u) => {
|
||||||
if (!await confirmDialog({ title: 'Reset two-step sign-in for ' + u.username + '?', text: 'Their authenticator app, security keys, passkeys and recovery codes are removed. They sign in with their password and can set it up again.', ok: 'Reset', danger: true })) return;
|
if (!await confirmDialog({ title: 'Reset two-step sign-in for ' + u.username + '?', text: 'Their authenticator app, passkeys and recovery codes are removed. They sign in with their password and can set it up again.', ok: 'Reset', danger: true })) return;
|
||||||
try { await api('POST', '/users/' + u.id + '/reset-mfa'); toast('Two-step sign-in reset for ' + u.username); reloadUsers(); } catch (x) { toast(x.message, true); }
|
try { await api('POST', '/users/' + u.id + '/reset-mfa'); toast('Two-step sign-in reset for ' + u.username); reloadUsers(); } catch (x) { toast(x.message, true); }
|
||||||
};
|
};
|
||||||
const deleteUser = async (u) => {
|
const deleteUser = async (u) => {
|
||||||
@@ -2017,7 +2025,7 @@
|
|||||||
|
|
||||||
h('section', { class: 'card', 'aria-labelledby': 'sgn' },
|
h('section', { class: 'card', 'aria-labelledby': 'sgn' },
|
||||||
h('h2', { id: 'sgn' }, 'Sign-in'),
|
h('h2', { id: 'sgn' }, 'Sign-in'),
|
||||||
h('p', { class: 'lead' }, 'Everyone sets up two-step sign-in under My account: an authenticator app, security keys such as a YubiKey, or passkeys. Changes apply immediately.'),
|
h('p', { class: 'lead' }, 'Everyone sets up two-step sign-in under My account: an authenticator app or passkeys, including on a YubiKey. Changes apply immediately.'),
|
||||||
h('label', { class: 'check' }, requireBox, h('span', null, 'Require two-step sign-in for everyone', h('br'),
|
h('label', { class: 'check' }, requireBox, h('span', null, 'Require two-step sign-in for everyone', h('br'),
|
||||||
h('span', { class: 'hint' }, 'Users without it are asked to set it up right after their password. To help someone who lost their phone or key, use Edit → Reset two-step sign-in.')))),
|
h('span', { class: 'hint' }, 'Users without it are asked to set it up right after their password. To help someone who lost their phone or key, use Edit → Reset two-step sign-in.')))),
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -26,12 +27,23 @@ const (
|
|||||||
argonKeyLen = 32
|
argonKeyLen = 32
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Every argon2 run takes argonMemory (64 MiB). argonSlots caps how many run
|
||||||
|
// at once, so a burst of sign-ins cannot run the server out of memory: two
|
||||||
|
// slots are 128 MiB at most.
|
||||||
|
var argonSlots = make(chan struct{}, 2)
|
||||||
|
|
||||||
|
func argonKey(pw, salt []byte, t, m uint32, p uint8, n uint32) []byte {
|
||||||
|
argonSlots <- struct{}{}
|
||||||
|
defer func() { <-argonSlots }()
|
||||||
|
return argon2.IDKey(pw, salt, t, m, p, n)
|
||||||
|
}
|
||||||
|
|
||||||
func hashPassword(pw string) (string, error) {
|
func hashPassword(pw string) (string, error) {
|
||||||
salt := make([]byte, 16)
|
salt := make([]byte, 16)
|
||||||
if _, err := rand.Read(salt); err != nil {
|
if _, err := rand.Read(salt); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
key := argon2.IDKey([]byte(pw), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
key := argonKey([]byte(pw), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||||
b64 := base64.RawStdEncoding
|
b64 := base64.RawStdEncoding
|
||||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||||
argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
|
argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
|
||||||
@@ -54,7 +66,7 @@ func verifyPassword(encoded, pw string) bool {
|
|||||||
if err1 != nil || err2 != nil {
|
if err1 != nil || err2 != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
got := argon2.IDKey([]byte(pw), salt, t, m, p, uint32(len(want)))
|
got := argonKey([]byte(pw), salt, t, m, p, uint32(len(want)))
|
||||||
return subtle.ConstantTimeCompare(got, want) == 1
|
return subtle.ConstantTimeCompare(got, want) == 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,13 +152,17 @@ type Auth struct {
|
|||||||
sessions map[string]*session
|
sessions map[string]*session
|
||||||
used map[string]tokenUse
|
used map[string]tokenUse
|
||||||
logins map[string]tokenUse // last sign-in per user ID
|
logins map[string]tokenUse // last sign-in per user ID
|
||||||
fails map[string]*failState
|
fails map[string]*failState // by lockKey
|
||||||
|
waiting int // sign-ins waiting for or running a password check
|
||||||
mfa mfaState
|
mfa mfaState
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
maxFailures = 5
|
maxFailures = 5
|
||||||
lockoutTime = 15 * time.Minute
|
lockoutTime = 15 * time.Minute
|
||||||
|
// maxWaiting sign-ins may wait for a password check; more are turned
|
||||||
|
// away until the queue is shorter.
|
||||||
|
maxWaiting = 16
|
||||||
)
|
)
|
||||||
|
|
||||||
func newAuth(s *Store) *Auth {
|
func newAuth(s *Store) *Auth {
|
||||||
@@ -155,23 +171,51 @@ func newAuth(s *Store) *Auth {
|
|||||||
|
|
||||||
func cookieName() string { return appName + "_session" }
|
func cookieName() string { return appName + "_session" }
|
||||||
|
|
||||||
var errLocked = errors.New("too many failed attempts, try again later")
|
var (
|
||||||
|
errLocked = errors.New("too many failed attempts, try again later")
|
||||||
|
errBusy = errors.New("too many sign-ins at once, try again in a moment")
|
||||||
|
)
|
||||||
|
|
||||||
|
// lockKey is what failed sign-ins are counted by: the IPv4 address, or the
|
||||||
|
// /64 network of an IPv6 address, since one device can pick any address in
|
||||||
|
// its /64.
|
||||||
|
func lockKey(ip string) string {
|
||||||
|
a, err := netip.ParseAddr(ip)
|
||||||
|
if err != nil || a.Unmap().Is4() {
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
p, _ := a.Prefix(64)
|
||||||
|
return p.String()
|
||||||
|
}
|
||||||
|
|
||||||
// Login checks the credentials and returns a new session id, or, for a user
|
// Login checks the credentials and returns a new session id, or, for a user
|
||||||
// with two-step sign-in, a ticket for the second step.
|
// with two-step sign-in, a ticket for the second step.
|
||||||
func (a *Auth) Login(user, pw, ip string) (sessionID, ticket string, err error) {
|
func (a *Auth) Login(user, pw, ip string) (sessionID, ticket string, err error) {
|
||||||
a.mu.Lock()
|
|
||||||
f := a.fails[ip]
|
|
||||||
if f != nil && time.Now().Before(f.until) {
|
|
||||||
a.mu.Unlock()
|
|
||||||
return "", "", errLocked
|
|
||||||
}
|
|
||||||
a.mu.Unlock()
|
|
||||||
|
|
||||||
cfg := a.store.Get()
|
cfg := a.store.Get()
|
||||||
if !cfg.passwordSet() {
|
if !cfg.passwordSet() {
|
||||||
return "", "", errors.New("no password is set; run: " + appName + " passwd")
|
return "", "", errors.New("no password is set; run: " + appName + " passwd")
|
||||||
}
|
}
|
||||||
|
// The attempt counts as failed before the password is checked, so
|
||||||
|
// parallel attempts cannot get past the lockout; a right password takes
|
||||||
|
// it back.
|
||||||
|
a.mu.Lock()
|
||||||
|
if a.lockedLocked(ip) {
|
||||||
|
a.mu.Unlock()
|
||||||
|
return "", "", errLocked
|
||||||
|
}
|
||||||
|
if a.waiting >= maxWaiting {
|
||||||
|
a.mu.Unlock()
|
||||||
|
return "", "", errBusy
|
||||||
|
}
|
||||||
|
a.waiting++
|
||||||
|
undo := a.failLocked(ip)
|
||||||
|
a.mu.Unlock()
|
||||||
|
defer func() {
|
||||||
|
a.mu.Lock()
|
||||||
|
a.waiting--
|
||||||
|
a.mu.Unlock()
|
||||||
|
}()
|
||||||
|
|
||||||
// An unknown username costs as much time as a wrong password, so the
|
// An unknown username costs as much time as a wrong password, so the
|
||||||
// answer time does not tell which usernames exist.
|
// answer time does not tell which usernames exist.
|
||||||
u := cfg.userByName(strings.TrimSpace(user))
|
u := cfg.userByName(strings.TrimSpace(user))
|
||||||
@@ -185,21 +229,13 @@ func (a *Auth) Login(user, pw, ip string) (sessionID, ticket string, err error)
|
|||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if !okUser || !okPw {
|
if !okUser || !okPw {
|
||||||
if f == nil {
|
|
||||||
f = &failState{}
|
|
||||||
a.fails[ip] = f
|
|
||||||
}
|
|
||||||
f.count++
|
|
||||||
if f.count >= maxFailures {
|
|
||||||
f.count = 0
|
|
||||||
f.until = time.Now().Add(lockoutTime)
|
|
||||||
}
|
|
||||||
return "", "", errors.New("wrong username or password")
|
return "", "", errors.New("wrong username or password")
|
||||||
}
|
}
|
||||||
|
undo()
|
||||||
if u.hasMFA() {
|
if u.hasMFA() {
|
||||||
return "", a.newTicketLocked(u, ip), nil
|
return "", a.newTicketLocked(u, ip), nil
|
||||||
}
|
}
|
||||||
delete(a.fails, ip)
|
delete(a.fails, lockKey(ip))
|
||||||
a.logins[u.ID] = tokenUse{At: time.Now(), IP: ip}
|
a.logins[u.ID] = tokenUse{At: time.Now(), IP: ip}
|
||||||
return a.newSessionLocked(cfg, u, sessionInfo{Started: time.Now(), IP: ip}), "", nil
|
return a.newSessionLocked(cfg, u, sessionInfo{Started: time.Now(), IP: ip}), "", nil
|
||||||
}
|
}
|
||||||
@@ -321,9 +357,9 @@ func (a *Auth) sweep() {
|
|||||||
delete(a.sessions, id)
|
delete(a.sessions, id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for ip, f := range a.fails {
|
for key, f := range a.fails {
|
||||||
if now.After(f.until) && f.count == 0 {
|
if now.After(f.until) && f.count == 0 {
|
||||||
delete(a.fails, ip)
|
delete(a.fails, key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for id, t := range a.mfa.tickets {
|
for id, t := range a.mfa.tickets {
|
||||||
|
|||||||
@@ -204,6 +204,9 @@ func (c *Config) applyDefaults() {
|
|||||||
c.Users = []User{u}
|
c.Users = []User{u}
|
||||||
}
|
}
|
||||||
c.Admin = nil
|
c.Admin = nil
|
||||||
|
for i := range c.Users {
|
||||||
|
dropSecurityKeys(&c.Users[i])
|
||||||
|
}
|
||||||
for i := range c.APITokens {
|
for i := range c.APITokens {
|
||||||
if c.APITokens[i].UserID == "" {
|
if c.APITokens[i].UserID == "" {
|
||||||
c.APITokens[i].UserID = c.Users[0].ID // tokens from before users existed
|
c.APITokens[i].UserID = c.Users[0].ID // tokens from before users existed
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package main
|
|||||||
import (
|
import (
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -38,6 +40,15 @@ type Kernel interface {
|
|||||||
Close() error
|
Close() error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readSysctl returns the trimmed content of a /proc/sys file, or "".
|
||||||
|
func readSysctl(path string) string {
|
||||||
|
b, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(b))
|
||||||
|
}
|
||||||
|
|
||||||
// Reconciler applies the config to the kernel whenever it is triggered and
|
// Reconciler applies the config to the kernel whenever it is triggered and
|
||||||
// remembers the outcome for the health report.
|
// remembers the outcome for the health report.
|
||||||
type Reconciler struct {
|
type Reconciler struct {
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"cmp"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/vishvananda/netlink"
|
"github.com/vishvananda/netlink"
|
||||||
"golang.zx2c4.com/wireguard/wgctrl"
|
"golang.zx2c4.com/wireguard/wgctrl"
|
||||||
@@ -318,14 +318,6 @@ func publicAddr(uplink string, v6 bool) (bool, string) {
|
|||||||
return false, "no address on " + uplink
|
return false, "no address on " + uplink
|
||||||
}
|
}
|
||||||
|
|
||||||
func readSysctl(path string) string {
|
|
||||||
b, err := os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return strings.TrimSpace(string(b))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (k *linuxKernel) Checks(c *Config) []Check {
|
func (k *linuxKernel) Checks(c *Config) []Check {
|
||||||
var out []Check
|
var out []Check
|
||||||
link, err := netlink.LinkByName(c.Server.Interface)
|
link, err := netlink.LinkByName(c.Server.Interface)
|
||||||
@@ -341,6 +333,19 @@ func (k *linuxKernel) Checks(c *Config) []Check {
|
|||||||
v := readSysctl("/proc/sys/net/ipv6/conf/all/forwarding")
|
v := readSysctl("/proc/sys/net/ipv6/conf/all/forwarding")
|
||||||
out = append(out, Check{"IPv6 forwarding", v == "1", "net.ipv6.conf.all.forwarding=" + v})
|
out = append(out, Check{"IPv6 forwarding", v == "1", "net.ipv6.conf.all.forwarding=" + v})
|
||||||
}
|
}
|
||||||
|
// With IPv6 forwarding on, accept_ra 1 means router announcements are
|
||||||
|
// ignored: an IPv6 route learned from them expires (see sysctlConf).
|
||||||
|
if readSysctl("/proc/sys/net/ipv6/conf/all/forwarding") == "1" {
|
||||||
|
up := cmp.Or(k.Uplink(c, true), k.Uplink(c, false))
|
||||||
|
if ra := readSysctl("/proc/sys/net/ipv6/conf/" + up + "/accept_ra"); up != "" && ra != "" {
|
||||||
|
ok := ra != "1"
|
||||||
|
detail := "net.ipv6.conf." + up + ".accept_ra=" + ra
|
||||||
|
if !ok {
|
||||||
|
detail += ": IPv6 from router announcements stops working; run " + appName + " update"
|
||||||
|
}
|
||||||
|
out = append(out, Check{"IPv6 router announcements", ok, detail})
|
||||||
|
}
|
||||||
|
}
|
||||||
ok, detail := firewallPresent()
|
ok, detail := firewallPresent()
|
||||||
out = append(out, Check{"nftables rules", ok, detail})
|
out = append(out, Check{"nftables rules", ok, detail})
|
||||||
up4 := k.Uplink(c, false)
|
up4 := k.Uplink(c, false)
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ import (
|
|||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -376,6 +378,92 @@ func TestUnitFile(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSysctlConf(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
conf, sys := filepath.Join(dir, "conf"), filepath.Join(dir, "net")
|
||||||
|
for name, ra := range map[string]string{"eth0": "1", "wlan0": "2", "eth1": "0", "br0": "1", "veth1": "1", "lo": "1"} {
|
||||||
|
_ = os.MkdirAll(filepath.Join(conf, name), 0o755)
|
||||||
|
_ = os.WriteFile(filepath.Join(conf, name, "accept_ra"), []byte(ra+"\n"), 0o644)
|
||||||
|
}
|
||||||
|
for _, name := range []string{"eth0", "wlan0", "eth1"} { // network cards
|
||||||
|
_ = os.MkdirAll(filepath.Join(sys, name, "device"), 0o755)
|
||||||
|
}
|
||||||
|
_ = os.MkdirAll(filepath.Join(sys, "veth1"), 0o755)
|
||||||
|
// br0 carries the default route; the lo line is the kernel's unreachable route.
|
||||||
|
routes := filepath.Join(dir, "ipv6_route")
|
||||||
|
_ = os.WriteFile(routes, []byte(
|
||||||
|
"00000000000000000000000000000000 00 00000000000000000000000000000000 00 fe800000000000000000000000000001 00000400 00000001 00000000 00000003 br0\n"+
|
||||||
|
"00000000000000000000000000000000 00 00000000000000000000000000000000 00 00000000000000000000000000000000 ffffffff 00000001 00000000 00200200 lo\n"), 0o644)
|
||||||
|
|
||||||
|
got := raInterfaces(conf, sys, routes)
|
||||||
|
if want := []string{"br0", "eth0", "wlan0"}; !slices.Equal(got, want) {
|
||||||
|
t.Fatalf("raInterfaces = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
c := sysctlConf(got)
|
||||||
|
for _, want := range []string{"net.ipv6.conf.all.forwarding=1\n", "net.ipv6.conf.default.accept_ra=2\n", "net.ipv6.conf.eth0.accept_ra=2\n", "net.ipv6.conf.br0.accept_ra=2\n"} {
|
||||||
|
if !strings.Contains(c, want) {
|
||||||
|
t.Errorf("sysctl conf lacks %q:\n%s", want, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(c, "eth1") || strings.Contains(c, "veth1") {
|
||||||
|
t.Errorf("sysctl conf names eth1 (accept_ra 0) or veth1 (virtual):\n%s", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginLockout(t *testing.T) {
|
||||||
|
store, err := openStore(filepath.Join(t.TempDir(), "config.json"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
hash, _ := hashPassword("a long test password")
|
||||||
|
_ = store.Update(func(c *Config) error { c.Users[0].PasswordHash = hash; return nil })
|
||||||
|
a := newAuth(store)
|
||||||
|
const right, wrong = "a long test password", "a wrong password"
|
||||||
|
|
||||||
|
// Ten wrong attempts at once from one /64: five are checked, the others
|
||||||
|
// are locked out before any password check.
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
var mu sync.Mutex
|
||||||
|
got := map[string]int{}
|
||||||
|
for i := range 10 {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
_, _, err := a.Login("admin", wrong, fmt.Sprintf("2001:db8::%x", i+1))
|
||||||
|
mu.Lock()
|
||||||
|
got[err.Error()]++
|
||||||
|
mu.Unlock()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
if got["wrong username or password"] != 5 || got[errLocked.Error()] != 5 {
|
||||||
|
t.Fatalf("parallel attempts: %v", got)
|
||||||
|
}
|
||||||
|
if _, _, err := a.Login("admin", right, "2001:db8::ffff"); !errors.Is(err, errLocked) {
|
||||||
|
t.Fatalf("same /64: %v, want locked", err)
|
||||||
|
}
|
||||||
|
if _, _, err := a.Login("admin", right, "2001:db8:0:1::1"); err != nil {
|
||||||
|
t.Fatalf("other /64: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A right password takes its own attempt back. With two-step sign-in
|
||||||
|
// the earlier failures stay, so wrong codes still lead to the lockout.
|
||||||
|
_ = store.Update(func(c *Config) error { c.Users[0].MFA = &UserMFA{TOTPSecret: newTOTPSecret()}; return nil })
|
||||||
|
ip := "192.0.2.7"
|
||||||
|
for range maxFailures - 1 {
|
||||||
|
_, _, _ = a.Login("admin", wrong, ip)
|
||||||
|
}
|
||||||
|
if _, tk, err := a.Login("admin", right, ip); err != nil || tk == "" {
|
||||||
|
t.Fatalf("5th attempt, right password: ticket %q, %v", tk, err)
|
||||||
|
}
|
||||||
|
if _, _, err := a.Login("admin", wrong, ip); err == nil || errors.Is(err, errLocked) {
|
||||||
|
t.Fatalf("6th attempt: %v, want wrong password", err)
|
||||||
|
}
|
||||||
|
if _, _, err := a.Login("admin", right, ip); !errors.Is(err, errLocked) {
|
||||||
|
t.Fatalf("7th attempt: %v, want locked", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestWriteIfChanged(t *testing.T) {
|
func TestWriteIfChanged(t *testing.T) {
|
||||||
p := filepath.Join(t.TempDir(), "x.conf")
|
p := filepath.Join(t.TempDir(), "x.conf")
|
||||||
if ch, err := writeIfChanged(p, "a\n", 0o644); !ch || err != nil {
|
if ch, err := writeIfChanged(p, "a\n", 0o644); !ch || err != nil {
|
||||||
@@ -1050,7 +1138,7 @@ func TestMFA(t *testing.T) {
|
|||||||
if o := adm("GET", "/auth/options", nil, 200); o["passkeys"] != false {
|
if o := adm("GET", "/auth/options", nil, 200); o["passkeys"] != false {
|
||||||
t.Fatalf("passkeys offered on an IP address: %v", o)
|
t.Fatalf("passkeys offered on an IP address: %v", o)
|
||||||
}
|
}
|
||||||
adm("POST", "/auth/mfa/keys/begin", map[string]bool{"passkey": true}, 400)
|
adm("POST", "/auth/mfa/keys/begin", nil, 400)
|
||||||
|
|
||||||
// Turn on the authenticator app; the first method brings recovery codes.
|
// Turn on the authenticator app; the first method brings recovery codes.
|
||||||
setup := adm("POST", "/auth/mfa/totp/setup", nil, 200)
|
setup := adm("POST", "/auth/mfa/totp/setup", nil, 200)
|
||||||
@@ -1121,3 +1209,30 @@ func TestMFA(t *testing.T) {
|
|||||||
t.Fatal("reset left methods behind")
|
t.Fatal("reset left methods behind")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestDropSecurityKeys checks that security keys from v0.3.0 are deleted on
|
||||||
|
// load, and recovery codes with them when nothing else is left.
|
||||||
|
func TestDropSecurityKeys(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "config.json")
|
||||||
|
cfg := `{"users": [
|
||||||
|
{"id": "a", "username": "a", "passwordHash": "x", "mfa": {"keys": [{"id": "k", "name": "YubiKey", "passkey": false}], "recoveryCodes": ["h"]}},
|
||||||
|
{"id": "b", "username": "b", "passwordHash": "x", "mfa": {"keys": [{"id": "k1", "name": "YubiKey", "passkey": false}, {"id": "k2", "name": "Mac", "passkey": true}], "recoveryCodes": ["h"]}}
|
||||||
|
]}`
|
||||||
|
if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
store, err := openStore(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c := store.Get()
|
||||||
|
if a := c.Users[0].MFA; len(a.Keys) != 0 || len(a.RecoveryCodes) != 0 {
|
||||||
|
t.Fatalf("user a kept %v", a)
|
||||||
|
}
|
||||||
|
if b := c.Users[1].MFA; len(b.Keys) != 1 || b.Keys[0].Name != "Mac" || len(b.RecoveryCodes) != 1 {
|
||||||
|
t.Fatalf("user b: %v", b)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(path); strings.Contains(string(b), "YubiKey") {
|
||||||
|
t.Fatal("security key still in config.json")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,9 +24,10 @@ import (
|
|||||||
"github.com/go-webauthn/webauthn/webauthn"
|
"github.com/go-webauthn/webauthn/webauthn"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Two-step sign-in for the web interface: an authenticator app (TOTP),
|
// Two-step sign-in for the web interface: an authenticator app (TOTP) and
|
||||||
// security keys such as a YubiKey and passkeys (both WebAuthn), plus
|
// passkeys (WebAuthn, also on a YubiKey), plus one-time recovery codes. A
|
||||||
// one-time recovery codes. API tokens never need a second step.
|
// passkey signs in on its own and also serves as the second step after a
|
||||||
|
// password. API tokens never need a second step.
|
||||||
//
|
//
|
||||||
// After a correct password, a user with two-step sign-in gets a short-lived
|
// After a correct password, a user with two-step sign-in gets a short-lived
|
||||||
// ticket instead of a session; the ticket and a code or key turn into the
|
// ticket instead of a session; the ticket and a code or key turn into the
|
||||||
@@ -41,16 +42,29 @@ type UserMFA struct {
|
|||||||
Handle []byte `json:"handle,omitempty"` // WebAuthn user handle
|
Handle []byte `json:"handle,omitempty"` // WebAuthn user handle
|
||||||
}
|
}
|
||||||
|
|
||||||
// MFAKey is a security key or passkey.
|
// MFAKey is a passkey.
|
||||||
type MFAKey struct {
|
type MFAKey struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Passkey bool `json:"passkey"` // discoverable: signs in without a password
|
Passkey bool `json:"passkey"` // false only for security keys added by v0.3.0, which are deleted
|
||||||
Created time.Time `json:"created"`
|
Created time.Time `json:"created"`
|
||||||
LastUsed *time.Time `json:"lastUsed,omitempty"`
|
LastUsed *time.Time `json:"lastUsed,omitempty"`
|
||||||
Credential webauthn.Credential `json:"credential"`
|
Credential webauthn.Credential `json:"credential"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// dropSecurityKeys deletes the security keys v0.3.0 could add; only
|
||||||
|
// passkeys are supported. A user left without a method loses their
|
||||||
|
// recovery codes too.
|
||||||
|
func dropSecurityKeys(u *User) {
|
||||||
|
if u.MFA == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u.MFA.Keys = slices.DeleteFunc(u.MFA.Keys, func(k MFAKey) bool { return !k.Passkey })
|
||||||
|
if !u.hasMFA() {
|
||||||
|
u.MFA.RecoveryCodes = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (u *User) hasMFA() bool {
|
func (u *User) hasMFA() bool {
|
||||||
return u.MFA != nil && (u.MFA.TOTPSecret != "" || len(u.MFA.Keys) > 0)
|
return u.MFA != nil && (u.MFA.TOTPSecret != "" || len(u.MFA.Keys) > 0)
|
||||||
}
|
}
|
||||||
@@ -166,7 +180,7 @@ func (w waUser) WebAuthnCredentials() []webauthn.Credential {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// keysAvailable reports whether security keys and passkeys can work on this
|
// keysAvailable reports whether passkeys can work on this
|
||||||
// address: WebAuthn needs a domain name (not an IP address) and a
|
// address: WebAuthn needs a domain name (not an IP address) and a
|
||||||
// certificate the browser trusts, or localhost.
|
// certificate the browser trusts, or localhost.
|
||||||
func (a *App) keysAvailable(r *http.Request) bool {
|
func (a *App) keysAvailable(r *http.Request) bool {
|
||||||
@@ -179,7 +193,7 @@ func (a *App) keysAvailable(r *http.Request) bool {
|
|||||||
|
|
||||||
func (a *App) webAuthn(r *http.Request) (*webauthn.WebAuthn, error) {
|
func (a *App) webAuthn(r *http.Request) (*webauthn.WebAuthn, error) {
|
||||||
if !a.keysAvailable(r) {
|
if !a.keysAvailable(r) {
|
||||||
return nil, badRequest("security keys and passkeys need a domain name with a trusted certificate")
|
return nil, badRequest("passkeys need a domain name with a trusted certificate")
|
||||||
}
|
}
|
||||||
scheme := "https"
|
scheme := "https"
|
||||||
if r.TLS == nil && hostOnly(r.Host) == "localhost" {
|
if r.TLS == nil && hostOnly(r.Host) == "localhost" {
|
||||||
@@ -198,12 +212,11 @@ type ticket struct {
|
|||||||
ip string
|
ip string
|
||||||
expires time.Time
|
expires time.Time
|
||||||
fails int
|
fails int
|
||||||
key *webauthn.SessionData // a security key challenge, once asked for
|
key *webauthn.SessionData // a passkey challenge, once asked for
|
||||||
}
|
}
|
||||||
|
|
||||||
type ceremony struct {
|
type ceremony struct {
|
||||||
userID string // "" for a passkey sign-in
|
userID string // "" for a passkey sign-in
|
||||||
passkey bool
|
|
||||||
data *webauthn.SessionData
|
data *webauthn.SessionData
|
||||||
expires time.Time
|
expires time.Time
|
||||||
}
|
}
|
||||||
@@ -223,23 +236,34 @@ func newMFAState() mfaState {
|
|||||||
|
|
||||||
var errBadTicket = errors.New("the sign-in expired; enter your password again")
|
var errBadTicket = errors.New("the sign-in expired; enter your password again")
|
||||||
|
|
||||||
// failLocked counts a failed attempt from ip toward the lockout. a.mu must
|
// failLocked counts a failed attempt from ip toward the lockout and returns
|
||||||
// be held.
|
// a function that takes it back, for an attempt counted before it was
|
||||||
func (a *Auth) failLocked(ip string) {
|
// checked. a.mu must be held, also when calling undo.
|
||||||
f := a.fails[ip]
|
func (a *Auth) failLocked(ip string) (undo func()) {
|
||||||
|
key := lockKey(ip)
|
||||||
|
f := a.fails[key]
|
||||||
if f == nil {
|
if f == nil {
|
||||||
f = &failState{}
|
f = &failState{}
|
||||||
a.fails[ip] = f
|
a.fails[key] = f
|
||||||
}
|
}
|
||||||
f.count++
|
f.count++
|
||||||
if f.count >= maxFailures {
|
locked := f.count >= maxFailures
|
||||||
|
if locked {
|
||||||
f.count = 0
|
f.count = 0
|
||||||
f.until = time.Now().Add(lockoutTime)
|
f.until = time.Now().Add(lockoutTime)
|
||||||
}
|
}
|
||||||
|
return func() {
|
||||||
|
switch {
|
||||||
|
case locked:
|
||||||
|
f.count, f.until = maxFailures-1, time.Time{}
|
||||||
|
case f.count > 0:
|
||||||
|
f.count--
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Auth) lockedLocked(ip string) bool {
|
func (a *Auth) lockedLocked(ip string) bool {
|
||||||
f := a.fails[ip]
|
f := a.fails[lockKey(ip)]
|
||||||
return f != nil && time.Now().Before(f.until)
|
return f != nil && time.Now().Before(f.until)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -289,7 +313,7 @@ func (a *Auth) finishSignIn(u *User, ip string) string {
|
|||||||
cfg := a.store.Get()
|
cfg := a.store.Get()
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
delete(a.fails, ip)
|
delete(a.fails, lockKey(ip))
|
||||||
a.logins[u.ID] = tokenUse{At: time.Now(), IP: ip}
|
a.logins[u.ID] = tokenUse{At: time.Now(), IP: ip}
|
||||||
return a.newSessionLocked(cfg, u, sessionInfo{Started: time.Now(), IP: ip})
|
return a.newSessionLocked(cfg, u, sessionInfo{Started: time.Now(), IP: ip})
|
||||||
}
|
}
|
||||||
@@ -430,7 +454,7 @@ func (a *App) loginRecovery(w http.ResponseWriter, r *http.Request) {
|
|||||||
a.signedIn(w, r, u, "recovery code")
|
a.signedIn(w, r, u, "recovery code")
|
||||||
}
|
}
|
||||||
|
|
||||||
// loginKeyBegin asks for one of the user's security keys or passkeys.
|
// loginKeyBegin asks for one of the user's passkeys, as the second step.
|
||||||
func (a *App) loginKeyBegin(w http.ResponseWriter, r *http.Request) {
|
func (a *App) loginKeyBegin(w http.ResponseWriter, r *http.Request) {
|
||||||
var in struct{ Ticket string }
|
var in struct{ Ticket string }
|
||||||
if err := readJSON(r, &in); err != nil {
|
if err := readJSON(r, &in); err != nil {
|
||||||
@@ -448,7 +472,7 @@ func (a *App) loginKeyBegin(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if u.MFA == nil || len(u.MFA.Keys) == 0 {
|
if u.MFA == nil || len(u.MFA.Keys) == 0 {
|
||||||
writeErr(w, badRequest("no security key is set up"))
|
writeErr(w, badRequest("no passkey is set up"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
opts, data, err := wa.BeginLogin(waUser{u}, webauthn.WithUserVerification(protocol.VerificationDiscouraged))
|
opts, data, err := wa.BeginLogin(waUser{u}, webauthn.WithUserVerification(protocol.VerificationDiscouraged))
|
||||||
@@ -488,13 +512,13 @@ func (a *App) loginKeyFinish(w http.ResponseWriter, r *http.Request) {
|
|||||||
cred, err := wa.FinishLogin(waUser{u}, *data, r)
|
cred, err := wa.FinishLogin(waUser{u}, *data, r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.auth.ticketFailed(id, ip)
|
a.auth.ticketFailed(id, ip)
|
||||||
slog.Warn("login failed", "user", u.Username, "remote", ip, "reason", "security key: "+err.Error())
|
slog.Warn("login failed", "user", u.Username, "remote", ip, "reason", "passkey: "+err.Error())
|
||||||
a.signInFailed(w, errors.New("the security key was not accepted"))
|
a.signInFailed(w, errors.New("the passkey was not accepted"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
a.keyUsed(u.ID, cred)
|
a.keyUsed(u.ID, cred)
|
||||||
a.auth.dropTicket(id)
|
a.auth.dropTicket(id)
|
||||||
a.signedIn(w, r, u, "security key")
|
a.signedIn(w, r, u, "passkey")
|
||||||
}
|
}
|
||||||
|
|
||||||
// keyUsed stores the key's new signature counter and when it was used.
|
// keyUsed stores the key's new signature counter and when it was used.
|
||||||
@@ -561,7 +585,7 @@ func (a *App) loginPasskeyFinish(w http.ResponseWriter, r *http.Request) {
|
|||||||
u := &cfg.Users[i]
|
u := &cfg.Users[i]
|
||||||
if u.MFA != nil && len(u.MFA.Handle) > 0 && bytes.Equal(u.MFA.Handle, handle) {
|
if u.MFA != nil && len(u.MFA.Handle) > 0 && bytes.Equal(u.MFA.Handle, handle) {
|
||||||
for _, k := range u.MFA.Keys {
|
for _, k := range u.MFA.Keys {
|
||||||
if k.Passkey && bytes.Equal(k.Credential.ID, rawID) {
|
if bytes.Equal(k.Credential.ID, rawID) {
|
||||||
found = u
|
found = u
|
||||||
return waUser{u}, nil
|
return waUser{u}, nil
|
||||||
}
|
}
|
||||||
@@ -587,7 +611,6 @@ func (a *App) loginPasskeyFinish(w http.ResponseWriter, r *http.Request) {
|
|||||||
type keyView struct {
|
type keyView struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Passkey bool `json:"passkey"`
|
|
||||||
Created time.Time `json:"created"`
|
Created time.Time `json:"created"`
|
||||||
LastUsed *time.Time `json:"lastUsed"`
|
LastUsed *time.Time `json:"lastUsed"`
|
||||||
}
|
}
|
||||||
@@ -604,7 +627,7 @@ func (a *App) mfaStatus(w http.ResponseWriter, r *http.Request) {
|
|||||||
if m := u.MFA; m != nil {
|
if m := u.MFA; m != nil {
|
||||||
keys := []keyView{}
|
keys := []keyView{}
|
||||||
for _, k := range m.Keys {
|
for _, k := range m.Keys {
|
||||||
keys = append(keys, keyView{k.ID, k.Name, k.Passkey, k.Created, k.LastUsed})
|
keys = append(keys, keyView{k.ID, k.Name, k.Created, k.LastUsed})
|
||||||
}
|
}
|
||||||
out["totp"], out["totpAdded"], out["keys"], out["recoveryLeft"] = m.TOTPSecret != "", m.TOTPAdded, keys, len(m.RecoveryCodes)
|
out["totp"], out["totpAdded"], out["keys"], out["recoveryLeft"] = m.TOTPSecret != "", m.TOTPAdded, keys, len(m.RecoveryCodes)
|
||||||
}
|
}
|
||||||
@@ -710,13 +733,8 @@ func (a *App) totpRemove(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||||
}
|
}
|
||||||
|
|
||||||
// keyBegin starts adding a security key ({"passkey": false}) or a passkey.
|
// keyBegin starts adding a passkey.
|
||||||
func (a *App) keyBegin(w http.ResponseWriter, r *http.Request) {
|
func (a *App) keyBegin(w http.ResponseWriter, r *http.Request) {
|
||||||
var in struct{ Passkey bool }
|
|
||||||
if err := readJSON(r, &in); err != nil {
|
|
||||||
writeErr(w, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
wa, err := a.webAuthn(r)
|
wa, err := a.webAuthn(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeErr(w, err)
|
writeErr(w, err)
|
||||||
@@ -748,17 +766,14 @@ func (a *App) keyBegin(w http.ResponseWriter, r *http.Request) {
|
|||||||
for _, k := range u.MFA.Keys {
|
for _, k := range u.MFA.Keys {
|
||||||
exclude = append(exclude, k.Credential.Descriptor())
|
exclude = append(exclude, k.Credential.Descriptor())
|
||||||
}
|
}
|
||||||
sel := protocol.AuthenticatorSelection{ResidentKey: protocol.ResidentKeyRequirementDiscouraged, UserVerification: protocol.VerificationDiscouraged}
|
sel := protocol.AuthenticatorSelection{ResidentKey: protocol.ResidentKeyRequirementRequired, UserVerification: protocol.VerificationRequired}
|
||||||
if in.Passkey {
|
|
||||||
sel = protocol.AuthenticatorSelection{ResidentKey: protocol.ResidentKeyRequirementRequired, UserVerification: protocol.VerificationRequired}
|
|
||||||
}
|
|
||||||
opts, data, err := wa.BeginRegistration(waUser{u}, webauthn.WithAuthenticatorSelection(sel), webauthn.WithExclusions(exclude))
|
opts, data, err := wa.BeginRegistration(waUser{u}, webauthn.WithAuthenticatorSelection(sel), webauthn.WithExclusions(exclude))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeErr(w, err)
|
writeErr(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
a.auth.mu.Lock()
|
a.auth.mu.Lock()
|
||||||
a.auth.mfa.enrolls[p.UserID] = &ceremony{userID: p.UserID, passkey: in.Passkey, data: data, expires: time.Now().Add(ticketTTL)}
|
a.auth.mfa.enrolls[p.UserID] = &ceremony{userID: p.UserID, data: data, expires: time.Now().Add(ticketTTL)}
|
||||||
a.auth.mu.Unlock()
|
a.auth.mu.Unlock()
|
||||||
writeJSON(w, http.StatusOK, opts)
|
writeJSON(w, http.StatusOK, opts)
|
||||||
}
|
}
|
||||||
@@ -792,13 +807,13 @@ func (a *App) keyFinish(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if name == "" {
|
if name == "" {
|
||||||
name = map[bool]string{false: "Security key", true: "Passkey"}[cer.passkey]
|
name = "Passkey"
|
||||||
}
|
}
|
||||||
if len(name) > maxKeyName {
|
if len(name) > maxKeyName {
|
||||||
name = name[:maxKeyName]
|
name = name[:maxKeyName]
|
||||||
}
|
}
|
||||||
var codes []string
|
var codes []string
|
||||||
key := MFAKey{ID: newID(), Name: name, Passkey: cer.passkey, Created: time.Now().UTC(), Credential: *cred}
|
key := MFAKey{ID: newID(), Name: name, Passkey: true, Created: time.Now().UTC(), Credential: *cred}
|
||||||
if err := a.store.Update(func(c *Config) error {
|
if err := a.store.Update(func(c *Config) error {
|
||||||
_, u := c.userByID(p.UserID)
|
_, u := c.userByID(p.UserID)
|
||||||
if u == nil || u.MFA == nil {
|
if u == nil || u.MFA == nil {
|
||||||
@@ -811,7 +826,7 @@ func (a *App) keyFinish(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeErr(w, err)
|
writeErr(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
a.audit(r, map[bool]string{false: "security key added", true: "passkey added"}[cer.passkey], "key", name)
|
a.audit(r, "passkey added", "key", name)
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "recoveryCodes": codes})
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "recoveryCodes": codes})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -865,7 +880,7 @@ func (a *App) keyRemove(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeErr(w, err)
|
writeErr(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
a.audit(r, "security key removed", "key", name)
|
a.audit(r, "passkey removed", "key", name)
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -917,17 +932,9 @@ func (a *App) resetMFA(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// mfaSummary is what user lists show.
|
// mfaSummary is what user lists show.
|
||||||
func mfaSummary(u *User) map[string]any {
|
func mfaSummary(u *User) map[string]any {
|
||||||
out := map[string]any{"totp": false, "keys": 0, "passkeys": 0}
|
out := map[string]any{"totp": false, "passkeys": 0}
|
||||||
if m := u.MFA; m != nil {
|
if m := u.MFA; m != nil {
|
||||||
keys, passkeys := 0, 0
|
out["totp"], out["passkeys"] = m.TOTPSecret != "", len(m.Keys)
|
||||||
for _, k := range m.Keys {
|
|
||||||
if k.Passkey {
|
|
||||||
passkeys++
|
|
||||||
} else {
|
|
||||||
keys++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out["totp"], out["keys"], out["passkeys"] = m.TOTPSecret != "", keys, passkeys
|
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 296 KiB |
|
Before Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 195 KiB |
|
Before Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 147 KiB |
|
Before Width: | Height: | Size: 81 KiB |
@@ -12,6 +12,7 @@ import (
|
|||||||
"os/user"
|
"os/user"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -273,7 +274,51 @@ WantedBy=multi-user.target
|
|||||||
// rewrite the unit for every release.
|
// rewrite the unit for every release.
|
||||||
const unitVersion = "unit-1"
|
const unitVersion = "unit-1"
|
||||||
|
|
||||||
const sysctlConf = "net.ipv4.ip_forward=1\nnet.ipv6.conf.all.forwarding=1\n"
|
// sysctlConf turns on forwarding. With IPv6 forwarding on, Linux ignores
|
||||||
|
// router announcements unless accept_ra is 2, and a server that gets its
|
||||||
|
// IPv6 route from them (SLAAC, e.g. a Raspberry Pi at home) loses IPv6 when
|
||||||
|
// the route expires. So every interface in ras keeps accepting them, as
|
||||||
|
// pivpn does for its uplink.
|
||||||
|
func sysctlConf(ras []string) string {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString("net.ipv4.ip_forward=1\nnet.ipv6.conf.all.forwarding=1\nnet.ipv6.conf.default.accept_ra=2\n")
|
||||||
|
for _, name := range ras {
|
||||||
|
fmt.Fprintf(&b, "net.ipv6.conf.%s.accept_ra=2\n", name)
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// raInterfaces returns the network cards and the interface of the IPv6
|
||||||
|
// default route, except those where router announcements are switched off
|
||||||
|
// (accept_ra 0). The directories are /proc/sys/net/ipv6/conf and
|
||||||
|
// /sys/class/net, routes is /proc/net/ipv6_route.
|
||||||
|
func raInterfaces(confDir, netDir, routes string) []string {
|
||||||
|
want := map[string]bool{}
|
||||||
|
if b, err := os.ReadFile(routes); err == nil {
|
||||||
|
for _, line := range strings.Split(string(b), "\n") {
|
||||||
|
f := strings.Fields(line)
|
||||||
|
if len(f) == 10 && f[0] == strings.Repeat("0", 32) && f[1] == "00" && f[9] != "lo" {
|
||||||
|
want[f[9]] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entries, _ := os.ReadDir(netDir)
|
||||||
|
for _, e := range entries {
|
||||||
|
// Only real devices: bridges, veth and tunnels come and go.
|
||||||
|
if _, err := os.Stat(filepath.Join(netDir, e.Name(), "device")); err == nil {
|
||||||
|
want[e.Name()] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for name := range want {
|
||||||
|
v := readSysctl(filepath.Join(confDir, name, "accept_ra"))
|
||||||
|
if v == "1" || v == "2" {
|
||||||
|
out = append(out, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
slices.Sort(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// writeSystemFiles writes the unit, sysctl and module files. It reports
|
// writeSystemFiles writes the unit, sysctl and module files. It reports
|
||||||
// whether the unit changed (systemd must then reload).
|
// whether the unit changed (systemd must then reload).
|
||||||
@@ -281,7 +326,8 @@ func writeSystemFiles() (unitChanged bool, err error) {
|
|||||||
if unitChanged, err = writeIfChanged(unitPath, unitFile(), 0o644); err != nil {
|
if unitChanged, err = writeIfChanged(unitPath, unitFile(), 0o644); err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
sysChanged, err := writeIfChanged(sysctlPath, sysctlConf, 0o644)
|
ras := raInterfaces("/proc/sys/net/ipv6/conf", "/sys/class/net", "/proc/net/ipv6_route")
|
||||||
|
sysChanged, err := writeIfChanged(sysctlPath, sysctlConf(ras), 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ type userView struct {
|
|||||||
LastLogin *tokenUse `json:"lastLogin"` // since the service started
|
LastLogin *tokenUse `json:"lastLogin"` // since the service started
|
||||||
Tokens int `json:"tokens"`
|
Tokens int `json:"tokens"`
|
||||||
You bool `json:"you"`
|
You bool `json:"you"`
|
||||||
MFA map[string]any `json:"mfa"` // {"totp": bool, "keys": n, "passkeys": n}
|
MFA map[string]any `json:"mfa"` // {"totp": bool, "passkeys": n}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) userView(c *Config, u *User, me string) userView {
|
func (a *App) userView(c *Config, u *User, me string) userView {
|
||||||
|
|||||||