0% found this document useful (0 votes)
48 views6 pages

Pangolin SQL Injection Guide

SQL injection vulnerabilities occur when user-supplied input is inserted into SQL queries without proper validation or escaping. This allows attackers to alter and control the structure of SQL queries in order to view hidden data, make unauthorized changes, or in some cases, execute dangerous system commands on the database host. The document provides examples of how SQL injection can be used to create unauthorized user accounts, list passwords from tables, modify passwords and privileges, and even add a new system user on the host operating system. It recommends avoiding SQL injection by validating all user input, using prepared statements with bound parameters, escaping special characters in queries, and limiting the privileges of the database account used by the application.

Uploaded by

Eddy Purwoko
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views6 pages

Pangolin SQL Injection Guide

SQL injection vulnerabilities occur when user-supplied input is inserted into SQL queries without proper validation or escaping. This allows attackers to alter and control the structure of SQL queries in order to view hidden data, make unauthorized changes, or in some cases, execute dangerous system commands on the database host. The document provides examples of how SQL injection can be used to create unauthorized user accounts, list passwords from tables, modify passwords and privileges, and even add a new system user on the host operating system. It recommends avoiding SQL injection by validating all user input, using prepared statements with bound parameters, escaping special characters in queries, and limiting the privileges of the database account used by the application.

Uploaded by

Eddy Purwoko
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • SQL Injection Overview
  • Examples of SQL Injection
  • Avoidance Techniques
  • Advanced Techniques and Security Practices
  • Custom Security Script

SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands. Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build an SQL query. The following examples are based on true stories, unfortunately. Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database. Example #1 Splitting the result set into pages ... and making superusers (PostgreSQL)
<?php $offset = $argv[0]; // beware, no input validation! $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $off set;"; $result = pg_query($conn, $query); ?>

Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL
0; insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd) select 'crack', usesysid, 't','t','crack' from pg_shadow where usename='postgres'; --

If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it. Note: It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL. A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged. Example #2 Listing out articles ... and some passwords (any database server)

<?php = "SELECT id, name, inserted, size FROM products WHERE size = '$size' ORDER BY $order LIMIT $limit, $offset;"; $result = odbc_exec($conn, $query); $query ?>

The static part of the query can be combined with another SELECT statement which reveals all passwords:
' union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable; --

If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened. SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames. Example #3 From resetting a password ... to gaining more privileges (any database server)
<?php $query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';"; ?>

But a malicious user sumbits the value ' or uid like'%admin%'; -- to $uid to change the admin's password, or simply sets $pwd to "hehehe', admin='yes', trusted=100 " (with a trailing space) to gain more privileges. Then, the query will be twisted:
<?php // $uid == ' or uid like'%admin%'; -$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%' ; --"; // $pwd == "hehehe', admin='yes', trusted=100 " $query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE ...;"; ?>

A frightening example how operating system level commands can be accessed on some database hosts. Example #4 Attacking the database hosts operating system (MSSQL Server)
<?php $query = "SELECT * FROM products WHERE id LIKE '%$prod%'"; $result = mssql_query($query); ?>

If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:
<?php $query = "SELECT * FROM products WHERE id LIKE '%a%' exec master..xp_cmdshell 'net user test testpass /ADD'-

-"; $result = mssql_query($query); ?>

MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine. Note: Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.

Image courtesy of xkcd

Avoidance Techniques
While it remains obvious that an attacker must possess at least some knowledge of the database architecture in order to conduct a successful attack, obtaining this information is often very simple. For example, if the database is part of an open source or other publiclyavailable software package with a default installation, this information is completely open and available. This information may also be divulged by closed-source code - even if it's encoded, obfuscated, or compiled - and even by your very own code through the display of error messages. Other methods include the user of common table and column names. For example, a login form that uses a 'users' table with column names 'id', 'username', and 'password'. These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.

y y

Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges. Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support. If the application waits for numerical input, consider verifying data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf(). Example #5 A more secure way to compose a query for paging
<?php settype($offset, 'integer'); $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;"; // please note %d in the format string, using %s would be meaningless $query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 2 0 OFFSET %d;", $offset); ?>

Quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_real_escape_string(), sqlite_escape_string(), etc.). If a database-specific string escape mechanism is not available, the addslashes() and str_replace() functions may be useful (depending on database type). See the first example. As the example shows, adding quotes to the static part of the query is not enough, making this query easily crackable. Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions. You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less.

Error Reporting

Encrypted Storage Model

[edit] Last updated: Fri, 21 Oct 2011


add a note User Contributed Notes SQL Injection kirby4 at live dot ca 19-Feb-2011 10:35

A good way to counter SQL injection for queries of type SELECT is use hash function on data by PHP and the database server. For example, it is possible to use the MySQL function MD5 () to produce a hash of data-server side , and the equivalent function in php web-server side. <?php $login = mysql_query("select f_uname, f_passwd from t_user where MD5(f_uname) = '".md5($uname)."' and MD5(f_passwd)='".md5($passwd)."'"); ?> Thus, the injected requests will be crushed and it will become much more difficult to obtain data in the database. Use both sides of the hash result in a comparison of hash, not the execution of the injected queries. Unfortunately, it probably does not work with other types of queries.

smunday at visionaryweb dot com 17-Dec-2010 10:58


Another suggestion would be to build a series of DB procedures / functions that you give the DB user access to to manipulate or select data. That way, all input would run through this exposed interface and all parameters are forced to be typecast (or rejected).

Anonymous 27-Sep-2010 04:16


Pangolin is an automatic SQL injection penetration testing tool developed by NOSEC. Its goal is to detect and take advantage of SQL injection vulnerabilities on web applications. Once it detects one or more SQL injections on the target host, the user can choose among a variety of options to perform an extensive back-end database management system fingerprint, retrieve DBMS session user and database, enumerate users, password hashes, privileges, databases, dump entire or user"s specific DBMS tables/columns, run his own SQL statement, read specific files on the file system and more.

wang dot liang dot com at gmail dot com 11-Mar-2010 11:11
another way to stop sql injection when you odbc_*: create two users, one has only select permission, the other has only delete, update, and insert permission, so you can use select-only user to call odbc_exec while you don't have to check the sql injection; and you use d/u/i only user to update database by calling odbc_prepare and odbc_execute.

fyrye 06-Aug-2009 10:59


Another way to prevent SQL injections as opposed to binary, is to use URL Encoding or Hex Encoding. I haven't seen a complete example of stopping SQL Injections, most refer to use the mysql_real_escape_string function or param statements. Several examples at [Link] Which will stop \x00, \n, \r, \, ', " and \x1a based attacks. Alot depends on your SQL query structure, though vector level attacks are still viable. Other than that build your own regex replacement to protect specific queries that could alter or compromise your database/results for specific sections of your processing pages. Also use unique table and field names. Not just putting _ infront of them... Example, don't store User/s or Customer/s information in a table named the same. And NEVER use the same form field names for database field names.

bendikt [at] armed [dot] nu 27-Jul-2009 02:31

i just played around with the array_walk function. It suddenly struck me that almost all super globals are arrays. So what i discovered was that i can apply the array_walk function to the super globals. Doing so you automatically run a function call through the super globals With this piece of code i wrote you should be able to secure most of you input data. <?php class secure { function secureSuperGlobalGET(&$value, $key) { $_GET[$key] = htmlspecialchars(stripslashes($_GET[$key])); $_GET[$key] = str_ireplace("script", "blocked", $_GET[$key]); $_GET[$key] = mysql_escape_string($_GET[$key]); return $_GET[$key]; } function secureSuperGlobalPOST(&$value, $key) { $_POST[$key] = htmlspecialchars(stripslashes($_POST[$key])); $_POST[$key] = str_ireplace("script", "blocked", $_POST[$key]); $_POST[$key] = mysql_escape_string($_POST[$key]); return $_POST[$key]; } function secureGlobals() { array_walk($_GET, array($this, 'secureSuperGlobalGET')); array_walk($_POST, array($this, 'secureSuperGlobalPOST')); } } ?> Note that you can modify this in anyway to suit your needs. The Script has been tested.

cu0001u0002u0003u0004u0005u0006u0007b	
u0004u0002
àu0001u0002u0003u0004u0005u0006u0003u0007u0005bu0005	
u000bu0005f
u0003fu0005u0003u000eu0001u0004fu0005u0003
u000fu0003u0010
u0004u0003u0011u0012u0013u0003u0014u000eu0005fu0015u0005
u0003u0016u0001u0003u0006u0005u0003u0017u0018u000bu0005fu0005u0007u0003u0004u0015u0017u0010u0019u0003u0001u0007u0003

u000eu0018u0005u0003
u0017u0010u0017u0003u0001u0003u0011u0012u0013u0003u0014u000eu0005fu0002u0003u0015
u0003u0003u0017fu000e
u0017u0005u0007u0003u0016
u0018u0018u0001u0007
u0019u0001u0002u0001u0003
u0003
u0004u001eu001abfu001fu0003u0003
u0003 !"#"$%u0003u0018u001cu0016u0003u0017u000b&bu0016u0003u0018u0017u0007bf	bu001cu0016u0003u0007u00188bu0003'()*u0003u0001fu0005u001cu001a+	u0007u0003
u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u00039:"("u0003u0007u00188bu0003
u00035u0004u0007u00188b5u0003
u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003u0003)
u001bu000fu0003u0017u0017u0016u001eu0005fu0003
u000eu0006u0018u0015u0017
u0003u0017u0010u0005u0003b	u000eu0005u0003u0001Îu0005u0003u0014u0003u0015u0005fu0001u0002u0004u0003u0007u0016u0016u0014u000eu0017u0015f
u0002u0011u0003u0013u0013u0005Î
u0003u0004u0005u0006u0002u0003u0007u0005u0004u0003u0002u0004u0005u0004u0003u0002u0004u000eu0001u0002u0002u0005u0014u0015u0007u0007Îu0005**u0003u0017
u0003
Gu000eu0007
u0019u0003u0017u0010u0005u0001u0003u0017u0010u0005u0003Gu0005u0006u0003u0007bu0003u0004u0015		u0003u0006u0005Au0003u0003
aÊ
%u0005bu0005fu0003u0016
u0001u0001u0005u0016u0017u0003u0017
u0003u0017u0010u0005u0003u0007u0017u0006
u0005u0003
u0003u0003
u000eu000bu0005fu000e
u0005fu0003
fu0003
u0003u0017u0010u0005u0003u0007u0017u0006
u0005u0003
u0004u0001u0005fu001au0003'
u0005u0003	u0004u0002
u0003
u0016u000e
u0017
u0018u0015u001du0005u0007u0003u000e
u0005f
u0003u0004u0015u0017u0010u0003bu0005fu0002u0003	u0015u0018u0015u0017u0005u0007u0003u000bfu0015bu0015	u0005u001cu0005
u001au0003u0003
a
Bu0003
u0005u0005u001cu0003u0015u000bu001fu0003	u0005u0003+u0005u001au0017	bfu0003!G#u0003u0018u0017Hb+	u0018u0005u0017u0003u0006u0005fu0003u001eu001abfu0018bu0007u0003u0005u0006u0003	u001fu0001bu0003!"#"$%u0003u0018u0007u0003u001au0007bu0003u0002u000bu0007u0002u0003
u0006u001au0017+	u0018u0005u0017u0003u0005u0017u0003u001cu000b	u000bu0003u0014u001fu0003A:Au0003u000bu0017u001cu0003	u0002bu0003u001cu000b	u000bu0014u000bu0007bu0003u0007bfu000ebfDu0003
u0018u0003Hu001au0007	u0003u0001u001bu000bu001fbu001cu0003u000bfu0005u001au0017u001cu0003u0015u0018	u0002u0003	u0002bu0003u000bffu000bu001f1u0015u000bu001b6u0003u0006u001au0017+	u0018u0005u0017Du0003
/	u0003u0007u001au001cu001cbu0017u001bu001fu0003u0007	fu001a+6u0003&bu0003	u0002u000b	u0003u000bu001b&u0005u0007	u0003u000bu001bu001bu0003u0007u001au0001bfu0003
u001bu0005u0014u000bu001bu0007u0003u000bfbu0003u000bffu000bu001fu0007Du0003
!u0005u0003u0015u0002u000b	u0003

You might also like