CyberSecurity

 # 🔒 CYBERSECURITY A TO Z - COMPLETE GUIDE (0 to 100)
# Everything You Need to Know About Cybersecurity - From Noob to Pro

================================================================================
TABLE OF CONTENTS
================================================================================

1. CYBERSECURITY FUNDAMENTALS
2. COMMON THREATS & ATTACKS
3. AUTHENTICATION & AUTHORIZATION
4. ENCRYPTION & CRYPTOGRAPHY
5. NETWORK SECURITY
6. WEB APPLICATION SECURITY
7. DATABASE SECURITY
8. API SECURITY
9. CLOUD SECURITY
10. INCIDENT RESPONSE
11. COMPLIANCE & STANDARDS
12. SECURITY TESTING
13. SECURE CODING PRACTICES
14. DEPLOYMENT SECURITY
15. MONITORING & DETECTION
16. REAL-WORLD IMPLEMENTATIONS


================================================================================
1. CYBERSECURITY FUNDAMENTALS
================================================================================

WHAT IS CYBERSECURITY?
Protection of computer systems, networks, and data from unauthorized access.
Prevents theft, damage, and disruption.
Three main pillars: Confidentiality, Integrity, Availability (CIA Triad)

CIA TRIAD:

CONFIDENTIALITY:
- Only authorized people access data
- No data leaks
- Encryption, access control
- Example: Your password should not be visible to anyone

INTEGRITY:
- Data is accurate and unchanged
- No unauthorized modifications
- Checksums, digital signatures
- Example: Bank transaction not altered during transfer

AVAILABILITY:
- Systems are accessible when needed
- No downtime
- Redundancy, backups
- Example: Website always up and responsive

CYBERSECURITY ROLES:

1. SECURITY ANALYST
   - Monitors systems for breaches
   - Analyzes security logs
   - Identifies vulnerabilities
   - Creates security reports

2. PENETRATION TESTER
   - Tests systems for vulnerabilities
   - Attempts to hack ethically
   - Documents findings
   - Recommends fixes

3. SECURITY ARCHITECT
   - Designs security systems
   - Plans security infrastructure
   - Creates security policies
   - Ensures compliance

4. INCIDENT RESPONDER
   - Responds to security incidents
   - Isolates affected systems
   - Investigates breaches
   - Recovers data

5. SECURITY ENGINEER
   - Implements security solutions
   - Develops security tools
   - Patches systems
   - Hardens infrastructure

SECURITY MINDSET:
✅ Assume nothing is secure by default
✅ Defense in depth (multiple layers)
✅ Zero trust model (verify everything)
✅ Principle of least privilege (minimal access)
✅ Regular testing and updates
✅ Document everything
✅ Continuous monitoring


================================================================================
2. COMMON THREATS & ATTACKS
================================================================================

THREAT vs VULNERABILITY vs ATTACK:

THREAT: Potential danger (hacker wants your data)
VULNERABILITY: Weakness in system (weak password)
ATTACK: Exploit vulnerability (hacker cracks password)

COMMON ATTACK TYPES:

1. PHISHING
What: Fraudulent emails/messages to trick users
Example: Email says "Click here to verify account"
Prevention:
  - Never click links in emails
  - Verify sender email address
  - Look for spelling errors
  - Check domain carefully (amaz0n.com vs amazon.com)
  - Use email filters
  - Multi-factor authentication

Code to detect phishing:
// Check for suspicious patterns
function isPhishingEmail(email) {
  const suspiciousPatterns = [
    /verify.*account/i,
    /click.*immediately/i,
    /urgent.*action.*required/i,
    /confirm.*payment/i,
    /update.*information/i
  ];
  
  return suspiciousPatterns.some(pattern => 
    pattern.test(email.subject) || pattern.test(email.body)
  );
}

2. MALWARE
What: Malicious software that harms system
Types:
  - Virus: Attaches to files, replicates
  - Worm: Self-replicating, spreads automatically
  - Trojan: Pretends to be legitimate, installs malware
  - Ransomware: Encrypts files, demands payment
  - Spyware: Monitors user activity
  - Adware: Shows unwanted ads

Prevention:
  - Antivirus software
  - Don't download from untrusted sources
  - Update software regularly
  - Use firewall
  - Regular backups

3. SQL INJECTION
What: Inserting malicious SQL commands into input fields
Example:
  Username: admin' OR '1'='1
  Password: anything
  
  Generated SQL: SELECT * FROM users WHERE username='admin' OR '1'='1'
  Result: Bypasses login (1=1 is always true)

Prevention:
  - Use parameterized queries (prepared statements)
  - Input validation
  - Escape special characters
  - Least privilege database user
  - Web Application Firewall (WAF)

Vulnerable code:
// BAD: SQL Injection vulnerability
const query = `SELECT * FROM users WHERE email='${email}'`;
db.query(query);

Safe code:
// GOOD: Parameterized query
const query = 'SELECT * FROM users WHERE email=$1';
db.query(query, [email]);

4. CROSS-SITE SCRIPTING (XSS)
What: Injecting malicious JavaScript into web pages
Example: Comment contains: <script>stealCookie()</script>
When other users view comment, script runs in their browser

Types:
  - Stored XSS: Malicious code stored in database
  - Reflected XSS: Malicious code in URL
  - DOM XSS: Malicious code modifies page through DOM

Prevention:
  - Escape output
  - Use Content Security Policy (CSP)
  - Input validation
  - Use security libraries

Vulnerable code:
// BAD: XSS vulnerability
app.get('/comment/:id', (req, res) => {
  const comment = db.getComment(req.params.id);
  res.send(`<p>${comment.text}</p>`); // User can inject scripts
});

Safe code:
// GOOD: Escape output
app.get('/comment/:id', (req, res) => {
  const comment = db.getComment(req.params.id);
  const escaped = escapeHtml(comment.text);
  res.send(`<p>${escaped}</p>`);
});

5. CROSS-SITE REQUEST FORGERY (CSRF)
What: Tricking user into making unauthorized request
Example: User logged into bank, visits malicious site
Malicious site has: <img src="bank.com/transfer?to=hacker&amount=1000">
Bank transfers money (user's browser has valid session cookie)

Prevention:
  - CSRF tokens (validate origin)
  - SameSite cookie attribute
  - Check HTTP referer header
  - Use POST instead of GET for sensitive actions

Protected code:
// Generate CSRF token
function generateCSRFToken() {
  return crypto.randomBytes(32).toString('hex');
}

// Middleware to verify CSRF token
app.post('/transfer', (req, res) => {
  const token = req.body._token;
  const sessionToken = req.session._token;
  
  if (token !== sessionToken) {
    return res.status(403).json({ error: 'Invalid CSRF token' });
  }
  
  // Process transfer
});

6. BRUTE FORCE ATTACK
What: Trying many passwords until one works
Example: Attacker tries 1 million passwords per second

Prevention:
  - Rate limiting (max 5 attempts per minute)
  - Account lockout (lock after 10 failed attempts)
  - CAPTCHA
  - Strong passwords
  - Multi-factor authentication

Code:
// Rate limiting for login
const loginLimiter = rateLimit({
  windowMs: 60 * 1000,      // 1 minute
  max: 5,                   // 5 attempts
  skipSuccessfulRequests: true  // Don't count successful logins
});

app.post('/login', loginLimiter, (req, res) => {
  // Login logic
});

7. MAN-IN-THE-MIDDLE (MITM)
What: Attacker intercepts communication between two parties
Example: Unencrypted Wi-Fi, attacker reads all traffic

Prevention:
  - Use HTTPS (encrypted)
  - VPN for public Wi-Fi
  - Certificate pinning
  - Verify SSL certificates

8. DDoS (DISTRIBUTED DENIAL OF SERVICE)
What: Many computers send traffic to overwhelm server
Result: Website becomes unavailable

Prevention:
  - Rate limiting
  - IP blocking
  - CDN (Cloudflare, AWS Shield)
  - Larger bandwidth capacity

9. PRIVILEGE ESCALATION
What: Regular user gains admin privileges
Example: Bug allows user to become admin

Prevention:
  - Principle of least privilege
  - Code review
  - Regular testing
  - Update software

10. ZERO-DAY EXPLOITS
What: Attack exploiting unknown vulnerability
No patch available yet
Very dangerous

Prevention:
  - Security monitoring
  - Intrusion detection
  - Regular backups
  - Assume breach mindset


================================================================================
3. AUTHENTICATION & AUTHORIZATION
================================================================================

AUTHENTICATION vs AUTHORIZATION:

AUTHENTICATION: Who are you? (Verify identity)
AUTHORIZATION: What can you do? (Verify permissions)

Example:
- Authentication: Login with username/password
- Authorization: User can view profile but not admin panel

AUTHENTICATION METHODS:

1. PASSWORD AUTHENTICATION
Simplest but most vulnerable
Weak passwords easily cracked

Problems:
✅ Users reuse passwords
✅ Weak passwords (123456)
✅ No protection if database hacked
✅ Easy to guess

Solution: Hash passwords!

2. PASSWORD HASHING

Never store passwords in plain text:
// BAD: Plain text password
user.password = "mypassword123";
db.save(user);

// GOOD: Hashed password
const hashedPassword = bcrypt.hashSync(password, 10);
user.password = hashedPassword;
db.save(user);

Hashing basics:
// One-way function
hash("password") = "$2b$10$xyz..."
hash("password") = "$2b$10$xyz..." (same input, same hash)
hash("Password") = "$2b$10$abc..." (different hash - case sensitive)

Impossible to reverse:
Can't do: unhash("$2b$10$xyz...") → "password"

Popular hashing algorithms:
- bcrypt: Industry standard, slow (2^10 iterations)
- Argon2: Modern, very slow (memory hard)
- scrypt: Good alternative
- PBKDF2: Fast, acceptable but not best

Use bcrypt or Argon2!

Hashing with bcrypt:
import bcrypt from 'bcrypt';

// Registration
const password = "myPassword123";
const hashedPassword = await bcrypt.hash(password, 10); // 10 = cost factor
await db.user.create({ email, password: hashedPassword });

// Login
const user = await db.user.findOne({ email });
const isValidPassword = await bcrypt.compare(password, user.password);
if (isValidPassword) {
  // Login successful
}

3. MULTI-FACTOR AUTHENTICATION (MFA)
Second layer of security
Multiple ways to verify identity

Types:
- Something you know: Password, PIN
- Something you have: Phone, Security key
- Something you are: Fingerprint, Face

MFA Methods:
- OTP (One-Time Password): 6-digit code from app
- SMS: Code sent via text message
- Email: Confirmation link in email
- Biometric: Fingerprint, face recognition
- Security key: Physical USB device

OTP Example:
// Generate 6-digit code
function generateOTP() {
  return Math.floor(100000 + Math.random() * 900000).toString();
}

// Send to user's phone/email
const otp = generateOTP();
await sendOTP(user.phone, otp);
await redis.set(`otp:${user.id}`, otp, 'EX', 300); // 5 minute expiry

// Verify OTP
app.post('/verify-otp', (req, res) => {
  const userOTP = await redis.get(`otp:${user.id}`);
  if (req.body.otp !== userOTP) {
    return res.status(401).json({ error: 'Invalid OTP' });
  }
  
  // Mark as verified
  req.session.mfaVerified = true;
});

4. JWT (JSON WEB TOKENS)
Stateless authentication
Token contains user information
Signed to prevent tampering

JWT Structure: header.payload.signature

Example:
Header: {"alg": "HS256", "typ": "JWT"}
Payload: {"userId": 123, "email": "user@example.com", "exp": 1234567890}
Signature: HMACSHA256(header.payload, secret)

JWT Example:
import jwt from 'jsonwebtoken';

// Generate JWT
function generateToken(user) {
  return jwt.sign(
    { userId: user.id, email: user.email },
    process.env.JWT_SECRET,
    { expiresIn: '24h' } // Token valid for 24 hours
  );
}

// Verify JWT
app.use((req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ error: 'No token' });
  }
  
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    res.status(401).json({ error: 'Invalid token' });
  }
});

AUTHORIZATION MODELS:

1. ROLE-BASED ACCESS CONTROL (RBAC)
Users have roles, roles have permissions
Example: Admin, User, Guest

// Middleware to check role
function requireRole(role) {
  return (req, res, next) => {
    if (req.user.role !== role) {
      return res.status(403).json({ error: 'Forbidden' });
    }
    next();
  };
}

app.delete('/users/:id', requireRole('admin'), (req, res) => {
  // Only admins can delete users
});

2. ATTRIBUTE-BASED ACCESS CONTROL (ABAC)
More fine-grained permissions
Based on attributes (user, resource, environment)

Example:
- User can view documents created by them
- User can view documents if department matches
- User can view documents during business hours

Implementation:
function canAccess(user, resource) {
  // Check multiple conditions
  if (resource.ownerId === user.id) return true; // Owner
  if (user.role === 'admin') return true; // Admin
  if (resource.department === user.department && resource.isShared) return true; // Department share
  return false;
}

3. ZERO TRUST MODEL
Never trust anything by default
Verify every request
- Verify user identity
- Verify device
- Verify location
- Verify intention
- Verify action

Implementation:
// Verify everything
async function verifyRequest(req) {
  // Verify JWT token
  const user = verifyJWT(req.token);
  
  // Verify device
  const device = await getDevice(req.deviceId);
  if (!device.verified) throw new Error('Device not trusted');
  
  // Verify location (IP must be in whitelist)
  if (!isIPWhitelisted(req.ip)) throw new Error('Location not trusted');
  
  // Verify action is allowed for user
  if (!canPerformAction(user, req.action)) throw new Error('Action not allowed');
  
  // Verify MFA for sensitive actions
  if (isSensitiveAction(req.action) && !req.mfaVerified) {
    throw new Error('MFA required');
  }
  
  return user;
}


================================================================================
4. ENCRYPTION & CRYPTOGRAPHY
================================================================================

ENCRYPTION: Converting data to unreadable form
DECRYPTION: Converting encrypted data back to readable form

WHY ENCRYPTION?
- Protects data in transit (network)
- Protects data at rest (storage)
- Ensures confidentiality
- Prevents unauthorized access

TYPES OF ENCRYPTION:

1. SYMMETRIC ENCRYPTION
Same key to encrypt and decrypt
Fast but key distribution problem
Who exchanges the key securely?

Algorithm: AES (Advanced Encryption Standard)
Key size: 128, 192, or 256 bits
Larger = more secure but slower

Example:
import crypto from 'crypto';

// Encrypt
const plaintext = "Secret message";
const key = crypto.randomBytes(32); // 256-bit key
const iv = crypto.randomBytes(16);  // Initialization vector
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);

let encrypted = cipher.update(plaintext, 'utf8', 'hex');
encrypted += cipher.final('hex');

// Decrypt
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');

console.log(decrypted); // "Secret message"

2. ASYMMETRIC ENCRYPTION
Different keys for encrypt and decrypt
Public key to encrypt, private key to decrypt
Solves key distribution problem

Algorithm: RSA
Key size: 2048, 4096 bits
Slower than symmetric but safer

How it works:
- Everyone has your public key
- Only you have private key
- Anyone can encrypt with public key
- Only you can decrypt with private key

Example:
import crypto from 'crypto';

// Generate key pair
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

// Encrypt with public key
const plaintext = "Secret message";
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(plaintext));

// Decrypt with private key
const decrypted = crypto.privateDecrypt(privateKey, encrypted);
console.log(decrypted.toString()); // "Secret message"

3. HYBRID ENCRYPTION (BEST)
Combine both:
- Use asymmetric to exchange symmetric key securely
- Use symmetric for fast data encryption

Process:
1. Generate random symmetric key
2. Encrypt symmetric key with public key (asymmetric)
3. Encrypt data with symmetric key (fast)
4. Send encrypted key + encrypted data
5. Recipient decrypts key with private key
6. Use decrypted key to decrypt data

HASHING RECAP:

Hashing vs Encryption:
ENCRYPTION: Can decrypt (reversible)
HASHING: Cannot unhash (irreversible)

Use cases:
- Encryption: Sensitive data that needs recovery
- Hashing: Passwords, verification

// ENCRYPTION: Reversible
const encrypted = encrypt("password"); // Can decrypt
const decrypted = decrypt(encrypted);  // Get original

// HASHING: Irreversible
const hash = hashPassword("password");     // Cannot unhash
const verified = bcrypt.compare("password", hash); // Only compare

DIGITAL SIGNATURES
Prove authenticity and non-repudiation

Process:
1. Sign data with private key
2. Anyone can verify with public key
3. Proves you signed it (only you have private key)

Example:
// Sign
const sign = crypto.createSign('sha256');
sign.update(data);
const signature = sign.sign(privateKey, 'hex');

// Verify
const verify = crypto.createVerify('sha256');
verify.update(data);
const isValid = verify.verify(publicKey, signature, 'hex');

HTTPS/SSL/TLS
Encryption for web traffic

How it works:
1. Client connects to server
2. Server sends SSL certificate (contains public key)
3. Client verifies certificate is valid
4. Client generates random key
5. Client encrypts key with server's public key
6. Server decrypts with private key
7. Both use shared key to encrypt communication

Certificate:
- Issued by trusted authority (CA)
- Contains domain name, public key, expiry
- Verified by browser
- Ensures you're talking to real server

Self-signed certificate (not trusted):
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

Using in Node.js:
import https from 'https';
import fs from 'fs';

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, app).listen(443);


================================================================================
5. NETWORK SECURITY
================================================================================

NETWORK LAYERS:

Layer 1: Physical (Cables, Wi-Fi)
Layer 2: Data Link (Switches, MAC addresses)
Layer 3: Network (Routers, IP addresses)
Layer 4: Transport (TCP, UDP, Ports)
Layer 5-7: Application (HTTP, DNS, SSH, FTP)

FIREWALLS
Block/allow traffic based on rules

Types:
- Stateless: Checks each packet independently
- Stateful: Tracks connection state
- Application-level: Understands protocols

Example rules:
- Allow inbound SSH (port 22) from office IPs only
- Block all inbound except HTTP (80) and HTTPS (443)
- Allow all outbound
- Block ICMP (ping) to prevent reconnaissance

Firewall setup example:

# iptables (Linux firewall)

# Default policies
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP

# Allow localhost
iptables -A INPUT -i lo -j ACCEPT

# Allow HTTPS
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow HTTP
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

# Allow SSH from specific IP
iptables -A INPUT -p tcp --dport 22 -s 203.0.113.0/24 -j ACCEPT

# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT

PORTS & SERVICES
Common ports:
- 22: SSH (remote access)
- 80: HTTP (unencrypted web)
- 443: HTTPS (encrypted web)
- 3306: MySQL (database)
- 5432: PostgreSQL (database)
- 6379: Redis (cache)
- 5000: Development server
- 8080: Alternative HTTP

NEVER expose:
- Database ports to internet
- SSH to internet (use VPN)
- Admin panels to internet
- Development ports

VPN (VIRTUAL PRIVATE NETWORK)
Encrypts all internet traffic through server
Hides your IP address
Secure on public Wi-Fi

How it works:
1. Connect to VPN server
2. All traffic encrypted
3. Exit through VPN IP
4. Website sees VPN IP, not yours

Benefits:
✅ Privacy on public Wi-Fi
✅ Bypass geographic restrictions
✅ Hide IP address
✅ Encrypt traffic

INTRUSION DETECTION SYSTEMS (IDS)
Monitor network for suspicious activity
Detect attacks in progress

Types:
- Host-based IDS: Runs on each computer
- Network-based IDS: Monitors network traffic

Example:
- Detect port scan attempts
- Detect DDoS attacks
- Detect malware command & control

LOAD BALANCER SECURITY
Distributes traffic across servers
Can filter malicious traffic

Benefits:
✅ DDoS protection
✅ Rate limiting
✅ SSL termination
✅ Geographic routing
✅ Health checks

DNS SECURITY
DNS translates domain to IP

Attacks:
- DNS Spoofing: Fake IP returned
- DNS Hijacking: Attacker controls DNS
- DNS Amplification: DDoS using DNS servers

Protection:
- DNSSEC: Digitally signed DNS responses
- Use trusted DNS (Cloudflare 1.1.1.1, Google 8.8.8.8)
- DNS over HTTPS (DoH)
- DNS over TLS (DoT)

Example - DNSSEC:
// Verify DNS response is signed correctly
const resolver = new dns.promises.Resolver();
resolver.setServers(['8.8.8.8']); // Google DNS supports DNSSEC

const records = await resolver.resolve4('example.com');
// Browser verifies DNSSEC signature automatically


================================================================================
6. WEB APPLICATION SECURITY
================================================================================

OWASP TOP 10
Most critical security risks in web applications

1. INJECTION (SQL, NoSQL, Command)
Already covered in SQL Injection section

2. BROKEN AUTHENTICATION
Weak password policies
Session fixation
Credential exposure

Prevention:
// Strong password requirements
function validatePassword(password) {
  if (password.length < 12) return false;
  if (!/[A-Z]/.test(password)) return false; // Uppercase
  if (!/[a-z]/.test(password)) return false; // Lowercase
  if (!/[0-9]/.test(password)) return false; // Number
  if (!/[!@#$%^&*]/.test(password)) return false; // Special char
  return true;
}

3. SENSITIVE DATA EXPOSURE
Unencrypted transmission
Unencrypted storage
Logging sensitive data

Prevention:
- Always use HTTPS
- Encrypt sensitive data at rest
- Don't log passwords
- Mask credit card numbers in logs

4. XML EXTERNAL ENTITIES (XXE)
XML parser loads external entities
Can read files, DoS

Prevention:
// Disable XXE
const parser = require('libxmljs');
const xmlDoc = parser.parseXml(xml, { nonet: true });

5. BROKEN ACCESS CONTROL
Users access resources they shouldn't
Horizontal privilege escalation (user A sees user B's data)
Vertical privilege escalation (user becomes admin)

Prevention:
// Check authorization before every operation
app.get('/user/:id', (req, res) => {
  const user = db.getUser(req.params.id);
  
  // Check authorization
  if (user.id !== req.authenticated.id && req.authenticated.role !== 'admin') {
    return res.status(403).json({ error: 'Forbidden' });
  }
  
  res.json(user);
});

6. SECURITY MISCONFIGURATION
Default credentials still active
Unnecessary services running
Outdated software
Error messages reveal system info

Prevention:
- Change all defaults
- Disable unused features
- Update software regularly
- Hide error details (show generic message)

// Generic error messages
app.use((err, req, res, next) => {
  console.error(err); // Log detailed error
  res.status(500).json({ error: 'Internal server error' }); // Generic response
});

7. CROSS-SITE SCRIPTING (XSS)
Already covered

8. INSECURE DESERIALIZATION
Unsafe unserialization of data
Can execute arbitrary code

Prevention:
// Bad: Can execute code
const data = JSON.parse(userInput); // Never do this

// Good: Validate before parsing
function safeJsonParse(json) {
  try {
    const data = JSON.parse(json);
    // Validate data structure
    if (typeof data !== 'object') throw new Error('Invalid data');
    return data;
  } catch (err) {
    throw new Error('Invalid JSON');
  }
}

9. USING COMPONENTS WITH KNOWN VULNERABILITIES
Outdated libraries with security bugs

Prevention:
// Check for vulnerabilities
npm audit

// Update packages
npm update

// Use lockfile
npm ci (uses package-lock.json exactly)

10. INSUFFICIENT LOGGING & MONITORING
No security logs
Can't detect breach

Prevention:
// Log security events
function logSecurityEvent(event, user, details) {
  console.log(JSON.stringify({
    timestamp: new Date().toISOString(),
    event,
    userId: user.id,
    ip: user.ip,
    details
  }));
}

// Log on:
- Failed login attempts
- Privilege escalation
- Data access (especially sensitive)
- Configuration changes
- API key usage

RATE LIMITING
Already covered in previous sections

CONTENT SECURITY POLICY (CSP)
Prevent XSS by controlling what scripts run

Example header:
Content-Security-Policy: 
  default-src 'self';
  script-src 'self' https://trusted-cdn.com;
  style-src 'self' 'unsafe-inline';
  img-src 'self' https:;

Explanation:
- default-src 'self': Only load from same origin by default
- script-src: Only allow scripts from self and trusted CDN
- style-src: Allow styles from self and inline
- img-src: Allow images from self and HTTPS

Express implementation:
app.use((req, res, next) => {
  res.set('Content-Security-Policy', "default-src 'self'");
  next();
});

HTTP SECURITY HEADERS:

// Prevent clickjacking
app.use((req, res, next) => {
  res.set('X-Frame-Options', 'DENY'); // Don't allow framing
  res.set('X-Content-Type-Options', 'nosniff'); // Prevent MIME sniffing
  res.set('X-XSS-Protection', '1; mode=block'); // Block detected XSS
  res.set('Strict-Transport-Security', 'max-age=31536000'); // Force HTTPS
  next();
});

CORS (CROSS-ORIGIN RESOURCE SHARING)
Control which origins can access your API

// Only allow specific origins
app.use(cors({
  origin: ['https://trusted-site.com', 'https://another-site.com'],
  credentials: true,
  methods: ['GET', 'POST']
}));


================================================================================
7. DATABASE SECURITY
================================================================================

DATABASE VULNERABILITIES:

1. SQL INJECTION
Already covered

2. WEAK CREDENTIALS
Default username/password still active

Prevention:
- Change root password immediately
- Create user-specific accounts
- Use strong passwords
- Store credentials in .env file (not git)

3. UNENCRYPTED DATA
Passwords stored in plain text
Credit card data not encrypted

Prevention:
// Always hash passwords
const hashedPassword = await bcrypt.hash(password, 10);

// Encrypt sensitive data
const encrypted = encrypt(creditCardNumber);

// Use HTTPS for transit

4. EXCESSIVE PERMISSIONS
Database user has admin access
Can delete entire database

Prevention:
// Create limited user
CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'strong_password';
GRANT SELECT, INSERT, UPDATE ON mydb.* TO 'app_user'@'localhost';

// Application uses limited user
// Separate admin user for migrations

5. BACKUP VULNERABILITIES
Backups not encrypted
Backups not stored securely
Backups not tested

Prevention:
// Encrypted backup
mysqldump --all-databases --single-transaction | gzip | openssl enc -aes-256-cbc > backup.sql.gz.enc

// Store backup securely (S3 with encryption)
// Test restore regularly

6. NO AUDIT LOGGING
Can't detect who accessed what

Prevention:
// Enable query logging (performance impact!)
SET GLOBAL general_log = 'ON';

// Or use application-level logging
app.post('/api/users/:id', async (req, res) => {
  const user = await db.getUser(req.params.id);
  await db.audit.log({
    action: 'UPDATE',
    table: 'users',
    recordId: req.params.id,
    userId: req.user.id,
    timestamp: new Date()
  });
  // Continue update
});

7. UNPATCHED DATABASE
Old version with known vulnerabilities

Prevention:
- Update regularly
- Subscribe to security advisories
- Test updates in staging first

DATABASE CONNECTION SECURITY:

// SSL connection to database
const pool = new Pool({
  host: 'db.example.com',
  port: 5432,
  database: 'mydb',
  user: 'app_user',
  password: process.env.DB_PASSWORD,
  ssl: {
    rejectUnauthorized: true,
    ca: fs.readFileSync('ca-cert.pem'),
    key: fs.readFileSync('client-key.pem'),
    cert: fs.readFileSync('client-cert.pem')
  }
});

PRINCIPLE OF LEAST PRIVILEGE:

// Bad: App user is admin
GRANT ALL PRIVILEGES ON *.* TO 'app_user'@'localhost';

// Good: Specific permissions only
GRANT SELECT, INSERT, UPDATE ON mydb.* TO 'app_user'@'localhost';

// Better: Different users for different functions
GRANT SELECT ON mydb.* TO 'app_read'@'localhost';
GRANT INSERT, UPDATE, DELETE ON mydb.logs TO 'app_write'@'localhost';
GRANT ALL ON mydb.* TO 'app_admin'@'localhost'; // For migrations only

ENCRYPTION AT REST:

// Application-level encryption (before storing)
async function saveSecretData(userId, data) {
  const encrypted = encrypt(data, process.env.ENCRYPTION_KEY);
  await db.query(
    'INSERT INTO secrets (user_id, data) VALUES ($1, $2)',
    [userId, encrypted]
  );
}

// Database-level encryption (built-in)
// PostgreSQL: pgcrypto extension
CREATE EXTENSION pgcrypto;
INSERT INTO users (email, password) VALUES ('user@example.com', crypt('password', gen_salt('bf')));

// MySQL: Transparent Data Encryption (TDE)
-- Enable in my.cnf
early-plugin-load = keyring_file.so
keyring_file_data = /var/lib/mysql-keyring/keyring


================================================================================
8. API SECURITY
================================================================================

API VULNERABILITIES:

1. INSUFFICIENT AUTHENTICATION
No API key required
Weak API key generation

Prevention:
// Require API key for all endpoints
app.use((req, res, next) => {
  const apiKey = req.headers['x-api-key'];
  if (!apiKey || !isValidApiKey(apiKey)) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  next();
});

// Generate strong API key
function generateApiKey() {
  return crypto.randomBytes(32).toString('hex');
}

2. API KEY EXPOSURE
API key in code (uploaded to GitHub)
API key in browser (exposed in JavaScript)
API key in logs

Prevention:
// Store in environment variables
const apiKey = process.env.API_KEY;

// Regenerate if exposed
// Rotate API keys regularly

// Never log API keys
console.log('API Key:', apiKey); // BAD

// Use API gateway to remove keys from logs
// Backend doesn't see API key

3. RATE LIMITING NOT ENFORCED
Unlimited API calls
Enables brute force and scraping

Prevention:
// Rate limit per API key
const limiter = rateLimit({
  keyGenerator: (req) => req.headers['x-api-key'],
  windowMs: 60 * 1000,
  max: 100
});

app.use('/api/', limiter);

4. VERSIONING ISSUES
API v1 deprecated but still working with bugs
Breaking changes not handled

Prevention:
// Support multiple versions
app.get('/api/v1/users', (req, res) => { /* v1 */ });
app.get('/api/v2/users', (req, res) => { /* v2 */ });

// Deprecation warning
app.get('/api/v1/users', (req, res) => {
  res.set('Deprecation', 'true');
  res.set('Sunset', 'Wed, 01 Jan 2025 00:00:00 GMT');
  // Return v1 data
});

5. SENSITIVE DATA IN RESPONSES
User passwords returned in API response
Personal information exposed

Prevention:
// Select only needed fields
app.get('/api/users/:id', async (req, res) => {
  const user = await db.query(
    'SELECT id, name, email FROM users WHERE id = $1',
    [req.params.id]
  );
  res.json(user);
});

// Or exclude sensitive fields
function safeUser(user) {
  const { password, ...safe } = user;
  return safe;
}

API AUTHENTICATION TYPES:

1. API KEY
Simplest but least secure
No expiration unless managed

// Add API key to header
const response = await fetch('/api/data', {
  headers: { 'X-API-Key': 'your-api-key' }
});

2. OAUTH 2.0
Industry standard
Third-party authentication

// Register with Google, GitHub, etc.
// User authorizes access
// Receive access token

3. JWT TOKENS
Stateless authentication
Expiration time

// Similar to session but token-based
const token = generateJWT(user);

4. MUTUAL TLS
Client and server both have certificates
Mutual authentication

// Require client certificate
https.createServer({
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),
  requestCert: true,
  rejectUnauthorized: true,
  ca: [fs.readFileSync('client-ca.pem')]
}, app);

API THROTTLING & QUOTAS:

// Limit by user tier
app.post('/api/process', (req, res) => {
  const user = req.user;
  const plan = getUserPlan(user);
  
  // Check quota
  const usage = await getMonthlyUsage(user.id);
  if (usage >= plan.requestLimit) {
    return res.status(429).json({ error: 'Quota exceeded' });
  }
  
  // Process request
});

WEBHOOK SECURITY:

// Verify webhook signature
app.post('/webhook', (req, res) => {
  const signature = req.headers['x-signature'];
  const payload = JSON.stringify(req.body);
  
  // Compute expected signature
  const expected = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET)
    .update(payload)
    .digest('hex');
  
  if (signature !== expected) {
    return res.status(401).json({ error: 'Invalid signature' });
  }
  
  // Process webhook
});


================================================================================
9. CLOUD SECURITY
================================================================================

CLOUD SECURITY LAYERS:

Physical → Network → Compute → Storage → Application

CLOUD PROVIDERS RESPONSIBILITY:

AWS, Azure, Google Cloud handle:
✅ Physical security
✅ Network infrastructure
✅ Hypervisor security
✅ Data center security

YOUR RESPONSIBILITY:
✅ Access control (IAM)
✅ Encryption (keys)
✅ Application security
✅ Data security

CLOUD SECURITY BEST PRACTICES:

1. IDENTITY & ACCESS MANAGEMENT (IAM)

Principle of least privilege:
// Bad: Overly permissive
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "*",
      "Resource": "*"
    }
  ]
}

// Good: Specific permissions
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "arn:aws:s3:::my-bucket/uploads/*"
    }
  ]
}

2. ENCRYPTION KEYS MANAGEMENT

// Bad: Encryption key in code
const key = 'my-secret-key';
const encrypted = encrypt(data, key);

// Good: Use key management service
const key = await kms.getKey('my-key-id');
const encrypted = await kms.encrypt(data, key);

AWS KMS (Key Management Service):
- Centralized key management
- Audit logging
- Automatic rotation
- Hardware security modules

3. NETWORK SECURITY

// Public subnets: Internet accessible
// Private subnets: Isolated, only internal access

// Security groups: Firewall rules
{
  "Inbound": [
    { "Protocol": "tcp", "Port": 443, "CIDR": "0.0.0.0/0" },  // HTTPS from anywhere
    { "Protocol": "tcp", "Port": 22, "CIDR": "10.0.0.0/8" }    // SSH from internal only
  ],
  "Outbound": [
    { "Protocol": "tcp", "Port": 443, "CIDR": "0.0.0.0/0" }    // HTTPS to anywhere
  ]
}

4. STORAGE SECURITY

// Encrypt data at rest
{
  "ServerSideEncryptionConfiguration": [
    {
      "Rules": [
        {
          "ApplyServerSideEncryptionByDefault": {
            "SSEAlgorithm": "AES256"
          }
        }
      ]
    }
  ]
}

// Control access
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::my-bucket/*",
      "Condition": {
        "StringEquals": {
          "aws:SourceVpc": "vpc-12345"
        }
      }
    }
  ]
}

5. LOGGING & MONITORING

// CloudTrail: Audit API calls
// CloudWatch: Monitor metrics and logs
// GuardDuty: Detect threats

Example CloudWatch alarm:
{
  "AlarmName": "HighAPIErrorRate",
  "MetricName": "4XXError",
  "Threshold": 100,
  "ComparisonOperator": "GreaterThanThreshold",
  "EvaluationPeriods": 2,
  "AlarmActions": ["arn:aws:sns:...send-alert"]
}

6. COMPLIANCE & GOVERNANCE

// Compliance frameworks
- SOC 2: Security, Availability, Integrity
- ISO 27001: Information security
- HIPAA: Healthcare data
- PCI DSS: Payment card data
- GDPR: European data protection

7. SECRETS MANAGEMENT

// Bad: Secrets in environment variables
process.env.DB_PASSWORD = 'password123';

// Good: Use secrets manager
const secret = await secretsManager.getSecret('db-password');

AWS Secrets Manager:
- Centralized storage
- Automatic rotation
- Audit logging
- Fine-grained access control

8. INFRASTRUCTURE AS CODE SECURITY

// Scan for vulnerabilities
terraform validate
terraform plan

// Use policy as code
# Enforce encryption
resource "aws_s3_bucket" "myBucket" {
  bucket = "my-bucket"
  
  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm = "AES256"  # Required
      }
    }
  }
}


================================================================================
10. INCIDENT RESPONSE
================================================================================

INCIDENT RESPONSE PLAN:

PREPARATION:
- Incident response team
- Communication plan
- Tools and resources
- Training

DETECTION & ANALYSIS:
- Detect security incident
- Confirm it's real (not false alarm)
- Assess severity
- Preserve evidence

CONTAINMENT:
- Short-term: Prevent further damage
  - Isolate affected systems
  - Disable compromised accounts
  - Block attacker IP
  
- Long-term: Remove malware
  - Patch vulnerability
  - Reset passwords
  - Clean system

ERADICATION:
- Remove root cause
- Patch all systems
- Change all credentials
- Verify malware removed

RECOVERY:
- Restore from backup
- Rebuild systems
- Restore data
- Verify integrity

POST-INCIDENT:
- Investigate what happened
- Document findings
- Improve processes
- Communicate lessons learned

INCIDENT SEVERITY LEVELS:

CRITICAL (Red):
- Data breach with personal information
- System completely compromised
- Active ransomware
- Requires immediate action

HIGH (Orange):
- Potential data exposure
- Multiple systems compromised
- Attackers still present
- Requires urgent action

MEDIUM (Yellow):
- Limited systems affected
- No confirmed data loss
- Isolated incident
- Requires timely action

LOW (Green):
- Single system or account
- Unsuccessful attack attempt
- No impact on data
- Routine response

FORENSICS & EVIDENCE:

// Preserve evidence
- Don't power off compromised system (data loss!)
- Disconnect network (prevent attacker from doing more damage)
- Take memory dump
- Image hard drive
- Collect logs
- Document everything

// Timeline of attack
12:34 - Unusual login from IP 1.2.3.4
12:45 - Access to sensitive files
13:00 - Data exfiltration to external server
13:15 - Malware installation detected
14:00 - Account disabled

THREAT HUNTING:
Actively search for indicators of compromise (IOCs)

// Indicators of compromise
- Unusual network traffic
- Failed login attempts
- Privilege escalation attempts
- Suspicious processes
- Unusual file modifications

// Hunt example
SELECT * FROM logs
WHERE 
  action = 'login_failed'
  AND timestamp > NOW() - INTERVAL 24 HOUR
GROUP BY source_ip
HAVING COUNT(*) > 10;


================================================================================
11. COMPLIANCE & STANDARDS
================================================================================

WHY COMPLIANCE?
Legal requirement
Customer trust
Security best practices
Insurance requirements

MAJOR STANDARDS:

1. GDPR (General Data Protection Regulation)
European data protection law

Key requirements:
- Explicit consent for data processing
- Right to data access
- Right to be forgotten
- Data portability
- Breach notification (72 hours)
- Privacy by design
- Data protection officer

Implementation:
// Get explicit consent
app.post('/register', (req, res) => {
  if (!req.body.acceptPrivacy) {
    return res.status(400).json({ error: 'Privacy policy required' });
  }
  // Store consent timestamp and version
  await db.user.create({
    email: req.body.email,
    consentVersion: PRIVACY_POLICY_VERSION,
    consentTime: new Date()
  });
});

// Allow data access
app.get('/my-data', authenticate, async (req, res) => {
  const data = await db.query(
    'SELECT * FROM user_data WHERE user_id = $1',
    [req.user.id]
  );
  res.json(data);
});

// Allow data deletion
app.delete('/my-data', authenticate, async (req, res) => {
  await db.query('DELETE FROM user_data WHERE user_id = $1', [req.user.id]);
  res.json({ message: 'Data deleted' });
});

// Breach notification
if (breachDetected) {
  notifyUsers24Hours();  // Notify within 72 hours
  notifyRegulator24Hours();  // Notify regulator
}

2. CCPA (California Consumer Privacy Act)
US data protection law (California)

Similar to GDPR:
- Right to know
- Right to delete
- Right to opt-out
- Do not sell data

3. HIPAA (Health Insurance Portability & Accountability Act)
Healthcare data protection (US)

Requirements:
- Encrypt data
- Access controls
- Audit logging
- Breach notification
- Business associate agreements

4. PCI DSS (Payment Card Industry Data Security Standard)
Credit card data protection

Requirements:
- Network security
- Data protection
- Vulnerability management
- Access control
- Monitoring & testing
- Information security policy

Example compliance:
- Level 1: 6M+ transactions/year
  - Regular vulnerability scans
  - Penetration testing
  - On-site audit
  
- Level 2-4: Fewer transactions
  - Self-assessment questionnaire
  - Vulnerability scans

Never store:
- Full credit card number
- CVV/CVC
- PIN
- Magnetic stripe data

5. SOC 2 (Service Organization Control)
Audit framework for service organizations

Types:
- Type 1: Point in time
- Type 2: Over time (6+ months)

Categories:
- Security: Protected from unauthorized access
- Availability: Systems available as committed
- Processing Integrity: Data processed accurately
- Confidentiality: Confidential information protected
- Privacy: Personal information handled per privacy notice

CERTIFICATION PROCESS:

1. Understand requirements
2. Implement controls
3. Document processes
4. Internal audit
5. External audit
6. Remediate findings
7. Certification issued
8. Maintain compliance

COMPLIANCE TOOLS:

- Compliance checklist
- Security policies
- Training programs
- Regular assessments
- Incident response plan


================================================================================
12. SECURITY TESTING
================================================================================

TYPES OF SECURITY TESTING:

1. PENETRATION TESTING
Authorized hacking to find vulnerabilities

Process:
1. Reconnaissance: Gather information
2. Scanning: Find open ports, services
3. Enumeration: Identify services, versions
4. Exploitation: Exploit vulnerabilities
5. Privilege escalation: Become admin
6. Covering tracks: Hide evidence
7. Reporting: Document findings

Tools:
- Nmap: Port scanning
- Metasploit: Exploitation framework
- Burp Suite: Web app testing
- Wireshark: Network traffic analysis

Example - Nmap scan:
nmap -sV -sC -A target.com

2. VULNERABILITY SCANNING
Automated scanning for known vulnerabilities

Tools:
- OWASP ZAP: Web application
- Qualys: Network
- Nessus: Network
- npm audit: Node.js dependencies

Example - npm audit:
npm audit

Output:
Found 5 vulnerabilities (2 high, 3 moderate)

Remediation:
npm audit fix

3. SECURITY CODE REVIEW
Manual code review for security issues

Focus on:
- Input validation
- Authentication/authorization
- Encryption
- Error handling
- Sensitive data logging
- Dependency vulnerabilities

Checklist:
✅ All inputs validated
✅ SQL injection prevented (parameterized queries)
✅ XSS prevented (output encoding)
✅ CSRF tokens present
✅ Passwords hashed
✅ Sensitive data not logged
✅ No hardcoded secrets
✅ Error messages don't leak info
✅ Dependencies up to date

4. STATIC APPLICATION SECURITY TESTING (SAST)
Analyze code without running it

Tools:
- SonarQube: Multi-language
- ESLint: JavaScript
- Bandit: Python
- Checkmarx: Enterprise

Example - ESLint security plugin:
// .eslintrc.json
{
  "plugins": ["security"],
  "extends": ["plugin:security/recommended"]
}

5. DYNAMIC APPLICATION SECURITY TESTING (DAST)
Test running application

Tools:
- OWASP ZAP
- Burp Suite
- Veracode

6. CONFIGURATION REVIEW
Check system configuration

Examples:
- SSL/TLS configuration
- Firewall rules
- Access control lists
- Password policies
- Logging configuration

Test SSL configuration:
# Check SSL/TLS
ssllabs.com/ssltest/analyze.html?d=example.com

Result: Grade A (excellent) to F (bad)

7. SOCIAL ENGINEERING TEST
Test human security awareness

Methods:
- Phishing emails
- Pretexting (social engineering)
- Physical security testing

Example:
- Send fake phishing email to employees
- Track who clicks
- Train those who fall for it

CONTINUOUS SECURITY TESTING:

// Run security tests on every commit
// GitHub Actions example
name: Security Tests
on: [push, pull_request]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Run npm audit
        run: npm audit
      
      - name: Run SAST
        run: npm run lint:security
      
      - name: Run DAST
        run: docker run owasp/zap:stable -t https://staging.example.com


================================================================================
13. SECURE CODING PRACTICES
================================================================================

INPUT VALIDATION

Never trust user input!

// Bad: Trust user input
app.post('/transfer', (req, res) => {
  const amount = req.body.amount;  // Could be negative, string, huge number
  transferMoney(amount);
});

// Good: Validate input
app.post('/transfer', (req, res) => {
  const amount = parseFloat(req.body.amount);
  
  if (isNaN(amount) || amount <= 0 || amount > 1000000) {
    return res.status(400).json({ error: 'Invalid amount' });
  }
  
  transferMoney(amount);
});

INPUT VALIDATION CHECKLIST:

✅ Type check (is it the right type?)
✅ Format check (is it the right format?)
✅ Range check (is it within acceptable range?)
✅ Length check (is it the right length?)
✅ Whitelist check (is it in list of allowed values?)

Example validation:
function validateUserInput(input) {
  // Type check
  if (typeof input.email !== 'string') {
    throw new Error('Email must be string');
  }
  
  // Format check
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.email)) {
    throw new Error('Invalid email format');
  }
  
  // Length check
  if (input.email.length > 255) {
    throw new Error('Email too long');
  }
  
  // Whitelist check - only alphanumeric + special chars
  if (!/^[a-zA-Z0-9@._+-]+$/.test(input.email)) {
    throw new Error('Invalid characters');
  }
  
  return true;
}

OUTPUT ENCODING

Prevent XSS by encoding output

// Bad: XSS vulnerability
res.send(`<p>${userComment}</p>`);

// Good: Escape HTML
const escaped = escapeHtml(userComment);
res.send(`<p>${escaped}</p>`);

// JavaScript encoding for attributes
const url = `javascript:alert('${userInput}')`;  // BAD

// URL encoding
const url = encodeURIComponent(userInput);

// JSON encoding for JavaScript
const jsonString = JSON.stringify(userData);
res.send(`<script>const data = ${jsonString};</script>`);

ERROR HANDLING

Don't expose system details!

// Bad: Leaks system info
app.get('/users/:id', (req, res) => {
  try {
    const user = db.query(`SELECT * FROM users WHERE id=${req.params.id}`);
    res.json(user);
  } catch (err) {
    res.status(500).send(err.toString());  // Shows detailed error
  }
});

// Good: Generic error message
app.get('/users/:id', (req, res) => {
  try {
    const user = db.query(`SELECT * FROM users WHERE id=$1`, [req.params.id]);
    res.json(user);
  } catch (err) {
    console.error(err);  // Log for debugging
    res.status(500).json({ error: 'Internal server error' });  // Generic message
  }
});

LOGGING

Log security events but not sensitive data

// Good: Log security events
function logSecurityEvent(event, details) {
  console.log(JSON.stringify({
    timestamp: new Date().toISOString(),
    event,
    userId: details.userId,
    action: details.action,
    ip: details.ip
  }));
}

// Bad: Logging sensitive data
console.log('User password:', password);  // NEVER
console.log('Credit card:', creditCard);   // NEVER

// Good: Don't log passwords/cards
console.log('User login attempt', {
  email: email,
  success: isValid,
  ip: req.ip
});

PARAMETERIZED QUERIES

Always use parameterized queries to prevent SQL injection

// Bad: SQL injection vulnerability
db.query(`SELECT * FROM users WHERE email='${email}'`);

// Good: Parameterized query
db.query('SELECT * FROM users WHERE email=$1', [email]);

// TypeScript-safe approach
interface User {
  id: number;
  email: string;
}

async function getUserByEmail(email: string): Promise<User | null> {
  const result = await db.query<User>(
    'SELECT * FROM users WHERE email=$1',
    [email]
  );
  return result.rows[0] || null;
}

SECURE DEFAULTS

// Bad: Insecure by default
const options = {
  debug: true,
  ssl: false,
  authentication: false
};

// Good: Secure by default
const options = {
  debug: false,
  ssl: true,
  authentication: true
};

NO HARDCODED SECRETS

// Bad: Secrets in code
const API_KEY = 'sk_test_abc123';
const DB_PASSWORD = 'MyPassword123';

// Good: Secrets in environment
const API_KEY = process.env.API_KEY;
const DB_PASSWORD = process.env.DB_PASSWORD;

// .env file (never commit to git)
API_KEY=sk_test_abc123
DB_PASSWORD=MyPassword123

// .gitignore
.env

PRINCIPLE OF LEAST PRIVILEGE

// Bad: Overly permissive
app.use(authenticate); // All endpoints require auth, but some should be public

// Good: Specific permissions
app.get('/public', (req, res) => res.json({}));  // Public

app.get('/api/data', authenticate, (req, res) => {  // Authenticated
  // Only this route requires auth
});

app.delete('/admin', authenticate, requireRole('admin'), (req, res) => {  // Admin
  // Only admins can delete
});

DEFENSE IN DEPTH

Multiple layers of security

Layer 1: Network
- Firewall
- DDoS protection
- VPN

Layer 2: Transport
- HTTPS/SSL/TLS

Layer 3: Authentication
- Username/password
- Multi-factor authentication

Layer 4: Authorization
- Role-based access control
- Attribute-based access control

Layer 5: Application
- Input validation
- Output encoding
- Rate limiting

Layer 6: Database
- Encrypted data
- Access control
- Audit logging


================================================================================
14. DEPLOYMENT SECURITY
================================================================================

SECURE DEPLOYMENT PROCESS:

1. BUILD SECURITY

// Scan dependencies for vulnerabilities
npm audit

// Use specific versions (not latest or *)
{
  "dependencies": {
    "express": "4.18.2",      // ✅ Specific version
    "axios": "^1.4.0"         // ✅ Minor version range
  }
}

// Remove unnecessary files from build
.dockerignore:
node_modules
npm-debug.log
.git
.env

2. IMAGE SECURITY (Docker)

// Use minimal base image
FROM node:20-alpine   // ✅ ~150MB

// Don't use latest tag
FROM node:latest      // ❌ Bad

// Run as non-root user
RUN adduser -S appuser
USER appuser

// Make filesystem read-only
RUN chmod -R 555 /app

// Scan image for vulnerabilities
docker scan myapp:1.0

3. CONFIGURATION MANAGEMENT

// Different config for different environments
// .env.development
NODE_ENV=development
DEBUG=true
LOG_LEVEL=debug

// .env.production
NODE_ENV=production
DEBUG=false
LOG_LEVEL=warn

// Load based on environment
const config = require(`./config.${process.env.NODE_ENV}.js`);

4. SECRETS MANAGEMENT

// Never commit secrets
// Use secrets manager
const secret = await secretsManager.getSecret('db-password');

// AWS Secrets Manager
aws secretsmanager create-secret --name prod/db/password --secret-string "password123"

// Kubernetes secrets
kubectl create secret generic db-credentials --from-literal=password=securepassword

// Rotate secrets regularly
// Audit secret access

5. DATABASE MIGRATIONS

// Always run migrations in transaction
BEGIN TRANSACTION;
ALTER TABLE users ADD COLUMN encrypted_data VARCHAR(255);
COMMIT;

// Rollback plan
ROLLBACK;

// Test migrations in staging first

6. HEALTH CHECKS & READINESS

// Liveness probe (is app running?)
app.get('/health/live', (req, res) => {
  res.json({ status: 'alive' });
});

// Readiness probe (is app ready to receive traffic?)
app.get('/health/ready', async (req, res) => {
  const dbHealth = await checkDatabase();
  const cacheHealth = await checkCache();
  
  if (!dbHealth || !cacheHealth) {
    return res.status(503).json({ status: 'not ready' });
  }
  
  res.json({ status: 'ready' });
});

// Kubernetes configuration
livenessProbe:
  httpGet:
    path: /health/live
    port: 8008
  initialDelaySeconds: 10
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /health/ready
    port: 8008
  initialDelaySeconds: 5
  periodSeconds: 5

7. DEPLOYMENT VALIDATION

// Security checklist before deploy
✅ All dependencies scanned for vulnerabilities
✅ Secrets not in code/logs
✅ SSL/TLS configured
✅ Database migrations tested
✅ Rate limiting enabled
✅ Logging enabled
✅ Monitoring enabled
✅ Health checks working
✅ Rollback plan documented
✅ Data backup confirmed

8. ZERO DOWNTIME DEPLOYMENT

// Blue-green deployment
Blue environment (current production)
Green environment (new version)

1. Deploy to green
2. Test green thoroughly
3. Switch traffic to green
4. Keep blue for rollback

// Rolling deployment (Kubernetes)
Gradually replace old pods with new ones
Maintain minimum availability

// Database changes
- Add column (backward compatible)
- Deploy code using new column
- Later: remove old column


================================================================================
15. MONITORING & DETECTION
================================================================================

SECURITY MONITORING:

1. LOG MONITORING

What to monitor:
- Authentication logs (login attempts, failures)
- Authorization logs (access denied events)
- Sensitive data access
- Configuration changes
- Audit logs

// Example: Monitor failed logins
SELECT COUNT(*) as failed_logins
FROM auth_logs
WHERE action = 'login_failed'
AND timestamp > NOW() - INTERVAL 1 HOUR
GROUP BY source_ip
HAVING COUNT(*) > 10;

2. ANOMALY DETECTION

Detect unusual patterns

Examples:
- User logging in from different country
- Bulk data download
- Access to sensitive tables
- New admin account created
- Massive file uploads

// Alert on anomaly
if (loginCountry !== usualCountry && loginCountry !== null) {
  sendSecurityAlert(`User ${user.id} logged in from new country: ${loginCountry}`);
  requireMFA = true;  // Force MFA
}

3. INTRUSION DETECTION

Detect attacks in progress

Indicators of compromise:
- Port scan activity
- Multiple login failures
- SQL injection attempts
- XSS payloads
- Privilege escalation attempts
- Unusual network traffic

// IDS signatures
if (url.includes("' OR '1'='1")) {
  // SQL injection attempt detected
  blockRequest();
}

if (payload.includes('<script>')) {
  // XSS attempt detected
  blockRequest();
}

4. SECURITY INFORMATION AND EVENT MANAGEMENT (SIEM)

Centralized logging and analysis

Features:
- Collect logs from all sources
- Correlate events
- Alert on patterns
- Generate reports
- Compliance reporting

Tools:
- Splunk
- ELK Stack (Elasticsearch, Logstash, Kibana)
- IBM QRadar
- Azure Sentinel

5. VULNERABILITY MANAGEMENT

Continuous vulnerability scanning

Process:
1. Scan for vulnerabilities
2. Prioritize by severity
3. Create tickets
4. Assign to team
5. Fix and verify
6. Document resolution

Scanning frequency:
- Production: Daily
- Staging: Weekly
- Development: Continuous

6. THREAT INTELLIGENCE

Subscribe to security feeds

What to monitor:
- Malware signatures
- Known exploit techniques
- Vulnerability disclosures
- Phishing campaigns
- APT (Advanced Persistent Threat) reports

Sources:
- NVD (National Vulnerability Database)
- CVE (Common Vulnerabilities and Exposures)
- Vendor advisories
- Security blogs


================================================================================
16. REAL-WORLD IMPLEMENTATIONS
================================================================================

COMPLETE SECURE APP EXAMPLE

src/app.ts:

import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import rateLimit from 'express-rate-limit';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { Pool } from 'pg';
import redis from 'redis';

// Helmet: Set security headers
app.use(helmet());

// CORS: Control cross-origin access
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(','),
  credentials: true
}));

// Rate limiting
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100,
  standardHeaders: true,
  legacyHeaders: false,
  skip: (req) => req.path === '/health'
});
app.use(limiter);

// Parse JSON
app.use(express.json({ limit: '1mb' }));

// Database pool
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: true } : false
});

// Redis client
const redisClient = redis.createClient({
  url: process.env.REDIS_URL
});

// Logger
function log(level: string, message: string, meta: any = {}) {
  console.log(JSON.stringify({
    timestamp: new Date().toISOString(),
    level,
    message,
    ...meta
  }));
}

// Authentication middleware
async function authenticateToken(req: any, res: any, next: any) {
  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    log('SECURITY', 'Missing authentication token', { ip: req.ip });
    return res.status(401).json({ error: 'Unauthorized' });
  }
  
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch (err) {
    log('SECURITY', 'Invalid token', { ip: req.ip });
    res.status(401).json({ error: 'Invalid token' });
  }
}

// Input validation
function validateEmail(email: string): boolean {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email) && email.length <= 255;
}

function validatePassword(password: string): boolean {
  return password.length >= 12 &&
         /[A-Z]/.test(password) &&
         /[a-z]/.test(password) &&
         /[0-9]/.test(password) &&
         /[!@#$%^&*]/.test(password);
}

// Register endpoint
app.post('/auth/register', async (req, res) => {
  try {
    const { email, password } = req.body;
    
    // Input validation
    if (!validateEmail(email)) {
      return res.status(400).json({ error: 'Invalid email' });
    }
    
    if (!validatePassword(password)) {
      return res.status(400).json({ error: 'Password too weak' });
    }
    
    // Check if user exists
    const existing = await pool.query(
      'SELECT id FROM users WHERE email = $1',
      [email]
    );
    
    if (existing.rows.length > 0) {
      return res.status(409).json({ error: 'User already exists' });
    }
    
    // Hash password
    const hashedPassword = await bcrypt.hash(password, 10);
    
    // Create user
    const result = await pool.query(
      'INSERT INTO users (email, password) VALUES ($1, $2) RETURNING id',
      [email, hashedPassword]
    );
    
    log('SECURITY', 'User registered', { userId: result.rows[0].id, email });
    
    res.json({ message: 'User registered successfully' });
  } catch (err) {
    log('ERROR', 'Registration error', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Login endpoint
app.post('/auth/login', async (req, res) => {
  try {
    const { email, password, otp } = req.body;
    
    // Check rate limit (login attempts)
    const loginAttempts = await redisClient.get(`login:${email}`);
    if (loginAttempts && parseInt(loginAttempts) > 5) {
      log('SECURITY', 'Account locked due to failed attempts', { email });
      return res.status(429).json({ error: 'Account locked' });
    }
    
    // Find user
    const result = await pool.query(
      'SELECT id, password FROM users WHERE email = $1',
      [email]
    );
    
    if (result.rows.length === 0) {
      await redisClient.incr(`login:${email}`);
      await redisClient.expire(`login:${email}`, 900); // 15 minutes
      log('SECURITY', 'Login failed - user not found', { email });
      return res.status(401).json({ error: 'Invalid credentials' });
    }
    
    const user = result.rows[0];
    
    // Verify password
    const validPassword = await bcrypt.compare(password, user.password);
    if (!validPassword) {
      await redisClient.incr(`login:${email}`);
      log('SECURITY', 'Login failed - invalid password', { email, userId: user.id });
      return res.status(401).json({ error: 'Invalid credentials' });
    }
    
    // Check MFA if enabled
    const mfaRequired = await pool.query(
      'SELECT mfa_enabled FROM users WHERE id = $1',
      [user.id]
    );
    
    if (mfaRequired.rows[0].mfa_enabled && !otp) {
      // Send OTP
      const otp = Math.floor(100000 + Math.random() * 900000).toString();
      await redisClient.set(`otp:${user.id}`, otp, 'EX', 300);
      // Send OTP via email/SMS
      log('SECURITY', 'OTP sent', { userId: user.id });
      return res.json({ message: 'OTP sent', requiresMFA: true });
    }
    
    // Verify OTP if required
    if (mfaRequired.rows[0].mfa_enabled) {
      const storedOtp = await redisClient.get(`otp:${user.id}`);
      if (otp !== storedOtp) {
        log('SECURITY', 'Invalid OTP', { userId: user.id });
        return res.status(401).json({ error: 'Invalid OTP' });
      }
      await redisClient.del(`otp:${user.id}`);
    }
    
    // Generate JWT
    const token = jwt.sign(
      { userId: user.id, email },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );
    
    // Clear login attempts
    await redisClient.del(`login:${email}`);
    
    log('SECURITY', 'User logged in', { userId: user.id, email });
    
    res.json({ token });
  } catch (err) {
    log('ERROR', 'Login error', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Protected endpoint
app.get('/api/data', authenticateToken, async (req, res) => {
  try {
    // Only return user's own data
    const result = await pool.query(
      'SELECT id, name FROM users WHERE id = $1',
      [req.user.userId]
    );
    
    if (result.rows.length === 0) {
      return res.status(404).json({ error: 'User not found' });
    }
    
    log('SECURITY', 'User accessed data', { userId: req.user.userId });
    
    res.json(result.rows[0]);
  } catch (err) {
    log('ERROR', 'API error', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Health check
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// Graceful shutdown
process.on('SIGTERM', async () => {
  log('INFO', 'Shutting down gracefully');
  await pool.end();
  await redisClient.quit();
  process.exit(0);
});

app.listen(8008, () => {
  log('INFO', 'Server started', { port: 8008 });
});

SECURITY CHECKLIST:

Pre-deployment:
✅ Dependencies scanned for vulnerabilities
✅ No secrets in code
✅ SSL/TLS configured
✅ Rate limiting enabled
✅ Input validation added
✅ Output encoding implemented
✅ Authentication implemented
✅ Authorization checks added
✅ Logging enabled
✅ Error messages generic
✅ Secrets in environment variables
✅ Database SSL enabled
✅ CORS configured properly
✅ Security headers set
✅ Health checks working

Post-deployment:
✅ Monitor logs for errors
✅ Check for security alerts
✅ Monitor CPU/memory
✅ Test with actual users
✅ Be ready to rollback


================================================================================
END OF CYBERSECURITY A TO Z GUIDE
================================================================================

You now have complete knowledge of cybersecurity from basics to production!

Key Takeaways:
✅ Understand threats and vulnerabilities
✅ Implement defense in depth (multiple layers)
✅ Use strong authentication and authorization
✅ Validate all input, encode all output
✅ Encrypt data in transit and at rest
✅ Monitor continuously for threats
✅ Regular security testing
✅ Incident response plan ready
✅ Keep software updated
✅ Follow compliance standards

Security Journey:
Understand Basics → Learn Common Attacks → Implement Defenses → Build Secure Apps → Monitor & Respond → Continuous Improvement

Remember: Security is not a product, it's a process!

Happy Securing! 🔒

Comments

Popular posts from this blog

VERTICAL SCALING 💋

prisma using in project idx 13.3