資料庫安全基礎入門知識簡介(轉)

BSDLite發表於2007-08-16
資料庫安全基礎入門知識簡介(轉)[@more@]現在,為了使得網站能夠提供各種各樣動態的內容,資料庫已經成為所有基於 WEB 應用程式最重要的元件。由於一些十分敏感或者保密的資訊可能會儲存在這樣的資料庫中,因此,您需要非常慎重的考慮如何保護它們。

為了能夠儲存或者檢索資訊,您需要連線到資料庫,傳送一個合法的查詢命令,得到結果,然後關閉連線。目前,在這個互動過程中最常用的查詢語言是“結構化查詢語言(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:


據庫所採取得措施和場所越多,攻擊者暴露、濫用資料庫中儲存的保密資訊的可能性就越小。請儘可能更好的設計資料庫結構和應用程式。

設計資料庫

一般來說第一步總是建立資料庫,除非您希望使用已經存在的第三方資料庫。當一個資料庫被建立後,它將被指定給一個所有者,即執行建立資料庫語句的使用者。通常,只有所有者(或者超級使用者)才能對該資料庫中的物件進行任何操作,為了能讓其它使用者使用該資料庫,需要進行許可權設定。

應用程式決不能用所有者或者超級使用者的賬號來連線到資料庫,因為這些使用者可以執行任何查詢,例如,修改資料結構(如刪除表格)或者刪除所有的內容。

您可以為應用程式不同的部分建立不同的資料庫賬號,使得它們職能對資料庫物件行使非常有限的許可權。對這些賬號應該只賦予最需要的許可權,同時應該防止相同的使用者能夠在不同的使用情況與資料庫進行交流。這也就是說,如果某一個入侵者利用這些賬號中的某一個獲得了訪問您資料庫的許可權,他們也僅僅能夠影響到您的應用程式力所能及的範圍。

您最好不要把所有的事物過程都放在 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.

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10617542/viewspace-962202/,如需轉載,請註明出處,否則將追究法律責任。

相關文章