Files
shopdb-flask/plugins/endpoints/api/agentauth.py
cproudlock f0377726a1 Give each endpoint its own credential and fix the review findings on the server
Per-PC credentials (replaces the 09-14 client-certificate attempt):
- POST /api/endpoints/enroll issues a credential to a PC that matches exactly
  one computer by hostname and BIOS serial and has none yet. Anything else
  (unknown or duplicate hostname, serial mismatch, already enrolled) waits as
  a request an admin approves or rejects. The agent's persisted nonce binds an
  approved request to the PC that asked.
- One auth helper serves every agent route. With X-Endpoint-Credential the
  asset comes from the credential and a request naming another PC gets 403
  ASSET_MISMATCH. The shared key still works for PCs that have not enrolled,
  is refused (401 SHARED_KEY_REFUSED) for any PC that has, and can be switched
  off. A revoked credential gets 401 CREDENTIAL_INVALID so the agent
  re-enrolls.
- The core collector accepts the credential for the computers, printers and
  endpoints collectors through two new plugin hooks exposed on shopdb.api
  (contract 0.33.0), and refuses the shared key for enrolled PCs.
- Admin API: enrollment list, approve, reject, revoke (un-enroll), settings.
  Migration API: per-PC readiness with blockers, and upgrade waves that
  package the agent once and queue the existing agent upgrade per PC.
- Migration 0023 creates endpointcredentials, endpointenrollrequests and
  endpointmigrationwaves, drops the certificate columns from assets where
  test databases have them, and renames app_fingerprint to appfingerprint.
  0021 and 0022 keep their ids but no longer alter the core assets table.
- Removed: client_cert.py, certificate renewal, the unauthenticated
  /test/client-cert route, nginx client certificate forwarding and the agent
  certificate script. The client-cert header could be forged on IIS, the key
  was readable by users, and the shared key remained a fallback.
- GET /settings/server-cert returns the SPKI SHA-256 pin for GE-Enforce.

Review fixes:
- report_command_result used g without importing it; every result was a 500.
- collect_log refuses setup answer files, appsettings, agent directories and
  key files at enqueue.
- Fleet alerts: alerttimeout and alertfleet agree with the migration, the
  scope is validated and a malformed scope no longer reaches the whole fleet,
  and the ack race no longer raises NameError.
- A refused break-glass override leaves no hold and no audit row.
- Agent upgrade checks locks and permissions before repackaging, and writes
  the package atomically.
- Server certificate upload validates the pair before replacing files;
  generation no longer builds an openssl config from user input; audit rows
  are actually written.
- Health evaluation runs in a savepoint so a caught error cannot lose the
  check-in.
- Required-app policies are found by appid, survive renames, and deleting an
  app deactivates policies that still name it. The UI and API now say such a
  policy only takes effect inside a business policy.
- Backfill handles duplicate fingerprints and rolls back a failed batch.
- Plugin settings routes skip a plugin whose hook raises.
- The setup token is no longer printed to the log.
- The naming gate checks top-level files again and handles odd file names.
- Removed root scratch scripts, one of which carried a token.
- Rewrote the fleet alert scheduling and app delta tests on real fixtures.
2026-09-15 12:03:53 -04:00

197 lines
6.2 KiB
Python

"""Agent authentication: per-PC credentials, with the shared key as fallback.
Every agent-facing endpoints route authenticates through authenticate_agent()
and, when the route names a PC, binds the caller through bind_hostname().
X-Endpoint-Credential The PC's own secret. The server derives the asset from
it; a hostname or assetid in the request that names a
different asset is refused with ASSET_MISMATCH.
X-API-Key The shared fleet key (or a collector-scoped managed
token). Accepted only while
plugin.endpoints.sharedkeyallowed is on, and never for a
PC that holds an active credential.
Only the sha256 of a credential is stored. The full secret exists once, in the
enroll response.
"""
import hashlib
import hmac
import re
import secrets
from datetime import datetime, timedelta, timezone
from flask import g, request
from shopdb.api import (
db, Setting, error_response, ErrorCodes, collector_authorized,
)
CREDENTIAL_HEADER = 'X-Endpoint-Credential'
CREDENTIAL_PREFIX = 'sdbe_'
# sdbe_ + 43 chars base64url (32 random bytes, unpadded).
_CREDENTIAL_PATTERN = re.compile(r'^sdbe_[A-Za-z0-9_-]{43}$')
DISPLAY_PREFIX_LENGTH = 12
SHARED_KEY_SETTING = 'plugin.endpoints.sharedkeyallowed'
AUTO_ENROLL_SETTING = 'plugin.endpoints.autoenroll'
CODE_CREDENTIAL_INVALID = 'CREDENTIAL_INVALID'
CODE_SHARED_KEY_REFUSED = 'SHARED_KEY_REFUSED'
CODE_ASSET_MISMATCH = 'ASSET_MISMATCH'
AUTH_CREDENTIAL = 'credential'
AUTH_SHARED_KEY = 'sharedkey'
# lastusedat is a display value, not an audit trail: one write per 5 minutes
# per PC keeps the long-poll from turning every claim into an UPDATE.
_TOUCH_INTERVAL = timedelta(minutes=5)
def _naive_utcnow():
return datetime.now(timezone.utc).replace(tzinfo=None)
def generate_credential():
return CREDENTIAL_PREFIX + secrets.token_urlsafe(32)
def hash_credential(secret):
return hashlib.sha256(secret.encode('utf-8')).hexdigest()
def shared_key_allowed():
return Setting.get(SHARED_KEY_SETTING, default=True) is not False
def auto_enroll_enabled():
return Setting.get(AUTO_ENROLL_SETTING, default=True) is not False
def active_credential_for(assetid):
from ..models import EndpointCredential
if assetid is None:
return None
return (EndpointCredential.query
.filter(EndpointCredential.assetid == assetid,
EndpointCredential.revokedat.is_(None))
.first())
def resolve_credential(secret, touch=True):
"""Asset id for an active credential, else None."""
from ..models import EndpointCredential
if not secret or not _CREDENTIAL_PATTERN.match(secret):
return None
digest = hash_credential(secret)
row = EndpointCredential.query.filter_by(credentialhash=digest).first()
if row is None or row.revokedat is not None:
return None
if not hmac.compare_digest(row.credentialhash, digest):
return None
if touch:
now = _naive_utcnow()
if row.lastusedat is None or now - row.lastusedat >= _TOUCH_INTERVAL:
row.lastusedat = now
db.session.commit()
return row.assetid
def resolve_hostname(hostname):
"""Asset id of the one computer with this hostname (case-insensitive)."""
from plugins.computers.models import Computer
hostname = (hostname or '').strip()
if not hostname:
return None
computer = (Computer.query
.filter(db.func.lower(Computer.hostname) == hostname.lower())
.first())
return computer.assetid if computer is not None else None
def shared_key_refused_for(hostname):
"""True when the shared key may not report for this hostname."""
if not shared_key_allowed():
return True
assetid = resolve_hostname(hostname)
return assetid is not None and active_credential_for(assetid) is not None
def credential_invalid_response():
return error_response(
CODE_CREDENTIAL_INVALID,
'Endpoint credential is unknown or revoked; enroll again',
http_code=401)
def shared_key_refused_response():
return error_response(
CODE_SHARED_KEY_REFUSED,
'The shared key is not accepted for this endpoint; use its credential',
http_code=401)
def asset_mismatch_response():
return error_response(
CODE_ASSET_MISMATCH,
'The request names a different endpoint than the credential',
http_code=403)
def authenticate_agent():
"""Authorize an agent request. Returns None when authorized, else a response.
Sets g.agentauth ('credential' or 'sharedkey') and g.agentassetid (the
credential's asset, or None until bind_hostname resolves one).
"""
g.agentauth = None
g.agentassetid = None
secret = request.headers.get(CREDENTIAL_HEADER)
if secret:
assetid = resolve_credential(secret.strip())
if assetid is None:
return credential_invalid_response()
g.agentauth = AUTH_CREDENTIAL
g.agentassetid = assetid
return None
error = collector_authorized('endpoints')
if error is not None:
return error
if not shared_key_allowed():
return shared_key_refused_response()
g.agentauth = AUTH_SHARED_KEY
return None
def is_credential_caller():
return getattr(g, 'agentauth', None) == AUTH_CREDENTIAL
def bind_hostname(hostname):
"""The asset this request acts for. Returns (assetid, error_response).
Credential: the credential's asset; a hostname naming another asset is an
ASSET_MISMATCH, and a missing hostname is fine.
Shared key: the hostname's asset (None when absent or unknown, for the
route to answer); an enrolled PC is refused.
"""
hostname = (hostname or '').strip()
if is_credential_caller():
if hostname and resolve_hostname(hostname) != g.agentassetid:
return None, asset_mismatch_response()
return g.agentassetid, None
if not hostname:
return None, None
assetid = resolve_hostname(hostname)
if assetid is not None and active_credential_for(assetid) is not None:
return None, shared_key_refused_response()
g.agentassetid = assetid
return assetid, None