Insecure Coding Examples
Below are examples of insecure code practices that expose applications to vulnerabilities. Each example highlights the issue and its consequences.
1. SQL Injection
Issue: Dynamic queries with unsanitized user input allow attackers to manipulate SQL statements.
Insecure Example (Python):
import sqlite3
def get_user(username):
conn = sqlite3.connect("example.db")
cursor = conn.cursor()
query = f"SELECT * FROM users WHERE username = '{username}'" # Bad practice!
cursor.execute(query)
return cursor.fetchone()
user_input = "'; DROP TABLE users; --" # Malicious input
print(get_user(user_input))
- Why insecure: The input is directly concatenated into the SQL query, allowing SQL injection (e.g., deleting tables or accessing unauthorized data).
2. Hardcoded Credentials
Issue: Hardcoding secrets like passwords exposes them if the code is leaked.
Insecure Example (Java):
public class DatabaseConfig {
public static void main(String[] args) {
String dbUsername = "admin";
String dbPassword = "password123"; // Hardcoded credential
System.out.println("Connecting to database...");
}
}
- Why insecure: Anyone with access to the code can view the credentials. If shared publicly, secrets are compromised.
3. Cross-Site Scripting (XSS)
Issue: Rendering unsanitized user input in a browser enables XSS attacks.
Insecure Example (HTML/JavaScript):
<!DOCTYPE html>
<html>
<body>
<h1>Welcome!</h1>
<script>
let userInput = prompt("Enter your name:");
document.write("Hello, " + userInput); // Bad practice: unsanitized input
</script>
</body>
</html>
Attack: An attacker inputs:
<script>alert('XSS Attack!');</script>
- Why insecure: The malicious script executes in the browser, leading to data theft, session hijacking, etc.
4. Improper Password Storage
Issue: Storing passwords in plain text is a severe security risk.
Insecure Example (Python):
users = {"admin": "password123"} # Password stored in plain text
def authenticate(username, password):
if users.get(username) == password:
print("Login successful!")
else:
print("Invalid credentials")
authenticate("admin", "password123")
- Why insecure: If attackers access the database, they can immediately read users' passwords.
5. Improper File Permissions
Issue: Incorrect file permissions can expose sensitive data to unauthorized users.
Insecure Example (Linux Bash):
# Create a file with world-readable permissions
touch secret.txt
chmod 777 secret.txt # Bad practice: Read/write/execute permissions for everyone
- Why insecure: Any user can view, edit, or delete the sensitive file.
6. Unencrypted Communication
Issue: Transmitting sensitive data over HTTP exposes it to interception.
Insecure Example (Python Requests):
import requests
url = "http://example.com/login" # Insecure HTTP
data = {"username": "user", "password": "pass123"}
response = requests.post(url, data=data)
print("Response:", response.text)
- Why insecure: Data sent over HTTP is not encrypted, allowing attackers to sniff passwords or other sensitive data.
7. Unrestricted File Uploads
Issue: Allowing any file type upload can lead to remote code execution.
Insecure Example (PHP):
<?php
if (isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'], "uploads/" . $_FILES['file']['name']); // No checks!
echo "File uploaded successfully!";
}
?>
- Why insecure: An attacker can upload a malicious
.phpscript, execute it, and take control of the server.
8. Using Weak Random Numbers for Security
Issue: Using weak random number generators compromises security tokens.
Insecure Example (Python):
import random
def generate_token():
return str(random.randint(100000, 999999)) # Predictable!
print("Token:", generate_token())
- Why insecure: Random tokens generated this way are predictable, enabling attackers to brute-force tokens.
9. Lack of Input Validation
Issue: Accepting any input allows unexpected behaviors or crashes.
Insecure Example (Python):
def process_input(age):
print(f"You are {int(age)} years old.") # No input validation
user_input = "abc" # Invalid input
process_input(user_input)
- Why insecure: Invalid input like "abc" can cause exceptions or unexpected program behavior.
10. Disabled Security Features
Issue: Developers sometimes disable security features for convenience.
Insecure Example (JavaScript - CORS):
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*"); // Allow all origins
next();
});
- Why insecure: This allows requests from any origin, increasing the risk of malicious requests.
Summary of Insecure Practices
- SQL Injection - Using unsanitized inputs in queries.
- Hardcoded Credentials - Embedding secrets in code.
- XSS - Rendering unsanitized user input.
- Plain Text Passwords - Storing passwords insecurely.
- Improper File Permissions - Overly broad file access.
- Unencrypted Communication - Transmitting sensitive data via HTTP.
- Unrestricted File Uploads - Allowing all file types without validation.
- Weak Random Numbers - Predictable security tokens.
- Lack of Input Validation - Accepting all user inputs.
- Disabled Security Features - Removing critical protections.
By recognizing and addressing these examples of insecure code, developers can significantly reduce vulnerabilities in their applications.
Comments
Post a Comment