程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> 關於MYSQL數據庫 >> 數據庫安全基礎入門知識簡介

數據庫安全基礎入門知識簡介

編輯:關於MYSQL數據庫

現在,為了使得網站能夠提供各種各樣動態的內容,數據庫已經成為所有基於 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.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved