Blog | G5 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.

// 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.

// 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.

// 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.

// 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.

// Example using Python and a database library
cursor.execute("SELECT * FROM users WHERE username = %s", (username,)) // Parameterized query prevents SQL injection
Exit mobile version