Secure Coding Guidelines
This document provides essential guidelines for writing secure code to protect your applications and user data from common vulnerabilities.
1. Input Validation and Sanitization
Untrusted input is a primary source of vulnerabilities. Always validate and sanitize all external input.
- Validate Input: Ensure input conforms to expected types, formats, lengths, and ranges.
- Sanitize Output: Encode or escape data when it's displayed in different contexts (e.g., HTML, SQL) to prevent injection attacks.
- Use Whitelisting: Prefer allowing only known-good input over blacklisting known-bad input.
Example of input validation (conceptual):
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
if (!isValidEmail(userInput.email)) {
// Handle invalid input
displayError("Invalid email address provided.");
}
2. Authentication and Authorization
Properly managing user identity and permissions is crucial.
- Strong Passwords: Enforce strong password policies (complexity, length) and store password hashes securely (e.g., using bcrypt, Argon2).
- Multi-Factor Authentication (MFA): Implement MFA for sensitive operations or accounts.
- Principle of Least Privilege: Grant users and processes only the minimum permissions necessary to perform their tasks.
- Session Management: Securely manage user sessions, using random session IDs, setting appropriate timeouts, and regenerating session IDs upon login.
3. Data Protection
Protect sensitive data both in transit and at rest.
- Encryption in Transit: Use HTTPS (TLS/SSL) for all communication to encrypt data between the client and server.
- Encryption at Rest: Encrypt sensitive data stored in databases or files.
- Minimize Data Collection: Collect only the data that is absolutely necessary.
- Secure Key Management: Protect cryptographic keys meticulously.
4. Error Handling and Logging
Handle errors gracefully and log security-relevant events.
- Avoid Revealing Sensitive Information: Do not expose stack traces, database errors, or other internal details to end-users.
- Comprehensive Logging: Log security-relevant events such as login attempts (success/failure), access to sensitive data, and administrative actions.
- Log Tamper Protection: Ensure logs are protected against modification.
5. Secure Development Practices
Adopt secure coding practices throughout the development lifecycle.
- Stay Updated: Keep libraries, frameworks, and dependencies updated to patch known vulnerabilities.
- Code Reviews: Conduct thorough code reviews with a focus on security.
- Static and Dynamic Analysis: Utilize security scanning tools (SAST, DAST) to identify potential issues early.
- Secure Defaults: Configure your application and its components with secure settings by default.
- Sanitize User-Generated Content: When displaying user-generated content, always sanitize it to prevent XSS attacks.
Cross-Site Scripting (XSS) Prevention
XSS vulnerabilities allow attackers to inject malicious scripts into web pages viewed by other users.
Always encode or escape user-provided data before rendering it in HTML:
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
const userData = "<script>alert('XSS')</script>";
const safeOutput = escapeHtml(userData);
// safeOutput will be <script>alert('XSS')</script>
SQL Injection Prevention
SQL injection occurs when an attacker can manipulate SQL queries by inserting malicious SQL code into input fields.
Use parameterized queries or prepared statements:
// Example using a hypothetical database library
const userId = getUserInput(); // Potentially malicious input
// UNSAFE: Direct string concatenation
// const query = "SELECT * FROM users WHERE id = " + userId;
// SAFE: Using parameterized queries
const query = "SELECT * FROM users WHERE id = ?";
db.execute(query, [userId]);
6. Regular Security Audits
Periodically conduct security audits, penetration testing, and vulnerability assessments to identify and address weaknesses.
By adhering to these guidelines, you can significantly improve the security posture of your applications and protect your users.