## Common Web Security Vulnerabilities
### What is Cross-Site Scripting (XSS)?
XSS occurs when an attacker injects malicious scripts into web pages viewed by other users. This can steal session cookies, redirect users, or deface websites.
#### Example: Vulnerable Code
A basic XSS vulnerability might look like this:
```html
XSS Example
Welcome,
```
#### Corrected Code
Sanitize user input to prevent XSS:
```php
Welcome, $username";
?>
```
---
## Secure Coding Practices
### 1. **Input Validation**
Always validate and sanitize user input before processing or displaying it. Use libraries like `htmlspecialchars` in PHP or security headers in frameworks.
### 2. **Secure HTTP Headers**
Set security headers like `Content-Security-Policy`, `X-Content-Type-Options`, and `X-Frame-Options` to enhance protection.
### 3. **Use Frameworks**
Leverage secure web frameworks that handle XSS, SQL injection, and other vulnerabilities out of the box (e.g., Django, Ruby on Rails).
### 4. **Parameterized Queries**
Prevent SQL injection by using prepared statements and parameterized queries.
### 5. **Session Security**
Use secure cookies (`HttpOnly`, `Secure`, `SameSite`) and rotate session IDs frequently.
---
## Key Takeaways
1. **XSS** is a critical vulnerability that allows attackers to inject scripts into web pages.
2. **Sanitize user input** and use secure frameworks to prevent XSS.
3. **Secure coding practices** like input validation and security headers are essential for robust web applications.
---
## Cheatsheet: Web Security Best Practices
| **Vulnerability** | **Solution** |
|--------------------------|-----------------------------------------------------------------------------|
| XSS | Sanitize input with `htmlspecialchars` or use secure frameworks. |
| SQL Injection | Use parameterized queries and prepared statements. |
| Insecure Deserialization | Avoid untrusted data in deserialization. Use secure libraries like Jackson. |
| CSRF (Cross-Site Request Forgery) | Implement CSRF tokens and verify origin headers. |
| Clickjacking | Use `X-Frame-Options` headers to prevent framing. |
---
By following these guidelines, web developers can significantly reduce the risk of security vulnerabilities and build more robust applications.