الأمن السيبراني
شرح حقن SQL: كيف تعمل وكيف تمنعها
افهم لماذا تُستغل الاستعلامات المبنية بدمج النصوص، وكيف تعالجها بالاستعلامات المهيّأة وقوائم السماح، وكيف تختبر تطبيقاتك بتفويض رسمي.
iTime Solutions 11 دقيقة قراءة
جزء من الدليل: دليل أمن الشبكات للمؤسسات: إطار عملي للشركات المصرية
SQL injection happens when an application builds a database query by pasting user input into the SQL text, so the database cannot tell where the developer's command ends and the user's data begins. An attacker who controls that input can change what the query does: read other records, bypass a login check, or modify data.
It has been understood for more than two decades, and it still ships in new code every week. This article explains the mechanism at a conceptual level, shows the vulnerable and safe patterns side by side, and gives you a checklist to test your own systems with authorisation.
Short answer: SQL injection works because user input is concatenated into SQL strings. You prevent it by using parameterised queries (prepared statements) for every value, allow-listing anything that cannot be a parameter such as column names, and giving the application's database account only the privileges it needs. Input filtering and a web application firewall are useful extra layers, not substitutes.
How does SQL injection actually work?
A database receives text and executes it. A login page might build this query from a username field:
# Python, vulnerable: do not do this
query = "SELECT id, role FROM users WHERE email = '" + email + "' AND password_hash = '" + pw_hash + "'"
cur.execute(query)
With a normal email, the database sees WHERE email = 'ahmed@example.com' AND .... But the code never checked what the email contained. If the value includes a quote character followed by SQL syntax, the quote closes the string literal early and whatever follows is parsed as SQL. The classic textbook illustration is a value like ' OR '1'='1, which turns the condition into one that is always true. The application meant to ask "does this user exist?" and instead asked "is anything true?".
That is the whole idea. Everything else in this field, from error-based extraction to blind techniques, is a variation on one theme: data crossed into the code channel. The cause is in the application, not in the database product. MySQL, PostgreSQL, SQL Server and Oracle are all affected equally if the code concatenates strings.
The impact depends on context. At the low end, an attacker reads rows they should not see. At the high end, a database account with excessive privileges lets them modify data, read files from the server, or pivot further into the network. The OWASP project ranks Injection fifth in its Top 10:2025, down from third in the previous edition, and records 62,445 CVEs in the category, with SQL injection alone accounting for more than 14,000 of them.
What types of SQL injection exist?
Knowing the types helps you recognise them in logs and in test reports. These are descriptions for defenders; none of them need exploit instructions to understand.
| Type | What the attacker observes | How it shows up for defenders |
|---|---|---|
| In-band (error-based, union-based) | Results or database error messages appear directly in the page | SQL error text in responses, unusually large result sets |
| Blind (boolean or time-based) | No data shown; page behaviour or response time changes | Many near-identical requests from one source, odd delays |
| Out-of-band | Database makes a network request to an attacker-controlled host | Unexpected outbound DNS or HTTP from the database server |
| Second-order | Malicious input is stored safely, then used unsafely later | Hard to see in request logs; appears when a different feature reads the data |
Second-order injection is the one reviewers miss. A developer who parameterises the signup form feels safe, but another script later builds a report query from the stored username by concatenation. Parameterise every query, not just the ones near user input.
Where does it still hide in modern applications?
New projects rarely write a raw login query like the one above. The vulnerabilities that remain tend to sit in a few predictable places:
- Search, filter and report screens with many optional conditions, where a developer assembles the WHERE clause in a loop.
- Sorting parameters such as
?sort=price&dir=descpassed straight into ORDER BY. - Raw-query escape hatches in frameworks and ORMs:
whereRaw,DB::raw,Model.objects.raw,text()and similar, used with string interpolation. - Legacy and custom code bolted onto an ERP, CMS or plugin, especially old PHP using
mysql_*or string-builtmysqli_querycalls. - Stored procedures that build dynamic SQL inside the procedure from their arguments.
- Internal tools written quickly, never reviewed, and assumed safe because "only staff use it".
How do you prevent SQL injection? Parameterised queries
The primary defence is to keep the query structure and the data on separate channels. You send the SQL with placeholders, then send the values separately. The database compiles the structure first, so a value can never become syntax, whatever characters it contains. The OWASP SQL Injection Prevention Cheat Sheet lists this as the first and most important defence.
The same login query, fixed (Python 3 with the standard sqlite3 module; psycopg uses %s placeholders, but the principle is identical):
# Python, safe: value is bound, not concatenated
cur.execute(
"SELECT id, role FROM users WHERE email = ? AND password_hash = ?",
(email, pw_hash),
)
In PHP with PDO (PHP 8.x), use named placeholders and turn off emulated prepares so the driver sends real prepared statements to MySQL:
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
]);
$stmt = $pdo->prepare('SELECT id, role FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
In Laravel, the query builder and Eloquent bind values for you. Problems appear when you use raw fragments, so pass bindings explicitly:
// Laravel 10/11: safe, with a binding
$rows = DB::select('SELECT id, name FROM customers WHERE city = ? AND active = ?', [$city, 1]);
// Also safe
$rows = Customer::whereRaw('LOWER(name) LIKE ?', ['%' . strtolower($term) . '%'])->get();
In Java the equivalent is PreparedStatement with ? placeholders; in .NET it is SqlCommand with Parameters.AddWithValue or typed parameters. If you are reviewing a codebase, the grep target is easy: look for SQL keywords next to string concatenation or interpolation, and treat each hit as a finding until proved otherwise.
What can parameters not protect?
Placeholders bind values only. You cannot bind a table name, a column name or a sort direction. For those, map the user's choice to a fixed value that your code owns:
// PHP: allow-list for ORDER BY
$sortable = ['price' => 'price', 'name' => 'name', 'date' => 'created_at'];
$col = $sortable[$_GET['sort'] ?? ''] ?? 'created_at';
$dir = (($_GET['dir'] ?? '') === 'desc') ? 'DESC' : 'ASC';
$stmt = $pdo->prepare("SELECT id, name, price FROM products WHERE category_id = :c ORDER BY $col $dir");
$stmt->execute(['c' => $categoryId]);
Here $col and $dir can only be values from your own list, so interpolating them is safe. The same applies to lists in IN (...): generate one placeholder per item, then bind the array, rather than joining the values into a string.
Two more caveats from the OWASP guidance. First, stored procedures are not automatically safe. If the procedure builds a dynamic SQL string by concatenating its arguments, it is just as injectable as application code. Second, escaping functions are a weak last resort; dialect and character-set differences make them easy to get wrong, which is why the cheat sheet discourages manual escaping.
What other layers reduce the damage?
Treat parameterisation as the fix and the following as limits on the blast radius if you miss something.
- Least privilege for the database account. A web application account needs SELECT, INSERT, UPDATE and DELETE on its own schema, not DBA rights, not access to other databases, and not file-read or command-execution privileges. Use a separate account per application. If injection happens, the attacker inherits only what that account can do. OWASP is blunt about this: do not give application accounts admin-type access.
- Generic error messages. Show users "something went wrong" with a reference ID, and log the SQL error server-side. Detailed database errors in the browser are a gift to an attacker.
- Input validation. Validate type, length and format (an ID is an integer, a date is a date). This catches mistakes and shrinks the attack surface but does not replace binding.
- Network position. The database should not be reachable from the internet or from user workstations. Only the application servers need access, on the database port, from a fixed address range. See our guide to network security fundamentals for how that segmentation is laid out.
- A web application firewall. A WAF with the OWASP Core Rule Set can block common attack patterns and buy time while you patch. It is not a fix: attackers vary encodings, and a WAF does not know which of your parameters are used in queries.
- Patching and dependencies. Many real-world injection flaws are in third-party plugins and old CMS components, not in your own code. Keep them updated and remove plugins you do not use.
The right combination depends on your stack, but the order of value is stable: parameters first, privileges second, network isolation third, WAF and monitoring after that.
How do you test your own application for SQL injection?
Only test systems you own or have written authorisation to test, and prefer a staging copy with synthetic data. Testing a production system, or anyone else's, without permission can be a criminal offence under Egypt's cybercrime legislation and under comparable laws elsewhere.
A sensible testing programme combines several approaches:
- Code review and static analysis (SAST): search for concatenated SQL and flag raw-query calls. This finds issues before they run.
- Dynamic scanning (DAST): point a scanner such as OWASP ZAP at your staging site to probe parameters automatically. Treat a clean result as "no obvious findings", not a guarantee.
- Manual review of risky features: search screens, report builders, export functions and any admin tool that accepts free-form filters.
- Penetration testing: an independent test, scoped and authorised in writing, for anything that holds customer or financial data. Our explanation of vulnerability assessment versus penetration testing helps you decide what to commission, and the phases of a penetration test shows what the process looks like.
- Pipeline checks: OWASP recommends adding SAST, DAST and IAST tools to CI/CD so flaws are caught before deployment.
How do you spot SQL injection attempts in your logs?
You will not always catch a successful attack, but you can often see the probing. Look at web server, WAF and database logs for:
- A burst of HTTP 500 responses or database syntax errors from a single address.
- Requests where parameters contain quote characters, SQL keywords, comment markers or unusually long values.
- Many near-identical requests with small variations, typical of automated tools.
- Responses that suddenly return far more data than usual, or queries from the application account that touch tables the application never normally reads.
- Outbound connections from the database server to the internet, which should be rare.
A SIEM or log platform makes these searchable; see how SIEM works and building monitoring with Wazuh. Set the database to log failed statements and slow queries, and alert when the application account starts failing with syntax errors.
If you confirm exploitation, treat it as a data incident. Isolate the application, preserve logs, rotate every credential stored in the database or in the application's configuration, and review whether personal data was exposed. Under Egypt's Personal Data Protection Law No. 151 of 2020, that may trigger a notification duty, so involve legal counsel early. The wider response sequence is covered in our incident response guide.
The video below is from the Computerphile channel on YouTube: "Hacking Websites with SQL Injection".

What to do next
- List every application and plugin that talks to a database, including ERP add-ons, internal tools and old PHP sites.
- Search each codebase for SQL built from strings and fix those queries with bound parameters. Start with login, search and anything public.
- Check the database account each application uses and remove every privilege it does not need.
- Make sure the database is not reachable from outside the application servers, and turn off detailed errors in production.
- Add SAST and DAST to your build pipeline and schedule an authorised penetration test for the public-facing systems.
SQL injection is one item in a broader programme; our enterprise network security guide shows where it fits, and the OWASP Top 10 overview covers its neighbours. iTime Solutions builds and secures web platforms and ERP integrations for companies in Egypt; if you want a review of an existing application or a secure build from the start, see our web development service or contact us.
References and further reading
أسئلة وأجوبة
هل يكفي استخدام ORM لمنع حقن SQL؟
يساعد الـ ORM لأنه يربط القيم تلقائياً في الاستخدام العادي، لكنه لا يحمي دوال الاستعلام الخام مثل whereRaw وDB::raw وraw() إذا بنيت النص بنفسك، ولا يهيّئ أسماء الأعمدة أو اتجاه الترتيب. راجع كل استدعاء خام ومرّر القيم كمعاملات مربوطة واستخدم قائمة سماح للمعرّفات.
هل يوقف جدار حماية تطبيقات الويب (WAF) حقن SQL؟
يحجب الـ WAF كثيراً من أنماط الهجوم الشائعة ويمنحك وقتاً لإصلاح الثغرة، لكنه ليس الحل. فالمهاجمون يغيّرون الترميز وشكل الطلبات، والـ WAF لا يعرف أي المعاملات تصل إلى استعلاماتك. أصلح الكود بالاستعلامات المهيّأة واعتبر الـ WAF طبقة إضافية مع المراقبة.
هل الإجراءات المخزنة (Stored Procedures) آمنة من حقن SQL؟
تكون آمنة فقط إذا استخدمت SQL ثابتاً أو ربطت القيم داخلها. الإجراء الذي يبني نص SQL ديناميكياً بدمج المعاملات قابل للحقن مثل كود التطبيق تماماً، حتى لو استدعاه التطبيق بمعامل. راجع جسم الإجراء وليس مكان الاستدعاء فقط.
هل يجوز قانونياً اختبار موقعي بحثاً عن حقن SQL؟
نعم، إذا كنت مالك النظام أو لديك تفويض كتابي من المالك ونطاق واضح للاختبار. يُفضّل استخدام نسخة تجريبية ببيانات وهمية والاتفاق على التوقيت مع مزود الاستضافة. أما اختبار نظام يخص الغير دون إذن فقد يُعد جريمة مهما كانت النية.
هل يكفي تهريب الرموز الخاصة أو تصفية المدخلات للحماية؟
ليس وحده. تختلف قواعد التهريب بين قواعد البيانات ومجموعات الأحرف ويسهل الخطأ فيها، وقوائم الكلمات الممنوعة يتم تجاوزها باستمرار. التحقق من المدخلات مفيد لرفض البيانات المشوهة، لكن الضابط الموثوق هو ربط القيم عبر المعاملات حتى لا تتحول البيانات إلى جزء من صيغة SQL.