When an attacker steals a service account key or API token, every request they make is authenticated and authorised, so the only thing that gives them away is that the identity starts behaving differently. Service accounts, workload roles and API keys are well suited to behavioural baselining because, unlike people, they normally do the same things from the same places on a predictable schedule. This guide explains which behaviours to baseline (source network, API calls, resources, timing, volume, user agent and credential), which log sources to use in AWS, Microsoft Entra ID, Google Cloud, Kubernetes and SaaS, how to build and tune baselines, what the built-in cloud detections already cover, and how to measure the result. It is written for detection engineers, identity security teams and cloud security architects. For turning these signals into a prioritised risk score, see the NHI Risk Scoring Guide; this page covers the detection layer underneath.
Key takeaways
- Machine identities are predictable, which makes deviations meaningful. A deployment role that has called the same 15 APIs from one VPC for a year and suddenly lists every bucket from a residential IP is a far stronger signal than most human anomalies.
- Baseline per identity and per credential, not per account. One service principal may have three secrets and a certificate; a sign-in with a key that is normally unused is itself an anomaly.
- Source network is the highest-value dimension. Stolen NHI credentials are almost always used from somewhere new: AWS GuardDuty has dedicated findings for instance credentials used outside AWS, and Entra ID Protection flags unfamiliar IP, ASN and country for service principals.
- First-seen actions beat volume thresholds. First use of an API, region, resource or permission-discovery call catches reconnaissance early; volume rules catch abuse only after damage has started.
- Baselines need change context. Feed deployments and configuration changes into the detection pipeline, or every release will look like a compromise and analysts will stop trusting the alerts.
Why baselining works for non-human identities
Static rules such as "alert on access from a Tor exit node" catch careless attackers. Behavioural baselining catches the rest: an attacker using a valid key from an ordinary cloud host, calling permitted APIs. It works well for NHIs because their behaviour is defined by code. A payment service calls the same endpoints for the same tables every day; a backup job runs at 02:00; a CI deployment role is only active during pipeline runs. The same property makes NHI baselines cheaper to build than human UEBA: there is less natural variance, so shorter learning windows and simpler models work. See the UEBA Guide for the human side and shared tooling.
NIST SP 800-53 Rev. 5 names this directly in AC-2(12) Account Monitoring for Atypical Usage, which asks organisations to monitor system accounts for atypical usage and report it. It applies to service accounts as much as to people.
What to baseline: the core dimensions
| Dimension | Examples of normal | Anomaly that matters | Typical attacker cause |
|---|---|---|---|
| Source network | Specific VPC endpoints, NAT gateway IPs, a CI provider's ranges, one cloud region | New IP, new ASN, residential or hosting provider not seen before, new country, IP outside the cloud for an instance credential | Key copied from code, logs or a compromised host and used elsewhere |
| API and action set | A fixed list of read and write calls | First-seen API, especially List*, Get*Policy, GetCallerIdentity-style identity checks, or IAM write calls | Reconnaissance, privilege escalation, persistence |
| Resources | Named buckets, tables, queues, projects | Access to resources outside the usual set, cross-account or cross-project calls | Data discovery and exfiltration |
| Region and service | One or two regions, a known set of services | Calls in unused regions or to new services (for example AI model APIs) | Resource abuse, hiding activity in unmonitored regions |
| Timing | Business hours, cron schedules, pipeline windows | Activity outside schedule, a dormant identity becoming active | Off-hours attacker use, reuse of forgotten accounts |
| Volume and rate | Stable calls per hour, low error rate | Spikes in calls, data transferred or access-denied errors | Bulk exfiltration, permission brute-forcing |
| Client fingerprint | One SDK and version, one user agent | CLI or browser user agent on a workload identity, new SDK | Human or attacker tooling using an NHI credential |
| Credential used | One active key or certificate per identity | Sign-in with a rarely used secret, newly added credential, credential type change | Attacker-added credential or a leaked old key |
The client fingerprint dimension also catches policy violations rather than attacks: an engineer using a production service account key from a laptop is OWASP NHI10 Human Use of NHI. See the OWASP NHI Top 10 NHI10 Human Use of NHI Guide.
Log sources by platform
| Platform | Source | Fields to baseline | Notes |
|---|---|---|---|
| AWS | CloudTrail management events (and data events for S3, Lambda and others where enabled) | userIdentity.arn, accessKeyId, sourceIPAddress, userAgent, eventName, eventSource, awsRegion, errorCode, recipientAccountId | Collect all regions into one trail; attackers use regions you do not watch. See the AWS CloudTrail Guide |
| Microsoft Entra ID | Service principal sign-in logs and, separately, managed identity sign-in logs | Service principal, IP address, resource, status, credential used | Managed identity sign-ins are excluded from the service principal log and appear only in their own log |
| Google Cloud | Cloud Audit Logs (Admin Activity, Data Access) | authenticationInfo.principalEmail, service account key ID, callerIp, methodName, resource | Data Access logs are off by default for most services; enable them for sensitive data |
| Kubernetes | API server audit logs | Service account username, verb, resource, namespace, source IP, user agent | Watch service accounts that start reading secrets or creating pods. See the Kubernetes Service Account Token Guide |
| Databases and warehouses | Native login and query history | Client IP, client driver, warehouse or schema, rows returned | Service users should have a narrow, stable query pattern |
| SaaS and APIs | Audit logs for API tokens and OAuth apps | Token ID, IP, endpoints, record counts | Coverage varies by vendor and licence tier; check before you rely on it |
What the platforms already detect
Before building custom models, turn on the native detections. They are trained on far more data than any single organisation has, but each covers only its own platform and only some identity types.
| Platform detection | Behaviour baselined | Coverage limits |
|---|---|---|
AWS GuardDuty *:IAMUser/AnomalousBehavior families (CredentialAccess, DefenseEvasion, Discovery, Exfiltration, Impact, InitialAccess, Persistence, PrivilegeEscalation) | An ML model over CloudTrail management events tracking factors such as the calling identity, location and specific API | Management events only for these findings; severity ranges from Low (Discovery) to High (Exfiltration, Impact) |
AWS GuardDuty UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS and .InsideAWS; ResourceCredentialExfiltration variants for ECS and Lambda | Instance or task credentials used from an external IP or a different AWS account | GuardDuty learns repeated remote sources as expected and stops alerting on them, so investigate the first alert |
| AWS CloudTrail Insights | API call rate and API error rate against a learned baseline, per region | Rate anomalies only, not identity-specific; extra cost |
| Microsoft Entra ID Protection: Suspicious Sign-ins (workload identities) | Baselines service principal sign-ins over 2 to 60 days; flags unfamiliar IP or ASN, target resource, user agent, hosting change, country or credential type | Managed identities are not in scope; full details and risk-based Conditional Access need Workload Identities Premium |
| Microsoft Entra ID Protection: Anomalous service principal activity, Suspicious API Traffic, Leaked Credentials | Unusual administrative directory changes, abnormal Graph traffic or enumeration, credentials found leaked | Same licensing and scope limits |
| Google Security Command Center Event Threat Detection | Rules such as Initial Access: Dormant Service Account Action, Dormant Service Account Key Created, Discovery: Service Account Self-Investigation, Initial Access: Leaked Service Account Key Used | Tier and rule availability vary; dormant rules apply to user-managed service accounts |
The Google "self-investigation" rule is worth copying to other clouds: a service account that suddenly queries its own permissions is very rarely doing so for a legitimate reason. In AWS the equivalent is a workload role calling IAM read APIs it has never called before.
Building baselines: a phased approach
- Inventory and classify. Join your NHI inventory to owners, environment and purpose (deployment, application runtime, integration, batch). Purpose sets expectations: a CI role should only be active during pipeline runs. See the Service Account Inventory Template.
- Centralise logs. Bring cloud audit, sign-in, Kubernetes audit and database logs into one store with a normalised identity key (role ARN, service principal ID, service account email, key ID).
- Learn per-identity profiles. For each identity, record the set of source networks (as CIDR or ASN), APIs, resources, regions, user agents, credentials and active hours over a learning window. Two to four weeks suits most workloads; monthly batch jobs need at least one full cycle. Entra's own learning period of 2 to 60 days is a useful reference.
- Start with first-seen rules. Alert when an identity uses a network, API, region or credential not in its profile. These are simple, explainable and catch most credential theft.
- Add peer-group comparison. Compare identities of the same purpose (for example all Lambda execution roles in a service). An identity that differs from its peers is suspicious even if its own history is short.
- Add rate and volume models. Use per-identity percentiles for calls per hour, bytes read and error rates. Alert on large deviations combined with a first-seen signal, not on volume alone.
- Run in shadow mode. Write alerts to a test index for two to four weeks, review them against change records and tune before paging anyone.
- Roll back safely. Keep each rule versioned and switchable; if a rule floods the queue after a platform change, disable it and re-learn rather than widening it permanently.
Decision guidance: small teams should rely on native detections plus a handful of first-seen rules on their most privileged identities (deployment roles, identities with IAM write or data export rights). Large estates with thousands of NHIs need automated profiling, peer groups and suppression driven by change management data, typically in the SIEM or an ITDR platform. See the ITDR Guide.
Detection rules worth having
| Rule | Logic | ATT&CK |
|---|---|---|
| Workload credential used off-platform | Credential issued to a cloud workload used from an IP outside the provider or the organisation's ranges | T1078.004, T1552.005 |
| First-seen identity discovery | Identity calls permission or identity enumeration APIs for the first time | T1087.004 |
| New credential added to an NHI | Access key, client secret or certificate created for an existing identity outside an approved pipeline | T1098.001 |
| Dormant identity active | No activity for 30 days or more, then any action | T1078 |
| Human tooling on an NHI | CLI, browser or console user agent on a workload credential | T1078 |
| New region or new service | First calls in an unused region or to a new service family | T1078.004 |
| Bulk data read | Volume of object or row reads far above the identity's percentile, combined with a new network or resource | T1530 |
| Logging tampering | Identity changes logging or monitoring configuration it has never touched; a first-time query of that configuration is an early warning | T1685 |
The LLMjacking campaigns show why first-seen rules matter: attackers with stolen cloud keys tested model access with deliberately invalid requests, checked whether invocation logging was enabled, requested model access for the first time and then spread usage across regions. Each step was a first-seen API or region for the identity, visible well before the bill arrived. For more rule content, see the Detection Engineering for Non-Human Identities Guide.
Responding to an anomaly
- Triage with context: check for a matching deployment or change record, the identity's owner and the credential involved. The anomaly is a lead, not a verdict.
- Contain the credential, not just the session: deactivate the specific key or secret, revoke active sessions where the platform supports it (for AWS, an explicit deny on tokens issued before a time), and check for credentials the attacker may have added.
- Use platform workflows: in Entra ID, confirm or dismiss the risky workload identity so the risk history and Conditional Access react; in AWS follow GuardDuty's remediation guidance for compromised credentials.
- Feed the result back: a confirmed benign change updates the baseline; a confirmed compromise becomes a test case for the rule.
Detection and measurement
Metrics that show the baselining programme is working:
- Percentage of privileged NHIs with an active behavioural profile and at least one first-seen rule.
- Log coverage: percentage of NHIs whose activity reaches the SIEM from every platform and region they use.
- Alert precision: share of NHI anomaly alerts that are true positives or policy violations, tracked per rule.
- Mean time from first anomalous action to credential deactivation, measured in incidents and purple team exercises.
- Number of human-use-of-NHI findings per month, trending down as owners move to proper human access.
Framework mapping
| Framework | Reference | Relevance |
|---|---|---|
| NIST SP 800-53 Rev. 5 | AC-2(12), SI-4, AU-6 | Monitoring accounts for atypical usage, system monitoring, audit review and analysis |
| NIST CSF 2.0 | DE.CM-03, DE.CM-09, DE.AE-02, DE.AE-03 | Monitoring technology usage, runtime environments, analysing and correlating events |
| ISO/IEC 27001:2022 Annex A | 8.15, 8.16 | Logging and monitoring activities |
| MITRE ATT&CK | T1078.004, T1098.001, T1087.004, T1530 | Valid cloud accounts, added cloud credentials, cloud account discovery, data from cloud storage |
| OWASP NHI Top 10 | NHI2, NHI10 | Leaked secrets used by attackers; humans using NHI credentials |
Common failure patterns
- Baselining the account, not the identity: rate anomalies across a whole AWS account hide one role behaving badly among thousands.
- Learning from a compromised period: if an attacker is already present during the learning window, their behaviour becomes normal. Review profiles of privileged identities by hand before trusting them.
- Ignoring regions and services you do not use: attackers go where logging and baselines are thin. Collect logs from every region.
- Alerting on volume only: by the time a volume threshold fires, data is gone. Combine first-seen and volume.
- No change feed: every release triggers alerts, analysts mute the rules, and real compromises pass unnoticed.
- Assuming native detection covers everything: Entra ID Protection does not cover managed identities, and GuardDuty stops alerting on remote sources it has seen repeatedly. Know the gaps and fill them.
Practitioner checklist
- Enable GuardDuty, Entra ID Protection for workload identities and Security Command Center threat detection where you run those platforms.
- Centralise cloud audit, sign-in, Kubernetes audit and database logs with a normalised identity and credential key.
- Build per-identity profiles of networks, APIs, resources, regions, user agents, credentials and active hours.
- Deploy first-seen rules for network, API, region and credential on privileged NHIs first.
- Alert on new credentials added to existing NHIs outside approved pipelines.
- Detect human tooling on workload credentials and route findings to the identity owner.
- Feed deployment and change records into suppression logic.
- Run new rules in shadow mode, track precision per rule and retire noisy ones.
- Rehearse containment: deactivate a key and revoke sessions within an agreed time.
Standards and references
- NIST: SP 800-53 Rev. 5 (AC-2(12) Account Monitoring for Atypical Usage)
- AWS: GuardDuty IAM finding types
- Microsoft Learn: Securing workload identities with ID Protection
- Google Cloud: Event Threat Detection overview
- AWS: Working with CloudTrail Insights
- Microsoft Learn: Service principal sign-ins
- OWASP: Non-Human Identities Top 10
- MITRE ATT&CK: Valid Accounts: Cloud Accounts
Related NHI Mgmt Group resources: NHI Risk Scoring Guide · Detection Engineering for Non-Human Identities Guide · UEBA Guide · AI Agent Behaviour Baselining and Anomaly Detection Guide · ITDR Guide