Secure Coding Examples

 Secure coding refers to the practice of writing software in a way that minimizes security vulnerabilities. Below are examples of secure coding practices in different contexts.


1. Input Validation

Issue: Unvalidated input can lead to injection attacks (SQL injection, Cross-Site Scripting).
Solution: Always validate and sanitize user inputs.

Example: SQL Injection Prevention (Python with SQLAlchemy)

from sqlalchemy import create_engine, text

# Database connection
engine = create_engine('sqlite:///example.db')

# Unsafe query (never do this!)
# user_input = "'; DROP TABLE users; --"

# Secure query using parameterized queries
def get_user(username):
    query = text("SELECT * FROM users WHERE username = :username")
    with engine.connect() as connection:
        result = connection.execute(query, {"username": username})
        return result.fetchone()

username = "john_doe"
print(get_user(username))
  • Why secure: Parameterized queries prevent SQL injection.

2. Avoid Hardcoded Secrets

Issue: Hardcoding passwords, keys, or tokens makes them easily accessible.
Solution: Use environment variables or secret managers.

Example (Python - .env file with dotenv)

  1. Store credentials in a .env file:

    DB_PASSWORD=super_secure_password
    
  2. Load and use securely:

from dotenv import load_dotenv
import os

# Load environment variables from .env file
load_dotenv()

db_password = os.getenv("DB_PASSWORD")
print("Database password loaded securely.")
  • Why secure: Secrets are not hardcoded in the codebase.

3. Encoding and Escaping Output

Issue: Unsanitized output can lead to Cross-Site Scripting (XSS).
Solution: Encode or escape user input before rendering in HTML.

Example (JavaScript - Escaping HTML)

function escapeHTML(str) {
  return str.replace(/[&<>"']/g, function (char) {
    const escape = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#039;'
    };
    return escape[char];
  });
}

let userInput = '<script>alert("XSS Attack!")</script>';
console.log(escapeHTML(userInput));
  • Why secure: This prevents the rendering of malicious scripts.

4. Secure Authentication

Issue: Weak passwords or insecure authentication mechanisms can be exploited.
Solution: Implement hashing, strong policies, and secure frameworks.

Example (Password Hashing with Bcrypt in Python)

import bcrypt

# Hash a password securely
password = "UserSecurePassword123"
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

print("Hashed Password:", hashed_password)

# Verify password
if bcrypt.checkpw(password.encode('utf-8'), hashed_password):
    print("Password matches!")
else:
    print("Password does not match.")
  • Why secure: Passwords are not stored in plain text. Hashing prevents exposure even if the database is compromised.

5. Principle of Least Privilege

Issue: Providing unnecessary access increases attack surfaces.
Solution: Limit permissions to the minimum required.

Example (Linux - Secure File Permissions)

# Create a file
touch secure_file.txt

# Restrict file permissions (owner read/write only)
chmod 600 secure_file.txt
  • Why secure: This ensures no unauthorized user can access the file.

6. Secure Communication (HTTPS/TLS)

Issue: Transmitting data over unencrypted channels exposes sensitive information.
Solution: Use HTTPS to encrypt communication.

Example (Python with Requests)

import requests

# Secure HTTPS request
url = "https://api.securewebsite.com/data"
response = requests.get(url)
if response.status_code == 200:
    print("Secure data retrieved:", response.json())
  • Why secure: Data transmitted over HTTPS is encrypted.

Summary of Key Practices

  1. Validate Input - Prevent injections.
  2. Secure Secrets - Use secret managers or .env files.
  3. Encode Output - Prevent XSS attacks.
  4. Hash Passwords - Avoid storing plain text passwords.
  5. Least Privilege - Grant only required access.
  6. Encrypt Communication - Use HTTPS/TLS for secure transmission.

By applying these secure coding principles, you can reduce vulnerabilities and protect your application from common attacks.

Comments

Popular posts from this blog

LiteSun Digital Timer Manual

Digital Advertising

Creating coloring pages from photo