Secure Coding Guidelines

This document provides essential guidelines for writing secure code to protect your applications and user data from common vulnerabilities.

Tip: Security is not an afterthought. Integrate security practices throughout the entire development lifecycle.

1. Input Validation and Sanitization

Untrusted input is a primary source of vulnerabilities. Always validate and sanitize all external 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.

3. Data Protection

Protect sensitive data both in transit and at rest.

4. Error Handling and Logging

Handle errors gracefully and log security-relevant events.

Warning: Generic error messages like "An error occurred" can hinder debugging. Provide meaningful but non-revealing error messages to users, and log detailed information server-side.

5. Secure Development Practices

Adopt secure coding practices throughout the development lifecycle.

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 &lt;script&gt;alert('XSS')&lt;/script&gt;
            

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.