SQL Injection

This commit is contained in:
PlexicusAI committed 2026-01-28 20:23:58 +00:00
1 parent 8a4f9f050b
commit b29ecdaaac
1 file changed
+31 -10
+31 -10
View File
@@ -13,23 +13,44 @@ if ($conn->connect_error) {
die("Conexión fallida: " . $conn->connect_error); die("Conexión fallida: " . $conn->connect_error);
} }
// Vulnerabilidad de SQL Injection /*
// El siguiente código es vulnerable a SQL Injection ya que el input del usuario se concatena directamente en la consulta SQL sin validación o sanitización. Brief analysis - ALEX:
This change fixes a SQL Injection vulnerability by using a parameterized prepared statement and strict validation of the 'id' parameter.
I will replace the concatenated SQL with a mysqli prepared statement binding the id as an integer; only index.php is modified.
*/
if(isset($_GET['id'])) { if(isset($_GET['id'])) {
$id = $_GET['id']; // Input del usuario tomado directamente desde la URL $id = $_GET['id']; // Input del usuario tomado directamente desde la URL
$sql = "SELECT * FROM usuarios WHERE id = $id"; // Vulnerable a SQL Injection
$result = $conn->query($sql);
if ($result->num_rows > 0) { // Whitelist/validate: allow only digits to prevent injection
while($row = $result->fetch_assoc()) { if (!preg_match('/^\d+$/', $id)) {
echo "id: " . $row["id"]. " - Nombre: " . $row["nombre"]. "<br>"; echo "Invalid id";
}
} else { } else {
echo "0 resultados"; $id_int = (int)$id;
// Use a prepared statement to avoid SQL injection
$stmt = $conn->prepare("SELECT id, nombre FROM usuarios WHERE id = ?");
if ($stmt) {
$stmt->bind_param("i", $id_int);
$stmt->execute();
$result = $stmt->get_result();
if ($result && $result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Nombre: " . $row["nombre"]. "<br>";
}
} else {
echo "0 resultados";
}
$stmt->close();
} else {
// Do not execute an unsafe query if prepare() failed
echo "Query preparation failed";
}
} }
} }
// Vulnerabilidad de Cross-Site Scripting (XSS)
// El siguiente código es vulnerable a XSS ya que imprime directamente en el HTML el contenido de una variable que puede ser manipulada por el usuario sin ninguna sanitización. // El siguiente código es vulnerable a XSS ya que imprime directamente en el HTML el contenido de una variable que puede ser manipulada por el usuario sin ninguna sanitización.
if(isset($_GET['mensaje'])) { if(isset($_GET['mensaje'])) {
$mensaje = $_GET['mensaje']; // Input del usuario susceptible a XSS $mensaje = $_GET['mensaje']; // Input del usuario susceptible a XSS