章 27. 数据库安全

今时今日,数据库系统已经成为各个动态网站上 web 应用程序的重要组成部分。由于非常敏感和机密的数据有可能保存在数据库中,所以对数据库实施保护就显得尤为重要了。

要从数据库中提取或者存入数据,就必须经过连接数据库、发送一条合法查询、获取结果、关闭连接等步骤。目前,能完成这一系列动作的最常用的查询语言是结构化查询语言 Structured Query Language (SQL)。可以看看攻击者是如何篡改 SQL 查询语句的

PHP 本身并不能保护数据库的安全。下面的章节只是讲述怎样用 PHP 脚本对数据库进行基本的访问和操作。

记住一条简单的原则:深入防御。保护数据库的措施越多,攻击者就越难获得和使用数据库内的信息。正确地设计和应用数据库可以减少被攻击的担忧。

设计数据库

第一步一般都是创建数据库,除非是使用第三方的数据库服务。当创建一个数据库的时候,会指定一个所有者来执行和新建语句。通常,只有所有者(或超级用户)才有权对数据库中的对象进行任意操作。如果想让其他用户使用,就必须赋予他们权限。

应用程序永远不要使用数据库所有者或超级用户帐号来连接数据库,因为这些帐号可以执行任意的操作,比如说修改数据库结构(例如删除一个表)或者清空整个数据库的内容。

应该为程序的每个方面创建不同的数据库帐号,并赋予对数据库对象的极有限的权限。仅分配给能完成其功能所需的权限,避免同一个用户可以完成另一个用户的事情。这样即使攻击者利用程序漏洞取得了数据库的访问权限,也最多只能做到和该程序一样的影响范围。

鼓励用户不要把所有的事务逻辑都用 web 应用程序(即用户的脚本)来实现。最好用视图(view)、触发器(trigger)或者规则(rule)在数据库层面完成。当系统升级的时候,需要为数据库开辟新的接口,这时就必须重做所有的数据库客户端。除此之外,触发器还可以透明和自动地处理字段,并在调试程序和跟踪事实时提供有用的信息。


add a note add a note User Contributed Notes
somebody at whocares dot com
11-May-2006 12:03
Encrypting user input doesn't do much to guard against SQL injection attacks.  Naturally, you want to encrypt sensitive information across the wire, but if a user puts in malicious data into an input field, any encryption scheme will just dutifully unpack it at the other and and still run the SQL injection hack if you haven't guarded against it.

Encryption is not magic pixie dust to sprinkle on things to make them more secure.
30-Jun-2005 06:57
you can also chamge CHMOD for some file containing "user names" or "passwords"
webmaster at rackhouse dot net
13-Mar-2005 06:08
On a database design point of view, you should make sure that you design databases in a manor that any query run from them need minimal input from the user and if it requires user input, that you encrypt where possible.
jjahn at SPAMSUCKS dot signicast dot com
21-Jun-2003 01:17
I would say one of the best ways to guard against SQL injection is to use the excellent PEAR DB package. If you prepare() and execute() your queries, PEAR will automagically addslashes and handle the query depending on your RDBMS. And of course, for repeatable queries prepare and execute will give you a bit of a readability and speed increase.