How to Prevent SQL Injection in PHP ?

p0qbke2.png


Hello dear members of TurkHackTeam,

How can you prevent the most commonly used SQL Injection attack in a system/project using PHP? I opened this topic to fully explain it to you, hoping it will be useful for you.

Firstly, what is SQL Injection? It is one of the most widespread and damaging web application security vulnerabilities. The most definitive and reliable way to protect against this vulnerability is to use parameterized SQL queries. Parameterized queries define SQL statements in advance, providing developers with easy usage and understanding. This allows us to process user inputs securely and prevent potential attacks.

Developers should avoid cleaning user inputs by removing special characters because such protections can lead to code tricks that attackers can bypass. To protect against SQL Injection attacks, developers should continue to use parameterized queries.

Here's an example of a parameterized SQL query:



Kod:
// Bağlantı kodları baz alınmamıştır.

// Parametreli SQL sorgusu
$kullaniciAdi = "kullanici123";
$sifre = "gizli123";
$sql = "SELECT * FROM kullanicilar WHERE kullanici_adi = :kullaniciAdi AND sifre = :sifre";

// Sorguyu hazırla
$stmt = $db->prepare($sql);

// Parametreleri bağla
$stmt->bindParam(":kullaniciAdi", $kullaniciAdi, PDO::PARAM_STR);
$stmt->bindParam(":sifre", $sifre, PDO::PARAM_STR);

// Sorguyu çalıştır
$stmt->execute();

// Sonuçları al
$sonuclar = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Sonuçların işlenmesi baz alınmamıştır.

Preventing SQL Injections in PHP

When coding web applications in any language, it is best to use parameterized SQL structures that provide protection against SQL Injection attacks, rather than accepting user inputs (GET/POST/Headers/Cookie) as unsafe and then cleaning these inputs. The following code represents a simple PHP application. This application can utilize GET or other HTTP methods and interacts with the MySQL database table "users."

Table: users
idusernamepasswordfirst_namelast_name
1akovskiniz$2y$10$1zvcD6d/YHBotnu20YY7FOKmSOrQxshznpOqwq2tWCI6k23e5vXG.AkovskinizTHT
2akovskiniztht$2y$10$wwF.H06rUN7PzXiVYJQIJeBkxrMaHYFK06DdRiVf2Y1WMOe2TDoLKArgeAkovskiniz

Kod:
<?php
/*
* 'id' parametresi girildiğinde bilgilerin hepsini görebiliriz
* Örnek - http://localhost/?id=1
*/

if (isset($_GET['id'])) {
    $id = $_GET['id'];

    $mysqli = new mysqli('localhost', 'dbuser', 'dbpasswd', 'sql_injection_example');
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }

    $sql = "SELECT username FROM users WHERE id = $id";
    if ($result = $mysqli->query($sql)) {
        while($obj = $result->fetch_object()) {
            print($obj->username);
        }
    }

    elseif($mysqli->error) {
        print($mysqli->error);
    }
}
?>


The problems in the code above are listed below, and addressing these issues will make the system more secure:

Input Validation
Issue Description: Although it is known that the user ID will always be a number, the code does not validate this input. While input validation does not prevent SQL Injection, it helps prevent misinterpretation of malicious user data by the database.
Solution: It is important to validate user input before processing the database query. Checking if the input value is a number helps enhance security.

Code Allows SQL Injection
Issue Description: The code directly includes user input (e.g., a GET parameter) in the SQL statement. This allows an attacker to perform SQL injection by sending a malicious query to the application's database.
Solution: Prefer to handle SQL queries containing user inputs with parameterized queries. Parameterized queries define sections of the SQL query that will not be affected by user inputs in advance.

Errors Are Displayed to Users
Issue Description: Displaying errors can provide information to attackers to develop a potential SQL Injection attack. Information such as database type and version can facilitate exploiting the SQL Injection vulnerability.
Solution: Avoid showing SQL errors to users. If error messages need to be displayed, use a generic error message that does not contain sensitive information.

Errors Are Not Logged
Issue Description: Error logs are important for identifying issues and preventing potential attacks. If database errors are not logged, you may miss important information sources that could help detect security vulnerabilities.
Solution: Instead of displaying database errors to users, securely log them to a file. This file should not be accessible via the web server. Logging errors to the PHP error log or another file is a good practice.

CONCLUSION
So, what you need to do is simple: parameterize SQL queries. This ensures that queries are secure and understandable. Parameterized queries are important for securely processing user inputs. When a query is defined, we use variables provided by the user as placeholders in the query. This allows the database to distinguish between user inputs and SQL commands, preventing attackers from performing SQL injection. Parameterized queries treat all user inputs as data and do not process them as commands.
Parameterized queries prevent SQL Injection vulnerabilities. Tools like PDO are effective in closing this vulnerability. PDO is easy to use, portable, and supports named parameters.


ctf0sk9.png


 
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.