Skip to content

Instantly share code, notes, and snippets.

@jfrantz1-r7
Last active November 7, 2019 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfrantz1-r7/4a942cae3a40dc7aaf241fefc0351e5d to your computer and use it in GitHub Desktop.
Save jfrantz1-r7/4a942cae3a40dc7aaf241fefc0351e5d to your computer and use it in GitHub Desktop.

Threat detection in AWS using InsightIDR

Just some notes

  • A list of all current eventName fields https://gist.github.com/jfrantz1-r7/207225e8811588a50c1e230222469053
  • responseElements will only apper in a cloudtrail log if something actually changes
  • When a role is assume in one account from another, there is a sharedEventID key in the logs that gets added. By searching multiple log streams, you can combine the view for multiple accounts to find matching logs to verify suspicious activity
  • There are a few different userIdentity types:
    • Root
    • IAMUser
    • AssumedRole
    • FederatedUser
    • AWSAccount
    • SAMLUser
    • WebIdentityUser
  • It would be a good idea to enforce where credentials originate from

Example IAM CloudTrail log

{
   "Records":[
      {
         "eventVersion":"1.05",
         "userIdentity":{
            "type":"IAMUser",
            "principalId":"AIDACKCEVSQ6C2EXAMPLE",
            "arn":"arn:aws:iam::111122223333:user/anaya",
            "accountId":"111122223333",
            "userName":"anaya"
         },
         "eventTime":"2018-08-29T16:24:34Z",
         "eventSource":"signin.amazonaws.com",
         "eventName":"ConsoleLogin",
         "awsRegion":"us-east-2",
         "sourceIPAddress":"192.0.2.0",
         "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:62.0) Gecko/20100101 Firefox/62.0",
         "requestParameters":null,
         "responseElements":{
            "ConsoleLogin":"Success"
         },
         "additionalEventData":{
            "MobileVersion":"No",
            "LoginTo":"https://console.aws.amazon.com/sns",
            "MFAUsed":"No"
         },
         "eventID":"3fcfb182-98f8-4744-bd45-10a395ab61cb",
         "eventType": "AwsConsoleSignin"
      }
   ]
}      

Simply grouping by eventName

InsightIDR query

groupby(eventName) calculate(count)

Take a look at errors with service actions

InsightIDR query

groupby(errorCode)

Access denied?

InsightIDR query

where(errorCode = "AccessDenied") calculate(count)

Root login detected

InsightIDR query

where(userIdentity.type = "Root" AND eventName = "ConsoleLogin") groupby(userIdentity.accountId)

Authentication without Multi-factor authentication

InsightIDR query

`where(eventType.AWSConsoleSignIn OR eventType.AwsApiCall = "Success" AND additionalEventData.MFAUsed = "No")

Looking for IAM users created from a specific IP address from the console

InsightIDR query

where(eventName = "CreateUser") groupby(sourceIPAddress)

Grouping of access denied API calls

InsightIDR Query

where(errorCode = "AccessDenied" OR errorCode = "Unauthorized.*") groupby(eventName)

Harder to implement in InsightIDR, but: Actions by accounts other than your own

Possible InsightIDR query?

where(userIdentity.accountId != /123456789012|123456789013|123456789014|123456789015/) groupby(eventName)

Using the above, you could combine with a number of events, such as:

ModifySnapshotAttribute
DeleteBucketEncryption
DeleteBucket
DeleteBucketPolicy
PutBucketVersioning
PutBucketAcl
PutBucketEncryption
DeleteBucketReplication
DeleteObject.*

AWS Region out-of-scope detection

InsightIDR query

where(awsRegion != /your|list|of|regions/)

userAgent?

This one is a little unclear for me. Organizations might have a strict list of user agents they can look for. I've seen a lot of "sophisticated" APT groups mess this up.

STS non-multi factor authenticated

Example log

"userIdentity": {
    "type": "AssumedRole",
    "principalId": "AROAIDPPEZS35WEXAMPLE:AssumedRoleSessionName",
    "arn": "arn:aws:sts::123456789012:assumed-role/RoleToBeAssumed/MySessionName",
    "accountId": "123456789012",
    "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
    "sessionContext": {
      "attributes": {
        "mfaAuthenticated": "false",
        "creationDate": "20131102T010628Z"
      },
      "sessionIssuer": {
        "type": "Role",
        "principalId": "AROAIDPPEZS35WEXAMPLE",
        "arn": "arn:aws:iam::123456789012:role/RoleToBeAssumed",
        "accountId": "123456789012",
        "userName": "RoleToBeAssumed"
      }
    }
}

InsightIDR Query

where(userIdentity.sessionContext.attributes.mfaAuthenticated = "false") groupby(userIdentity.arn)

A collection of eventNames that may be interesting

Being honest, might be a good idea to look at Destroy.* no matter what.

DeleteTrail
StopLogging
UpdateTrail
CreatePolicyVersion
SetDefaultPolicyVersion
CreateAccessKey
CreateLoginProfile
UpdateLoginProfile
AttachUserPolicy
PutUserPolicy
UpdateAssumeRolePolicy

EC2 metadata service

This has been under the microscope a lot as a potential vector. Capital One knows this first hand https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html Basically, allows you to leverage credential information associated with a virtual machine in AWS. Some notes:

  • Don't store anything sensitive in any boostrap/cloudinit/userdata script upon instantiation
  • If an instance requires an IAM role use the absolute lowest amount of permissions possible
  • If you do not use the metadata API endpoint, use a system level firewall to allow only the root user to access this
    • iptables -A OUTPUT -m owner ! --uid-owner root -d 169.254.169.254 -j DROP
    • New-NetFirewallRule -DisplayName "EC2 Metadata" -Direction Outbound -Action Block -RemoteAddress 169.254.169.254 -Authentication Required -LocalUser "D:(A;;CC;;;S-1-5-32-544)"

I have an SSM document I need to find that will actually check this on every EC2 instance and verify if it's being applied on a cron job or in reaction to an event from cloudtrail. Will update when i find it, if i can't, i'll just come up with it again.

AWS Macie (via CloudWatch events)

We currently don't have a way of easily ingesting CloudWatch events. The best way (imo) is using an SQS queue and ingesting them as a custom log in InsightIDR.

Example log

{
  "version": "0",
  "id": "CWE-event-id",
  "detail-type": "Macie Alert",
  "source": "aws.macie",
  "account": "111122223333",
  "time": "2017-04-24T22:28:49Z",
  "region": "us-east-1",
  "resources": [
    "arn:aws:macie:us-east-1:111122223333:trigger/trigger_id/alert/alert_id",
    "arn:aws:macie:us-east-1:111122223333:trigger/trigger_id"
  ],
  "detail": {
    "notification-type": "ALERT_CREATED",
    "name": "Scanning bucket policies",
    "tags": [
      "Custom_Alert",
      "Insider"
    ],
    "url": "https://lb00.us-east-1.macie.aws.amazon.com/111122223333/posts/alert_id",
    "alert-arn": "arn:aws:macie:us-east-1:111122223333:trigger/trigger_id/alert/alert_id",
    "risk-score": 8,
    "trigger": {
      "rule-arn": "arn:aws:macie:us-east-1:111122223333:trigger/trigger_id",
      "alert-type": "basic",
      "created-at": "2017-01-02 19:54:00.644000",
      "description": "Alerting on failed enumeration of large number of bucket policies",
      "risk": 8
    },
    "created-at": "2017-04-18T00:21:12.059000",
    "actor": "555566667777:assumed-role:superawesome:aroaidpldc7nsesfnheji",
    "summary": {ALERT_DETAILS_JSON}
  }
}

Identifying ransomware events

InsightIDR query

I don't know how to do this InsightIDR query. We would be looking for the Ransomware tag in the tags array. I'll have to test this further when i have more time

List of Macie default tags

  • Configuration compliance – Related to compliance-controlled content, policy, configuration settings, control and data plane logging, and patch level.

  • Data compliance – Related to the discovery of compliance or security-controlled content, such as the existence of Personally Identifiable Information (PII), or access credentials.

  • File hosting – Related to you hosting possible malware, unsafe software, or attackers' command and control infrastructure through compromised hosts or storage services.

  • Service disruption – Configuration changes that can lead to you being unable to access resources in your own environment.

  • Ransomware – Potentially malicious software or activity designed to block your access to your own computer system until a sum of money is paid.

  • Suspicious access – Access to your resources from a risky anomalous IP address, user, or system, such as an attacker masquerading their connection through a compromised host.

  • Identity enumeration – A series of API calls or accesses enumerating access levels to your systems that can possibly indicate the early stages of an attack or compromised credentials.

  • Privilege escalation – Successful or unsuccessful attempts to gain elevated access to resources that are normally protected from an application or user, or attempts to gain access to your system or network for an extended period of time.

  • Anonymous access – Attempted access to your resources from an IP address, user, or service with the intent to hide a user's true identity. Examples include the use of proxy servers, virtual private networks, and other anonymity services such as Tor.

  • Open permissions – Identification of sensitive resources protected by potentially overly permissive (and thus risky) access control mechanisms.

  • Location anomaly – An anomalous and risky location of the access attempt to your sensitive data.

  • Information loss – An anomalous and risky access to your sensitive data.

  • Credentials loss – Possible compromise of your credentials.

Severity levels for AWS Macie logging

  • Critical – Describes a security issue that can result in a compromise of the information confidentiality, integrity, and availability in your infrastructure. We recommend that you treat this security issue as an emergency and implement an immediate remediation. The main difference between a Critical and High severity is that a Critical severity alert might be informing you of a security compromise of a large number of your resources or systems. A High severity alert is informing you of a security compromise of one or several of your resources or systems.

  • High – Describes a security issue that can result in a compromise of the information confidentiality, integrity, and availability in your infrastructure. We recommend that you treat this security issue as an emergency and implement an immediate remediation.

  • Medium – Describes a security issue that can result in a compromise of the information confidentiality, integrity, and availability in your infrastructure. We recommend that you fix this issue at the next possible opportunity, for example, during your next service update.

  • Low – Describes a security issue that can result in a compromise of the information confidentiality, integrity, and availability in your infrastructure. We recommend that you fix this issue as part of one of your future service updates.

  • Informational – Describes a particular security configuration detail of your infrastructure. Based on your business and organization goals, you can either note this information or use it to improve the security of your systems and resources.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment