mirror of
https://github.com/UNITRONIX/BetterDesk.git
synced 2026-11-24 01:52:12 +00:00
0429c4080d
Full report and per-finding status in docs/security/AUDIT_2026-11-13.md.
Critical
- POST /api/bd/register now requires an Ed25519 proof of possession for a
first registration and for any public_key/uuid rotation, rejects banned and
soft-deleted ids before writing, and is rate limited per IP. Knowing a device
id is no longer enough to flood inventory, resurrect a removed device or
swap its key.
- Signal RegisterPk with old_id is applied only when the supplied key or the
machine UUID matches the stored peer, so an unauthenticated caller can no
longer move and delete someone else's row. Stock RustDesk change-ID (no pk,
matching UUID) still works.
- The Go server runs as betterdesk from /usr/local/bin/betterdesk-server and
/opt/rustdesk is no longer group-writable at the directory level, so the
console user cannot replace the binary. DSNs and the bootstrap admin password
are gone from systemd units.
High
- /metrics and /api/health/detail require the metrics allowlist or an API key;
public /api/health returns only {status, version}.
- Panel login consults the shared account-lockout tracker (429 + Retry-After);
delegated 2FA fails closed; pending-2FA state is written after session
regeneration; GET /logout no longer destroys the session.
- HTTP->HTTPS redirect no longer trusts the Host header or absolute request
targets.
- Desktop login no longer pre-renders the account list; a rate-limited
/login/lookup returns at most 8 prefix matches.
- Panel section overrides are clamped to the role ceiling, so a per-user policy
cannot grant a permission the role lacks.
- /api/devices/:id/* is covered by one scope guard (tags, rename, change-id,
restore, access-policy).
- applyUpdate verifies an optional Ed25519-signed manifest and can be made
fail-closed with UPDATE_REQUIRE_SIGNED_MANIFEST=true.
- The privileged broker no longer manages DATABASE_URL, SESSION_SECRET,
DEFAULT_ADMIN_PASSWORD, UPDATE_GITHUB_TOKEN, API_KEY_PATH,
ORG_PEER_VAULT_KEY, SMTP_PASS or API_TOKEN_EXPIRY_DAYS, and reports a
protocol version so a stale broker is detectable.
- Peer status/online/metrics/linked/policy endpoints require device.view and
enforce organisation scope.
Medium / low
- Backup restore enforces a decompressed-size and entry-count budget.
- limit/offset clamped on the console and in the Go audit handlers; public
audit writes are rate limited.
- Data embedded in inline <script> blocks goes through safeJsonScript; the
pairing page escapes the suggested host.
- Go toolchain and builder images bumped to go1.26.11 (GO-2026-6859); the
console requires at least that version to rebuild the server.
- Workflow Actions pinned to commit SHAs; Dependabot tracks github-actions.
- Restart tokens compared with crypto.timingSafeEqual.
Tooling
- scripts/security/pentest-local.sh / .ps1 local security gate.
- scripts/check-security-regressions.sh CI gate (unit credentials, inline
script escaping), wired into Secret Scan.
- Two long-standing red tests fixed (platform loopback address, missing
panelAccessPolicyService mock).
Verified on the test host: /metrics 401, /api/health/detail 401,
/api/peers/online 401, desktop login ships an empty user list, unproven
register returns 403, Host spoofing redirects to the configured public host,
and the broker reports version 2 with a secret-free manifest.
Thanks: INSOLVE (Honorary); Marco Jakobs (@jacotec); MyNameisStitch (@MyNameisStitch); Redspin (@playerumpknow); muopc (@muopc)
180 lines
6.8 KiB
JavaScript
180 lines
6.8 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Device scope guard (audit H9, 2026-11-13).
|
|
*
|
|
* The scope check used to be copied into individual handlers and several
|
|
* mutations were missed — an operator with a restricted device scope could
|
|
* rename, retag, re-id or restore devices outside their groups by guessing the
|
|
* id. The guard is now mounted once for `/api/devices/:id`.
|
|
*/
|
|
|
|
const request = require('supertest');
|
|
const { createTestApp } = require('./helpers');
|
|
|
|
jest.mock('../services/betterdeskApi', () => ({
|
|
getPeerTelemetry: jest.fn().mockResolvedValue({ success: false }),
|
|
getConnectionMode: jest.fn().mockResolvedValue({ success: true, data: { controllable: false } }),
|
|
setConnectionMode: jest.fn().mockResolvedValue({ success: true }),
|
|
getPeer: jest.fn().mockResolvedValue(null),
|
|
getPeerIncludingDeleted: jest.fn().mockResolvedValue(null),
|
|
}));
|
|
|
|
jest.mock('../services/database', () => ({
|
|
logAction: jest.fn().mockResolvedValue(undefined),
|
|
getPeerSysinfo: jest.fn().mockResolvedValue(null),
|
|
getLatestPeerMetric: jest.fn().mockResolvedValue(null),
|
|
getPeerMetrics: jest.fn().mockResolvedValue([]),
|
|
getDeviceGroupsForPeer: jest.fn().mockResolvedValue([]),
|
|
getUserGroupsForUser: jest.fn().mockResolvedValue([]),
|
|
getAllDeviceGroups: jest.fn().mockResolvedValue([]),
|
|
getDeviceGroupMembers: jest.fn().mockResolvedValue([]),
|
|
getDeviceGroupByGuid: jest.fn().mockResolvedValue(null),
|
|
getAllFolders: jest.fn().mockResolvedValue([]),
|
|
getAllFolderAssignments: jest.fn().mockResolvedValue({}),
|
|
getUserPeerGrants: jest.fn().mockResolvedValue([]),
|
|
getSetting: jest.fn().mockResolvedValue(null),
|
|
cascadePeerIdChange: jest.fn().mockResolvedValue(undefined),
|
|
purgePanelPeerRecord: jest.fn().mockResolvedValue(undefined),
|
|
cleanupDeletedPeerData: jest.fn().mockResolvedValue(undefined),
|
|
}));
|
|
|
|
jest.mock('../services/serverBackend', () => ({
|
|
getAllDevices: jest.fn().mockResolvedValue([]),
|
|
getDeviceById: jest.fn().mockResolvedValue(null),
|
|
updateDevice: jest.fn().mockResolvedValue({ changes: 1 }),
|
|
deleteDevice: jest.fn().mockResolvedValue({ success: true }),
|
|
restoreDevice: jest.fn().mockResolvedValue({ success: true }),
|
|
changePeerId: jest.fn().mockResolvedValue({ success: true }),
|
|
setPeerTags: jest.fn().mockResolvedValue({ success: true }),
|
|
isBetterDesk: jest.fn().mockResolvedValue(true),
|
|
}));
|
|
|
|
const db = require('../services/database');
|
|
const serverBackend = require('../services/serverBackend');
|
|
const deviceGroupService = require('../services/deviceGroupService');
|
|
const devicesRoutes = require('../routes/devices.routes');
|
|
|
|
/**
|
|
* Operator "olga" may see only devices tagged `Volunteers`. Device IN1 is in
|
|
* scope, OUT1 is not.
|
|
*/
|
|
function createScopedApp(role = 'operator') {
|
|
const app = createTestApp();
|
|
app.use((req, _res, next) => {
|
|
req.session.userId = 7;
|
|
req.session.user = { id: 7, username: 'olga', role };
|
|
next();
|
|
});
|
|
app.use('/', devicesRoutes);
|
|
return app;
|
|
}
|
|
|
|
function mockScope() {
|
|
db.getUserGroupsForUser.mockResolvedValue([{ guid: 'volunteers', name: 'Volunteers' }]);
|
|
db.getAllDeviceGroups.mockResolvedValue([{
|
|
guid: 'vol-group',
|
|
name: 'Volunteers',
|
|
source_type: 'manual',
|
|
tag_filter: '',
|
|
allowed_users: ['olga'],
|
|
allowed_groups: [],
|
|
folder_id: null,
|
|
}]);
|
|
db.getDeviceGroupMembers.mockResolvedValue(['IN1']);
|
|
// Deny-by-default scope: without this, a group ACL only *adds* visibility and
|
|
// ungrouped devices stay visible (that is the documented "open" default).
|
|
db.getSetting.mockResolvedValue('restricted');
|
|
deviceGroupService.invalidateDeviceScopeDefaultCache();
|
|
serverBackend.getDeviceById.mockImplementation(async (id) => {
|
|
if (id === 'IN1') return { id: 'IN1', hostname: 'In scope', tags: [] };
|
|
if (id === 'OUT1') return { id: 'OUT1', hostname: 'Out of scope', tags: [] };
|
|
return null;
|
|
});
|
|
}
|
|
|
|
describe('device scope guard (audit H9)', () => {
|
|
let app;
|
|
|
|
beforeEach(() => {
|
|
jest.clearAllMocks();
|
|
mockScope();
|
|
app = createScopedApp();
|
|
});
|
|
|
|
it('allows a mutation for an in-scope device', async () => {
|
|
const res = await request(app)
|
|
.post('/api/devices/IN1/rename')
|
|
.send({ display_name: 'Renamed' });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(serverBackend.updateDevice).toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects rename for an out-of-scope device', async () => {
|
|
const res = await request(app)
|
|
.post('/api/devices/OUT1/rename')
|
|
.send({ display_name: 'Hijacked' });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(serverBackend.updateDevice).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects tag replacement for an out-of-scope device', async () => {
|
|
const res = await request(app)
|
|
.put('/api/devices/OUT1/tags')
|
|
.send({ tags: ['owned'] });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(serverBackend.setPeerTags).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects a change-id for an out-of-scope device', async () => {
|
|
const res = await request(app)
|
|
.post('/api/devices/OUT1/change-id')
|
|
.send({ newId: 'STOLEN01' });
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(serverBackend.changePeerId).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects a restore for an out-of-scope device', async () => {
|
|
serverBackend.getDeviceById.mockImplementation(async (id) => {
|
|
if (id === 'OUT1') return { id: 'OUT1', soft_deleted: true, tags: [] };
|
|
return { id: 'IN1', hostname: 'In scope', tags: [] };
|
|
});
|
|
|
|
const res = await request(app).post('/api/devices/OUT1/restore').send({});
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(serverBackend.restoreDevice).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects deleting the access policy of an out-of-scope device', async () => {
|
|
const res = await request(app).delete('/api/devices/OUT1/access-policy');
|
|
|
|
expect(res.status).toBe(403);
|
|
});
|
|
|
|
it('lets an unrestricted admin through without the scope lookups', async () => {
|
|
const adminApp = createScopedApp('admin');
|
|
serverBackend.getDeviceById.mockResolvedValue({ id: 'OUT1', hostname: 'Any', tags: [] });
|
|
|
|
const res = await request(adminApp)
|
|
.post('/api/devices/OUT1/rename')
|
|
.send({ display_name: 'Admin edit' });
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(serverBackend.updateDevice).toHaveBeenCalled();
|
|
});
|
|
|
|
it('does not block anonymous callers before authentication runs', async () => {
|
|
const anon = createTestApp();
|
|
anon.use('/', devicesRoutes);
|
|
|
|
const res = await request(anon).post('/api/devices/OUT1/rename').send({ display_name: 'x' });
|
|
|
|
expect(res.status).toBe(401);
|
|
});
|
|
});
|