<?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 Syed Hasan on Medium]]></title>
        <description><![CDATA[Stories by Syed Hasan on Medium]]></description>
        <link>https://medium.com/@syedhasan010?source=rss-22603242779b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aeg08r45la_qw9myOKMO4w.jpeg</url>
            <title>Stories by Syed Hasan on Medium</title>
            <link>https://medium.com/@syedhasan010?source=rss-22603242779b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:23:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@syedhasan010/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[Management of MFA Devices in AWS IAM]]></title>
            <link>https://syedhasan010.medium.com/management-of-mfa-devices-in-aws-iam-d890c7c4ed9a?source=rss-22603242779b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d890c7c4ed9a</guid>
            <category><![CDATA[mfa]]></category>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[identity-management]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Fri, 25 Nov 2022 18:37:57 GMT</pubDate>
            <atom:updated>2022-11-25T18:37:57.099Z</atom:updated>
            <content:encoded><![CDATA[<p>Just last week, AWS released a <a href="https://aws.amazon.com/blogs/security/you-can-now-assign-multiple-mfa-devices-in-iam/?ck_subscriber_id=1931286896">new feature</a> to most AWS cloud customers — <strong>you can now assign multiple MFA devices to your root and other IAM users.</strong> Previously, due to just one device, you’d have to go through <a href="https://aws.amazon.com/premiumsupport/knowledge-center/lost-broken-mfa/">long procedures</a> (often with no resolution) in case of lost devices, incorrect emails, and (privileged and uncooperative) ex-employees — well, no more.</p><blockquote>While we’re at the subject; let’s have a quick refresher on management of MFA devices in IAM.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*0yd_INj-6X0qGnROx5F3cw.png" /></figure><h4>Creation of MFA Devices</h4><p>Creation of a new MFA device generates the <strong>CreateVirtualMFADevice </strong>API call which contains everything about the affected user and referenced resources (the device added to the user in this case).</p><p>Here’s an excerpt from the CloudTrail entry against the API call which doesn’t actually log the user against which the device was created (though you can find the originator from the <strong>userIdentity </strong>key):</p><pre>...    <br>  &quot;requestParameters&quot;: {<br>        &quot;path&quot;: &quot;/&quot;,<br>        &quot;virtualMFADeviceName&quot;: &quot;root-account-mfa-device&quot;<br>    },<br>    &quot;responseElements&quot;: {<br>        &quot;virtualMFADevice&quot;: {<br>            &quot;serialNumber&quot;: &quot;arn:aws:iam::{AccountId}:mfa/root-account-mfa-device&quot;<br>        }<br>    }<br>...</pre><p>Subsequently, you’ll also see the <strong>EnableMFADevice </strong>API call which suggests the newly created device was just enabled for usage (i.e., logins).</p><pre>...<br>  &quot;requestParameters&quot;: {<br>       &quot;userName&quot;: &quot;AWS ROOT USER&quot;,<br>        &quot;serialNumber&quot;: &quot;arn:aws:iam::{AccountId}:mfa/root-account-mfa-device&quot;<br>    }<br>...</pre><p>Let’s setup another device, generating the same set of events. Checking the logged call, I see the following parameters:</p><pre>...   <br>  &quot;requestParameters&quot;: {<br>       &quot;path&quot;: &quot;/&quot;,<br>        &quot;virtualMFADeviceName&quot;: &quot;another-device&quot;<br>    },<br>    &quot;responseElements&quot;: {<br>        &quot;virtualMFADevice&quot;: {<br>            &quot;serialNumber&quot;: &quot;arn:aws:iam::{AccountId}:mfa/another-device&quot;<br>        }<br>    },<br>...</pre><h4>ConsoleLogin Event Analysis:</h4><p>As stated in the AWS news release already, <strong>ConsoleLogin </strong>events now <em>include the MFA device</em> <em>used to authenticate to the user account </em>as part of the call (log) as well. That’s a good addition as well.</p><p>For instance, if you don’t utilize an MFA device to authenticate, you’ll see it accordingly in the log:</p><pre>...<br>    &quot;additionalEventData&quot;: {<br>        &quot;LoginTo&quot;: &quot;https://us-east-1.console.aws.amazon.com/...&quot;,<br>        &quot;MobileVersion&quot;: &quot;No&quot;,<br>        &quot;MFAUsed&quot;: &quot;No&quot;<br>    },<br>...</pre><p>Similarly, using a device now references the MFA device in the call (which was previously created and enabled for usage):</p><pre>...   <br>  &quot;additionalEventData&quot;: {<br>        &quot;LoginTo&quot;: &quot;https://us-east-1.console.aws.amazon.com/...&quot;,<br>        &quot;MobileVersion&quot;: &quot;No&quot;,<br>        &quot;MFAIdentifier&quot;: &quot;arn:aws:iam::{AccountId}:mfa/another-device&quot;,<br>        &quot;MFAUsed&quot;: &quot;Yes&quot;<br>    },<br>...</pre><p>In case of a device breach or other reasons, you can easily disable the MFA device generating the <strong>DisableMFADevice </strong>and <strong>DeleteVirtualMFADevice </strong>API call. You can easily disable it by heading to the <strong>Security Credentials </strong>tab and selecting the device (<em>Manage</em>) under <strong>Multi-factor Authentication.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68YjjQ1T7WnPzNyr2PZsTg.png" /></figure><p>Logging in with the disabled device should now generate failed API calls against <strong>ConsoleLogin</strong>:</p><pre>...    <br>    &quot;errorMessage&quot;: &quot;Failed authentication&quot;,<br>    &quot;requestParameters&quot;: null,<br>    &quot;responseElements&quot;: {<br>        &quot;ConsoleLogin&quot;: &quot;Failure&quot;<br>    },<br>    &quot;additionalEventData&quot;: {<br>        &quot;LoginTo&quot;: &quot;https://us-east-1.console.aws.amazon.com/...&quot;,<br>        &quot;MobileVersion&quot;: &quot;No&quot;,<br>        &quot;MFAUsed&quot;: &quot;No&quot;<br>    },<br>...</pre><p>It can also be monitored for as these actually indicate the right credential pair is being used just that the MFA code being entered is wrong or that the device doesn’t exist as it didn’t in our case — <em>might warrant some form of action</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d890c7c4ed9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detection & Compromise: Secrets from the AWS Secrets Manager]]></title>
            <link>https://syedhasan010.medium.com/detection-compromise-secrets-from-the-aws-secrets-manager-b6b4cab52730?source=rss-22603242779b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6b4cab52730</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-secrets-manager]]></category>
            <category><![CDATA[cloud-compromise]]></category>
            <category><![CDATA[forensics]]></category>
            <category><![CDATA[detection-engineering]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Sun, 04 Sep 2022 13:46:52 GMT</pubDate>
            <atom:updated>2022-09-04T13:46:52.744Z</atom:updated>
            <content:encoded><![CDATA[<p>Public exposure of secrets — privileged credentials used to access resources— can lead to adverse outcomes for organizations. Today, we’ll walk over the <strong>Secrets Manager</strong> service on the AWS Cloud which is fairly handy when it comes to the creation and management of secrets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*7sy9M1KJbDQ1rmqBuyhHrQ.png" /></figure><p>I’ll not be digging into the specifics of “how” the service works; rather we’ll see “how” to detect these secret compromises and “what” to do in such a case — considering it does fall under the customer’s responsibility in the <a href="https://aws.amazon.com/compliance/shared-responsibility-model/"><em>Shared Responsibility</em></a><em> </em>model.</p><h3>Why go for “Secrets”?</h3><p>Secrets, in essence, offer a gateway to the <strong>crown jewels </strong>of an organization. Whether it’s credentials to the database, API keys to your accounts, encryption keys, or whatever — they’re potentially used to access privileged environments and are, therefore, lucrative targets for your adversaries.</p><p>As a case study, we’ll take <a href="https://www.wired.com/story/cryptojacking-tesla-amazon-cloud/">Tesla’s infamous crypto-jacking compromise</a> in account. How’d it go down? A publicly exposed Kubernetes administration console with no password. That’s not the end of it — one of the pods or containers included “<em>privileged credentials</em>” to an entirely different cloud environment.</p><blockquote>That’s how the attackers dug in, starting off from a console to retrieving secrets, escalating privileges, and deploying their scripts to complete the objectives of their crypto-jacking operation.</blockquote><p>Whew; that’s precisely why Secrets Management is an important aspect of operational security today.</p><h3>Compromising Secrets</h3><p>Before we move on to detecting a compromise of secrets on the cloud, let’s first script together potential attack vectors. One thing’s for sure — to access or abuse these secrets, <strong>an adversary would have to get access to credentials allowing permissions to AWS Secrets Manager.</strong></p><p>For a demonstration, I’ve configured (<em>read:</em> misconfigured) a few services in my AWS account. For brevity’s sake, I’ll also assume there’s a compromised EC2 instance and the ‘adversary’ has gained access to it. Let’s see what can I do with my access.</p><p>Let’s start by checking if there’s an Instance Profile (role) assigned to the instance using the metadata service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jhrWAetceLmADLTIsOH-Q.png" /></figure><p>So, there’s a role attached to the instance. If I try to list more information about the role — no success. As the error suggests, I don’t have enough permissions to retrieve data from the iam service. Okay, let’s not ring alarms by brute forcing permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0YpSxkpmIDHMzi-ntBtaQ.png" /></figure><p>(Keeping it short) Let’s try the list-secrets API call to the Secrets Manager service (you can also try to go for services like S3):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fXpRTgwdCpQeS4SB9o6wg.png" /></figure><p>Success! I see the role does have (some) permissions to the manager. Let’s dig into this secret by retrieving the value using the get-secret-value API call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4grED6Si-3psE8Q3MfoPrQ.png" /></figure><p>Let’s also parse this JSON into readable credentials (or values of the SecretString key) using jq:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11Jc4zw46hQGoSkEaOENoQ.png" /></figure><p>What are the chances that these are <strong>valid</strong> credentials? I’ve configured a profile with these credentials using the aws configure utility. Let’s retry some of the previous IAM calls which failed on the configured instance profile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_lC--FwJdRAjsxk_yZTSQ.png" /></figure><p>Success! I won’t explore what other permissions are assigned to this user but generally speaking, permissions to use IAM opens up a lot of potential attack vectors to pivot into.</p><h3>Detecting the Compromise</h3><p>Now that the offense part of this compromise is complete — let’s discuss <strong>detection methodologies</strong>. If you’ve got a trail configured in CloudTrail, you can analyze the telemetry from your users, API, or service events to dig into figuring out the root cause of the compromise.</p><h4>Parsing CloudTrail Data (Athena)</h4><p>If you’re a fan of Athena, integrate your CloudTrail logs via S3 and <a href="https://docs.aws.amazon.com/athena/latest/ug/cloudtrail-logs.html">parsing them</a> won’t be a difficult task at all. Since this article has spanned a couple weeks, I don’t have the telemetry anymore but I did manage to dump the logs out in CSV. So, I’ll also give a quick brief on how to add CSV data to Athena (since I couldn’t find much on it over the web).</p><blockquote><strong>Not interested in learning about Athena or how to parse CTL data using the service? Skip to the next heading: “CloudTrail Log Analysis”</strong></blockquote><p>Head over to <em>Athena. </em>Let’s start by setting up an <strong>Output Location </strong>for the workspace we’re currently working in — which is the location where query results are stored. Create a new bucket for this configuration data, switch to the <em>Settings </em>tab in Athena, and press <em>Manage </em>to populate the <strong>Query Result Location </strong>field with an S3 buckets location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zDyfQpxIvuyqHpvfD1_oA.png" /><figcaption>Query Result Location</figcaption></figure><p>Head back into the query editor and let’s create a new table by hovering over the <strong>Create </strong>option under <em>Tables &amp; Views. </em>Since my CSV sheet is in an S3 bucket, I’ll choose <strong>S3 Bucket </strong>as my data source. Fill in details of the database (new or existing), table, and the S3 input (the actual bucket’s location ending with the prefix not the file name). Select <strong>CSV </strong>under Data Format and bulk-add columns. Here’s what I added (I removed the spaces between the column names and converted the column names into title case):</p><p>UserName String, AwsAccessKey String, EventTime String, EventSource String, EventName String, AwsRegion String, SourceIpAddress String, UserAgent String, ErrorCode tring, Resources String, RequestId String, EventId String, Read-only String, EventType String, RecipientAccountId String, EventCategory String</p><p>You might wonder — why didn’t I specify structs for the <em>Resources </em>or other similar columns? Well, that isn’t a permissible operation in the bulk-addition feature. You can, however, go through the struggle to update the fields format using DDL queries (<strong>I won’t</strong>).</p><p>That’s it. Create the table and you’re good to go — here’s a sample query (change the table name accordingly):</p><p>SELECT * from &quot;ctl-csv-data&quot;</p><h4>CloudTrail Log Analysis</h4><p>CloudTrail practically logs every API call made by any resource, service, or principal in the AWS account.</p><p>Let’s first list down all <em>distinct </em>event sources using the query: SELECT DISTINCT eventsource from &quot;ctl-csv-data&quot; .</p><p>I’m interested in the Secrets Manager service so let’s filter on it as the eventSource: SELECT * from &quot;ctl-csv-data&quot; WHERE eventsource=&#39;secretsmanager.amazonaws.com&#39; and we see just two users attempting calls against the service — i-0cc...3237 (an instance) and cloud_user .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRC57N_NphncvMkp0ZjOuw.png" /><figcaption>Events against the Secrets Manager service</figcaption></figure><p>Now the obvious suspect here is the instance itself generating 12 requests (using the configured instance profile) and all those API calls are GetSecretValue. Does this suggest a compromise? <em>Not at all</em>. It could very well be an administrator or a CRON script requesting credentials from the Secrets service — this is where an analyst has to add in “context” to the alarming results.</p><p>If we cater in the time to these requests, the pattern does seem suspicious as all requests are generated in a span of <em>4 minutes</em>. So, where do we pivot from here? We could look at the instance’s activity and see what else has happened at the instance level and if it warrants a closer look.</p><p>Six (unique) events in total in our fetched logs — GetSecretValue would’ve been followed by a KMS Decrypt call (as the secret could’ve been encrypted using a service key). There are denied events on the IAM service as well which is interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weiaW8auR152lZ8ewvaCgg.png" /><figcaption>API calls generated from the (potentially) compromised instance</figcaption></figure><p>So, one thing’s for sure — since the Decrypt calls don’t fail, whoever executed the calls does have access to the secrets as well. A chat with the administrator and you get to know that there are ‘access credentials’ for the myadministratoruser inthe secrets! <em>Whoops!</em></p><p>The adversary could’ve logged in using the stolen valid credentials. To pivot, let’s filter the data against the user. Now we see just two calls against GetInstanceProfile. A slip here from the adversary was to configure these credentials on a machine exposing the IP address in the sourceIpAddress field. Had they been configured on the instance, the source IP would’ve pointed to the instance again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2MeboGx_b1bLqfhVzq9Cw.png" /><figcaption>Events from the ‘myadministrator’ user</figcaption></figure><p>You can further pivot into the activity against the IP address in CloudTrail logs or perhaps the instance’s OS or service (web server) logs to find evidence of the initial compromise.</p><h4>Other (Potential) Pivots</h4><p>Secrets Manager, like most services, allows <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_examples_cross.html"><strong>cross-account access</strong></a> to resources created within it. For that, the adversary would have to update the <strong>resource policy </strong>of the compromised secret and the <strong>identity policy </strong>of the IAM user(s). Since we saw compromise of a user with access to the IAM service, the adversary could’ve modified both policies and assigned cross-account access for hidden access.</p><blockquote><em>Mind you — this would also require updates to the key policy of the KMS key so the secret could be decrypted.</em></blockquote><p>Why would that be needed if the secret has already been compromised? Secrets Manager allows auto-rotation of credentials of certain secret types using Lambda functions. Persistence in such cases will help the adversary get the updated secrets (or credentials).</p><p>If your analysts don’t monitor for activities in unused regions, the <strong>Secret Replication </strong>feature could also be used wherein the adversary would replicate the secrets in the specified region without raising alarms. Keep your alerts generic to all regions and especially monitor unused regions for suspicious activity.</p><p>In case of an adversary attempting to disrupt your services and delete resources (e.g., secrets), the Secrets Manager places a mandatory (minimum) wait period of 7 days after which the key is actually deleted. Regardless, monitoring for such API calls can yield good results.</p><p>Here’s a <a href="https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_examples.html">good read</a> from the AWS documentation on the Secrets Manager on <strong>Permission Policies </strong>outlining some of the API calls from the service and their individual implications.</p><h3>Handling Compromised Credentials</h3><p>Great, you’ve detected a <em>secret</em> compromise. What next? Trigger your Incident Response process! As part of it, you can take several actions:</p><h4><strong>Revoke &amp; Rotate</strong></h4><p>Classic. Mind you — revoking and rotating credentials isn’t going to do much if the root cause of the compromise is still soundly letting intruders in. Fix the root-cause, closely monitor the intruder, and once you’re certain you’ve tracked all activity and that all open holes have been patched, hit the kill switch.</p><p><strong>Revoking credentials </strong>is possible for individual users under the Security Credentials tab. You can either delete the key entirely, monitor it for usage, or make it inactive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCcvEgO2Fer2GsByNDzsWg.png" /><figcaption>Revoking access keys for users (via IAM)</figcaption></figure><p>If you’d like to go a step further and disable the user entirely, that’s also possible under the same tab. You can also <strong>rotate the credentials </strong>for the user yourself or force a password reset on the new login.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sk-1Hl3e2nWfUgjMel7ytA.png" /><figcaption>Rotating credentials for AWS users (via IAM)</figcaption></figure><p>What if it’s an instance profile, like we saw in our CloudTrail telemetry? Well, you can <strong>revoke sessions </strong>for roles as well. Under the Revoke Session tab in the role, press Revoke Active Sessions and that’d terminate all open sessions (<em>new sessions can still be created!</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hfi8xcAuCVwm098R2tVUQ.png" /><figcaption>Revoking all active sessions (via IAM roles)</figcaption></figure><h4>Tune Overly-permissive Policies</h4><p>Let’s be clear; the blast radius of the compromise could’ve been a lot smaller if only the permissions assigned to the instance profile or the user were limited and instead of a service key, a user-based KMS key would’ve been used with a strict key policy.</p><p>Tune the policies, remove all unneeded permissions, and if you <em>must </em>allow access to critical APIs, then filter on the resources as well (e.g., only the secret which is needed by the script or application running on the instance rather than all secrets).</p><h4>Delete Resources</h4><p>Identified the users or roles behind the compromise? Time to check what activity or operations they might’ve performed on your AWS cloud and list all such unauthorized resources. Once you’re certain all such resources have been identified, it’s time to delete or terminate the resources so your bill doesn’t surprise you.</p><p>You might also wish to isolate some of these resources (e.g. instances) to perform forensics, study the compromise, and improve detection or prevention controls based on your findings.</p><h3>Acknowledgements</h3><p><a href="https://www.inversecos.com/2022/05/detection-and-compromise-azure-key.html">Lina Lau’s</a> articles on Detection and Compromise on the Azure Cloud have been a great source of inspiration for kick-starting this series on Detecting Compromises on the AWS Cloud. Give her content a read <a href="https://www.inversecos.com/2022/05/detection-and-compromise-azure-key.html">here</a>!</p><p>Did you like reading this? Leave a comment on what else would you like to read or improve in this article — I’m always open for constructive criticism!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6b4cab52730" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Session Manager: Securing Access to Cloud Resources]]></title>
            <link>https://syedhasan010.medium.com/aws-session-manager-securing-access-to-cloud-resources-8657533dd6a1?source=rss-22603242779b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8657533dd6a1</guid>
            <category><![CDATA[systems-manager]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[aws-ssm]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[session-manager]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Tue, 21 Jun 2022 15:45:30 GMT</pubDate>
            <atom:updated>2022-06-21T15:45:30.137Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing resources on the cloud — with both security and scalability at mind— can quickly get out of hands. Luckily, AWS released the Systems Manager which is a collection of tools or functions which can help us manage assets in the cloud while minimizing the time and efforts required to resolve operational problems within them. A tool within this suite is the <strong>Session Manager.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*_sxLPC9184kGX1QvoZoPnQ.png" /></figure><p>Session Manager allows secure access to instances in the AWS cloud or on-premise infrastructure (via AWS PrivateLink) without leaving the browser (or your CLI). Using the service, we can easily launch a one-click in-browser shell and run (virtually) a large subset of commands in the bash shell. Neither do you have to allow inbound ports to your infrastructure, nor do keys need to be managed — it’s all handled by the Session Manager.</p><blockquote>Limited security exposure, session auditing and logging, and ease of node management — sign me up!</blockquote><h3>Getting Started with Session Manager</h3><p>Session Manager or any other tool from the Systems Manager suite isn’t readily able to access any instance. An agent needs to be installed on the endpoints, permissions need to be assigned to roles, instance profiles need to be created, and only then can you go ahead and start sessions on your instances.</p><h4>Creating an IAM Role</h4><p>Systems Manager doesn’t have permissions, by default, to perform actions on instances. AWS requires explicit assignment of permissions to the instance which needs to be managed by the Systems Manager. As such, you can either create an entirely new role or add permissions for access to the Systems Manager to an existing role (and later assign it to your EC2 instance via an <em>Instance Profile</em>).</p><p>Here, I’ll create a new role with <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/getting-started-create-iam-instance-profile.html#create-iam-instance-profile-ssn-logging">necessary permissions</a> for Session Manager and Amazon S3 (I’ll cover the ‘why’ later):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66e2aa1fd67df4b4ea9751de9636ddfb/href">https://medium.com/media/66e2aa1fd67df4b4ea9751de9636ddfb/href</a></iframe><p><strong>Note: </strong>You need to create a new customer-managed key via KMS and update the key-name value (in the kms:Decrypt permission) to the ARN of the CMK. You also need to create a new bucket in S3 and update the Resource value of the S3 permissions to include the ARN of the bucket. Here’s how my resource fields look:</p><ul><li>arn:aws:s3:::myssmauditingbucket/prod-account/*</li><li>arn:aws:kms:us-east-1:{ID}:key/6ad11c3c-ec08–403c-82d5–97c1d8b8a764</li></ul><p>The role needs to be created for the EC2 service (select AWS Service under Trusted Entity and EC2 under use-cases) for it to be used as an Instance Profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9mEEIK8kD4R1dgovRCneQ.png" /><figcaption>Role Creation via IAM</figcaption></figure><p><strong>What’s significant about these permissions? </strong>There’s three sets of permissions here:</p><ul><li>ssmmessages refers to the <a href="https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonsessionmanagermessagegatewayservice.html#amazonsessionmanagermessagegatewayservice-actions-as-permissions"><strong>Session Manager Message Gateway Service</strong></a><strong> </strong>which is primarily tasked with the creation and management of data/control channels which connect an instance to the Systems Manager service</li><li>kms is used for encryption of session data (which is optional but recommended)</li><li>s3 is used for logging session data from a session to the specific S3 bucket (more on this soon)</li></ul><p><a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-service-role.html">Here’s</a> a guide from AWS on creation of an IAM service role for on-premise or hybrid environments.</p><h4>Creating or Assigning an Instance Profile</h4><p>Instance profiles are practically just roles which are applicable to EC2 instances to assign them permissions to access other services in the AWS cloud. Let’s assign our newly created role to an instance.</p><p>If you’re creating a new instance, you’ll find the setting under the Advanced Details tab. If it’s already launched, you can Modify the IAM Role by selecting your instance, going to Actions, and changing the settings under the Security tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*56f6vkEIZpmSvBW4zxIepw.png" /><figcaption>Assignment of Instance Profile</figcaption></figure><h4>Starting Sessions</h4><p>All done? Let’s spin up a few sessions. You can do so in several ways (documented <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html#start-sys-console">here</a>). I’ll simply head over to my EC2 console, press Connect, and select Session Manager. Press Connect and that should be it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1FSzGNF-Vv3-h13WGiGyg.png" /><figcaption>Starting Sessions via the Session Manager</figcaption></figure><p>Here’s how my in-browser shell looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pXjEV-9lR-ief9k6eibvQ.png" /><figcaption>A Sample Session from the Session Manager</figcaption></figure><p>Similarly, I can start a session using the AWS CLI. Create a user with programmatic access, configure the profile, and then issue the following command:</p><p>aws ssm start-session --target {InstanceID} --profile {default}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvnuXEgYDG918taABeOHHQ.png" /><figcaption>Session Started via the AWS CLI</figcaption></figure><h3>Configuring Session Manager</h3><p>Well, that’s all out-of-the-box work with little to no extra configuration. If you’ve worked with SSM before, exposing it to anyone can also pose a security risk in itself. It’s why you need to configure and restrict access to the service. These could include modifying permissions or settings like:</p><ul><li>Session timeouts and maximum duration</li><li>Encrypting sessions</li><li>Denying permission to certain users</li></ul><p>Here’s where <strong>System Manager Documents </strong>come into play. These documents hold region-specific preferences for an AWS account. However, explicit permissions must be assigned to update these documents. Just as we explored the Gateway Services’ permissions before, the following permissions are assigned to users for managing SSM documents:</p><ul><li>CreateDocument</li><li>GetDocument</li><li>UpdateDocument</li><li>DeleteDocument</li></ul><p>By default, a document is created in the region from which the service is accessed. It’s a boilerplate document with the same configurations as set in the Preferences of the Systems Manager. Here’s an example with Cloudwatch configured for streaming:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*94_oeyEjsj3lITYM8ngnxQ.png" /><figcaption>SSM-SessionManagerRunShell Default SSM Document</figcaption></figure><p>Again, you might want to restrict a particular user to be able to update a particular resource (or SSM document in this case). You can restrict these permissions in your IAM policy to the SSM document resource (e.g. SSM-SessionManagerRunShell). Here’s an example from AWS:</p><p>{ “Action”: [ “ssm:CreateDocument”, “ssm:GetDocument”, “ssm:UpdateDocument”, “ssm:DeleteDocument” ], “Effect”: “Allow”, “Resource”: [ “arn:aws:ssm:us-east-2:123456789012:document/SSM-SessionManagerRunShell” ] }</p><p>The SSM Document captures all these configurations via a simple JSON file. Here’s how a sample document looks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e994553372253fc94e12e2f749620df/href">https://medium.com/media/2e994553372253fc94e12e2f749620df/href</a></iframe><p>You can even specify the usage of these documents as part of your IAM policies. Here’s an example of me explicitly requesting the usage of the my-sesh-doc document as part of all session creations on the specified instance (from the user to which this policy will be assigned):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*mHn2AvhW0b94BmTzTMgXTA.png" /><figcaption>IAM Policy to Restrict SSM Usage</figcaption></figure><p>To configure Session Timeouts or Maximum Durations from the console — you can head over to Systems Manager, open up Preferences for Session Manager and edit out the fields. Similarly, encryption of session data can be enabled by selecting a symmetric encryption key from KMS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f24QgvItJCC_QJEc7grKZw.png" /><figcaption>Configuring the SSM Service</figcaption></figure><h4>Restricting Commands</h4><p>Custom session documents can be used to permit a set of commands as part of an interactive session as well. Using the InteractiveCommands session type document, we can restrict a session to a particular set of commands (ping here).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*-h0BS7whw6o2Rwp-_65Vbg.png" /><figcaption>InteractiveCommands Session Type Document</figcaption></figure><p>Here’s how enforcement looks when it’s run via the CLI (paired with the IAM policy shared above):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acYBS_2sRDnmGSCGgj9cvw.png" /><figcaption>Launching an Interactive Session with Custom Documents</figcaption></figure><h3>Auditing and Logging Sessions</h3><p>Session activity can be audited using CloudTrail. This includes calls like a connection or session start, document delete and all other calls made to/from an instance and the Systems Manager service. Depending on your use-case, there’s a lot of potential on automating anomalies and monitoring of suspicious API calls.</p><p>Session History is also maintained under Session History in the Session Manager console (under Systems Manager service. Session termination is also possible from the Sessions tab — depending on your permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6BdStcqsKiatmYclsT24g.png" /><figcaption>Sessions and Session History</figcaption></figure><h4>Logging Sessions</h4><p>Sessions can also be logged or streamed to <strong>Amazon S3 or CloudWatch Logs.</strong></p><p>Logging vs. streaming — which one should you prefer?</p><ul><li>Streaming allows you to continuously receive commands from all active sessions in a JSON format — for forwarding to EventBridge, monitoring, or generating alarms based on custom needs. It is currently only possible via CloudWatch</li><li>Session data can only be logged or uploaded at the very end of the session. There’s no continuous stream of messages. This is better suited for archiving. It is possible via both CloudWatch and S3.</li></ul><p>For this blog, I chose S3 to log all my session data (as I previously discussed — permissions for S3 are required to log data to the specified bucket). To enable either of the two settings:</p><ol><li>Open up Systems Manager</li><li>Head to Session Manager</li><li>Open up Preferences</li><li>Select either of the two — CloudWatch logging or S3 logging</li><li>Enable S3 logging and configure the bucket name and prefix (optional)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgTtxgKqqn6nnFI2CSbpQA.png" /><figcaption>Configuring S3 logging for SSM</figcaption></figure><p>Let’s connect to the instance via SSM again and see if the session data is logged to S3. After launching and terminating an instance, here’s a file in our S3 bucket:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9u3i5YmysbH8FlHmYLfVQ.png" /><figcaption>S3 Bucket with Session Log file</figcaption></figure><p>Open it up and voila — all our session data was logged:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQxuNFOiG7aLeeVkGrfYqw.png" /><figcaption>Contents of the Session Log file</figcaption></figure><blockquote><strong>Mind you — session data includes both the input and output. Sensitive data, if input with these configurations, will be logged in the session data!</strong></blockquote><h3>What’s Next?</h3><p>Session Manager can save countless hours of security teams trying to limit exposure from sensitive ports for login. Review your environment — is Session Manager the need of the hour? Will it serve any purpose? Can auditing and logging be enabled (if already using it) without risks? Get to work! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8657533dd6a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Instance Metadata Service: A Quick Refresher]]></title>
            <link>https://syedhasan010.medium.com/aws-instance-metadata-service-a-quick-refresher-4b61ed9af23a?source=rss-22603242779b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b61ed9af23a</guid>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[instance-metadata]]></category>
            <category><![CDATA[imd]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 17:31:19 GMT</pubDate>
            <atom:updated>2022-06-09T17:31:19.659Z</atom:updated>
            <content:encoded><![CDATA[<p>Elastic Compute Cloud (EC2) was the third service released by Amazon under its “Web Services” banner. This was late into 2007 when AWS was rapidly expanding and innovating solutions for its end users. One such service released within EC2 was the <strong><em>Instance Metadata Service </em></strong>(IMDS)— a handy service exposed to each compute instance which can be used to retrieve an instance’s configuration data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*eEMbI9pII6D6eq7UfI3n5A.png" /></figure><p>How is this service helpful?</p><p>Often, you’d want to securely access information about your instance’s configuration for launching resources or deciding your service’s logics. Manual efforts by the UI become exhaustive as you scale this beyond a few instances. The service, exposed in the form of a <strong>link-local IP address</strong> to the instance, can be used to query information via scripts, CLI or the SDK, and used to perform a range of <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMI-launch-index-examples.html">operations</a>. You can query information from the following categories about your instance(s):</p><ul><li>Host: Instance ID, AMI, AMI Launch Index, etc.</li><li>Network: Public/Private IPs, Subnet, Security Groups, etc.</li><li>User-data: Custom bootstrap scripts which execute at instance start-up</li><li>So many more available <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-categories.html">here</a>!</li></ul><h3>Querying the IMDS</h3><p>IMDS is exposed via a link-local IP address, <strong><em>169.254.169.254</em></strong>, to the instance and behaves like a REST interface accepting requests and generating responses. Now mind you, these requests never leave the network — i.e., these requests never go through the typical flow of going outbound from your security groups, NACLs, or the Internet Gateway. Instead, they’re resolved by the AWS hypervisor (upon which your instance is hosted) which returns information requested by your specific URL.</p><p>So, how does a sample query look like? Here’s an example:</p><p>curl <a href="http://169.254.169.254/latest/meta-data/">http://169.254.169.254/latest/meta-data/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*1Lu7h3IkLKdDBY3L3B0UFg.png" /><figcaption>Output via IMDSv1 Call</figcaption></figure><p>If you run this from your instance, you’ll be returned with a list of categories (I mentioned before) which will further need to be appended to the URL to retrieve data. Here’s another example:</p><p>curl <a href="http://169.254.169.254/latest/meta-data/">http://169.254.169.254/latest/meta-data/</a>instance-id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbGGP7frhce3c-2KDDediw.png" /><figcaption>Retrieving Instance ID via IMDSv1</figcaption></figure><p>If you’d like to use IPv6 (which needs to be specifically enabled during Instance launch or via modify-instance-metadata-options calls) to reach out to the service, you can use the following link-local address:</p><p>curl http://[fd00:ec2::254]/latest/meta-data/</p><p>To what extent can I really retrieve information from this service? Let’s see. Digging through the list of categories — you’ll come across <strong>Security Credentials</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAzUPUq3rR4al7F4zWYkMA.png" /><figcaption>IMDS — Accessing Security Credentials</figcaption></figure><p>Using this endpoint, you can retrieve (and I quote):</p><blockquote>“…the temporary security credentials associated with the role”</blockquote><p>You can go so far as to retrieve credentials for a role associated with an instance. If it were a highly privileged role assigned to that instance, re-use of the role could lead to <em>devastating outcomes</em>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9vKvJmxranOsMc00QWwtQ.png" /><figcaption>Retrieving the Instance’s Security Credentials via IMDSv1</figcaption></figure><h3>Something’s Clearly Wrong Here…</h3><p>There’s no form of authentication, verification, or accountability as to who’s making these requests. We’ve seen compromises in the past where EC2 instances were prone to SSRF attacks and the actors were able to query the metadata service from vulnerable applications. Practically leaving credentials open for anyone to steal.</p><p>Once you’ve got all three — the <em>AccessKey</em>, the <em>SecretAccessKey</em>, and the <em>Token </em>— you can do pretty much anything with the credentials. Fire up your CLI or the SDK and run whatever’s possible through the privileges assigned to the credentials.</p><h3>Say Hello to IMDSv2</h3><p><a href="https://aws.amazon.com/blogs/security/defense-in-depth-open-firewalls-reverse-proxies-ssrf-vulnerabilities-ec2-instance-metadata-service/">IMDSv2</a> offers protection against SSRF and three other issues with its predecessor. It does so by enforcing <strong>session authentications </strong>such that the user has to first acquire a token and then pass it in subsequent requests to retrieve the desired data.</p><p>SSRF is mitigated by only allowing the PUT method for requests to get session authentication tokens. Most applications either use a GET or POST method in their backend API calls . Same goes for WAFs which allow POST requests to go through but rarely allow PUT requests. Since the method never aligns, the vulnerability can’t be exploited.</p><p>Here’s how the requests look now; first we generate a token with a valid time to live value (maximum 6 hours — 21600 seconds):</p><p>curl -X PUT &quot;http://169.254.169.254/latest/api/token&quot; -H &quot;X-aws-ec2-metadata-token-ttl-seconds: 10000&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58V0OfQdC3auieUTym7mdQ.png" /><figcaption>Retrieving the Authentication Token via IMDSv2</figcaption></figure><p>Then, we re-use the acquired token to send out a request to the IMDS: (assuming I’ve stored the token in the $TOKEN variable)</p><p>curl -H “X-aws-ec2-metadata-token: $TOKEN” http://169.254.169.254/latest/meta-data/instance-id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6F_yDipdWbEtByj3siN3OQ.png" /><figcaption>Retrieving Instance ID via IMDSv2</figcaption></figure><p>To further improve the security of the secret token, the token is never stored by the service itself. This way, whenever the calling process exits or the session is terminated, the session token is terminated as well. It also restricts the token to the subject instance. Though there’s no limit to the number of sessions, calling processes, or requests per session.</p><p>PS: PUT requests with an X-Forwarded-For header are immediately rejected which I believe is a decent measure for forwarded requests.</p><h3>Migrating to IMDSv2</h3><p>Luckily, migration isn’t a pain. Both versions of the metadata service are available to instances and<strong> enabled by default</strong>. It’s up to the tenant to disable either of the two or both the versions on their instances.</p><p>There’s also a helpful <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/viewing_metrics_with_cloudwatch.html">CloudWatch metric</a> — MetadataNoToken — which can help keep track of what instances are still using the older version of the service.</p><h4>Disabling IMDSv1</h4><p>You can easily disable IMDSv1 at the launch of your instance. While launching it, take a look at the <strong>Advanced Details </strong>section and look for the <em>Metadata Version </em>parameter. By selecting <strong>V2 Only </strong>you can ensure your instance only allows the upgraded version of the metadata service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*itlQpnBtoDE4xh3_FuTkNQ.png" /><figcaption>Disabling IMDSv1</figcaption></figure><p>What if you’ve already launched the instance with IMDSv1 enabled? Access the instance and run the following modify-instance-metadata-options call via the CLI to require tokens on all HTTP requests to the IMDS endpoint (replace ‘x’ with your instance ID):</p><p>aws ec2 modify-instance-metadata-options --instance-id X --http-tokens required --http-endpoint enabled</p><p>Using SCPs or IAM policies, you can also restrict the launch of instances with IMDSv1 enabled (or it being enabled at all if there’s no legitimate use-case).</p><h4>Response Hop Limits</h4><p>By default, the PUT request to retrieve the token can only go through a single hop to reach the metadata service. Any increment and the request gets rejected. However, this is concerning for containerized applications which have to communicate to IMDS via the host itself. In such cases, the response hop limit can be increased using the same modify-instance-metadata-options call:</p><p>aws ec2 modify-instance-metadata-options --instance-id X --http-put-response-hop-limit 5 --http-endpoint enabled</p><h3>What Next?</h3><p>Disable or upgrade the service? Put up controls? Secure yourself! But hey, due diligence comes first. Check to see if any legitimate application is dependent on the older version of the IMDS. If so, they first need to be made compatible with the IMDSv2. Once compatible, it’s time to get to work 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b61ed9af23a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Honest Review of TCM Security’s Practical Malware Analysis and Triage]]></title>
            <link>https://syedhasan010.medium.com/honest-review-of-tcm-securitys-practical-malware-analysis-and-triage-e0285e773523?source=rss-22603242779b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0285e773523</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[tcm-security]]></category>
            <category><![CDATA[pmat]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Wed, 17 Nov 2021 15:22:18 GMT</pubDate>
            <atom:updated>2021-12-28T17:47:55.068Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Review of TCM Security’s Practical Malware Analysis and Triage</h3><p>Cyber-defense trainings and certifications are incredibly expensive. In a world where SANS charges thousands of bucks for trainings from world-class professionals, Heath Adam’s work via TCM Security is nothing short of ‘amazing’.</p><p>I’ve been a personal fan of Heath and his continued promise to help beginners in the field progress without emptying their pockets. <a href="https://academy.tcm-sec.com/p/practical-malware-analysis-triage?affcode=770707_4ydqd2r7">TCM’s Practical Malware Analysis and Triage (PMAT)</a> is one of the latest trainings from their collection — aiming to assist up and coming malware analysts and helping them improve their craft.</p><p>Now that I’ve successfully completed the course on my own — I figured it was time to quickly script a review to help others get a quick idea as to what the course presents and what should they expect while jumping right in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*i5OKyxj3gL8MNqVh_ZnQUw.png" /><figcaption>Certificate of Completion</figcaption></figure><h3>PMAT: Practical Malware Analysis and Triage</h3><p><a href="https://academy.tcm-sec.com/p/practical-malware-analysis-triage?affcode=770707_4ydqd2r7">PMAT</a> is a fairly intensive training authored and delivered by <a href="https://twitter.com/HuskyHacksMK?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor">@HuskyHacks </a>(Matt Kelly). Looking at the targeted audience (as per the training’s page), it is focused on beginners and intermediate analysts looking to upskill themselves. We’ll take an in-depth look at the course curriculum later. For now, here’s what the course enrollment offers you:</p><ul><li>Access to the student-only channel on Discord to receive support from the instructor and other students</li><li>Access to 9+ hours of engaging, instructional video content</li><li>Access to the PMAT Lab repository containing dozens of malware samples designed to teach you the fundamentals</li><li>Course completion certificate</li></ul><h4>Course Curriculum</h4><p>The curriculum covers everything from basic static analysis to advanced dynamic analysis — along with several other helpful bits — such as analyzing shellcode, macro-enabled documents, and others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*VFGEHjU3Iw9p1H6Z1kD6kQ.png" /><figcaption><a href="https://academy.tcm-sec.com/p/practical-malware-analysis-triage?affcode=770707_4ydqd2r7">TCM Security’s Practical Malware Analysis &amp; Triage</a></figcaption></figure><p>The course curriculum is properly designed to take an analyst from the start till the end — explaining the entire thought process an analyst should ideally go through while breaking down malware and reporting it to the world. Not only that, you get to work on an amazing queue of malware samples (most, custom written by Matt to assist newcomers) — at the end of which stands — WannaCry (the “Boss Fight”).</p><h4>Course Content</h4><p>Let’s break the course down into four sections — setup, basic analysis, advanced analysis, and specialties (shellcode, maldocs, automation, etc.).</p><p><strong>Setup </strong>is quite simple. A FLARE VM is setup alongside a REMNUX machine which are then bridged together in a private network to isolate the two machines. The training prerequisites do suggest that you need a good workstation to setup the lab environment successfully. However, if you’re unable to do so, you might want to try alternative solutions so as to run a single virtual machine for e.g. use FakeNet instead of INetSim to see if the objectives of the lesson are met.</p><p><strong>Basic Analysis </strong>was quite beginner-friendly and I loved how Matt explained concepts to ensure everyone could be on the same playing field. Static and dynamic analysis help pave the way for advanced analysis and are nicely followed up by an exercise to help put the concepts to use.</p><p><strong>Advanced Analysis </strong>is where I’d say beginners might feel light-headed. Matt’s overview of x86 assembly and disassembling malware in Cutter was decent. Advanced dynamic analysis, on the other hand, was fairly good. However, these sections were no match for the exercise which was later presented to the students i.e. SickoMode. The Nim-based binary and its analysis was a fairly difficult challenge (in comparison to the lessons) and presented a steep learning curve.</p><p>All in all, this section requires more exercises and in-depth explanations. I had covered some of these topics in Practical Malware Analysis (by FireEye’s analysts) and felt comfortable going through the course; however, other beginners might need serious work off-course to understand this section properly. Perhaps the Twitch stream with the final exercise’s analysis also needs to be shifted up in the course such that students can directly learn from Matt’s analysis. Currently, the stream is at the end of the course — where I feel it serves less purpose.</p><p><strong>Specialties </strong>is where I felt I fell in love with the course. Analyzing malicious documents, identifying Go binaries, and working with shellcode was super beneficial and can serve as the starting ground for someone looking to expertise in these specialties.</p><p>I knew what Jupyter Notebooks were but this course was the formal introduction to the might of this amazing automation suite. <em>Blue Jupyter </em>motivated me to kickstart my own automation notebooks and I’d say would be highly beneficial for anyone already armed with the might of Python. The sections for report writing and Yara rules were handy additions and concluded the course in just the right fashion — ensuring analysts are able to produce content and ensure their analysis is read by others.</p><h4>Malware and Custom Samples</h4><p>Every single video in the course is complemented with a malware sample — mostly custom developed by Matt — to help analysts practice the lesson. Two challenges and a “Boss Fight” is also added into the course which makes the learning experience quite awesome!</p><p>The “Boss Fight” — featuring WannaCry — was also an exciting challenge which ensures the analyst puts all newly learned concepts to use. However, I would highly suggest students to review the complementary blog attached by Matt to analyze the malware (if they’re stuck) rather than the basic walkthrough.</p><h4>Matt’s Discord</h4><p>Soon after enrollment, you’ll see your glistening invite to Matt’s personal Discord server. For me, personally, this was an much-needed addition to the course as it gets the student a bridge to the author and other students who’re likely going through the same content.</p><p>Whatever problems I’ve come across (or other students for that matter), Matt has been quick to respond and help out in any way possible (other students were quite helpful as well). I know as the course scales and students start coming in, it might be a tad bit difficult for him but by then the pre-existing knowledge in the server should be self-sufficient for anyone coming for assistance.</p><h3>Conclusion</h3><p>With the $30 price tag, the course is definitely a steal. The course has gray areas but I’ve seen two students pass on suggestions (similar to my review) to Matt and his humble response to the suggestions meant he’d be adding in content to ensure the course is truly serving its intended audience. I’m sure once Matt polishes a few sections in the course, it’s going to be far more valuable than the default price tag put by TCM Security.</p><p>Just to summarize a few hard-hitting questions —</p><p>Who is the course for? Beginners in malware analysis and reversing though you should know basics to some degree to ace the advanced sections of the course.</p><p>Should you get it? YES. If you aren’t able to solve the exercises, there’s plenty of material to help you acquire the knowledge necessary to continue. The course simply puts up a methodical way of analyzing malware. You’re still going to have a structured thought process by following the course — unlike by following a random assortment of open-sourced knowledge which might lead you astray.</p><p>Want to give the original course curriculum a look? You can do so <a href="https://academy.tcm-sec.com/p/practical-malware-analysis-triage?affcode=770707_4ydqd2r7">here</a> while also easily signing up for it if you feel like going through the technical course!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0285e773523" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reversing with IDA: Cross-references]]></title>
            <link>https://syedhasan010.medium.com/reversing-with-ida-cross-references-42b311245a75?source=rss-22603242779b------2</link>
            <guid isPermaLink="false">https://medium.com/p/42b311245a75</guid>
            <category><![CDATA[using-ida]]></category>
            <category><![CDATA[cross-reference]]></category>
            <category><![CDATA[aids]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[reversing-with-ida]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Sun, 19 Sep 2021 10:45:53 GMT</pubDate>
            <atom:updated>2021-09-19T10:45:53.069Z</atom:updated>
            <content:encoded><![CDATA[<p>Cross-references, or more commonly referred to as <em>xrefs</em>, are used to identify references (usage/call or declaration) of a particular function, string, variable, etc. Example — if you’ve identified a particular function (a VM check) being called inside another subroutine (installation of a backdoor), you might be interested in knowing other calls to the same function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*76V30iRpNgcV74ojbvG9AQ.png" /></figure><h3>Categories of Cross-references</h3><p>Cross-references can be categorized as follows:</p><ul><li>Code cross-references</li><li>Data cross-references</li></ul><p>Let’s explore the two in a short section next.</p><h4>Code Cross-references</h4><p>Code cross-references are used to identify relationships between function calls, declarations, or jumps. Let’s take a look at an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Rg1bbz8hE8b-RGLXvcqvUA.png" /><figcaption>CODE XREF shows the reference to the actual jump</figcaption></figure><p>Here, we can see that <strong>loc_1000D325 </strong>has a code cross-reference to <strong>sub_1000D2F9+19</strong>. It suggests that this location is accessed by the function (sub_*) at the address 1000D2F9 and an offset of 0x19 into the function. Next, the arrow shows us that the code is at a lower address than the reference and the ‘j’ suggests it’s a jump.</p><p>Much like this jump, there are several other cross-reference types as I’ll discuss later on.</p><h4>Data Cross-references</h4><p>Much like code cross-references, data cross-references can help us keep track of data being accessed or written throughout the binary. For example, you might find an IP address being referenced in a few functions; using xrefs, you can identify all those functions easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*IkMpSVHzrUu_cj4T6bDI6w.png" /><figcaption>DATA XREF shows several strings being referenced in functions</figcaption></figure><p>Here, we can see several data strings being referenced in functions. For example, the <strong>aThePidofProces_1 </strong>is being referenced in the function, <strong>sub_1000D5B0 </strong>and at on offset of 0x264. The direction is upwards again suggesting the function is at a lower address than string’s address.</p><p>For the DATA XREF to <strong>aCopySToSSucces </strong>you can see two cross-references being listed. IDA restricts listing multiple references by default. You can change this setting and show as many references as you want. It is under ‘Options’ — ‘General’ — ‘Cross-references’.</p><h3>Listing Cross-references</h3><p>If you’ve identified an offset or a function and would like to list all cross-references, you can simply do so by selecting the label and pressing ‘<strong>X</strong>’ to list all cross-references to that particular label (or identifier).</p><p>‘<strong>CTRL+X</strong>’ shows us cross-references to the address (cursor’s selection does not matter as it is worked with addresses not identifiers). ‘<strong>CTRL+J</strong>’ shows us cross-references from the address</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*e_ifye0wSoyzGVpG3UsQvw.png" /><figcaption>Cross-references to the offset, ‘aCopySToSucces’</figcaption></figure><p>Here, we can find the following information:</p><ul><li><strong>Direction: </strong>Whether the target reference is at a higher (Down) or lower (Up) address</li><li><strong>Type</strong>: Type of the cross-reference</li><li><strong>Address/Text: </strong>Address of the target reference and the actual code/text at that particular address</li></ul><p>Similarly, we can also view the information in a graphical view. Select ‘View’, Go into ‘Graphs’ and select either of the three xref charts available. You can:</p><ul><li>View xrefs from the identifier (where the reference ‘goes to’)</li><li>View xrefs to the identifier (where the reference ‘comes from’)</li><li>Use a custom xref chart with several customization options (this is particularly helpful in larger binaries and to filter out unhelpful identifiers)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*UNkIrUpQF1gA686_saJ9ZA.png" /><figcaption>Custom XREF chart in IDA</figcaption></figure><h3>Types of Cross-references</h3><p>From the official Hex-Rays documentation [2], we can find <strong>13 </strong>types of cross-references. A few of these cross-reference types are listed below:</p><ul><li>O: Offset — Address is taken by the identifier selected by the cursor (there’s no read or write operation here)</li><li>R: Read access — Data is being read from the address</li><li>W: Write access — Data is being written at the address</li><li>J: Far (Inter-segment) jump — Code being jumped to is in a different code segment than the current segment</li><li>j: Near (Intra-segment) jump — Code being jumped to is in the same code segment as the identifier</li><li>P: Far (Inter-segment) call — Call is in a different code segment</li><li>p: Near (Intra-segment) call — Call is in the same code segment</li></ul><h3>Conclusion</h3><p>Cross-references can be really helpful when reversing binaries. You can quickly identify the purpose of a function by identifying its calls or look for interesting code by the data it references. Hopefully, this guide was a quick hands-on to getting started with cross-references.</p><h3>References</h3><p>[1] <a href="https://hex-rays.com/blog/igor-tip-of-the-week-16-cross-references/">Hex-Rays’ Tip of the Week by Igor</a></p><p>[2] <a href="https://hex-rays.com/products/ida/support/idadoc/1305.shtml">Cross-reference Attributes</a></p><p>[3] <a href="https://hex-rays.com/blog/igor-tip-of-the-week-17-cross-references-2/">Adding Cross-references</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42b311245a75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forensic Analysis of an LNK File]]></title>
            <link>https://syedhasan010.medium.com/forensics-analysis-of-an-lnk-file-da68a98b8415?source=rss-22603242779b------2</link>
            <guid isPermaLink="false">https://medium.com/p/da68a98b8415</guid>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[forensics]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[shortcuts]]></category>
            <category><![CDATA[windows]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Thu, 12 Aug 2021 16:51:51 GMT</pubDate>
            <atom:updated>2021-08-12T17:02:40.252Z</atom:updated>
            <content:encoded><![CDATA[<h3>LNK File Analysis: LNKing It Together!</h3><p>Shell Links or more commonly known to native Windows users as shortcut files — technically known by their extension <strong>LNK </strong>— serve to be one of the most fruitful initial access vectors for threat actors. A seemingly harmless file with a dubious icon and the hopes of malware operators on its back — the file kicks into action and spurs stages onto stages of malware to compromise a system — bravo!</p><blockquote>The purpose of this article is to dig into the <strong>Shell Link Binary </strong>file format powering LNK files and analyzing how these simple shortcuts (LNKs) are potential gateways to havoc.</blockquote><h3>Shell Link Binary (File Format)</h3><p>The <a href="https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-shllink/16cb4ca1-9339-4d0c-a68d-bf1d6cc0f943"><strong>Shell Link Binary Format</strong></a><strong> </strong>is what powers LNK files. It describes a structure — say a container to hold objects in — called a <strong>‘shell link’ </strong>— jargon for shortcut or an LNK file. The purpose of it is rather simple — to <strong>access one</strong> <strong>data object by means of another object</strong>. To do so, it’d have to store some form of reference to the target data object (called a ‘<strong>link target</strong>’) for the source to create a relation (called a ‘<strong>link</strong>’) to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6QzNAjkjhWmneXdh7g6IxQ.png" /><figcaption>Figure 1: Overview of the Shell Link Binary file format</figcaption></figure><p>Shell links are composed of several other structures which compose the file itself. These structures are listed below below:</p><ul><li>SHELL_LINK_HEADER</li><li>LINKTARGET_IDLIST</li><li>LINKINFO</li><li>STRING_DATA</li><li>EXTRA_DATA</li></ul><p>Strap in — this isn’t going to be the most ‘fun’ section. Though you’ll need the information to make sense of the output from a parser (we’ll discuss that in the next section).</p><h4>SHELL_LINK_HEADER</h4><p>The SHELL_LINK_HEADER is the only structure within a link file which is mandatory for an LNK file to conform to the file format. This is due to the fact that this header contains key information about the target file, attributes pertaining to that file, and other structures such as <em>LinkFlags </em>to identify the presence of other optional headers (structures).</p><p>For example, for the LINKTARGET_IDLIST structure to exist, the <strong>HasLinkTargetIDList </strong>attribute would have to be set in the LinkFlags sub-structure of this header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3MUsFckhGrBxerDDhdo6w.png" /><figcaption>Figure 2: Overview of the SHELL_LINK_HEADER structure</figcaption></figure><p>The complete list of attributes within LinkFlags is available at Microsoft’s documentation <a href="https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-shllink/ae350202-3ba9-4790-9e9e-98935f4ee5af">here</a>.</p><h4>LINKTARGET_IDLIST</h4><p>Assuming <strong>HasLinkTargetIDList </strong>is set under LinkFlags in the previous structure, this structure stores references to the targets location(s) on the filesystem.</p><p>However, these references aren’t simple fully qualified paths (e.g., C:\ABC\aFile.txt). Rather, the <a href="https://docs.microsoft.com/en-us/windows/win32/shell/namespace-intro"><em>Shell </em>namespace</a> organizes files (or objects) such that each file is known by its <strong>ItemID </strong>(the <a href="https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishellfolder-getdisplaynameof">GetDisplayNameOf </a>method within the IShellFolder interface can be used to convert pointers to these IDs to <a href="https://docs.microsoft.com/en-us/windows/win32/shell/folder-info">readable display names</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKtAGabM4CTgDn7rFZT2Eg.png" /><figcaption>Figure 3: Overview of the LINKTARGET_IDLIST structure</figcaption></figure><p>An organized list of these ItemIDs is what creates an IDList which is further encapsulated in the LINKTARGET_IDLIST structure.</p><h4>LINKINFO</h4><p>Similarly, if the <strong>HasLinkInfo </strong>attribute is set under LinkFlags in the first header, the LINKINFO structure is populated. This structure holds information useful to resolve link targets and identify their location including the drive volume, serial numbers, labels, and local paths.</p><h4>STRING_DATA</h4><p>The STRING_DATA section is majorly controlled by the LinkFlags structure in the SHELL_LINK_HEADER. For example, if the <strong>HasWorkingDir </strong>and <strong>HasRelativePath </strong>attributes are set within LinkFlags, you’d be able to see the working directory and a relative path of the link target in this structure.</p><p>Another important attribute is <strong>HasArguments</strong>, which specifies the command-line argument with which the link shall be executed.</p><h4>EXTRA_DATA</h4><p>Now, the final structure in a link file is the EXTRA_DATA structure which holds all other complementing information about a link target. Although the complete list is available <a href="https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-shllink/c41e062d-f764-4f13-bd4f-ea812ab9a4d1">here</a>, a few are worthy of a mention:</p><ul><li><strong>EnvironmentVariableDataBlock </strong>structure is useful when the link target has a corresponding environment variable as well</li><li><strong>TrackerDataBlock </strong>offers another way to locate and resolve the link target using the Link Tracking Service — which can help identify if the target file was copied or moved. It can also return information such as the MachineID (NetBIOS name) where the target last existed and a MAC address</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDvZ88OQgjjdsBuweELyPg.png" /><figcaption>Figure 4: Overview of the EXTRA_DATA structure</figcaption></figure><h3>Parsing LNK Files</h3><p>Isn’t it rather tedious to go through the specification each time? Luckily, our peers have done an awesome job at parsing LNK files and reveal data instantly.</p><p>To pick one from a long list of parsers, I’d go for <a href="https://twitter.com/ericrzimmerman?lang=en">Eric Zimmerman</a>’s <a href="https://ericzimmerman.github.io/#!index.md">LECm</a>d. There’s multiple ways to view the output, option to suppress details, MAC to vendor conversion, and so much more.</p><p>To use it, simply pull the tool from the repo and run it from a shell. To view the help:</p><pre>LECmd.exe -h</pre><p>Here’s how I’ve parsed a sample:</p><pre>LECmd.exe -f &quot;C:\Users\X\Desktop\HxD.lnk&quot;</pre><p>Here’s a glimpse of the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuNDr5667FJRLzy5VH8B8g.png" /><figcaption>Figure 5: Output of LECmd on a Sample LNK file</figcaption></figure><p>If you’ve read it till here — you should have an idea as to what each section in the output represents. Now, let’s turn it up a notch and see how threat actors love to meddle with these files!</p><h3>The Dark Side of LNK Files</h3><p>Mostly, threat actors use the command-line feature of LNK files to enable the file to act as a downloader. Let’s take a look at how <a href="https://www.virustotal.com/gui/file/460c098565a7f5866bb96281ebada37d8e3a7f9e4112de663a05bba470e27929/detection">a typical but malicious LNK file</a> looks to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*3HNSnPVPh_P4mkFnMnl9Wg.png" /><figcaption>Figure 6: How sweet is it?</figcaption></figure><p>Dig into its properties and there’s a nasty call to… <strong>hsmta</strong>. Whatever that is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*td6atgoFWuqfyR1JV55Aqw.png" /><figcaption>Figure 7: Call to ‘hsmta’ with a URL (likely a downloader)</figcaption></figure><p>So, it starts up in C:\Windows and moves on to its target location but there’s no <strong>hsmta</strong>. Well, there’s an mshta.exe (a Windows utility used to execute compiled HTML files) — and this utility is renown for malice. But what’s happening here?</p><p>If you were to press ‘Open File Location’ now — you’d hit ‘mshta’ even though the target box clearly mentions some other binary. Now, there were dozens of points where we saw references to the link target in the file specification. Let’s parse this file and view it in detail. Here’s a summary of those paths where a target’s path is parsed:</p><pre>Relative Path: ..\..\..\Windows\System32\hsmta.exe</pre><pre>...<br>    Local path: C:\Windows\System32\hsmta.exe</pre><pre>...<br>-File ==&gt; mshta.exe<br>    Short name: hsmta.exe<br>    Modified: 2021-01-02 03:07:32<br>    Extension block count: 1</pre><pre>--------- Block 0 (Beef0004) ---------<br>    Long name: mshta.exe<br>    Created: 2021-01-02 03:07:32<br>    Last access: 2021-01-02 03:07:32<br>    MFT entry/sequence #: 215068/6 (0x3481C/0x6)</pre><pre>...<br>Environment variables: %windir%\System32\hsmta.exe</pre><pre>...<br>28636aa6-953d-11d2-b5d6-00c04fd918d0\30     Parsing Path                        ==&gt; C:\Windows\System32\hsmta.exe</pre><p>There are <strong>five </strong>instances where a fake executable name is registered here. LNK files go through several ways to hunt down the link target. Here, when the short name is rendered useless, the long name is used to resolve the link target (the path is actually taken from the EnvironmentVariableDataBlock, the absence of which will make the LNK useless) and execute the malicious link file.</p><p>Unfortunately, that’s not it.</p><p>You’d think the <strong>Target</strong> box in the file’s properties would be able to hold the entire command-line argument in it. But it can’t. The field is actually limited to 260 characters. Whereas the entire command-line argument field supports 4096 characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*ZGE3myu7rQnug8_f7gt_Dw.png" /><figcaption>Figure 8: Nothing suspicious here. Just a cmd.exe call… move on.</figcaption></figure><p>Threat actors are <a href="https://www.virustotal.com/gui/file/eb0c32389e7099df711fa1f7bfaef770144f196db191cc2d9c46979ccf75d3a3/detection">known</a> to add whitespace or paddings to the field. This pushes malicious commands outside the scope of the box. Now if an uninformed user were to view the file for suspicious indicators, there would be nothing and a compromise might be underway.</p><h3>What Can We Do About It?</h3><p>Writing detection rules is perhaps one of the most efficient way to detect and thwart malicious attempts to execute LNK files.</p><p>Florian Roth’s Signature Base repository is also home to several good Yara rules to <a href="https://github.com/Neo23x0/signature-base/blob/master/yara/gen_susp_lnk_files.yar">detect LNK files</a> being dropped from an array of sources e.g. ZIP files or to detect a rather <a href="https://twitter.com/cyb3rops/status/1042091463226675201?s=20">suspicious set of LinkFlags</a>.</p><p>Using the TrackerDataBlock, you can also use the NetBIOS name, MAC address, and volume serial number to track an actor across multiple intrusions and campaigns. The metadata has proven to be quite useful as can be seen in this <a href="https://www.fireeye.com/blog/threat-research/2018/11/not-so-cozy-an-uncomfortable-examination-of-a-suspected-apt29-phishing-campaign.html">FireEye intrusion analysis</a>.</p><p>Lastly, it’s never too late to gently inform your users of good and bad clicks. Through informed lessons of what to do when receiving devious emails or unknown files showing up conveniently — just don’t ever click it.</p><p>That’s it for this one, folks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da68a98b8415" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Defender’s Toolkit 102: Sigma Rules]]></title>
            <link>https://syedhasan010.medium.com/defenders-toolkit-102-sigma-rules-4a623acb2036?source=rss-22603242779b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a623acb2036</guid>
            <category><![CDATA[writing-sigma-rules]]></category>
            <category><![CDATA[sigma]]></category>
            <category><![CDATA[detection-use-cases]]></category>
            <category><![CDATA[sigma-rules]]></category>
            <category><![CDATA[how-to-write-sigma]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Sat, 06 Mar 2021 10:26:29 GMT</pubDate>
            <atom:updated>2021-03-06T14:20:38.718Z</atom:updated>
            <content:encoded><![CDATA[<p>Now that the intelligence community is finally reaching its due maturity, advisories shared with fellow organizations often contain useful detection use-cases. If we were to travel back a few years, an average analyst would dread the manual conversion of these use-cases into searchable queries for the logging platform or SIEM. What we duly needed was a standard — a way to write a query once and search it everywhere —that is precisely what <strong>Sigma </strong>provides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*C-8u5XuwUzX3413YIOsIGg.png" /></figure><h3><strong>What is Sigma?</strong></h3><p>Sigma is the brainchild of Florian Roth and Thomas Patzke. To quote the <a href="https://github.com/SigmaHQ/sigma">GitHub</a> page of the open-source tool, Sigma:</p><blockquote><strong>is a generic and open signature format that allows you to describe relevant log events in a straightforward manner.</strong></blockquote><p>Let’s reference back to our problem. One single use-case had to be converted for every single SIEM or centralized logging platform available to SOC’s all over the world. Luckily, Sigma rules (a use-case converted into the Sigma specification is called a rule) serve as a strict format for analysts to describe a particular use-case and convert it for whichever platform they want.</p><p>Writing Sigma rules is fairly easy and follow the YAML serialization format (we’ll discuss the specification later) which is quite flexible to accommodate custom fields. One of the best features is it doesn’t restrict to a particular log file or extension. You may even use it via <em>grep </em>on the command-line. The re-usability of rules and ease of sharing is one of the many reasons why researchers (like myself) love this tool!</p><h3>Writing Sigma Rules</h3><p>We’ve previously discussed how a Sigma rule is encapsulated in a YAML file. This YAML file follows a standard or specification set by the authors of Sigma. It is available on the <a href="https://github.com/SigmaHQ/sigma/wiki/Specification">GitHub</a> page as well. Just to summarize that information — the following sections constitute a good rule:</p><ul><li>Metadata (Title, ID, Author, References, Tags, Level)</li><li>Log Source (Define the log source which will be used to collect the data from e.g. the Windows Security log channel)</li><li>Detections (selections, filters, and conditions)</li><li>False-positives</li><li>Optional (and custom) tags</li></ul><p>The official specification over GitHub has a detailed explanation of every section and the fields within each one of them. If you’d like a thorough review of the specification — head to the <a href="https://github.com/SigmaHQ/sigma/wiki/Specification">link</a>. If you’d like a quick introduction to getting started with Sigma rules and writing them — read ahead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*QNSsrn9I_tMI0Hsi2tDvfA.png" /><figcaption>A Sample Rule to Detect Mimikatz</figcaption></figure><h3>How to Start Writing Sigma Rules?</h3><p>Let’s break the process down into small, achievable steps.</p><h4>Step 1: Acquire the Sigma repository [Optional]</h4><p>The official Sigma repository contains all documentation, sample rules, and compilers required to convert the Sigma into queries. To get started, fetch the Sigma repository and store it on your disk:</p><pre>git clone https://github.com/SigmaHQ/sigma</pre><h4>Step 2: Create a YAML file</h4><p>Let’s start writing the Sigma rule by creating a new YAML file locally. You can use your favorite development environment or editor (even Notepad <em>if you love excruciating pain</em>). With code editors, you can easily format, syntax-check, and highlight your YAML file without hitting your head against a wall. Once the file is created, let’s copy the specification into the file: (<em>excuse any mistakes you might notice as we’ll fix it while writing the rule</em>)</p><pre>title:<br>id:<br>status:<br>description:<br>author:<br>references:<br>logsource:<br>   category:<br>   product:<br>   service:<br>   definition:<br>detection: <br>   condition: <br>fields: <br>falsepositives:<br>level: <br>tags:</pre><h4>Step 3: Provide Input to Attributes</h4><p>Our next step is to fill the required attributes by acquiring information from the source of the detection use-case. For this particular example, I’ll cheat and open one of rules from the Sigma repository which are available under the<em> .\rules\ </em>directory.</p><p>Here a few attributes which are almost always available to us in advisories:</p><pre>title: Mimikatz Command Line<br>id: a642964e-bead-4bed-8910-1bb4d63e3b4d<br>description: Detection well-known mimikatz command line arguments<br>author: Teymur Kheirkhabarov, oscd.community<br>date: 2019/10/22<br>modified: 2020/09/01<br>references:<br>    - <a href="https://www.slideshare.net/heirhabarov/hunting-for-credentials-dumping-in-windows-environment">https://www.slideshare.net/heirhabarov/hunting-for-credentials-dumping-in-windows-environment</a><br>falsepositives:<br>    - Legitimate Administrator using tool for password recovery<br>level: medium<br>status: experimental</pre><p>Here, the <strong>status </strong>attribute defines the maturity of the rule itself. It can have either one of these values:</p><ul><li>Stable — Usable in production environments</li><li>Test — Tuning is required if an FP is thoroughly vetted</li><li>Experimental — Usable in the test environment and needs tuning to reduce the noise and FPs</li></ul><p>Similarly, the <strong>level </strong>attribute defines the criticality of the rule itself. If an alert is indeed generated based on the rule — what should you be doing? Based on internal processes, the following four values can be used for the Level attribute and responded to accordingly:</p><ul><li>Low</li><li>Medium</li><li>High</li><li>Critical</li></ul><p>Next up — we have the <strong>logsource </strong>and <strong>detection </strong>sections. Let’s cover them one by one. From the same rule:</p><pre>logsource:<br>    category: process_creation<br>    product: windows</pre><p>The <strong><em>logsource </em></strong>section covers the log data itself upon which the detection clauses will be applicable. It can have three major attributes:</p><ul><li>Category — log files which fall under a particular category e.g. DNS server logs, process_creation, file_event logs, etc.</li><li>Product — log files generated by a particular product e.g. windows (Eventlog), linux, splunk, etc.</li><li>Service — Subset of a product’s log e.g. security, powershell, sysmon, etc.</li></ul><p>For our example, we’ve used the <strong>process_creation </strong>category which caters to generic logs of process creation under the Windows Eventlog.</p><pre>detection:<br>    selection_1:<br>        CommandLine|contains:<br>            - DumpCreds<br>            - invoke-mimikatz<br>    selection_2:<br>        CommandLine|contains:<br>            - rpc<br>            - token<br>            - crypto<br>            - dpapi<br>            - sekurlsa<br>            - kerberos<br>            - lsadump<br>            - privilege<br>            - process<br>    selection_3:<br>        CommandLine|contains:<br>            - &#39;::&#39;<br>    condition: selection_1 or selection_2 and selection_3</pre><p>For the <strong>detection </strong>section, we’ve defined the following attributes:</p><ul><li>Selections — What you actually wish to select/search from the log data</li><li>Conditions — How should the selection or filters be evaluated</li></ul><p>Here, the selection (search-identifier) matches the CommandLine field in the log data and uses the transformation modifier (contains) in order to check if the listed keywords are available or not. A short list of modifiers is listed below:</p><ul><li>contains</li><li>all</li><li>base64</li><li>endswith</li><li>startswith</li></ul><p>We can also use wildcard characters to match a wide list of keywords in the log data. For example, instead of a hardcoded path, we wish to find logs of execution for cmd.exe — we can use ‘<strong><em>\*cmd.exe’</em>. </strong>All three selections repeat the same format. Finally, the condition attribute evaluates the three selections by means of a logical OR operation.</p><p>For conditions, we can evaluate the expressions using:</p><ul><li>Logical AND/OR operations</li><li>1 of (selection) OR all of (selection) — this you might recognize from Yara as well</li><li>Negation using ‘not’ — e.g. <strong>not</strong> selection</li><li>Grouping expressions by using parenthesis — e.g. <strong>(selection1 and selection2) or selection3</strong></li></ul><p>Mind you — there is much more to learn here about modifiers (type vs. transformation modifiers), various categories, lists and maps in selections, grouping of conditions and aggregations. Sadly, this article can’t contain it all. I, once again, urge you to read the specification (thoroughly) once so you can easily write better rules.</p><h4>Step 4: Compiling the Rule</h4><p>In order to convert the Sigma rule into searchable queries for your SIEM or logging platform, you can use the <strong>Sigmac </strong>tool shipped with Sigma itself. Head into the<em> .\tools\ </em>directory and execute Sigmac :</p><pre>python .\sigmac -h</pre><p>Sigmac allows you to convert a particular rule for a <strong>target</strong> like Splunk, QRadar, or even PowerShell. Sigmac also uses field mappings to convert fields used in the rule into actual fields available for the desired target. For example, the CommandLine field might be converted into “Command Line” for your custom solution (based on your target/configuration).</p><p>In order to view all available targets, configurations, and modifiers, simply run:</p><pre>python .\sigmac --lists</pre><p>To finally convert the rule for a target (e.g. Splunk) use: (We also require the -c flag for configurations to correctly set the field mappings)</p><pre>python .\sigmac -t splunk -c splunk-windows ..\rules\windows\process_creation\win_mimikatz_command_line.yml</pre><blockquote>You can now go ahead and use the rule on your Splunk instance!</blockquote><p>To read more about Configurations and Field Mapping — refer to the source: <a href="https://github.com/SigmaHQ/sigma/blob/master/tools/README.md">https://github.com/SigmaHQ/sigma/blob/master/tools/README.md</a></p><p>One quicker way of writing Sigma rules is to review the .\<em>rules\ </em>directory, find the rule of your preference (or the one which has similar detections/selections), and go about editing it. This can save you some time. Though make sure you edit the attributes so the newly written rule is unique as well. It’s fairly common to take inspiration from the available rules (especially during the learning phase).</p><h3>Using Uncoder.io</h3><p>SOC Prime has also released a tool named <a href="https://uncoder.io/">Uncoder</a>. Using the web interface, you can easily write and play around with Sigma rules on the web. It allows you to write, edit, test, and compile the rules for a variety of targets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sNfEBUZOUMnENLE8tYpeg.png" /><figcaption>Sample Rule translated via Uncoder</figcaption></figure><h3>Conclusion</h3><p>Writing Sigma rules is quite easy. Though there are sophisticated conditions and selections as well, you can easily grasp them in time. The authors have done a tremendous job with the documentation of the tool and its compiler for newcomers to understand. Make sure to practice writing Sigma rules every now and then so you can write them to aid your Incident Response process or empower your SOC in the longer run.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a623acb2036" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VBA Purging — What Purpose Does It Serve?]]></title>
            <link>https://syedhasan010.medium.com/vba-purging-what-purpose-does-it-serve-1f3ff6c7fd01?source=rss-22603242779b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f3ff6c7fd01</guid>
            <category><![CDATA[malicious-document]]></category>
            <category><![CDATA[vba-purging]]></category>
            <category><![CDATA[macro]]></category>
            <category><![CDATA[microsoft-office]]></category>
            <category><![CDATA[forensics]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 10:47:12 GMT</pubDate>
            <atom:updated>2020-11-27T10:47:12.919Z</atom:updated>
            <content:encoded><![CDATA[<h3>VBA Purging — How Effective Is It?</h3><p>Attackers have long been searching for ways to meddle with the day-to-day operations of an average computer user. It’s no wonder the <em>Microsoft Office </em>suite has been one of the key targets of adversaries to compromise endpoints. What better than to dispatch a seemingly-harmless office document to a rather naive user? It’s mayhem.</p><p>Owing to the popularity of <a href="https://attack.mitre.org/techniques/T1204/002/">Office documents</a> as a technique to carry out <em>execution</em>, I’ll be discussing an interesting strategy employed by attackers to further increase the chances of evasion. Although first brought to light by Didier Stevens in February 2020 — the technique <strong>VBA Purging </strong>is slowly gaining popularity. We can, however, classify several malicious documents to have already employed the technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZhxHj4wUT3XnOKNPcwOEg.png" /></figure><p>Before we dig into the technique itself — let’s take a closer look at the fundamentals of VBA and the binary file formats powering macros today.</p><h3>A Quick Intro to VBA and Document File Formats</h3><p>VBA, an abbreviation for <strong><em>Visual Basic Applications</em></strong>, is a programming language used to extend the functionality of Microsoft Office applications. Through the power of a small piece of (macro) code, you could do so much for automation, repetition, and general administration tasks. Owing to the powerful nature of the language, it didn’t take long before malicious macro codes were mainstreamed and now account for majority of the malicious attachments sent via emails.</p><p>Before Microsoft Office 2007, the <strong><em>Compound File Binary Format (CFBF) </em></strong>was the default file format for majority of its applications — otherwise known as the <strong><em>Object Linking and Embedding (OLE) </em></strong>file format. Today, Office applications use the Office Open XML (OOXML) file format wherein the objects within the document are structured in an XML-like format and then zipped. However, the embedded macros or VBA project file is still formatted using the CFBF file format — and this is precisely why we’ll be studying it next.</p><p>We’ll be referencing the file formats with the term — compound file. Why is that? Just as file systems offer structured storage for a variety of application-specific data streams, the compound file offers a structured solution to store different types of objects in a single file.</p><p>Two types of objects are available within a compound file — storage and stream objects. You can think of storage objects as directories composing of multiple files, whereas files are the stream objects. To avoid recreation of the file upon addition of a new object, the hierarchy-like structure also maintains an internal structure to identify the next location to storage objects in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*HtoF0kkkYuCW66M8uMGccg.png" /><figcaption>Figure 1 — A compound file hierarchy with storage and stream objects. Courtesy: <a href="https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-cfb/50708a61-81d9-49c8-ab9c-43c98a795242">Microsoft</a></figcaption></figure><p>Just as you see “Storage 1” under the Root Storage, we have a “VBA” storage in macro-enabled documents (often under the “Macro” storage as well). Here’s the usual representation of a VBA project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*FsPV4DDxwJoMF_yDB9paRg.png" /><figcaption>Figure 2 — VBA storage hierarchy following the compound file format. Courtesy: <a href="https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-ovba/005bffd7-cd96-4f25-b75f-54433a646b88">Microsoft</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*pBNbFOaXwVtjDqeZu1RIIw.png" /><figcaption>Figure 3 — Module Streams of a VBA project. Courtesy: <a href="https://blog.nviso.eu/2020/02/25/evidence-of-vba-purging-found-in-malicious-documents/">Nviso</a></figcaption></figure><p>Our ‘Module Streams’ are what contain the actual code (or modules which host routines or data) that powers the embedded macros. Now these module streams are further broken down into two parts — <strong><em>PerformanceCache (P-Code) and CompressedSourceCode. </em></strong>The PerformanceCache contains the source code in its compiled form, whereas the CompressedSourceCode section contains the actual VBA source code but in a compressed form. Now — you can make some sense of it. When a new VBA macro is added to a document, it’s the responsibility of the VBA engine to store copies of the compiled code to the PerformanceCache section. The two sections are further separated by an offset defined in the <strong><em>dir </em></strong>stream called by <strong><em>MODULEOFFSET.</em></strong></p><p>Though you should also note that the compiled code in PerformanceCache is version and architecture dependent. If the compiled VBA code’s version or architecture don’t match, the compiled code serves no purpose. It’s again handed off to the VBA engine to decompress (using Microsoft’s own compression algorithm) the CompressedSourceCode section, compile it on the run-time, and run the code.</p><p>Similarly, once you’ve executed the P-code from a macro-enabled document, a tokenized form of it is stored in the document’s VBA storage under __SRP__ streams (followed by a number). These streams can help execute the code much faster. However, these streams and the code contained within them is also Office-version specific and previously discussed techniques are run if the versions don’t match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*GzmIY_PjwlYwLIg3am0pmQ.png" /><figcaption>Figure 4 — A sample document with macros and the VBA structure where ‘ThisDocument’ is the Module Stream</figcaption></figure><h3>Is it Stomped or Purged?</h3><p>VBA stomping or purging revolve around the aforementioned sections in the module streams. VBA Stomping came to light in 2018 when security researchers from Walmart explored the possibility of removing the CompressedSourceCode section of the module stream without impacting the execution of the macro but thwarting defenses set to detect strings with great efficiency. Though this is great in theory, recall the fact that if the source code for the macro is removed, the Office application will immediately fall back to the compiled code. What happens if the version and architecture don’t match? Nothing!</p><p>This is where things take an awry turn and you need some bits of recon on the target host to make this a success. If you’re certain about the version of Office on the system, Stomping the VBA can be quite effective against detection on the malicious document.</p><p>VBA Purging, on the other hand, revolves around removing the PerformanceCache section from the module streams. To completely remove evidence of the P-Code section, the MODULEOFFSET between the two sections is set to <strong>0 </strong>by modifying the _VBA_PROJECT stream and removes all __SRP__ streams which also contain PerformanceCache data. Once you remove the compiled code, AV engines and Yara rules which rely on complete string matches are broken and the macros will be able to bypass them easily (due to the compressed nature of the source code which is still left intact).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*pgtesp-KghWCHJ-osjJlzw.png" /><figcaption>Figure 5 — Purged and non-purged documents and the differences between them</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*y2gRh5_ylvo0-o_6d2TkoA.png" /><figcaption>Figure 6 — Using the -i parameter in oledump to visualize PerformanceCache and CompressedSourceCode sections in Module1 on the non-purged document</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*cwkow2OoBueodGMMvZsudQ.png" /><figcaption>Figure 7 — Same view for the purged document shows no PerformanceCache section</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*Fs9draXk_6jz3oqFpFesFg.png" /><figcaption>Figure 6 — Strings in the non-purged document</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*ohzi4N-eWkqNRHHdeZXH1w.png" /><figcaption>Figure 7 — Strings from the Purged document which have the same functionality yet are compressed</figcaption></figure><h3>What’s The Next Step for Defense?</h3><p>VBA purging can make static analysis a tad-bit hard and leave IDS or Yara rules useless since the static strings they rely on are available in the P-code section. For example, the shell creation of object creation function <em>CreateObject </em>won’t be available in the CompressedSourceCode section as a single string but would most probably be broken down.</p><p>There are still opportunities to hunt and detect VBA purging actively evading defenses. <a href="https://www.fireeye.com/blog/threat-research/2020/11/purgalicious-vba-macro-obfuscation-with-vba-purging.html">FireEye </a>has done an excellent job at covering those detections by putting their own Red Team’s developed purging tool called — <a href="https://github.com/fireeye/OfficePurge">OfficePurge</a>.</p><p>One of those techniques rely on the minimum size of the _VBA_PROJECT stream — 7 bytes. Though this is based on the fact that the length of the PerformanceCache section should always be seven bytes less than the size of the _VBA_PROJECT stream. You can view the Yara rule at <a href="https://www.fireeye.com/blog/threat-research/2020/11/purgalicious-vba-macro-obfuscation-with-vba-purging.html">FireEye’s </a>own coverage of the technique. Though it should be known that the techniques to detect VBA purging also have a chance of including benign documents which have their PerformanceCache sections removed but aren’t technically malicious.</p><p>In order to prevent macros from execution, you can employ these strategies:</p><ul><li>Train employees to pick apart malicious from harmless documents</li><li>Disable macros if not necessary</li><li>Use antimalware products to detect malicious documents containing malicious macros or VBA code</li><li>If macros can’t be disabled, make sure only signed macros are run or they are in trusted files</li><li>Block macros in Office to run from the Internet (often used for template injections). Excellent coverage by <a href="https://www.microsoft.com/security/blog/2016/03/22/new-feature-in-office-2016-can-block-macros-and-help-prevent-infection/?source=mmpc">Microsoft</a> to utilize Group Policies to enforce the change across the environment</li></ul><h3>Conclusion</h3><p>Office documents and their popularity amongst masses will keep attracting malicious users to try and evade defenses using new techniques. VBA purging is one such technique which breaks traditional defenses or weakens them. It is imperative to instruct end-users to ensure the authenticity of a document before opening it and to stay wary of documents which appear anomalous from the get-go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f3ff6c7fd01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital Forensics Write-up — Web Server Case by Ali Hadi]]></title>
            <link>https://syedhasan010.medium.com/digital-forensics-write-up-web-server-case-by-ali-hadi-340f6d919f9c?source=rss-22603242779b------2</link>
            <guid isPermaLink="false">https://medium.com/p/340f6d919f9c</guid>
            <category><![CDATA[dfir]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[forensics]]></category>
            <category><![CDATA[writeup]]></category>
            <dc:creator><![CDATA[Syed Hasan]]></dc:creator>
            <pubDate>Mon, 26 Oct 2020 08:48:07 GMT</pubDate>
            <atom:updated>2020-10-26T08:48:07.471Z</atom:updated>
            <content:encoded><![CDATA[<h3>Digital Forensics Write-up — Web Server Case by Ali Hadi</h3><p>The article is a write-up for challenge number one — the Web Server Case — by Ali Hadi on his blog, ‘<a href="https://www.ashemery.com/dfir.html"><em>ashemery.com</em></a>’. The premise is set to:</p><blockquote>A company’s web server has been breached through their website.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAwvULiYHWbrE8IT_qTEyA.png" /></figure><h3>Questions</h3><p>For this investigation, we’re asked to answer the following questions:</p><ol><li>What type of attacks has been performed on the box?</li><li>How many users has the attacker(s) added to the box, and how were they added?</li><li>What leftovers (files, tools, info, etc) did the attacker(s) leave behind? (assume our team arrived in time and the attacker(s) couldn’t clean and cover their tracks)</li><li>What software has been installed on the box, and were they installed by the attacker(s) or not?</li><li>Using memory forensics, can you identify the type of shell code used?</li><li>What is the timeline analysis for all events that happened on the box?</li><li>What is your hypothesis for the case, and what is your approach in solving it?</li></ol><h3>Tool-set</h3><p>For the purpose of this write-up, I’m going to utilize the following set of tools:</p><ol><li>AccessData FTK Imager</li><li>Autopsy (I prefer this for analysis)</li><li>Registry Explorer by Eric Zimmerman</li><li>Volatility</li><li><a href="https://github.com/jschicht/Mft2Csv">Mft2Csv</a></li><li><a href="https://github.com/jschicht/LogFileParser">LogFileParser</a></li></ol><h3>Let’s Seek Some Solutions!</h3><p>Focusing on the premise again — we know the box served as a <em>server</em>. Let’s analyze the system image in <strong>FTK Imager</strong> to see the filesystem and identify whether it’s a Windows or Linux-based machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*WehKOlwd2Bf7akvlX7if-w.png" /><figcaption>NTFS formatted filesystem with Windows</figcaption></figure><p>Observe the ‘xampp’ folder at the bottom — this indicates the installation of XAMPP, a web-server solution pack, likely based on the <em>LAMP </em>stack. Let’s dig into the server’s folder and hunt for Apache logs.</p><p>Generally, on Windows-based Apache installations, you can find the location of the <em>access or error </em>logs at: [the location of the ‘xampp’ folder might differ on your web-server]</p><pre>C:\xampp\apache\logs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*2tpjc2c7sUfP2XYuTTfZFQ.png" /><figcaption>Apache Logs</figcaption></figure><p>Let’s export these to the forensics workstation and see if we can dig into them for more insight into the attack. Exploring the <em>install.log </em>file, we can figure out the following information from it:</p><pre>Installing Apache HTTP Server 2.x with</pre><pre>DomainName = example.com<br>ServerName = <a href="http://www.example.com/">www.example.com</a><br>ServerAdmin = admin@example.com<br>ServerPort = 80<br>ServerSslPort = 443<br>ServerRoot = c:/Apache24</pre><p>The web server is running on standard HTTP/HTTPS ports of <strong>80/443</strong>.</p><p>The holy grail here is the <strong>access.log </strong>file. First thing’s first, let’s get a headcount of the total IP addresses which tried communicating with the server:</p><pre>cat access.log | awk &#39;{print $1}&#39; | sort | uniq -c | sort -nr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xONU5uK47dW676gMGsImcA.png" /><figcaption>IP addresses communicating with the server</figcaption></figure><p>In this dataset, the general outlier, <strong><em>192.168.56.102</em></strong>, appears to be the most in touch with the server. Let’s grep the logs containing this IP address from the log file into a separate file to reduce the noise: (I’ve also separately analyzed logs from other IP addresses but they appear to be harmless. During an investigation, you might want to poke every bit of evidence for intelligible leads.)</p><pre> grep &quot;192.168.56.102&quot; access.log &gt;&gt; 192-168-56-102-access_log.log</pre><p>Next, let’s check the user-agent field in these logs to see if we can get something useful:</p><pre>cat 192-168-56-102-access_log.log | awk -F\&quot; {print $6} | sort | uniq -c | sort -nr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ek-4PL_bJ00M0-o-bNiWnw.png" /><figcaption>Usage of SQLMAP</figcaption></figure><p>Judging my the top user-agent, it’s clear that the attackers used <strong>sqlmap</strong>, an automated tool to detect SQL injection in websites. Using that, we can map the <strong>Initial Access </strong>tactic to:</p><blockquote>Exploit Public-Facing Application (<a href="https://attack.mitre.org/techniques/T1190/">T1190</a>)</blockquote><p>Since the rest of the user-agents seem pretty generic, I’ll pivot to the logs with the sqlmap useragent. After separating them from the main log file, we have an even smaller dataset to work on. By exploring the URI field in these logs, we can clearly see the injection attempts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlHWW8Hw3S2lvigb2sxxBg.png" /><figcaption>SQL Injection attempts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQDwItCyj4Ok62mJ8i698g.png" /><figcaption>A file being sent over exploiting SQL injection vulnerabilities — /tmpukudk.php</figcaption></figure><p>If we run a scan on the access logs against ‘tmp’, we can retrieve more such files being referenced in the logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9m9E91xoQfXt9M8P9qZ9DQ.png" /><figcaption>Four tmp files being created and then deleted via the command prompt</figcaption></figure><p>However, these files appear to have been deleted and you can verify that by checking the forensics image provided. Well, we’ll explore recovering them later.</p><p>Apart from that, the access logs also show attempts to exploit XSS vulnerabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-qq6vPH-RIKt9JTul6m4w.png" /><figcaption>XSS Vulnerabilities</figcaption></figure><p>and unrestricted file upload vulnerabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*tKF99vKhuihjHQyNQrUfUA.png" /><figcaption>Unrestricted file upload vulnerabilities shows PHP based web shells</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*2B8JuEjuutubHUNgWNFz2g.png" /><figcaption>Commands executed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swQ5MUgov9xjc9smC5Fd9A.png" /><figcaption>Proof the commands were executed by the attacker</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Avc7ZNEaM3W5H2LRX9_CsQ.png" /><figcaption>Local File Inclusion</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3JLYqBjcO7ug-oz_mL60A.png" /><figcaption>‘exec’ endpoint — POST requests show the attacker must’ve sent some input here</figcaption></figure><p>Sadly, we can’t see the data sent with POST requests in the access logs. We’ll get back to exploring this again — hopefully with the help of the memory sample.</p><p>Lastly, we see the attacker appears to have launched a command prompt window using the command <strong>cmd </strong>from the web-shell:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UlG1OzDh6ZsSzUzGk1pC-w.png" /><figcaption>“cmd” spawned using the webshell</figcaption></figure><p>For better time-lining — let’s note the timestamp as well: <strong>03/Sep/2015:00:21:37 -0700.</strong></p><p>The windows event logging service was running at the bare minimum and has no logs. Therefore, it’s time to pivot to a different evidence source — most likely the memory image acquired. We’ll come back to the forensic image later.</p><p>Using Volatility, let’s retrieve more information about the memory image and the profile required using:</p><pre>volatility -f memdump.mem imageinfo<br>...<br> Suggested Profile(s) : VistaSP1x86, Win2008SP1x86, Win2008SP2x86<br> Number of Processors : 1<br> Image Type (Service Pack) : 1<br> Image date and time : 2015–09–03 10:04:05 UTC+0000<br> Image local date and time : 2015–09–03 03:04:05 -0700<br>...</pre><p>Using the VistaSP1x86 profile, let’s start off with the processes:</p><pre>volatility -f memdump.mem --profile=VistaSP1x86 pslist</pre><pre>volatility -f memdump.mem --profile=VistaSP1x86 psscan</pre><pre>volatility -f memdump.mem --profile=VistaSP1x86 pstree</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*0rBaEhLZ2MSFDFpb8zjwyg.png" /><figcaption>‘cmd.exe’ processes under explorer.exe</figcaption></figure><p>Based on the output of the process scans, no malicious binary appears to be running on the system right now. Since we have two command prompt windows open [<strong>PID: 612, 1972</strong>], let’s explore them a bit more.</p><pre>. 0x83e7b7f8:cmd.exe 612 816 1 72 2015–08–23 10:30:44 UTC+0000</pre><pre>. 0x84259100:cmd.exe 1972 816 1 19 2015–09–02 09:28:30 UTC+0000</pre><p>Though you should note the dates for execution of the two consoles. The one on 23–08–2015 isn’t relevant to our case as the actual execution under the webshell was carried out on 03/Sep/2015:00:21:37 -0700 [UTC and GMT times are different here]. Let’s exclude the console window with the PID 612 from our analysis.</p><p>Let’s run scans for consoles, command prompt arguments, or command history:</p><pre>volatility -f memdump.mem --profile=VistaSP1x86 cmdline</pre><pre>volatility -f memdump.mem --profile=VistaSP1x86 consoles</pre><pre>volatility -f memdump.mem --profile=VistaSP1x86 cmdscan</pre><p>Here, ‘cmdline’ simply returns the command-line arguments for each process. ‘consoles’ and ‘cmdscan’ both return command history by scanning different structures. Once you run this, you’ll come across several commands the attacker tried to execute. If you’d like an output-less view of the commands, run “cmdscan”.</p><pre>CommandProcess: csrss.exe Pid: 524<br>CommandHistory: 0x5a24708 Application: cmd.exe Flags: Allocated, Reset<br>CommandCount: 17 LastAdded: 16 LastDisplayed: 16<br>FirstCommand: 0 CommandCountMax: 50<br>ProcessHandle: 0x2d8<br>Cmd #0 @ 0xe907c8: ipconfig<br>Cmd #1 @ 0xe91af8: cls<br>Cmd #2 @ 0xe91db0: ipconfig<br>Cmd #3 @ 0x5a34bd0: net user user1 user1 /add<br>Cmd #4 @ 0x5a34eb8: net user user1 root@psut /add<br>Cmd #5 @ 0x5a34c10: net user user1 Root@psut /add<br>Cmd #6 @ 0x5a24800: cls<br>Cmd #7 @ 0x5a34c58: net /?<br>Cmd #8 @ 0x5a34d88: net localgroup /?<br>Cmd #9 @ 0x5a34f48: net localgroup “Remote Desktop Users” user1 /add<br>Cmd #10 @ 0x5a34c70: net /?<br>Cmd #11 @ 0xe911b0: netsh /?<br>Cmd #12 @ 0xe907e8: netsh firewall /?<br>Cmd #13 @ 0xe91218: netsh firewall set service type = remotedesktop /?<br>Cmd #14 @ 0xe91288: netsh firewall set service type = remotedesktop enable<br>Cmd #15 @ 0xe91300: netsh firewall set service type=remotedesktop mode=enable<br>Cmd #16 @ 0xe91380: netsh firewall set service type=remotedesktop mode=enable scope=subnet</pre><p>A general overview of the commands is as follows:</p><ul><li>The attacker ran IP configuration commands to identify the source IP of the box</li><li>The attacker added the user <strong>user1 </strong>to the Remtoe Desktop Users group using net</li><li>The attacker configured the Firewall to allow Remote Desktop from within the same subnet</li></ul><p>With this, we validated the following subset of TTPs and their relevant tactics</p><blockquote>Command and Scripting Interpreter (<a href="https://attack.mitre.org/techniques/T1059/">T1059</a>) — Execution</blockquote><blockquote>Account Creation (<a href="https://attack.mitre.org/techniques/T1136/">T1136</a>) — Persistence</blockquote><p>I’ve also extracted the registry hives from:</p><ul><li>%SystemRoot%\System32\config</li><li>{Username}\Documents\NTUser.dat</li></ul><p>From the SAM hive, we can recover the list of users on the system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*iXCVjsorsDvQhvpeXmYQhw.png" /><figcaption>Shows two users added at the same time — ‘hacker and user1&#39; — we have proof of the user ‘user1’</figcaption></figure><p>We didn’t see the <strong>hacker </strong>user being added to the system using the web-shell. Well, what else could’ve caused this to happen? Remember the <strong>exec </strong>endpoint exploitation we left behind. It could be a good pointer to pivot from here. But we didn’t have the POST data. How else can we explore that? Let’s jump back to our memory sample and see if we can find the process related to the Apache server.</p><pre>httpd.exe   2796   2768     1     92 2015-08-23 10:32:21 UTC+0000<br>httpd.exe   2880   2796    155    483 2015-08-23 10:32:26 UTC+0000</pre><p>So, the PIDs 2796 and 2880 belong to httpd.exe, the binary serving up the Apache server. Let’s dump their memory space by using Volatility again:</p><pre>volatility -f mempdump.mem --profile=VistaSP1x86 memdump -p 2796 --dump-dir E:\<br>volatility -f mempdump.mem --profile=VistaSP1x86 memdump -p 2880 --dump-dir E:\</pre><p>Running a simple strings search on these dumps, I’m going to save the results. Then, let’s see if the attacker tried to run the ‘net’ command via the command injection vulnerability to add the user ‘hacker’ to the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*ttCpLHKOrnGTe-OFG7U0tw.png" /><figcaption>Same commands being executed for the second account — hacker</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*GfiqvCf1PzY2ljqDMK23vw.png" /><figcaption>Output from the second process’ dump</figcaption></figure><p>If we review one of the commands, it has an IP field followed by an “%26%26”. If you run the URL Decode Cyber-chef recipe on it, you can retrieve the actual value — which is ‘&amp;&amp;’. This means, the attacker tried to send these two values and since the input wasn’t filtered — both the commands executed. One thing’s for sure — all command injections will then follow the same format. The actual IP followed by the ‘&amp;&amp;’ and then the attacker’s command. We can use this information to look for more such commands being run on the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iwwythtv75pJwQNbXE3ZSg.png" /><figcaption>Command Injection</figcaption></figure><p>Though we can safely conclude that the command injection exploitation was only used to perform reconnaissance on the system and administrator. Let’s pivot our focus from the ‘exec’ endpoint to the more important — web shells written to disk by SQL-map during the SQLi exploitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1Vnk45O9cx0UOhnO97Lug.png" /><figcaption>Exploitation of SQLi using SQLMAP</figcaption></figure><p>Two of these ‘tmp’ files appear to be droppers. After execution, we see GET requests to the ‘tmpukudk’ file, and after that, a completely new shell file ‘tmpbiwuc.php’. The actual shell commands are executed by tmpbiwuc file. After that, both the files are removed from the system.</p><p>Even parsing the MFT couldn’t help me trace these files back. Though I didn’t stop there. I further parsed the <strong>NTFS Journal LogFile </strong>for more information on the droppers. The LogFile captures changes to all entities in a volume. These changes — allocation, rename, deletions or similar actions — are recorded in the shape of transactions. These transactions are actually used to backtrack and resolve problems in the volume (if they’re not committed). Using LogFileParser by jschicht, I parsed the LogFile (retrieved from the forensics image). Though the timestamps don’t appear to be that clear, we can still find allocation and deletion for our droppers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4daAGwJZbqeNAiFUMIxqjQ.png" /><figcaption>tmpukdk.php — the dropper</figcaption></figure><h3>Let’s Summarize it All</h3><p><strong>Question Number 1:</strong></p><p>Several attacks were performed on the server in question to exploit vulnerabilities. Some of these vulnerabilities are listed below:</p><ol><li>SQL Injection</li><li>Command Injection</li><li>Local File Inclusion</li><li>Cross-site Scripting</li><li>Unrestricted file uploads</li><li>Web-shells</li><li>Brute-forcing (haven’t discussed it but you can review access logs for it)</li></ol><p><strong>Question Number 2:</strong></p><p>Two — hacker and user1</p><p><strong>Question Number 3:</strong></p><p>From the MFT entries we parsed before (using Mft2Csv), we can identify the following files being stored to disk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJqmaPtsWGZUJnS9XM02CQ.png" /><figcaption>Output extracted from Mft2Csv</figcaption></figure><p><strong>Question Number 4:</strong></p><p>No software was <strong>installed </strong>on the system by the attacker. We can review Setup.evtx (from the Winevt log folder) for evidence. Normal installations include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*f8DI8r0z77iAsrFzDiDJaw.png" /></figure><p><strong>Question Number 5:</strong></p><p>We’ve dumped memory from the httpd process to identify signs of shellcode. The answer is summarized in our discussion above.</p><p><strong>Question Number 6:</strong></p><p>Here’s the timeline I’ve gathered from this investigation:</p><ul><li>02/09/2015 07:10:41 — Requests from the IP 192.168.56.102 start coming in from the browser IceWeasel (typically installed on Kali Linux as well)</li><li>02/09/2015 09:04:35 — ‘exec’ endpoint exploited by means of command injection attacks, followed by net commands to create the users ‘hacker’ and ‘user1’, then addition to the Remote Desktop Users group</li><li>02/09/2015 09:31:16 — LFI vulnerability being exploited to access administrator files, PHP configurations, and logs</li><li>02/09/2015 10:49 — SQLi attacks</li><li>02/09/2015 11:15:40 — SQLmap being used to automated SQLi attacks</li><li>02/09/2015 11:25 — Droppers ‘tmpukudk’ and ‘tmpbiwuc’ being dropped and then drop webshells on the endpoint</li><li>03/09/2015 07:14:41 — Creation of webshells.zip on the system which includes more command shells inside — including C99</li><li>03/09/2015 07:21:40 — Access and run commands via the webshell</li></ul><p><strong>Question Number 7:</strong></p><p>DVWA is an intentionally vulnerable application used by researchers to practice on penetration testing capabilities. However, in this scenario, the application was hosted and exploited. We started off from the log sources, then pivoted to host logs, registries, and finally the memory for manifestation of attacks. The attacker used several exploits at the start to compromise the endpoint, gain persistence via creation of accounts, and dropping the webshells. The attackers could’ve achieved much more by utilizing RDP but didn’t do so.</p><h3>Conclusion</h3><p>The ‘Web Server Case’ was definitely interesting to learn and revise analysis strategies you’d normally equip during an investigation. Download the files, review a write-up if you will, or get started on your own. If you do stumble, it’s perfectly fine to seek help and remember the technique for future use!</p><p>Good luck and happy hunting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=340f6d919f9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>