<?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 thsecdev on Medium]]></title>
        <description><![CDATA[Stories by thsecdev on Medium]]></description>
        <link>https://medium.com/@thsecdev?source=rss-c994d3e17cd2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C6_8xLYa38OOPjS--vSbJA.jpeg</url>
            <title>Stories by thsecdev on Medium</title>
            <link>https://medium.com/@thsecdev?source=rss-c994d3e17cd2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:08:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thsecdev/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[Toward Secure Code: How to secure File Upload on ExpressJs using Multer]]></title>
            <link>https://medium.com/@thsecdev/toward-secure-code-how-to-secure-file-upload-on-expressjs-using-multer-6598b1715bb4?source=rss-c994d3e17cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6598b1715bb4</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[owasp-top-10]]></category>
            <category><![CDATA[unrestricted-file-upload]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[multer]]></category>
            <dc:creator><![CDATA[thsecdev]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 17:21:33 GMT</pubDate>
            <atom:updated>2025-01-08T02:05:18.266Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome again to installment of Toward Secure Code, where we look into common web application vulnerabilities and explore how to secure our applications against them. Today, we’ll focus one of the common features in web application , <strong>File Uploads.</strong> While allowing users to upload files might be a good features or an important piece in your application, also it creates a potential security risks if not handled correctly, improperly managed file uploads can lead to vulnerabilities such as <strong>File Injection</strong>, <strong>Remote Code Execution (RCE)</strong>, and <strong>Denial of Service (DoS)</strong> attacks. e.g., File Injection occurs when an application improperly handles file paths or user-supplied file names, allowing attackers to manipulate file operations such as reading, writing, or executing unintended files on the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*JM9gIi7wxr_E_osV_LH5hQ.png" /></figure><p>Today, we’ll try to explore secure coding practices to mitigate File injection (File Upload) within an Express.js application using <strong>Multer</strong>, a popular middleware for handling multipart/form-data. We&#39;ll guide you through configuring Multer securely, validating uploads, and setting up your server to mitigate common threats.</p><h3>Understanding File Upload Vulnerabilities</h3><blockquote>A file upload vulnerability occurs when a web application allows users to upload files without properly validating or sanitizing the input. Attackers can exploit this by uploading malicious files, such as scripts or executables, which the server might execute or process in unintended ways.</blockquote><h4>Common Types of File Upload Attacks</h4><ul><li><strong>Web Shell Uploads</strong>: Attackers upload scripts (e.g., PHP, ASP, JSP) that allow them to execute commands on the server remotely.</li><li><strong>Malware Distribution</strong>: Uploading files that contain malware to infect users who download them.</li><li><strong>Cross-Site Scripting (XSS)</strong>: Uploading files with embedded scripts that execute in the context of other users’ browsers.</li><li><strong>Denial of Service (DoS)</strong>: Uploading extremely large files to exhaust server resources.</li></ul><p>To mitigate these risks, it’s essential to implement robust validation, sanitization, and storage strategies for uploaded files.</p><h3>Configuring Multer for Secure File Uploads</h3><p>Multer is a middleware for handling multipart/form-data, primarily used for uploading files. To ensure file uploads are secure, we&#39;ll configure Multer with the following considerations:</p><ol><li><strong>Storage Configuration</strong>: Define where and how files are stored.</li><li><strong>File Type Validation</strong>: Restrict uploads to specific file types.</li><li><strong>File Size Limitation</strong>: Prevent excessively large file uploads.</li></ol><h3>Storage Configuration</h3><p>Multer have has two options of storage:</p><ul><li>diskStorage:Stores uploaded files directly on the server’s filesystem.</li><li>memoryStorage: Stores uploaded files in memory as Buffer objects.</li></ul><p>We will be using memoryStorage , because it offers security advantages by keeping uploaded files in memory and turn them into buffer like <strong>Path Traversal</strong> or <strong>Direct File Execution</strong>, thus we can implement validation and controlled processing before persisting them.</p><pre>// Define storage strategy using memory storage<br>const storage = multer.memoryStorage();</pre><p>⚠️⚠️ But we should put in consideration some performance issues , if a user upload a large file we would quickly consume server RAM or if we face high upload volumes, and as loaded files are stored in RAM, which could potentially be accessed by other parts of the application or in the event of a memory leak. for this we should implement mitigations such as <strong>Least Privilege, File Size Limits …</strong></p><figure><img alt="meme of server burning" src="https://cdn-images-1.medium.com/max/480/1*dw0HoLKLRd2IoVqTh5dBog.gif" /></figure><h3>Limits Configuration</h3><p>The limits attribute in Multer’s configuration, used for specifying the size limits and other constraints on the incoming data (e.g., fieldSize,fileSize..)</p><pre>// Define maximum file size (2 MB)<br>const limits = {<br>    fileSize: 2 * 1024 * 1024 // 2 MB<br>    files: 1 // Allow only one file per upload<br>    // you can explore other attributes in Multer documentation<br>};</pre><p>This file-size cap helps reduce <strong>DoS</strong> attacks (where a malicious user tries to upload extremely large files to overwhelm disk or memory) and controlling resource usage ensuring server remains responsive.</p><h3><strong>File Filter Configuration</strong></h3><p>fileFilter is a function used to control the <strong>acceptance</strong> of files based on custom criteria. It acts as a gatekeeper, allowing you to <strong>accept</strong> or <strong>reject</strong> files before they&#39;re processed further. The purpose of this function us to validate incoming files and specific <strong>criteria</strong> such as file type, size, or any other custom validation logic you deem necessary.</p><pre>// Define allowed MIME types and extensions<br>export const allowedMimeTypes = [&#39;image/jpeg&#39;, &#39;image/png&#39;, &#39;image/gif&#39;]; <br>const allowedExtensions = [&#39;.jpeg&#39;, &#39;.jpg&#39;, &#39;.png&#39;, &#39;.gif&#39;];<br><br>// Define filter strategy<br>const fileFilter = (_, file, cb) =&gt; {<br>    try {<br>      <br>        // Check MIME type<br>        if (!allowedMimeTypes.includes(file.mimetype)) {<br>            return cb(new Error(&#39;Invalid MIME type!&#39;), false);<br>        }<br><br>        // Check file extension<br>        const ext = path.extname(file.originalname).toLowerCase();<br>        if (!allowedExtensions.includes(ext)) {<br>            return cb(new Error(&#39;Invalid file extension!&#39;), false);<br>        }<br>        return cb(null, true);<br><br>    } catch (error) {<br>        return cb(new Error(&#39;Could not process file type!&#39;), false);<br>    }<br>};</pre><p>In our case, we want users only to upload legitimated images, for this purpose we used <strong>MIME Type Validation</strong> and <strong>File Extension Validation, </strong>this will try to prevents files with disallowed MIME types (e.g., executable scripts) from being uploaded and guards against files that might have deceptive extensions aiming to bypass MIME type checks. But additional validation is needed because fileFilter only inspects metadata.</p><h3>Additional Validation Enhancements</h3><h4>Buffer-Based File Type Validation</h4><p>Some attackers tempt to manipulate the Content-Type header or file extensions to disguise malicious files (e.g., uploading a .jpg file containing executable code) and uploading an arbitrary file types that can lead to security vulnerabilities, such as uploading scripts or executables that the server might execute inadvertently.</p><p>For this we will use file-type is a popular Node.js library designed to <strong>detect the file type</strong> of a given buffer or stream by examining the <strong>magic numbers</strong> (signature bytes) at the beginning of the file (e.g., jpeg images Starts with FFD8FF). This method provides a reliable way to determine a file&#39;s true type, regardless of its file extension or declared MIME type.</p><pre> // Validate the actual file type using buffer<br>    const type = await fileTypeFromBuffer(req.file.buffer);<br>    if (!type || !allowedMimeTypes.includes(type.mime)) {<br>        console.log(`Detected file type: ${type.mime}`);<br>        console.log(&#39;File type not allowed based on buffer analysis.&#39;);<br>        return res.status(400).send(&#39;Invalid file type.&#39;);<br>    }</pre><p>By verifying the file’s content against known signatures, you ensure that the file is genuinely of the expected type, thwarting attempts to upload malicious files disguised with benign extensions. Combining fileFilter (which checks MIME types and extensions) with file-type&#39;s buffer inspection provides multiple layers of validation, significantly reducing the risk of successful attack.</p><h4>Re-encode Uploaded Files</h4><p>Attackers can craft files to be valid in multiple formats simultaneously (e.g., both JPEG and PDF), to bypass file upload restrictions while including malicious code. The file appears legitimate to validation checks but can execute harmful code when processed. This technique called <strong>Polyglot.</strong></p><p>In the specific case of a JPEG web shell, here is how it works: A JPEG file format allows arbitrary data after the end marker (FF D9 in hexadecimal). An attacker can append PHP code after this marker while maintaining a valid JPEG structure. When this file is processed as an image, it displays normally. However, if executed as PHP, the malicious code runs.The primary security concerns with polyglot files includes Remote Code Execution,Bypass of Security Controls and Server Compromise.</p><pre>// Remove all metadata including comments<br>    const processedBuffer = await sharp(req.file.buffer)<br>        .withMetadata(false)<br>        .toFormat(&#39;jpeg&#39;, { quality: 80 })<br>        .toBuffer();</pre><p>In case of uploaded file are images we can use Sharp Node.js image processing library that allows you to manipulate and transform images with ease. We have to strip metadata for both privacy and security risks concerns , by eliminating embedded metadata data that could reveal personal or system information (e.g.,camera information, geolocation) and removing potential vectors for attacks that target metadata processing vulnerabilities (e.g,. embedded harmful scripts).</p><h3>Additional Considerations</h3><ul><li><strong>Path Traversal Prevention</strong>: Guards against attackers attempting to place files outside the intended directories, which could lead to unauthorized access or execution (check my GitHub repo for implementation).</li><li><strong>Antivirus Scanning</strong>: Detects known malicious patterns or signatures within the file, including those that might exploit polyglot characteristics using scanning tools like <a href="https://www.clamav.net/">ClamAV</a> or cloud-based scanning services.</li><li><strong>Sanitize File Names: Pr</strong>events directory traversal attacks and ensures that file names do not contain malicious characters you can generate unique file names using UUIDs or other mechanism.</li><li><strong>Rate Limiting</strong>: Implementing rate limiting (e.g., with express-rate-limit) can restrict the number of uploads per IP address or user within a given timeframe.</li><li><strong>Regularly Update Dependencies: </strong>Keeps your application protected against known vulnerabilities in Multer or other dependencies.</li></ul><p>FULL IMPLEMENTATION ON <a href="https://github.com/Tharbouch/Toward-Secure-Code/tree/main/File%20Upload">MY GITHUB REPO</a>.</p><p>Stay tuned for more articles in the <strong>Toward Secure Code</strong> series, where we continue to explore practical security vulnerabilities and demonstrate how to fix them in modern web applications. <strong>Happy Coding Securely!</strong></p><h3><strong>Resources</strong></h3><ul><li><strong>File-type Documentation</strong>: <a href="https://github.com/sindresorhus/file-type">sindresorhus/file-type</a></li><li><strong>Multer Documentation</strong>: <a href="https://github.com/expressjs/multer">expressjs/multer</a></li><li><strong>Sharp Documentation</strong>: <a href="https://github.com/lovell/sharp">lovell/sharp</a></li><li><strong>ClamAV Integration</strong>: <a href="https://www.clamav.net/">ClamAV Official Site</a>.</li><li><strong>Express Rate Limit</strong>: <a href="https://github.com/nfriedly/express-rate-limit">express-rate-limit</a></li><li><strong>Helmet Documentation</strong>: <a href="https://github.com/helmetjs/helmet">helmetjs/helmet</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6598b1715bb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Toward Secure Code: Insecure Direct Object References (IDOR) in a Flask]]></title>
            <link>https://medium.com/@thsecdev/toward-secure-code-insecure-direct-object-references-idor-in-a-flask-c2bedb83b30d?source=rss-c994d3e17cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2bedb83b30d</guid>
            <category><![CDATA[idor-vulnerability]]></category>
            <category><![CDATA[web-application-security]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[idor]]></category>
            <dc:creator><![CDATA[thsecdev]]></dc:creator>
            <pubDate>Fri, 13 Dec 2024 01:23:26 GMT</pubDate>
            <atom:updated>2024-12-13T01:27:07.335Z</atom:updated>
            <content:encoded><![CDATA[<p>In our continued journey<em> Toward Secure Code </em>,we’re going to explore another common and dangerous web application vulnerability: Insecure Direct Object References (IDOR). This vulnerability arises when sensitive application resources (like user orders, profiles, or documents) are referenced by IDs that can be manipulated by an attacker. Without proper authorization checks, malicious users can access or modify data they don’t own.</p><p>In this article, we’ll examine a vulnerable Flask application that suffers from an IDOR vulnerability. We will then demonstrate how to exploit it and finally show how to fix it, ensuring that only authorized users can access and modify their own resources.</p><h3>Understanding IDOR</h3><blockquote>An IDOR vulnerability arises when an application exposes a reference to an internal object (like a file, database record, or key) based on user-supplied input without sufficient authorization checks. This allows attackers to manipulate these references to access data they’re not authorized to view, for example, if an application fetches order details by using a URL like /api/orders/123, an attacker may guess that changing this ID to /api/orders/124 might let them access another user’s order. If the application does not verify that the authenticated user is indeed the owner of order 124, it has an IDOR vulnerability. The term IDOR was popularized by its appearance in the OWASP 2007 Top Ten.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JQRsR1Ckm3zHjCnq" /></figure><p><strong>Key Points:</strong></p><ul><li>Relying solely on user-supplied resource identifiers (like document_id) can lead to unauthorized data exposure.</li><li>Proper authorization checks on the server side must ensure that the requesting user has permission to view or modify the referenced resource.</li><li>Client-side checks or relying on “security by obscurity” (like non-sequential IDs) are insufficient. The server must enforce authorization strictly.</li></ul><h3>The Vulnerable Code</h3><p>Below is a sneak-peak from a Flask server Lab that demonstrates the IDOR issue, you can find the rest of the code on my GitHub repository down below ,The Lab allows users to register, log in, create orders, and view or update orders by ID. However, the GET and PUT endpoints for a specific order fail to verify that the currently authenticated user owns that order.</p><pre># Vulnerable Endpoint: No ownership check for the order!<br>@app.route(&#39;/api/orders/&lt;int:order_id&gt;&#39;, methods=[&#39;GET&#39;, &#39;PUT&#39;])<br>@jwt_required()<br>def manage_order(order_id):<br>    # Vulnerability: We do not verify that the order belongs to the current user!<br>    order = Order.query.get(order_id)<br>    if not order:<br>        return jsonify({&#39;message&#39;: &#39;Order not found&#39;}), 404<br><br>    if request.method == &#39;GET&#39;:<br>        # Any authenticated user can view this order, regardless of who owns it<br>        order_data = {<br>            &#39;id&#39;: order.id,<br>            &#39;item_name&#39;: order.item_name,<br>            &#39;quantity&#39;: order.quantity,<br>            &#39;price&#39;: order.price,<br>            &#39;shipping_address&#39;: order.shipping_address,<br>            &#39;payment_status&#39;: order.payment_status,<br>            &#39;user_id&#39;: order.user_id<br>        }<br>        return jsonify(order_data), 200<br><br>    if request.method == &#39;PUT&#39;:<br>        # Any authenticated user can update this order simply by knowing the order_id<br>        data = request.get_json()<br>        order.shipping_address = data.get(&#39;shipping_address&#39;, order.shipping_address)<br>        order.payment_status = data.get(&#39;payment_status&#39;, order.payment_status)<br>        db.session.commit()<br>        return jsonify({&#39;message&#39;: &#39;Order updated successfully&#39;}), 200</pre><p><strong>The IDOR Vulnerability:</strong></p><ul><li>The /api/orders/&lt;int:order_id&gt; endpoint returns (GET) and updates (PUT) an order by order_id.</li><li>The code doesn’t check if the authenticated user (from get_jwt_identity()) is actually the owner of the order.</li><li>An attacker logged in as user, can simply change the order_id in the request URL to access or modify another user’s orders.</li></ul><h3>Exploiting the Vulnerability</h3><p>Let’s say we have two users: User1 and User2. User1 is logged in and receives an access_token. The user knows its own order IDs (e.g., 1, 2), but what if user2 guesses user1’s order ID (3, 4, etc.) and tries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyHt5xl9LBbOtsSiuH7VMA.png" /><figcaption>Log in as user2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pC4DJyFxuhW8j-LySCM_3w.png" /><figcaption>Accessing user1’s order using user2 account</figcaption></figure><p>If Order #1 belongs to user1, the server still returns it to user2 because it never checks ownership. Similarly, user1 could perform a PUT request to update user2’s order details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*me3waHeYZwNCJ3eFTN-2wQ.png" /><figcaption>updating order 1 details</figcaption></figure><p>If the server updates the order successfully, user2 has just modified user1’s order — classic IDOR exploitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-v3D9FhqTdp4pZWnqEydYA.png" /><figcaption>the server updates the order successfully.</figcaption></figure><h3>Securing the Implementation</h3><p>To prevent IDOR:</p><ol><li><strong>Check Ownership on the Server:</strong><br>Whenever accessing a resource that should be private, the server must verify that the authenticated user owns it. If current_user_id != order.user_id, deny access with a 403 Forbidden.</li><li><strong>Rely on Server-Side Authorization Controls:</strong><br>Don’t trust any client-supplied identifiers for sensitive actions. The server should enforce authorization logic internally.</li><li><strong>Use Consistent Authorization Logic:</strong><br>Apply the same verification to all operations (GET, PUT, DELETE) on protected resources.</li></ol><h3>The Secure Version</h3><p>Below is a secure implementation of the same endpoint. Before returning or updating an order, we verify that the order’s user_id matches the current_user_id. If not, we return 403 Forbidden.</p><pre># Secure Endpoint: View or update order details require checking <br># if the order belongs to current user<br>@app.route(&#39;/api/orders/&lt;int:order_id&gt;&#39;, methods=[&#39;GET&#39;, &#39;PUT&#39;])<br>@jwt_required()<br>def manage_order(order_id):<br>    <br>    current_user_id = get_jwt_identity()<br>    <br>    order = Order.query.get(order_id)<br>    if not order:<br>        return jsonify({&#39;message&#39;: &#39;Order not found&#39;}), 404<br><br>    if current_user_id != order.user_id:<br>        return jsonify({&#39;message&#39;: &#39;Unauthorized&#39;}),401<br>    <br>    if request.method == &#39;GET&#39;:<br>    # Only order owner can view this order <br>        order_data = {<br>            &#39;id&#39;: order.id,<br>            &#39;item_name&#39;: order.item_name,<br>            &#39;quantity&#39;: order.quantity,<br>            &#39;price&#39;: order.price,<br>            &#39;shipping_address&#39;: order.shipping_address,<br>            &#39;payment_status&#39;: order.payment_status,<br>            &#39;user_id&#39;: order.user_id<br>        }<br>        return jsonify(order_data), 200<br><br>    if request.method == &#39;PUT&#39;:<br>        # Only order owner can update this order<br>        data = request.get_json()<br>        order.shipping_address = data.get(&#39;shipping_address&#39;, order.shipping_address)<br>        order.payment_status = data.get(&#39;payment_status&#39;, order.payment_status)<br>        db.session.commit()<br>        return jsonify({&#39;message&#39;: &#39;Order updated successfully&#39;}), 200</pre><p><strong>What’s Improved?</strong></p><ul><li>Before returning or updating the order, we check if order.user_id != current_user_id.</li><li>If the user is not the owner, we return a 403 Forbidden response.</li><li>Attackers can no longer simply guess another order’s ID to access or modify it.</li></ul><h3>Additional Security Recommendations</h3><ul><li><strong>Use Role-Based Access Control (RBAC):</strong> For administrative endpoints that allow viewing all users’ orders, ensure you check the user’s role (e.g., admin) before granting access.</li><li><strong>Minimize Guessable Identifiers:</strong> While IDOR depends on missing authorization checks, using UUIDs or non-sequential IDs can slow down brute forcing. Still, authorization checks remain the crucial defense.</li><li><strong>Regular Auditing and Logging:</strong> Monitor logs for unusual patterns of resource access (e.g., many failed attempts to access nonexistent IDs).</li></ul><p>Insecure Direct Object References are a prevalent and often easy-to-exploit vulnerability. By performing server-side authorization checks to ensure that the authenticated user owns or is permitted to access the requested resource, you can effectively mitigate IDOR vulnerabilities.</p><p>Stay tuned for more articles in my <strong>“Toward Secure Code”</strong> series, where we will continue to explore practical security vulnerabilities and how to fix them in modern web applications.</p><h3>References</h3><p>source code link : <a href="https://github.com/Tharbouch/Toward-Secure-Code/tree/main/IDOR%20(Insecure%20Direct%20Object%20Reference)">https://github.com/Tharbouch/Toward-Secure-Code/tree/main/IDOR%20(Insecure%20Direct%20Object%20Reference)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2bedb83b30d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Toward Secure Code: Broken Access Control-How Weak JWT Implementations Enable Role Escalation in…]]></title>
            <link>https://medium.com/@thsecdev/toward-secure-code-broken-access-control-how-weak-jwt-implementations-enable-role-escalation-in-5f70fa8a28b9?source=rss-c994d3e17cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f70fa8a28b9</guid>
            <category><![CDATA[broken-access-control]]></category>
            <category><![CDATA[web-security]]></category>
            <dc:creator><![CDATA[thsecdev]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 14:24:26 GMT</pubDate>
            <atom:updated>2024-12-13T00:07:42.456Z</atom:updated>
            <content:encoded><![CDATA[<h3>Toward Secure Code: Broken Access Control-How Weak JWT Implementations Enable Role Escalation in Node.js</h3><p>Access control is a necessity in web application security, ensuring that only authorized users can perform certain actions and access specific resources based on their assigned roles. However, misconfiguration and weak implementations can lead to vulnerabilities, such as Broken Access Control, allowing attackers to escalate their privileges and gain unauthorized access.</p><p>In this article, which is the first in my new series <em>“Toward Secure Code”</em>, we’ll explore a common weakness in Role-Based Access Control (RBAC) implementations that use JSON Web Tokens (JWT) in Node.js applications. We’ll demonstrate how improper JWT handling can be exploited to bypass access controls and provide secure solutions to fortify your application against such threats.</p><p>before we start , we need to understand what’s Role-Based Access Control.</p><h4>Role-Based Access Control (RBAC)</h4><p>RBAC is one of access control , it’s a mechanism that restricts system access to authorized users based on their roles within an organization.<strong>RBAC</strong> is one of the most widely adopted models in web applications due to its simplicity and effectiveness in managing permissions based on user roles.</p><h3>Moving Forward: Exploring a Vulnerable RBAC Implementation in Node.js</h3><p>Now that we have a foundational understanding of Role-Based Access Control (RBAC), let’s delve into a practical example. We’ll explore a simple Node.js application that implements RBAC using JSON Web Tokens (JWT). However, this implementation contains critical vulnerabilities that can be exploited to bypass access controls and escalate user privileges.</p><h4>Example of weak RBAC Implementation</h4><p>Below is a sample Node.js application that demonstrates a basic RBAC system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*UcQ6jyRliAWZZLt2VlU1RA.png" /></figure><p>While it appears secure at first glance, let’s take a look on those middleware if we can find some flaws in JWT handling can lead to significant security breaches.</p><h4>Skipping JWT Signature Verification</h4><p><strong>JWT (JSON Web Token) authentication</strong> is a standard mechanism to securely transmit data between the client and server. However, the way JWTs are handled in this code introduces a severe vulnerability — <strong>signature verification is entirely skipped</strong>.</p><pre>function authenticateToken(req, res, next) {<br>    const authHeader = req.headers[&#39;authorization&#39;];<br>    const token = authHeader &amp;&amp; authHeader.split(&#39; &#39;)[1];<br>    if (!token) return res.sendStatus(401);<br><br>    try {<br>        const decoded = jwt.decode(token, { complete: true });<br>        if (!decoded) throw new Error(&#39;Invalid token&#39;);<br>        req.user = decoded.payload; // Trusting client-supplied data<br>        next();<br>    } catch (err) {<br>        console.error(&#39;JWT Decoding Failed:&#39;, err);<br>        res.sendStatus(403);<br>    }<br>}</pre><p>The issue lies in the use of jwt.decode(), which only decodes the token without verifying its signature. The signature is critical for ensuring the integrity and authenticity of the token. Here&#39;s why this is problematic:</p><ul><li><strong>Signature Bypass</strong>: Since the signature is not verified, attackers can forge or modify a token and send it to the server, which will trust the contents. For example, an attacker could change their role from “user” to “admin” and gain unauthorized access to administrative features.</li><li><strong>Token Forgery</strong>: Attackers can create a token with any payload they want, bypassing the security controls in place. The application will trust the token because no check is done to ensure that it was issued by the legitimate server.</li></ul><p>And because the application is <strong>trusting the user’s role from an unverified JWT</strong>, the role data can be easily manipulated by an attacker. For example, if the attacker sends a token with the role set to “admin”, they would bypass the role check and gain access to administrative endpoints.</p><pre>function authorizeRoles(roles) {<br>    return (req, res, next) =&gt; {<br>        if (!roles.includes(req.user.role)) {<br>            return res.sendStatus(403); // Forbidden if role doesn&#39;t match<br>        }<br>        next();<br>    };<br>}</pre><p>The middleware checks whether the user’s role (stored in req.user.role) matches the allowed roles for a given route. While this may seem secure, it becomes vulnerable when combined with the <strong>JWT authentication vulnerability</strong>.</p><p>we can exploit this vulnerability easily since the application blindly trusts the data extracted from the unverified token, it becomes vulnerable to unauthorized access</p><p>The attack could use any tool to capture the returned token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMxS-dG4X8dK6IILk18Wdw.png" /><figcaption>login to capture JWT.</figcaption></figure><p>And by using tools like jwt.io or other online JWT generators. By modifying the payload we can escalate higher privilege role (e.g., changing &quot;role&quot;: &quot;user&quot; to &quot;role&quot;: &quot;admin&quot;),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPVOQpzAP7tFsMhtJhcoRQ.png" /></figure><p>Then submiting this token through an API request. Since the signature is not verified, the server accepts the altered token, allowing the attacker to bypass the RBAC system and gain unauthorized access to restricted endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33ZcRJcjqDHXkzt0Eo7h-Q.png" /><figcaption>Altering role in the JWT payload allow us to gain unauthorized access to admin endpoint.</figcaption></figure><p><strong>Securing the Implementation: Proper JWT Verification</strong><br>To prevent such exploits, we need to verify the JWT signature using the jwt.verify() method, which ensures that the token was issued by the server and has not been tampered with. Below is the updated code:</p><pre>function authenticateToken(req, res, next) {<br>    const authHeader = req.headers[&#39;authorization&#39;];<br>    const token = authHeader &amp;&amp; authHeader.split(&#39; &#39;)[1];<br>    if (!token) return res.sendStatus(401); // Unauthorized<br><br>    jwt.verify(token, SECRET_KEY, { algorithms: [&#39;HS256&#39;] }, (err, user) =&gt; {<br>        if (err) {<br>            console.error(&#39;JWT Verification Failed:&#39;, err);<br>            return res.sendStatus(403); // Forbidden<br>        }<br>        req.user = user;<br>        next();<br>    });<br>}</pre><p>In this implementation, the jwt.verify() function checks the token’s signature against the secret key (SECRET_KEY) and ensures that only tokens issued by the server are accepted. Additionally, the algorithms parameter specifies the accepted signing algorithm (HS256), providing an extra layer of security. After fixing the authentication process, the authorization middleware will now function correctly, only granting access to users with verified roles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AjXj4ONx4Y2LlZJiglxVg.png" /><figcaption>Attackers cannot manipulate their roles by altering JWT payloads now.</figcaption></figure><p><strong>Additional Security Recommendations</strong><br>Here are some additional steps to further secure your Node.js application’s JWT-based authentication system:</p><ol><li><strong>Set Short Token Expiration</strong>: Use short expiration times for JWT tokens (exp claim) to reduce the impact of token theft.</li><li><strong>Use Strong Secret Keys</strong>: Ensure that the secret key used to sign the JWT is a strong, complex, and securely stored key.</li><li><strong>Implement Refresh Tokens</strong>: Use refresh tokens for long-lived sessions. Store these tokens securely on the server side and issue new JWTs as needed.</li><li><strong>Role Validation</strong>: Validate roles server-side in conjunction with signature verification. Don’t rely solely on the role field in the JWT payload for critical operations.</li><li><strong>Monitor and Log Failed Authentication Attempts</strong>: Keep track of failed JWT verification attempts and set up alerts to detect potential attacks.</li></ol><p>JWTs provide a powerful mechanism for securing web applications, misconfigurations and improper implementation can expose applications to severe vulnerabilities, such as broken access control. By ensuring the signature is always verified and taking additional precautions, you can safeguard your Node.js applications against these risks.</p><p>Stay tuned for more articles in my <strong>“Toward Secure Code”</strong> series, where we will continue to explore practical security vulnerabilities and how to fix them in modern web applications.</p><h4>References</h4><p>secure code link : <a href="https://github.com/Tharbouch/Toward-Secure-Code/tree/main/Role-Based%20Authentication%20and%20Authorization%20/secure/backendNode">https://github.com/Tharbouch/Toward-Secure-Code/tree/main/Role-Based%20Authentication%20and%20Authorization%20/secure/backendNode</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f70fa8a28b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>