What are XSS and SQL Injection Vulnerabilities?
Cross-Site Scripting (XSS): Allows the execution of malicious scripts in a user's browser, which can lead to information theft or manipulation of a page's content.
SQL Injection: This involves the manipulation of SQL queries through insecure input, which can allow unauthorized access to databases or the alteration of information.
XSS Prevention Example in JavaScript
This code shows how to sanitize user input to prevent XSS attacks:
function sanitizeInput(input) {
const temp = document.createElement("div");
temp.textContent = input;
return temp.innerHTML;
}
const userInput = "<script>alert('Hacked!')</script>";
const safeInput = sanitizeInput(userInput);
console.log(safeInput); // Safe output without script execution
By sanitizing input, we prevent the browser from executing malicious code.
SQL Injection Prevention Example in Python
This code shows how to run a secure query using parameters in SQLite:
import sqlite3
def get_user(user_id):
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
# Safe query using parameters
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
user = cursor.fetchone()
conn.close()
return user
# Safe usage
safe_user = get_user(1)
print(safe_user)
By using parameterized queries, we prevent malicious data from altering the SQL query.
Conclusion
Preventing vulnerabilities such as XSS and SQL injection is essential to ensuring application security. Implementing secure practices when handling input and queries significantly reduces the risk of attacks.