类型: 安全缺陷
SQL注入是一种数据库攻击手段。攻击者通过向应用程序提交恶意代码来改变原SQL语句的含义,进而执行任意SQL命令,达到入侵数据库乃至操作系统的目的。
例如:下面代码片段中,动态构造并执行了一个SQL查询来认证用户。
public void doPrivilegedAction(HttpServletRequest request, char[] password) throws SQLException {Connection connection = getConnection();if (connection == null) {// handle error}try {String username = request.getParameter("username");String pwd = hashPassword(password);String sqlString = "SELECT * FROM db_user WHERE username = '" + username + "' AND password = '" + pwd + "'";Statement stmt = connection.createStatement();ResultSet rs = stmt.executeQuery(sqlString);if (!rs.next()) {throw new SecurityException( "User name or password incorrect");}// Authenticated; proceed} finally {try {connection.close();} catch (SQLException x) {// forward to handler}}}
在上面的例子中,攻击者能够自由控制输入的字符串变量username和password中的内容,他们可以使用下面的关于username的字符串进行SQL注入。
validuser’ OR ‘1’=’1
当其注入到命令时,命令就会变成:
SELECT  FROM db_user WHERE username=’validuser’ OR ‘1’=’1’ AND password=’’
同样,攻击者可以为password提供如下字符串。
‘ OR ‘1’=’1
当其注入到命令时,命令就会变成:
SELECT  FROM db_user WHERE username=’’ AND password=’’ OR ‘1’=’1’
