AI agents now open shells, SSH sessions and database connections with privileged credentials, and most of those sessions bypass the brokering, recording and approval controls built for human administrators. Vaulting keeps the secret away from the model, but once a connection is open the agent can still run any command the account allows. This guide covers the next layer: routing agent shell, SSH and database sessions through a privileged session broker, recording them in a form a reviewer can use, filtering commands and queries, and elevating privilege just in time for one task. It is written for PAM, platform and security engineering teams who are putting coding, SRE or data agents near production systems.
Key takeaways
- A vaulted secret is not a governed session. Credential injection stops the agent seeing the password; it does nothing about what the agent runs once connected, so the session itself needs a broker, a recording and limits.
- Route every agent connection through one choke point. Agents should reach servers and databases only via a broker or proxy that authenticates the agent identity, injects a short-lived credential and records the session; direct network paths should be closed.
- Record at the right layer. A screen-style recording of an agent session is hard to review; command, query and tool-call logs tied to the agent identity, the task and the human who started it are what investigators use.
- Filter destructive actions outside the model. Deny lists for commands and SQL statements, read-only roles by default and out-of-band approval for irreversible operations must be enforced by the broker or the target, not by prompt instructions.
- Elevate per task, then expire. Standing write or admin rights for agents are the root cause in several agent incidents; issue time-boxed certificates, roles or database grants scoped to one environment and one task.
Why agent sessions need their own controls
Privileged session management (PSM) puts an intermediary between the person and the target system, injects the credential and records what happens. The Privileged Session Management Guide covers that model for human administrators. Agents change three assumptions in it.
- Speed and volume: an agent can issue hundreds of commands in the time a human reviewer reads one, so after-the-fact review alone does not prevent damage. Controls that act before the command runs carry more weight.
- Intent comes from text: the agent's next action is shaped by prompts, retrieved documents and tool output, any of which can carry injected instructions. OWASP describes this risk as Excessive Agency (LLM06:2025) and recommends minimising extension permissions and requiring human approval for high-impact actions, enforced in a downstream system where possible.
- Credentials get found, not issued: coding agents read repositories and configuration files. In the PocketOS Database Deletion 2026 incident, a coding agent used a platform token it found in an unrelated file; the token was account-scoped rather than limited to the domain task it was created for, and one API call deleted a production database and its volume-level backups.
The lesson for PSM is that the session boundary, not the agent's reasoning, is where privilege has to be bounded. See the Credential Vaulting for AI Agents Guide for keeping secrets out of prompts and context; this page assumes that is in place.
Brokering patterns for agent access
There are four common ways to put a broker in front of agent sessions. Most organisations end up with two or three, chosen by target type.
| Pattern | How it works | Strengths | Watch out for |
|---|---|---|---|
| Protocol-aware PAM proxy | Agent connects to a proxy for SSH, RDP or a database protocol; the proxy authenticates the agent, injects the target credential from the vault and records traffic | Full command or query capture; credential never reaches the agent runtime | The proxy must parse the protocol; encrypted tunnels through it may be opaque |
| Short-lived certificate issuance | Broker signs an SSH user certificate or database client certificate per task, with principals, validity window and forced command | No reusable secret to leak; expiry is built into the credential | Logging then depends on the target host and its audit configuration |
| Cloud-native session service | Agent uses the cloud provider's session service (for example AWS Systems Manager Session Manager) authorised by its workload role | No inbound ports; ties session to a cloud identity and its audit trail | Logging coverage varies by connection mode (see below) |
| Tool or MCP server as broker | Agent never gets a shell; it calls narrow tools (run approved query, restart service) that a server executes with its own credential | Smallest blast radius; easy to approve and log per call | The tool server becomes the privileged system and needs PSM-grade hardening |
The tool pattern is usually safest for routine work because it removes the open-ended shell. Keep interactive shells and SQL consoles for tasks that cannot be expressed as tools, and broker those. See the Least Privilege for AI Agent Tool Use page for tool scoping, and the MCP Server Security Checklist when the broker is an MCP server.
Know where your recording goes blind
Brokers are only as good as their visibility. AWS documents that Session Manager logging "isn't available for Session Manager sessions that connect through port forwarding or SSH", because SSH encrypts the session data and Session Manager only acts as a tunnel. The same principle applies to any proxy: if the agent tunnels SSH or a database protocol through it end to end, the proxy sees bytes, not commands. Either terminate the protocol at the broker, or collect the record on the target (shell audit, database audit) and correlate it.
Issuing and scoping agent credentials per session
The session credential should carry the scope, not just the identity. OpenSSH certificates show the controls most brokers expose in some form.
| Control | OpenSSH setting | What it does for an agent session |
|---|---|---|
| Validity window | ssh-keygen -V on the certificate | Certificate is rejected outside its window; issue for the task duration only |
| Principals | ssh-keygen -n; AuthorizedPrincipalsFile on the host | Certificate is valid only for listed accounts, so a staging certificate cannot log in to production accounts |
| Forced command | force-command certificate option; ForceCommand in sshd_config | Runs a fixed wrapper instead of a shell; the requested command is available to the wrapper for allow-listing |
| Source restriction | source-address certificate option | Certificate works only from the broker or agent runner network ranges |
| Feature removal | no-pty, no-port-forwarding, no-agent-forwarding; PermitTTY, AllowTcpForwarding, PermitOpen | Removes interactive terminals and tunnels the task does not need |
| Trust anchor | TrustedUserCAKeys | Hosts trust the broker's CA instead of per-host authorized_keys entries |
Two caveats from the OpenSSH manual matter here. ForceCommand does not limit TCP, agent, socket or X11 forwarding, so disable those separately (or with DisableForwarding). And disabling TCP forwarding does not improve security if the account can still get a shell, because it can run its own forwarder. For agents, the answer is usually no shell at all: a forced wrapper that accepts only approved commands. See the SSH Protocol and Certificate Authority Guide for CA operations.
For databases, the equivalent is a per-task login or role with an expiry, granted the minimum privilege. OWASP's own example for LLM06 is an agent that only needs read access to a products table, enforced "by applying appropriate database permissions for the identity that the LLM extension uses to connect to the database". Default agents to read-only roles in non-production; grant write or DDL only through a just-in-time request.
Command and query filtering
Filtering is the control that acts before damage, so it deserves more design effort for agents than for humans. The Session Recording vs Command Filtering page compares the two in general; for agents, apply filtering in layers.
- Target permissions first: the account or role cannot run the dangerous action at all (no
DROP, no volume delete, nosudo). This is the only layer that holds if everything else is bypassed. - Broker policy second: allow lists of commands or statement classes per task type, with deny rules for destructive patterns such as recursive deletes,
TRUNCATE,DROP, role changes and backup or snapshot deletion. - Approval third: statements that match a high-impact class pause and wait for a named human to approve in a channel the agent cannot write to. See the Dual control and four-eyes approval for privileged and agent actions page for approval design.
- Platform safety nets last: soft delete, deletion protection and backups held outside the credential's reach. After the PocketOS incident, the platform concerned reported making API deletes soft deletes for 48 hours.
Text-matching deny lists are easy to evade by rephrasing, aliasing or encoding a command, so treat them as a tripwire and a source of alerts, not a boundary. The boundary is layer 1.
Recording that a reviewer can use
NIST SP 800-53 AU-14 (Session Audit) asks for the capability to record or view session content and says session auditing should be developed with legal counsel. For agents, a useful record has these fields.
| Field | Why it matters | Typical source |
|---|---|---|
| Agent identity and version | Distinguishes agents and model or prompt versions that share infrastructure | Broker authentication, agent platform |
| Initiating human or ticket | Establishes accountability and on-behalf-of context | Agent platform, change ticket |
| Task and scope granted | Lets the reviewer judge whether actions fitted the request | JIT request record |
| Each command, query or tool call with parameters | The actual evidence; maps to AC-6(9) Log Use of Privileged Functions | Broker, shell audit, database audit |
| Result and rows affected | Separates a failed attempt from a completed change | Target system, broker |
| Policy decisions | Shows blocks, approvals and who approved | Broker policy engine |
For PostgreSQL targets, pgAudit adds statement-level session logging by class (READ, WRITE, FUNCTION, ROLE, DDL, MISC) and object-level logging for specific tables. Its documentation is candid about limits: logging is best effort, superusers cannot be reliably audited, and volume can affect latency. That is another reason never to give agents superuser rights. Store records where the agent's credentials cannot alter them (AU-9), and see the AI Agent Observability and Incident Response Guide for joining session records to prompts and tool traces.
Recording humans is monitoring of workers and data protection law applies. Agent sessions often contain human data too (query results, ticket text), so set retention and access for agent recordings with the same care.
Just-in-time elevation for agents
NIST SP 800-53 AC-2(6) Dynamic Privilege Management and the NCSC's secure system administration principle to take access away when it is not needed both point the same way: agents should hold no standing privilege on production targets. A practical flow:
- The agent, or its orchestrator, requests elevation naming the target, environment, task, maximum duration and statement or command classes.
- Policy auto-approves low-risk classes (read-only in non-production) and routes others to a named approver.
- The broker issues a credential bound to that scope: a certificate with principals and validity window, or a database role grant with an expiry.
- The session runs through the broker with recording and filtering active.
- At expiry or task completion the credential lapses, the grant is revoked and the session is terminated (AC-12 Session Termination).
See the JIT Access Guide for the general model and the Just-in-Time Access for Non-Human Identities page for machine-specific patterns.
Choosing an approach
- Small teams, few agents: start with the tool pattern and read-only database roles; use a cloud session service with full logging for the rare interactive task. Avoid running a full PAM proxy you cannot staff.
- Existing PAM estate: onboard agents as a distinct identity class in the current broker, with their own policies; do not let them reuse human admin profiles.
- Heavy SSH estates: a broker-run SSH CA with forced-command wrappers scales better than per-host keys and gives expiry by design.
- Regulated data: prefer a protocol-terminating proxy so query content and results can be logged and masked centrally.
- Coding agents in developer environments: keep production credentials out of the workspace entirely; production changes go through the pipeline, not the agent's session. See the AI Agents in DevOps and SRE page.
Implementation roadmap
- Inventory: list every agent that can reach a server, cluster or database, the credential it uses and the network path. Flag credentials found in repositories or workspaces.
- Close direct paths: restrict target network access so agent runners can reach only the broker; keep a time-boxed exception register.
- Onboard in audit mode: route one agent class through the broker with recording on and filtering in alert-only mode for two to four weeks; review what it actually runs.
- Build allow lists from evidence: turn the observed commands and statement classes into per-task policies; move destructive classes to approval.
- Enforce in rings: non-production first, then production read-only, then production write with JIT. Keep the previous route available for rollback during each ring, with its use alerted.
- Remove standing credentials: revoke long-lived tokens and keys the agent used before; rotate any that were exposed in code.
- Harden the broker: treat it as tier zero. Microsoft notes PIM and PAM solutions "typically store the credentials for most or all privileged roles in the organization, making them a highly lucrative target". See Securing the jump host and bastion itself.
Detection and measurement
Alert on: agent identities authenticating to targets without a broker session; agent sessions outside an approved JIT window; blocked destructive statements; any use of credentials issued to one environment against another; and an agent credential used interactively by a human.
| Metric | Target direction |
|---|---|
| Share of agent privileged sessions that pass through the broker | Towards 100% |
| Agent identities with standing write or admin rights on production | Towards zero |
| Median lifetime of agent session credentials | Minutes to hours, not days |
| Destructive actions executed without recorded human approval | Zero |
| Agent sessions with a complete record (identity, initiator, task, commands, results) | Towards 100% |
| Long-lived credentials found in agent-readable repositories or workspaces | Falling each month |
Common failure patterns
- Broad tokens in reach of the agent: a credential created for one narrow job but scoped to a whole account, stored where an agent can read it, as in the PocketOS Database Deletion 2026 incident.
- Prompt rules as controls: telling the agent not to delete production in its instructions, with nothing at the broker or target to stop it.
- Tunnelled sessions counted as recorded: SSH or database traffic tunnelled through a session service that cannot see inside it, while dashboards show the session as logged.
- Agents on human admin profiles: agents reusing a human's PAM account or vault entry, so records cannot separate human and agent actions.
- Backups inside the blast radius: snapshots deletable with the same credential the agent holds.
- Superuser for convenience: granting superuser to make an agent work, which also defeats database audit tools that cannot reliably audit superusers.
Framework mapping
| Framework | Reference | How it applies to agent sessions |
|---|---|---|
| NIST CSF 2.0 | PR.AA-05; PR.PS-04; DE.CM-03 | Least-privilege entitlements for agents; session logs generated for monitoring; agent activity monitored |
| NIST SP 800-53 Rev. 5 | AC-6, AC-6(9), AC-2(6), AC-12, AC-17, AU-9, AU-14, IA-9 | Least privilege, logging privileged functions, dynamic privilege, session termination, remote access, protected audit records, session audit, service authentication |
| CIS Controls v8.1 | Control 5 (Account Management), Control 6 (Access Control Management), Control 8 (Audit Log Management) | Dedicated agent accounts, controlled privileged access, retained session logs |
| ISO/IEC 27001:2022 Annex A | A.8.2 Privileged access rights; A.8.15 Logging; A.8.16 Monitoring activities | Allocation and review of agent privilege; session records; monitoring for anomalies |
| MITRE ATT&CK | T1078 Valid Accounts; T1021.004 SSH; T1485 Data Destruction; mitigation M1026 Privileged Account Management | Misuse of agent credentials, SSH lateral movement and destructive actions that brokering and filtering are meant to limit |
| OWASP Top 10 for LLM Applications 2025 | LLM06:2025 Excessive Agency | Minimise permissions, act in the user's context, require approval for high-impact actions |
Practitioner checklist
- Every agent that can reach a server, cluster or database is inventoried with its credential and network path.
- Agent runners can reach privileged targets only through a broker, proxy, session service or tool server.
- Agent credentials are issued per task with an expiry, scoped to one environment and the accounts the task needs.
- Agents have no interactive shell where a forced command or tool will do; forwarding and terminals are disabled.
- Destructive commands and SQL classes are denied at the target and require out-of-band human approval at the broker.
- Session records capture agent identity, initiating human, task, each command or query and its result, stored where the agent cannot alter them.
- Tunnelled connections are either terminated at the broker or audited on the target.
- Backups and snapshots cannot be deleted with any credential an agent holds.
- The broker is hardened and administered as a tier zero system.
Standards and references
- NIST: SP 800-53 Rev. 5 Security and Privacy Controls
- OWASP: Top 10 for LLM Applications 2025 (LLM06 Excessive Agency)
- NCSC: Secure system administration
- Microsoft Learn: Securing privileged access intermediaries
- OpenBSD: sshd_config manual
- OpenBSD: ssh-keygen manual (certificates)
- AWS: Logging session activity in Session Manager
- pgAudit: PostgreSQL Audit Extension documentation
Related NHI Mgmt Group resources: Privileged Session Management Guide · Credential Vaulting for AI Agents Guide · Agent Identity vs Agent Session Identity · AI Agent Kill Switch and Containment Guide