ºìÁªLinuxÃÅ»§
Linux°ïÖú

Êý¾Ý¿â°²È«»ù´¡ÈëÃÅ֪ʶ¼ò½é

·¢²¼Ê±¼ä:2006-10-19 00:44:54À´Ô´:ºìÁª×÷Õß:hlMiracle
ÏÖÔÚ£¬ÎªÁËʹµÃÍøÕ¾Äܹ»Ìṩ¸÷ÖÖ¸÷Ñù¶¯Ì¬µÄÄÚÈÝ£¬Êý¾Ý¿âÒѾ­³ÉΪËùÓлùÓÚ WEB Ó¦ÓóÌÐò×îÖØÒªµÄ×é¼þ¡£ÓÉÓÚһЩʮ·ÖÃô¸Ð»òÕß±£ÃܵÄÐÅÏ¢¿ÉÄÜ»á´æ´¢ÔÚÕâÑùµÄÊý¾Ý¿âÖУ¬Òò´Ë£¬ÄúÐèÒª·Ç³£É÷ÖصĿ¼ÂÇÈçºÎ±£»¤ËüÃÇ¡£

ΪÁËÄܹ»´æ´¢»òÕß¼ìË÷ÐÅÏ¢£¬ÄúÐèÒªÁ¬½Óµ½Êý¾Ý¿â£¬·¢ËÍÒ»¸öºÏ·¨µÄ²éѯÃüÁµÃµ½½á¹û£¬È»ºó¹Ø±ÕÁ¬½Ó¡£Ä¿Ç°£¬ÔÚÕâ¸ö½»»¥¹ý³ÌÖÐ×î³£ÓõIJéѯÓïÑÔÊÇ¡°½á¹¹»¯²éѯÓïÑÔ£¨Structured Query Language, SQL£©¡±¡£Çë²ÎÔÄÒÔÏÂÄÚÈÝÒÔÁ˽âºÚ¿ÍÈçºÎ¡°ÀûÓà SQL ²éѯ¹¥»÷¡±¡£

ÕýÈçÄúËùÖªµÀµÄ£¬PHP ×ÔÉí²¢ÎÞ·¨±£»¤ÄúµÄÊý¾Ý¿â¡£ÒÔÏÂÕ½ڵÄÄÚÈÝÖ¼ÔÚ½éÉÜÓйØÈçºÎÀûÓà PHP ½Å±¾·ÃÎʺͲÙ×÷Êý¾Ý¿âµÄ×î»ù´¡µÄ֪ʶ¡£

Çë¼ÇסÕâ¸ö¼òµ¥µÄ·¨Ôò£º¾¡¿ÉÄÜÉî²ã´ÎµÄ·ÀÓù¡£ÎªÁ˱£»¤ÄúµÄÊý

If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:


¾Ý¿âËù²ÉÈ¡µÃ´ëÊ©ºÍ³¡ËùÔ½¶à£¬¹¥»÷Õß±©Â¶¡¢ÀÄÓÃÊý¾Ý¿âÖд洢µÄ±£ÃÜÐÅÏ¢µÄ¿ÉÄÜÐÔ¾ÍԽС¡£Ç뾡¿ÉÄܸüºÃµÄÉè¼ÆÊý¾Ý¿â½á¹¹ºÍÓ¦ÓóÌÐò¡£

Éè¼ÆÊý¾Ý¿â

Ò»°ãÀ´ËµµÚÒ»²½×ÜÊǽ¨Á¢Êý¾Ý¿â£¬³ý·ÇÄúÏ£ÍûʹÓÃÒѾ­´æÔڵĵÚÈý·½Êý¾Ý¿â¡£µ±Ò»¸öÊý¾Ý¿â±»½¨Á¢ºó£¬Ëü½«±»Ö¸¶¨¸øÒ»¸öËùÓÐÕߣ¬¼´ÔËÐн¨Á¢Êý¾Ý¿âÓï¾äµÄÓû§¡£Í¨³££¬Ö»ÓÐËùÓÐÕߣ¨»òÕß³¬¼¶Óû§£©²ÅÄܶԸÃÊý¾Ý¿âÖеĶÔÏó½øÐÐÈκβÙ×÷£¬ÎªÁËÄÜÈÃÆäËüÓû§Ê¹ÓøÃÊý¾Ý¿â£¬ÐèÒª½øÐÐȨÏÞÉèÖá£

Ó¦ÓóÌÐò¾ö²»ÄÜÓÃËùÓÐÕß»òÕß³¬¼¶Óû§µÄÕ˺ÅÀ´Á¬½Óµ½Êý¾Ý¿â£¬ÒòΪÕâЩÓû§¿ÉÒÔÖ´ÐÐÈκβéѯ£¬ÀýÈ磬ÐÞ¸ÄÊý¾Ý½á¹¹£¨Èçɾ³ý±í¸ñ£©»òÕßɾ³ýËùÓеÄÄÚÈÝ¡£

Äú¿ÉÒÔΪӦÓóÌÐò²»Í¬µÄ²¿·Ö½¨Á¢²»Í¬µÄÊý¾Ý¿âÕ˺ţ¬Ê¹µÃËüÃÇÖ°ÄܶÔÊý¾Ý¿â¶ÔÏóÐÐʹ·Ç³£ÓÐÏÞµÄȨÏÞ¡£¶ÔÕâЩÕ˺ÅÓ¦¸ÃÖ»¸³Óè×îÐèÒªµÄȨÏÞ£¬Í¬Ê±Ó¦¸Ã·ÀÖ¹ÏàͬµÄÓû§Äܹ»ÔÚ²»Í¬µÄʹÓÃÇé¿öÓëÊý¾Ý¿â½øÐн»Á÷¡£ÕâÒ²¾ÍÊÇ˵£¬Èç¹ûijһ¸öÈëÇÖÕßÀûÓÃÕâЩÕ˺ÅÖеÄijһ¸ö»ñµÃÁË·ÃÎÊÄúÊý¾Ý¿âµÄȨÏÞ£¬ËûÃÇÒ²½ö½öÄܹ»Ó°Ïìµ½ÄúµÄÓ¦ÓóÌÐòÁ¦ËùÄܼ°µÄ·¶Î§¡£

Äú×îºÃ²»Òª°ÑËùÓеÄÊÂÎï¹ý³Ì¶¼·ÅÔÚ WEB Ó¦ÓóÌÐò£¨¼´ÄúµÄ½Å±¾£©ÖÐÀ´ÊµÊ©£¬¶ø³ä·ÖµÄÀûÓÃÊý¾Ý¿â½á¹¹£¬Ê¹ÓÃÊÓͼ£¨view£©¡¢´¥·¢Æ÷£¨trigger£©»òÕß¹æÔò£¨rule£©¡£Èç¹ûÐèÒª¶Ôϵͳ½øÐÐÉý¼¶£¬ÔòÐèÒª¶ÔÊý¾Ý¿â¿ª±ÙеĶ˿ڣ¬Òò´ËÄúÐèÒª¶Ôÿһ¸ö¶ÀÁ¢µÄÊý¾Ý¿â¿Í»§ÖØÐÂÉèÖÃȨÏÞ¡£×ÜÖ®£¬´¥·¢Æ÷¿ÉÒÔ±»ÓÃÀ´Í¸Ã÷µØºÍ×Ô¶¯µØ´¦Àí×ֶΣ¬¸ÃÌØÐÔ¿ÉÒÔÔÚµ÷ÊÔÓ¦ÓóÌÐòµØÎÊÌâ»òÕß×·×Ùºǫ́ÊÂÎïʱÌṩ±ãÀûÐÅÏ¢¡£

Á¬½ÓÊý¾Ý¿â

Äú¿ÉÄÜÏ£Íûͨ¹ý SSL ½¨Á¢Á¬½ÓÀ´¼ÓÃÜ¿Í»§¶ËºÍ·þÎñ¶ËÖ®¼äµÄͨѶÒÔÔö¼Ó°²È«ÐÔ£¬»òÕßÄú¿ÉÒÔʹÓà ssh À´¼ÓÃÜ¿Í»§¶ËºÍÊý¾Ý¿â·þÎñÆ÷Ö®¼äµÄÍøÂçÁ¬½Ó¡£Èç¹ûÄúʵʩÁËÕâЩ´ëÊ©£¬Ôò¼àÊÓÄúµÄÍøÂçÁ÷Á¿ÒÔ¼°ÒÔÕâÖÖ·½Ê½»ñÈ¡ÐÅÏ¢½«±ä³ÉÊ®·Ö¸´ÔӵŤ×÷¡£

¼ÓÃܴ洢ģÐÍ

SSL/SSH protects data travelling from the client to the server, SSL/SSH does not protect the persistent data stored in a database. SSL is an on-the-wire protocol. Once an ttacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database tself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption. The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this case with its several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data be stored first, and decrypts it when retrieving. See the references for further examples how encryption works. In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may be also taken into consideration. The well-known example for the hashing is storing the MD5 hash of a password in a database, instead of the password itself. See also crypt() and md5().

Àý×Ó 15-5. ʹÓþ­¹ý¹þÏ£ÔËËãµÄÃÜÂë×Ö¶Î


// storing password hash
$query = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
addslashes($username), md5($password));
$result = pg_exec($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
addslashes($username), md5($password));
$result = pg_exec($connection, $query);

if (pg_numrows($result) > 0) {
echo "Welcome, $username!";
}
else {
echo "Authentication failed for $username.";
}



SQL ¹¥»÷

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 a 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.

Àý×Ó 15-6. ½«½á¹û¼¯·ÖÀëµ½Ò³ÃæÖУ¬È»ºó´´Ô쳬¼¶Óû§(PostgreSQL and MySQL)


$offset = argv[0]; // beware, no input validation!
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// with PostgreSQL
$result = pg_exec($conn, $query);
// with MySQL
$result = mysql_query($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 decimal number. However, someone
tries to break in with appending urlencode()'d form of the following to the URL


// in case of PostgreSQL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
select 'crack', usesysid, 't','t','crack'
from pg_shadow where usename='postgres';
--

// in case of MySQL
0;
UPDATE user SET Password=PASSWORD('crack') WHERE user='root';
FLUSH PRIVILEGES;


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.

×¢: 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. What the attacker needs only is to try if there is any submitted variable used in SQL statement which is 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.

Àý×Ó 15-7. ÁгöÎÄÕ£¬ÒÔ¼°Ò»Ð©ÃÜÂ루ÈκÎÊý¾Ý¿â·þÎñÆ÷£©


$query = "SELECT id, name, inserted, size FROM products
WHERE size = '$size'
ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $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 UPDATEs are also subject to attacking your database. These queries are also hreatened 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 examing the form variable names, or just simply brute forcing. There are not so many naming convention for fields storing passwords or usernames.

Àý×Ó 15-8. ÀûÓÃÖØÉèÃÜÂëÀ´»ñÈ¡¸ü¶àµÄȨÏÞ£¨ÈκÎÊý¾Ý¿â·þÎñÆ÷£©


$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:
// $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. Àý×Ó 15-9. ¹¥»÷Êý¾Ý¿âÖ÷»úµÄ²Ù×÷ϵͳ (MSSQL Server)

$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:


$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.


×¢: 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 so vulnerable in other manner.


Ô¤·ÀµÄ¼¼ÇÉ

You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management ystem or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.


These attacks are mainly based on exploiting the code not being written with security in mind. Never trust on any kind of input, especially 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.



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) onwards the Perl compatible Regular Expressions support.


If the application waits for numerical input, consider to verify data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().

Àý×Ó 15-10. ¸ü¼Ó°²È«µÄ·ÖÒ³²éѯÓï¾ä


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 20 OFFSET %d;",
$offset);



Quote each non numeric user input which is passed to the database with addslashes() or addcslashes(). See the first example. As the examples shows, quotes burnt into the static part of the query is not enough, and can be easily hacked.

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. 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. The more detail is generally better.
ÎÄÕÂÆÀÂÛ

¹²ÓÐ 0 ÌõÆÀÂÛ