1---2name: secure-coding3description: OWASP secure coding practices, language-specific security considerations, input validation and output encoding, authentication and authorization patterns, cryptography best practices, secure API design, and common security anti-patterns4---5
6# Secure Coding
7
8## OWASP Secure Coding Practices
9
10### Input Validation
11
12- **Validate All Input**: Validate all input from untrusted sources (user input, APIs, files)
13- **Whitelist Approach**: Use whitelisting (allow-list) instead of blacklisting
14- **Validate Type, Length, Format**: Validate data type, length, and format
15- **Sanitize Output**: Encode output to prevent injection attacks
16- **Canonicalize Input**: Canonicalize input before validation to prevent bypasses
17
18### Output Encoding
19
20- **Context-Specific Encoding**: Use encoding appropriate for the context (HTML, JavaScript, URL, CSS)
21- **Encode User-Generated Content**: Encode all user-generated content before output
22- **Use Framework Encoding**: Use framework-provided encoding functions
23- **Avoid Manual Encoding**: Avoid manual encoding as it's error-prone
24
25### Authentication
26
27- **Strong Passwords**: Enforce strong password policies (length, complexity, rotation)
28- **Secure Password Storage**: Use strong, slow hashing algorithms (bcrypt, Argon2, scrypt)
29- **Multi-Factor Authentication**: Implement MFA for sensitive operations
30- **Secure Session Management**: Use secure, HTTP-only, SameSite cookies
31- **Session Expiration**: Implement appropriate session timeout
32- **Secure Password Reset**: Implement secure password reset mechanisms
33
34### Authorization
35
36- **Principle of Least Privilege**: Grant minimum necessary permissions
37- **Role-Based Access Control**: Implement RBAC for authorization
38- **Attribute-Based Access Control**: Consider ABAC for complex authorization
39- **Deny by Default**: Deny access by default, explicitly allow
40- **Check Authorization on Every Request**: Verify authorization on every request
41- **Avoid IDOR**: Prevent Insecure Direct Object References
42
43### Cryptography
44
45- **Use Standard Algorithms**: Use well-vetted, standard cryptographic algorithms
46- **Avoid Rolling Your Own Crypto**: Never implement custom cryptography
47- **Use Secure Key Management**: Properly generate, store, and rotate keys
48- **Use Authenticated Encryption**: Use authenticated encryption (AEAD) when possible
49- **Avoid Deprecated Algorithms**: Avoid MD5, SHA1, RC4, DES, etc.
50- **Use TLS**: Use TLS for all network communications
51
52### Error Handling
53
54- **Generic Error Messages**: Use generic error messages for users
55- **Detailed Logging**: Log detailed error information server-side
56- **Don't Leak Information**: Avoid leaking sensitive information in errors
57- **Handle Exceptions**: Properly handle exceptions to prevent information disclosure
58- **Custom Error Pages**: Use custom error pages to prevent information leakage
59
60## Language-Specific Security Considerations
61
62### JavaScript/TypeScript
63
64- **XSS Prevention**: Use frameworks with built-in XSS protection (React, Vue, Angular)
65- **Content Security Policy**: Implement CSP to mitigate XSS
66- **Avoid eval()**: Avoid using eval() and similar dynamic code execution
67- **Validate JSON**: Validate JSON input before parsing
68- **Use Strict Mode**: Use strict mode to catch common errors
69- **Sanitize HTML**: Use DOMPurify or similar libraries for HTML sanitization
70
71### Python
72
73- **SQL Injection**: Use parameterized queries or ORM
74- **Command Injection**: Avoid shell=True in subprocess calls
75- **Pickle Security**: Avoid unpickling untrusted data
76- **Template Injection**: Use secure template engines (Jinja2 auto-escaping)
77- **YAML Loading**: Use yaml.safe_load() instead of yaml.load()
78- **Input Validation**: Validate input using libraries like pydantic
79
80### Java
81
82- **SQL Injection**: Use PreparedStatement or JPA
83- **XSS Prevention**: Use OWASP ESAPI or framework-provided encoding
84- **Deserialization**: Avoid deserializing untrusted data
85- **XML Security**: Disable XML external entities (XXE)
86- **Path Traversal**: Validate file paths to prevent directory traversal
87- **Secure Random**: Use SecureRandom for cryptographic random numbers
88
89### Go
90
91- **SQL Injection**: Use prepared statements with sql package
92- **Path Traversal**: Use filepath.Join() and validate paths
93- **Command Injection**: Avoid shell commands, use exec package
94- **Template Injection**: Use html/template with auto-escaping
95- **Error Handling**: Always handle errors explicitly
96- **Input Validation**: Validate input before use
97
98### C/C++
99
100- **Buffer Overflows**: Use safe string functions (strncpy_s, snprintf)
101- **Memory Safety**: Use memory-safe alternatives when possible
102- **Integer Overflow**: Check for integer overflow before arithmetic
103- **Format String Vulnerabilities**: Avoid user-controlled format strings
104- **Use Safe Libraries**: Use safe string and memory libraries
105- **Static Analysis**: Use static analysis tools to catch issues
106
107### PHP
108
109- **SQL Injection**: Use PDO with prepared statements
110- **XSS Prevention**: Use htmlspecialchars() or framework escaping
111- **File Upload**: Validate and sanitize uploaded files
112- **Include Files**: Avoid user-controlled include files
113- **Type Juggling**: Be aware of PHP's type juggling
114- **Configuration**: Use secure configuration settings
115
116## Input Validation and Output Encoding
117
118### Input Validation Techniques
119
120- **Type Validation**: Validate data type (integer, string, date, etc.)
121- **Length Validation**: Validate minimum and maximum length
122- **Format Validation**: Validate format (email, phone, URL, etc.)
123- **Range Validation**: Validate numeric ranges
124- **Pattern Validation**: Use regex patterns for complex validation
125- **Business Rule Validation**: Validate against business rules
126
127### Output Encoding Contexts
128
129- **HTML Context**: Encode for HTML entities (<, >, &, ", ')
130- **JavaScript Context**: Encode for JavaScript strings
131- **URL Context**: Encode for URL parameters
132- **CSS Context**: Encode for CSS values
133- **Attribute Context**: Encode for HTML attributes
134
135### Encoding Libraries
136
137- **JavaScript**: DOMPurify, encodeURI(), encodeURIComponent()
138- **Python**: html.escape(), urllib.parse.quote()
139- **Java**: OWASP ESAPI, Apache Commons Text
140- **Go**: html.EscapeString(), url.QueryEscape()
141- **PHP**: htmlspecialchars(), urlencode()
142
143## Authentication and Authorization Patterns
144
145### Authentication Patterns
146
147- **Multi-Factor Authentication**: Require multiple factors for authentication
148- **Password Hashing**: Use bcrypt, Argon2, or scrypt for password hashing
149- **Password Policies**: Enforce strong password policies
150- **Account Lockout**: Implement account lockout after failed attempts
151- **Password Reset**: Implement secure password reset flows
152- **Session Management**: Use secure session management practices
153
154### Authorization Patterns
155
156- **Role-Based Access Control (RBAC)**: Assign permissions to roles, roles to users
157- **Attribute-Based Access Control (ABAC)**: Use attributes for fine-grained access control
158- **Access Control Lists (ACL)**: Define access rights for resources
159- **Capability-Based Security**: Use capabilities for access control
160- **Policy-Based Access Control**: Use policies for access decisions
161- **Hybrid Approaches**: Combine multiple authorization patterns
162
163### Session Management
164
165- **Secure Cookies**: Use secure, HTTP-only, SameSite cookies
166- **Session Expiration**: Implement appropriate session timeout
167- **Session Fixation**: Generate new session ID after authentication
168- **Session Storage**: Store session data securely
169- **Logout**: Implement proper logout functionality
170- **Concurrent Sessions**: Limit concurrent sessions if needed
171
172## Cryptography Best Practices
173
174### Encryption
175
176- **Use Standard Algorithms**: Use AES-256, ChaCha20-Poly1305, or similar
177- **Use Authenticated Encryption**: Prefer AEAD modes (GCM, CCM, ChaCha20-Poly1305)
178- **Key Management**: Use proper key management (HSM, KMS, key rotation)
179- **IV/Nonce**: Use unique IV/nonce for each encryption
180- **Key Derivation**: Use PBKDF2, Argon2, or scrypt for key derivation
181- **Avoid ECB Mode**: Never use ECB mode for encryption
182
183### Hashing
184
185- **Use Strong Hashes**: Use SHA-256 or stronger for general hashing
186- **Password Hashing**: Use bcrypt, Argon2, or scrypt for passwords
187- **Salt**: Use unique salt for each password hash
188- **Slow Hashing**: Use computationally expensive hashing for passwords
189- **Avoid MD5/SHA1**: Avoid MD5 and SHA1 for security purposes
190
191### Key Management
192
193- **Key Generation**: Use cryptographically secure random number generators
194- **Key Storage**: Store keys securely (HSM, KMS, encrypted at rest)
195- **Key Rotation**: Rotate keys regularly
196- **Key Separation**: Use different keys for different purposes
197- **Key Destruction**: Securely destroy keys when no longer needed
198- **Key Escrow**: Consider key escrow for recovery if needed
199
200### TLS/SSL
201
202- **Use TLS 1.3**: Prefer TLS 1.3 when available
203- **Strong Ciphers**: Use strong cipher suites
204- **Certificate Validation**: Always validate certificates
205- **HSTS**: Implement HTTP Strict Transport Security
206- **Perfect Forward Secrecy**: Use cipher suites with PFS
207- **Disable Weak Protocols**: Disable SSLv2, SSLv3, TLS 1.0, TLS 1.1
208
209## Secure API Design
210
211### API Security Best Practices
212
213- **Authentication**: Implement strong authentication (OAuth 2.0, JWT, API keys)
214- **Authorization**: Implement proper authorization for all endpoints
215- **Rate Limiting**: Implement rate limiting to prevent abuse
216- **Input Validation**: Validate all input to API endpoints
217- **Output Encoding**: Encode output appropriately
218- **Error Handling**: Use generic error messages, log details server-side
219- **HTTPS**: Always use HTTPS for API communication
220- **API Versioning**: Use versioning to manage breaking changes
221- **Documentation**: Document security considerations
222- **Monitoring**: Monitor API usage for anomalies
223
224### REST API Security
225
226- **Stateless**: Keep APIs stateless
227- **Resource-Based Design**: Design around resources
228- **HTTP Methods**: Use HTTP methods correctly (GET, POST, PUT, DELETE)
229- **Status Codes**: Use appropriate HTTP status codes
230- **Pagination**: Implement pagination for large datasets
231- **Filtering/Sorting**: Allow filtering and sorting
232- **CORS**: Configure CORS appropriately
233- **CSRF**: Implement CSRF protection for state-changing operations
234
235### GraphQL Security
236
237- **Query Depth Limiting**: Limit query depth to prevent DoS
238- **Query Complexity Limiting**: Limit query complexity
239- **Rate Limiting**: Implement rate limiting
240- **Authentication**: Implement authentication at the resolver level
241- **Authorization**: Implement authorization at the resolver level
242- **Introspection**: Disable introspection in production
243- **Field-Level Authorization**: Implement field-level authorization
244
245## Common Security Anti-Patterns
246
247### Code Anti-Patterns
248
249- **Hardcoded Secrets**: Never hardcode passwords, API keys, or tokens
250- **SQL String Concatenation**: Never concatenate SQL strings
251- **Shell Command Concatenation**: Never concatenate shell commands
252- **eval() Usage**: Avoid using eval() or similar functions
253- **Trust Client-Side Validation**: Never trust client-side validation
254- **Ignore Error Messages**: Don't ignore error messages
255- **Roll Your Own Crypto**: Never implement custom cryptography
256
257### Configuration Anti-Patterns
258
259- **Default Credentials**: Never use default credentials in production
260- **Debug Mode**: Never enable debug mode in production
261- **Verbose Error Messages**: Don't expose detailed errors to users
262- **Insecure Defaults**: Don't use insecure default configurations
263- **Unnecessary Services**: Don't run unnecessary services
264- **Open Ports**: Don't expose unnecessary ports
265
266### Architecture Anti-Patterns
267
268- **Security Through Obscurity**: Never rely on obscurity for security
269- **Single Layer of Defense**: Never rely on a single security control
270- **Trust Boundaries**: Don't trust components across trust boundaries
271- **Assume Safe Input**: Never assume input is safe
272- **Ignore Logging**: Don't ignore security logging
273- **Skip Testing**: Never skip security testing
274
275### Development Anti-Patterns
276
277- **Skip Code Review**: Never skip security code reviews
278- **Ignore Dependencies**: Don't ignore dependency vulnerabilities
279- **Rush Deployment**: Don't rush deployments without testing
280- **Disable Security Controls**: Never disable security controls for convenience
281- **Ignore Alerts**: Don't ignore security alerts
282- **Assume It's Secure**: Never assume something is secure without verification