Get a Pentest and security assessment of your IT network.

Cyber Security

Secure Coding Basics

TL;DR

This guide covers essential coding practices to prevent common vulnerabilities like injection flaws, cross-site scripting (XSS), and broken authentication. It focuses on input validation, output encoding, secure storage, and proper session management.

1. Input Validation – The First Line of Defence

Never trust user input! Always validate data before using it in your application. This means checking the type, format, and length of the input to ensure it meets expected criteria.

  • Whitelisting vs Blacklisting: Prefer whitelisting (allowing only known good characters/patterns) over blacklisting (blocking known bad ones). Blacklists are easily bypassed.
  • Server-Side Validation: Client-side validation is helpful for user experience, but it’s not secure. Always perform validation on the server.
// Example in Python (using regular expressions)
import re

def validate_username(username):
  pattern = r'^[a-zA-Z0-9_]+$' # Only letters, numbers and underscores allowed
  if re.match(pattern, username):
    return True
  else:
    return False

2. Output Encoding – Preventing XSS

Cross-Site Scripting (XSS) occurs when malicious scripts are injected into your website. Encode user input before displaying it to prevent browsers from executing the script.

  • HTML Encoding: Use appropriate HTML encoding for different contexts (e.g., attributes, tags, text).
  • Context-Aware Encoding: The correct encoding depends on where you’re using the data. For example, JavaScript requires a different encoding than HTML.
// Example in PHP
<?php
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8'); // Encode for safe display in HTML ?>

3. Secure Storage – Protecting Sensitive Data

Protect sensitive data like passwords and API keys by storing them securely.

  • Hashing Passwords: Never store passwords in plain text. Use strong hashing algorithms (e.g., bcrypt, Argon2) with salts.
  • Salting: Add a unique random salt to each password before hashing. This prevents rainbow table attacks.
  • Encryption: Encrypt sensitive data at rest and in transit.
// Example using Python's hashlib library
import hashlib
salt = 'your_unique_salt'
hashed_password = hashlib.sha256((password + salt).encode('utf-8')).hexdigest()

4. Broken Authentication – Securing Login

Implement robust authentication mechanisms to prevent unauthorized access.

  • Strong Password Policies: Enforce minimum length, complexity requirements and regular password changes.
  • Multi-Factor Authentication (MFA): Add an extra layer of security by requiring users to provide multiple forms of identification.
  • Session Management: Use secure session IDs, set appropriate session timeouts, and regenerate session IDs after login.
// Example in JavaScript (setting a secure cookie)
document.cookie = "session_id=" + sessionId + "; path=/; secure; HttpOnly"; // 'secure' flag for HTTPS only, 'HttpOnly' prevents client-side script access

5. SQL Injection – Preventing Database Attacks

SQL injection occurs when malicious SQL code is inserted into your database queries.

  • Prepared Statements: Use prepared statements (parameterized queries) to separate data from the SQL code.
  • ORM Frameworks: Object-Relational Mapping (ORM) frameworks often provide built-in protection against SQL injection.
// Example using Python and a database library
cursor.execute("SELECT * FROM users WHERE username = %s", (username,)) // Parameterized query prevents SQL injection
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation