Overview
Security is a critical aspect of system design. It is essential to protect the system from unauthorized access, data breaches, and other security threats. In this guide, we’ll explore key security concepts and best practices that you should consider when designing a system.Encryption Fundamentals
Symmetric Encryption
A single key is used for both encryption and decryption: Characteristics:- Same key encrypts and decrypts data
- Much faster than asymmetric encryption
- Suitable for bulk data encryption
- Key distribution is challenging
- AES (Advanced Encryption Standard) - most widely used
- DES (Data Encryption Standard) - legacy, now considered insecure
- 3DES (Triple DES) - more secure than DES
- ChaCha20 - modern alternative to AES
- Encrypting large amounts of data
- Disk encryption
- Database encryption
- Encrypting PII (Personally Identifiable Information)
Asymmetric Encryption
Uses a pair of keys: public key and private key: Characteristics:- Public key encrypts, private key decrypts
- More secure - private key never shared
- Slower due to complex mathematical operations
- Solves key distribution problem
- RSA - most widely used
- ECC (Elliptic Curve Cryptography) - more efficient than RSA
- DSA (Digital Signature Algorithm)
- Diffie-Hellman - for key exchange
- HTTPS/TLS handshake
- Digital signatures
- SSH authentication
- Email encryption (PGP/GPG)
Authentication and Authorization
Authentication Methods
1. Password-Based Authentication- Most common but weakest form
- Must use strong password policies
- Always hash passwords (bcrypt, Argon2, scrypt)
- Never store passwords in plain text
- Something you know (password)
- Something you have (phone, token)
- Something you are (biometrics)
- Dramatically increases security
- JWT (JSON Web Tokens)
- OAuth tokens
- Session tokens
- API keys
- Fingerprint
- Face recognition
- Voice recognition
- Iris scan
- TLS client certificates
- Mutual TLS (mTLS)
- Used in service-to-service communication
Authorization Patterns
Role-Based Access Control (RBAC)- Assign permissions to roles
- Assign roles to users
- Simple and widely used
- Example: Admin, Editor, Viewer roles
- Permissions based on attributes
- More flexible than RBAC
- Can consider context (time, location, etc.)
- More complex to implement
- Specify permissions for each resource
- Fine-grained control
- Can become complex at scale
Session Management
Session vs JWT vs OAuth
Session-Based AuthenticationCons: Requires server-side storage, doesn’t scale horizontally easily JWT (JSON Web Token)
Cons: Cannot easily revoke, larger payload, token theft concerns OAuth 2.0
- Industry standard for authorization
- Allows third-party access without sharing credentials
- Multiple grant types (authorization code, implicit, client credentials)
- Used by Google, Facebook, GitHub for login
Common Security Threats
Injection Attacks
SQL Injection- Attacker inserts malicious SQL code
- Prevention: Use parameterized queries, ORMs
- Example:
' OR '1'='1to bypass authentication
- Similar to SQL injection but for NoSQL databases
- Prevention: Validate and sanitize input, use query builders
- Attacker executes system commands
- Prevention: Avoid system calls with user input, use whitelisting
Cross-Site Scripting (XSS)
Types:- Stored XSS: Malicious script stored in database
- Reflected XSS: Script in URL parameters
- DOM-based XSS: Script manipulates DOM directly
- Sanitize user input
- Encode output
- Use Content Security Policy (CSP) headers
- Use frameworks with built-in XSS protection
Cross-Site Request Forgery (CSRF)
- Attacker tricks user into performing unwanted actions
- Prevention:
- CSRF tokens
- SameSite cookie attribute
- Verify Origin/Referer headers
- Re-authentication for sensitive operations
Distributed Denial of Service (DDoS)
- Overwhelm system with traffic
- Prevention:
- Rate limiting
- Web Application Firewall (WAF)
- CDN with DDoS protection
- Auto-scaling
- Geo-blocking
Man-in-the-Middle (MITM)
- Attacker intercepts communication
- Prevention:
- Use HTTPS everywhere
- Certificate pinning
- HSTS (HTTP Strict Transport Security)
- Validate SSL certificates
API Security Best Practices
Use HTTPS
Always encrypt data in transit with TLS/SSL
Implement Rate Limiting
Prevent abuse and DDoS attacks
Validate Input
Never trust user input, validate and sanitize
Use API Keys
Authenticate API consumers
Implement OAuth 2.0
For third-party access delegation
Log and Monitor
Detect suspicious activity early
Version Your APIs
Deprecate insecure versions safely
Use CORS Properly
Control which domains can access your API
Data Protection
Data at Rest
- Encryption: Encrypt sensitive data in databases
- Key Management: Use dedicated key management services (AWS KMS, Azure Key Vault)
- Access Controls: Restrict who can access data
- Backups: Encrypt backups, test restore procedures
Data in Transit
- TLS/SSL: Encrypt all network communication
- VPN: Use VPNs for sensitive internal communication
- Certificate Management: Keep certificates up to date
- Perfect Forward Secrecy: Protect past communications if keys compromised
Data Masking and Tokenization
Data Masking- Hide sensitive data in non-production environments
- Replace real data with realistic fake data
- Preserve data format and relationships
- Replace sensitive data with non-sensitive tokens
- Store mapping in secure token vault
- Commonly used for credit card numbers
- More secure than encryption for some use cases
Security Headers
Protect web applications with HTTP security headers:Secure Password Storage
Best Practices:-
Use Strong Hashing Algorithms:
- bcrypt (recommended)
- Argon2 (newer, more secure)
- scrypt
- PBKDF2
-
Add Salt:
- Unique salt for each password
- Prevents rainbow table attacks
-
Use Proper Work Factor:
- Make hashing computationally expensive
- Slows down brute force attacks
-
Never Use:
- MD5 or SHA1 for passwords
- Simple encryption (passwords should be hashed, not encrypted)
- No salt or global salt
Security Monitoring and Incident Response
Security Monitoring
- Log all authentication attempts
- Monitor for unusual patterns
- Track API usage and anomalies
- Use intrusion detection systems (IDS)
- Implement Security Information and Event Management (SIEM)
Incident Response Plan
- Preparation: Have plan and tools ready
- Detection: Identify security incidents
- Containment: Limit damage
- Eradication: Remove threat
- Recovery: Restore normal operations
- Lessons Learned: Improve security posture
Related Guides
Explore security topics in depth:- How does HTTPS work?
- Symmetric vs Asymmetric Encryption
- OAuth 2.0 Explained
- JWT 101
- Session vs Token vs JWT vs SSO
- How to Store Passwords in Database
- Digital Signatures
- How to Design a Secure System
- Top 12 Tips for API Security
Security is not a one-time effort but an ongoing process. Stay updated with latest threats and best practices. Always follow the principle of least privilege and defense in depth.