Security: CSRF Protection, Input Validation, and Secure JSON
Security: CSRF Protection, Input Validation, and Secure JSON
CSRF Protection क्या है?
CSRF यानी Cross-Site Request Forgery एक ऐसा web attack होता है जिसमें attacker किसी authenticated user के browser के जरिए unwanted actions perform करवा लेता है। इसका main उद्देश्य होता है – user की authorization का misuse करना।
उदाहरण के लिए, मान लो कोई user किसी banking site में login है, और उसी समय attacker एक malicious link भेज देता है। अगर user उस link पर click करता है तो उसके session का उपयोग करके attacker unauthorized transaction कर सकता है।
CSRF कैसे काम करता है?
CSRF attack तब possible होता है जब:
- User किसी site में already login होता है।
- Attacker user को एक hidden malicious request भेजता है।
- Browser automatically cookies या session tokens attach कर देता है।
CSRF Attack का Example
<img src="http://bank.com/transfer?amount=5000&to=attacker_account">
ऊपर दिए गए code में अगर user पहले से bank में login है तो ये image tag एक GET request execute कर देगा, जिससे पैसे attacker के account में ट्रांसफर हो सकते हैं।
CSRF Protection के Methods
CSRF से बचने के लिए developers कुछ महत्वपूर्ण techniques use करते हैं:
- CSRF Token का उपयोग: हर form या request के साथ एक unique, unpredictable token भेजा जाता है जो server-side पर verify होता है।
- SameSite Cookies: Cookies में
SameSiteattribute set करने से third-party requests पर cookies नहीं भेजी जातीं। - Double Submit Cookie Technique: Token को cookie और hidden form field दोनों में भेजा जाता है और दोनों का match check किया जाता है।
- Referer Header Validation: Server incoming request का referer header verify करता है कि request trusted domain से ही आई हो।
CSRF Token Implementation Example (Java Servlet)
// Generate token and store in session
String csrfToken = UUID.randomUUID().toString();
session.setAttribute("csrfToken", csrfToken);
// Include token in form
<form method="POST" action="/submit">
<input type="hidden" name="csrfToken" value="${csrfToken}">
<input type="text" name="username">
<input type="submit" value="Submit">
</form>
// Validate token on server
String requestToken = request.getParameter("csrfToken");
String sessionToken = (String) session.getAttribute("csrfToken");
if(sessionToken != null && sessionToken.equals(requestToken)){
// process request
} else {
response.sendError(403, "Invalid CSRF token");
}
Input Validation क्या होती है?
Input Validation web application security का सबसे पहला और जरूरी step है। इसका मतलब है — user द्वारा दिए गए data को verify करना कि वह valid, expected और safe है या नहीं।
अगर input properly validate नहीं किया गया तो attacker SQL Injection, XSS, Command Injection जैसे attacks कर सकता है।
Input Validation के प्रकार
- Client-side Validation: ये validation browser में JavaScript के द्वारा की जाती है ताकि user को तुरंत feedback मिले। लेकिन ये पूरी तरह secure नहीं होती।
- Server-side Validation: ये validation server पर की जाती है और security के लिए यह बहुत जरूरी होती है क्योंकि attacker client-side rules को bypass कर सकता है।
Good Input Validation Practices
- हर input field के लिए allowed characters define करो (whitelisting approach)।
- Input data का type (जैसे integer, string, email) validate करो।
- Maximum length limit set करो ताकि buffer overflow या large payload attacks से बचा जा सके।
- Special characters को escape या sanitize करो ताकि injection attacks न हों।
Java Example of Input Validation
String username = request.getParameter("username");
if(username != null && username.matches("^[a-zA-Z0-9_]{3,15}$")) {
out.println("Valid Username");
} else {
out.println("Invalid Username");
}
Common Vulnerabilities बिना Input Validation के
| Vulnerability | Cause | Impact |
|---|---|---|
| SQL Injection | SQL queries में raw user input जोड़ना | Data leak या modification |
| XSS (Cross Site Scripting) | Input में HTML/JS code allow करना | Session hijack या phishing |
| Command Injection | OS level commands को input से execute करना | System control loss |
Prepared Statement से SQL Injection Prevention
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE email=?");
ps.setString(1, email);
ResultSet rs = ps.executeQuery();
Secure JSON Transmission
Modern web applications में JSON (JavaScript Object Notation) का use data transfer के लिए बहुत common है। लेकिन अगर इसे securely handle न किया जाए तो attacker data intercept या manipulate कर सकता है।
JSON से जुड़ी Common Security Issues
- Unencrypted JSON data network पर भेजना।
- Improper JSON parsing जिससे data tampering हो सकती है।
- Cross-Origin Resource Sharing (CORS) configuration गलत होना।
Secure JSON Practices
- Use HTTPS: हमेशा secure connection (SSL/TLS) पर JSON data भेजो ताकि data encryption बनी रहे।
- Validate JSON Structure: JSON schema के according structure verify करो।
- Escape user-controlled fields: ताकि JSON Injection न हो।
- Set proper CORS policies: केवल trusted domains को data access allow करो।
- Implement Authentication & Authorization: JSON data access केवल authorized users को दो।
Example: Secure JSON Response in Servlet
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
JsonObject jsonResponse = new JsonObject();
jsonResponse.addProperty("status", "success");
jsonResponse.addProperty("message", "Data fetched securely");
response.getWriter().write(jsonResponse.toString());
JSON Schema Validation Example (Java)
JSONObject jsonObject = new JSONObject(inputJson);
Schema schema = SchemaLoader.load(new JSONObject(schemaDefinition));
schema.validate(jsonObject); // Throws exception if invalid
Important Security Headers for JSON
| Header | Purpose |
|---|---|
| Content-Type: application/json | Ensure browser treats data as JSON |
| X-Content-Type-Options: nosniff | Prevent MIME type confusion |
| Access-Control-Allow-Origin | Restrict cross-domain JSON access |
Web Security Best Practices Summary
- हर request के साथ CSRF Token validate करो।
- Input data को हमेशा sanitize और validate करो।
- JSON responses में security headers जोड़ो।
- HTTPS mandatory रखो ताकि transmission secure रहे।
- Logging और monitoring enable करो ताकि suspicious activity detect हो सके।
- Regular security testing करो — जैसे Penetration Testing और Vulnerability Scanning।
Developer Tips for Exam और Project Preparation
- CSRF Token कैसे generate और validate किया जाता है — इसका code याद रखो।
- Input Validation के regex patterns समझो और practical implement करो।
- JSON Secure Handling और CORS configuration exam में frequently पूछे जाते हैं।
- अगर project बना रहे हो तो HTTPS, CSRF Token, Validation हमेशा include करो।
- OWASP (Open Web Application Security Project) की top 10 vulnerabilities ज़रूर पढ़ो।
इन तीनों security measures — CSRF Protection, Input Validation और Secure JSON — को implement करने से web application काफी हद तक secure बन जाती है और real-world attacks से बचाव होता है।