Lessons From 3 Hack The Box Modules On Frontend Security

Security is a critical aspect of creating robust web applications that is often overlooked at the beginning of a frontend developer's journey. Because of this, one can acquire unsafe secure coding habits that over time are more difficult to unlearn. For this reason, I set aside time to learn different security practices and concepts that I hope will make me a better programmer.

Thus, recently, I completed three modules on Hack The BoxIntroduction to Web Applications, Web Requests, and JavaScript Deobfuscation. These challenges offered hands-on experience with understanding common web vulnerabilities, improving secure coding practices, and working securely with APIs. In this article, I’ll share the key lessons I learned from each module and how they apply to frontend development, particularly when working with JavaScript and web APIs, along with practical examples using cURL and insights into real-world vulnerabilities.

Module 1: Introduction to Web Applications

What I Learned:

  • An Overview of Core Components of Web Applications:

    • Frontend (HTML, CSS, JavaScript).
    • Backend (server-side logic and APIs).
    • Databases (data storage and retrieval).
  • Frontend Vulnerabilities:

    • Sensitive Data Exposure: Leaking sensitive information in the frontend (e.g., API keys, tokens).
    • Cross-Site Scripting (XSS): Injected malicious scripts can execute in the browser.
    • Cross-Site Request Forgery (CSRF): Exploiting authenticated sessions to perform unauthorized actions.
  • Backend Vulnerabilities:

    • Broken Authentication and Access Control: Allowing unauthorized users to access restricted resources.
    • Malicious File Upload: Uploading files that execute malicious code on the server.
    • Command Injection: Injecting commands into server-side processes.
    • SQL Injection: Exploiting poorly sanitized database queries.

Using dangerouslySetInnerHTML in React

I take this opportunity to share an example of insecure coding I wasn't aware of back when I started learning to work with Next.js (v12) which I corrected later on. After having followed a series of tutorials, I intended to create a blog application to apply the things I learned. However, despite having succeeded in creating the desired functionality, I used dangerouslySetInnerHTML to render HTML content for the blog posts from markdown files. For example:

export default function Post({ postData }) {
  return (
    <article>
        <h1>{postData.title}</h1>   
        <div dangerouslySetInnerHTML={{ __html: postData.contentHtml }}/>
    </article>
  )}

While this approach can render formatted blog content, it poses significant security risks, primarily the potential for Cross-Site Scripting (XSS) attacks if the markdown content is not sanitized. A malicious user could inject malicious scripts into the markdown, leading to severe security vulnerabilities.

A Safer Alternative Without dangerouslySetInnerHTML

Instead of using dangerouslySetInnerHTML, I found react-markdown—an npm package that makes it easy for beginners to safely parse the markdown content into React components, avoiding the risks associated with injecting raw HTML. Following the package's documentation, I refactored the code to safely render blog content from a markdown file. Here's a snippet:

export default function BlogPost({ postData }) {
    return (
        <article>
            <h1>{postData.title}</h1>
            <Markdown>{postData.content}</Markdown>
        </article>
    );
}

Public CVEs and CVSS

  • CVE (Common Vulnerabilities and Exposures): A public database of known vulnerabilities. For example, identifying the version of a web application (e.g., via HTTP headers or error messages) can help attackers correlate it with a CVE entry to exploit known vulnerabilities.
  • CVSS (Common Vulnerability Scoring System): An open-source standard for assessing the severity of vulnerabilities. CVEs with a CVSS score of 8-10 are considered critical and are prime targets for attackers.

Proactive Measures to Improve Code Security:

  • Avoid exposing sensitive data in the frontend (e.g., API keys, tokens).
  • Use tools like APIsec Scan to scan my web application for vulnerabile APIs as it offers complete test coverage across 100% of the OWASP API Top 10.
  • Regularly scan my code base with tools like Snyk to identify vulnerabile packages and update dependencies to patch known vulnerabilities listed in CVEs.
  • Handle errors and avoid verbose error messages as they can give useful clues to malicious users to craft their attack.

Module 2: Web Requests

What I Learned:

  • Understanding HTTP Basics: HTTP methods like GET, POST, PUT, and DELETE are the backbone of web communication. Knowing how to use them securely is essential.
  • Common API Vulnerabilities:
    • Improper handling of user inputs in API requests.
    • Overly permissive CORS (Cross-Origin Resource Sharing) policies.
  • Importance of Validation: Always validate and sanitize input on both client and server sides to prevent attacks like SQL Injection or Command Injection.

Performing CRUD Operations with cURL:

With cURL, we can perform all four CRUD operations (Create, Read, Update, Delete) on a REST API. However, in a real-world application, such actions are typically restricted based on user privileges. Allowing any user to modify or delete data without proper authentication and authorization would be considered a serious vulnerability. To authenticate users, we often pass a cookie or an authorization header (e.g., a JWT token). Below are examples of performing CRUD operations securely:

  • Create (POST): To create a new resource, such as adding a new user to a database:
curl -X POST http://example.com/api/users \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_JWT_TOKEN" \
     -d '{"name": "John Doe", "email": "john@example.com"}'

This sends a POST request with the user data in JSON format. The Authorization header ensures that only authenticated users can perform this action.

  • Read (GET): To retrieve data, such as fetching a list of users:
curl -X GET http://example.com/api/users \
     -H "Authorization: Bearer YOUR_JWT_TOKEN"

This GET request retrieves the list of users. Without the Authorization header, the server should reject the request if the endpoint is protected. The same goes for not having the necessary privilege to access this endpoint.

  • Update (PUT): To update an existing resource, such as modifying a user's email:
curl -X PUT http://example.com/api/users/1 \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_JWT_TOKEN" \
     -d '{"email": "newemail@example.com"}'

This PUT request updates the email of the user with ID 1. Again, the Authorization header ensures that only authorized users can make changes.

  • Delete (DELETE): To delete a resource, such as removing a user from the database:
curl -X DELETE http://example.com/api/users/1 \
     -H "Authorization: Bearer YOUR_JWT_TOKEN"

This DELETE request removes the user with ID 1. Without proper authentication, allowing such actions would be a critical security flaw.

Proactive Measures to Improve Code Security:

  • Authentication and Authorization: Always ensure that API requests are authenticated and authorized. For example, use JWT tokens or OAuth to restrict access to sensitive operations.
  • Role-Based Access Control (RBAC): Implement RBAC to define what actions each user role (e.g., admin, editor, viewer) can perform.
  • Input Validation: Validate and sanitize all inputs on both the client and server sides to prevent injection attacks.
  • Restrict Unused HTTP Methods: To avoid the scenario in which the application could behave unexpectedly, disable any HTTP verbs/methods that the application is not using. This helps reduce the attack surface of the API.

By practicing these operations, I learned how to interact with APIs more securely and understood the importance of restricting access to sensitive actions.

Module 3: JavaScript Deobfuscation

What I Learned:

  • Understanding JavaScript Obfuscation: Attackers often hide malicious scripts through obfuscation techniques (e.g., minified, encoded, or scrambled JavaScript). This can make it difficult to understand what the code is doing at first glance.
  • Techniques to Deobfuscate JavaScript:
    • Using browser developer tools (e.g., the “Pretty Print” feature in Chrome DevTools).
    • Pasting the formatted code into an online deobfuscator.
    • Analyzing variable names, functions, and execution flow.

Real-World Applications:

  • Identifying and reversing malicious scripts in compromised web applications.
  • Debugging poorly written or intentionally obfuscated third-party libraries.

How This Applies to Frontend Developers:

  • Debugging Third-Party Libraries: Frontend developers often integrate third-party libraries or SDKs into their applications. If these libraries are obfuscated (intentionally or poorly written), understanding how to deobfuscate JavaScript can help debug issues or identify potential vulnerabilities.
  • Improving Code Security: Understanding obfuscation techniques can also help frontend developers secure their own code. For example, while obfuscation is not a substitute for proper security practices, it can add a layer of complexity for attackers attempting to reverse-engineer sensitive logic.

Practical Examples with cURL:

  • Finding API Keys in Obfuscated Code: To identify if sensitive information, such as API keys, is embedded in obfuscated JavaScript, the file can downloaded and analyzed. For example:
curl -O http://example.com/static/js/app.min.js

After downloading, using tools like Chrome DevTools or an online tool to deobfuscate and search for sensitive information. This is especially useful when working with third-party scripts or debugging security issues.

  • Interacting with Obfuscated API Endpoints: Sometimes, obfuscated JavaScript may reveal hidden API endpoints. For example:
curl -X GET http://example.com/api/hiddenEndpoint -H "Authorization: Bearer FOUND_API_KEY"

This allows me to verify whether the endpoint is functional and whether it exposes sensitive data.

Key Takeaways for the 3 Hack the Box Modules:

  • Build Secure JavaScript Practices:

    • Always validate and sanitize user inputs.
    • Use tools like ESLint to enforce secure coding standards.
    • Avoid exposing sensitive data in the browser.
  • Work Securely with APIs:

    • Implement proper authentication and authorization (e.g., OAuth, API tokens).
    • Never hard-code API keys or sensitive information in JavaScript codebase and use environment variables instead.
    • Ensure CORS policies are restrictive and only allow trusted origins.
  • Learn to Think Like an Attacker:

    • Understanding how attackers exploit vulnerabilities helps me write more defensive and secure code.
    • Regularly test my application using tools like OWASP ZAP, Burp Suite, APIsec Scan and browser dev tools.
  • Continuous Learning:

    • Security is an evolving field—stay updated with common vulnerabilities (e.g., via OWASP Top 10).
    • Practice solving challenges on platforms like Hack The Box to improve my skills.

Conclusion

By completing these Hack The Box modules, I gained a better understanding of how to create secure frontend applications. As a frontend developer, my role in building secure web applications goes beyond just writing clean code—it's about proactively defending against vulnerabilities and ensuring user data is protected. I encourage other developers to explore platforms like Hack The Box to strengthen their security mindset while honing their technical skills. If you're a developer, let me know what other resources you are exploring to make your code safer!


Liked this article? Share it on:

logo

Hope you enjoyed exploring my coding journey and found something useful or inspiring. I'd be glad if you checked back later for updates and new projects!

Socials

Connect with me on my social handles.

Copyright 2023 ©Devroxana. All rights reserved.

Part of the images on this website have been provided by Icons8 and IconScout.

To improve your experience on this site, we use privacy-friendly analytics. By continuing to visit you agree to our privacy policy. Please review it. Understood X