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.
145 lines
5.5 KiB
Python
145 lines
5.5 KiB
Python
"""Seed the agent self-upgrade script into the ShopDB script library.
|
|
|
|
run_script only delivers bodies that live in the script library, pinned by
|
|
SHA-256. The upgrade template therefore has to exist as a real Script row with
|
|
a stored body before any upgrade can be pushed.
|
|
|
|
The template is source-controlled at
|
|
plugins/endpoints/api/templates/upgrade-shopdbagent.ps1 and seeded from there
|
|
rather than typed into the library by hand, so the reviewed script and the one
|
|
endpoints actually run are the same artifact. Editing the row's body in the UI
|
|
is pointless - the next seed overwrites it.
|
|
|
|
It lives under the plugin, not under agent/, because the Docker image copies
|
|
shopdb/, plugins/, migrations/ and scripts/ but NOT agent/. A template read
|
|
from agent/ resolves fine on a developer checkout and then fails in the
|
|
deployed container, which is the worst place to discover it.
|
|
|
|
One placeholder is rendered at seed time: the agent application's appid, which
|
|
only exists once agentregistry has created the row. Rendering happens BEFORE
|
|
the digest is computed, so the stored body and its sha256 always agree; a
|
|
substitution done after hashing would fail the agent's verification.
|
|
"""
|
|
|
|
import hashlib
|
|
import os
|
|
import uuid
|
|
|
|
from shopdb.api import Script, db, script_body_location
|
|
|
|
from . import agentregistry
|
|
|
|
# Reserved script name. Unique in the library, which makes seeding idempotent
|
|
# and keeps a hand-made script from colliding with the managed one.
|
|
UPGRADE_SCRIPT_NAME = 'ShopDB Endpoint Agent Self-Upgrade'
|
|
|
|
_UPGRADE_DESCRIPTION = (
|
|
'Managed: downloads the current published agent bundle and replaces the '
|
|
'installed agent in place, then restarts the service. Seeded from source '
|
|
'control - edits here are overwritten.'
|
|
)
|
|
|
|
# Substituted with the agent application's appid so the script can fetch its
|
|
# payload from the existing collector-authenticated app-package route.
|
|
_APPID_TOKEN = '{{AGENT_APPID}}'
|
|
|
|
_TEMPLATE_FILENAME = 'upgrade-shopdbagent.ps1'
|
|
|
|
|
|
def template_path():
|
|
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
|
'templates', _TEMPLATE_FILENAME)
|
|
|
|
|
|
def _script_dir():
|
|
"""Where script bodies live. Resolved through the contract surface helper
|
|
so this cannot drift from the directory the download route serves from."""
|
|
directory, _prefix = script_body_location()
|
|
return directory
|
|
|
|
|
|
def render_template(appid):
|
|
"""Return the upgrade script body with the appid substituted.
|
|
|
|
Raises if the placeholder is missing: that means the template was edited
|
|
in a way that breaks the download, and seeding a script that would fetch
|
|
from a literal '{{AGENT_APPID}}' path is worse than refusing.
|
|
"""
|
|
with open(template_path(), 'r', encoding='utf-8') as handle:
|
|
body = handle.read()
|
|
if _APPID_TOKEN not in body:
|
|
raise ValueError(
|
|
'upgrade template is missing the {} placeholder; refusing to seed '
|
|
'a script that cannot resolve its package'.format(_APPID_TOKEN))
|
|
return body.replace(_APPID_TOKEN, str(appid))
|
|
|
|
|
|
def seed_upgrade_script():
|
|
"""Create or refresh the managed upgrade script row and its body.
|
|
|
|
Returns a dict describing the seeded script, or None when the agent
|
|
application row does not exist yet (nothing to point the download at).
|
|
Idempotent: unchanged input rewrites nothing and leaves the digest alone.
|
|
"""
|
|
app = agentregistry.get_agent_application()
|
|
if app is None:
|
|
return None
|
|
|
|
body = render_template(app.appid).encode('utf-8')
|
|
digest = hashlib.sha256(body).hexdigest()
|
|
|
|
script = Script.query.filter_by(scriptname=UPGRADE_SCRIPT_NAME).first()
|
|
created = script is None
|
|
if created:
|
|
script = Script(
|
|
scriptname=UPGRADE_SCRIPT_NAME,
|
|
scriptdescription=_UPGRADE_DESCRIPTION,
|
|
# SYSTEM: the script stops a service, writes into Program Files,
|
|
# and edits HKLM. None of that is available in a user context.
|
|
runcontext='system',
|
|
# Failures always report; success is opt-in. Capture it here
|
|
# because an upgrade that "succeeded" but rolled back internally
|
|
# is only diagnosable from the transcript.
|
|
captureoutput=True,
|
|
)
|
|
db.session.add(script)
|
|
db.session.flush()
|
|
|
|
# Body filename follows the library convention (script-<id>.ps1) so the
|
|
# collector download route serves it like any other script.
|
|
filename = 'script-{}.ps1'.format(script.scriptid)
|
|
path = os.path.join(_script_dir(), filename)
|
|
|
|
unchanged = (script.filename == filename and script.sha256 == digest
|
|
and os.path.isfile(path))
|
|
if not unchanged:
|
|
os.makedirs(_script_dir(), exist_ok=True)
|
|
# Temp-then-replace so an interrupted write cannot leave a truncated
|
|
# body at the path the row's digest already claims to describe.
|
|
temppath = '{}.{}.tmp'.format(path, uuid.uuid4().hex)
|
|
try:
|
|
with open(temppath, 'wb') as handle:
|
|
handle.write(body)
|
|
os.replace(temppath, path)
|
|
except BaseException:
|
|
try:
|
|
os.remove(temppath)
|
|
except OSError:
|
|
pass
|
|
raise
|
|
script.filename = filename
|
|
script.sha256 = digest
|
|
|
|
script.scriptdescription = _UPGRADE_DESCRIPTION
|
|
db.session.commit()
|
|
|
|
return {
|
|
'scriptid': script.scriptid,
|
|
'scriptname': script.scriptname,
|
|
'created': created,
|
|
'updated': not unchanged,
|
|
'sha256': digest,
|
|
'bytes': len(body),
|
|
'appid': app.appid,
|
|
}
|