MySQL如何防止SQL注入

       最近,在写程序时开始注意到sql注入的问题,由于以前写代码时不是很注意,有一些sql会存在被注入的风险,那么防止sql注入的原理是什么呢?我们首先通过PrepareStatement这个类来学习一下吧! 
作为一个IT业内人士只要接触过数据库的人都应该知道sql注入的概念及危害,那么什么叫sql注入呢?我在这边先给它来一个简单的定义:sql注入,简单来说就是用户在前端web页面输入恶意的sql语句用来欺骗后端服务器去执行恶意的sql代码,从而导致数据库数据泄露或者遭受攻击。 
      那么,当我们在使用数据库时,如何去防止sql注入的发生呢?我们自然而然地就会想到在用JDBC进行连接时使用PreparedStatement类去代替Statement,或者传入的条件参数完全不使用String字符串,同样地,在用mybatis时,则尽量使用#{param}占位符的方式去避免sql注入,其实jdbc和mybatis的原理是一致的。我们都知道当我们使用PreparedStatement去写sql语句时,程序会对该条sql首先进行预编译,然后会将传入的字符串参数以字符串的形式去处理,即会在参数的两边自动加上单引号(’param’),而Statement则是直接简单粗暴地通过人工的字符串拼接的方式去写sql,那这样就很容易被sql注入。 
那么,如果PreparedStatement只是仅仅简单地通过把字符串参数两边加上引号的方式去处理,一样也很容易被sql注入,显然它并没有那么傻。比如说有如下一张表:

create table user
(
    id  int4  PRIMARY KEY,
    name VARCHAR(50) not null,
    class VARCHAR(50)
)

里面有如下几条数据:

INSERT INTO `user` VALUES ('1', '张三', '1班');
INSERT INTO `user` VALUES ('2', '李四', '2班');
INSERT INTO `user` VALUES ('3', '王五', '3班');
INSERT INTO `user` VALUES ('4', '赵六', '4班');

这里我们使用mybatis的 {param} 和 #{param} 两个不同的占位符来作为示例解释 Statement 和 PreparedStatement (mybatis和jdbc的低层原理是一样的)。首先{param} 和 #{param} 两个不同的占位符来作为示例解释 Statement 和 PreparedStatement (mybatis和jdbc的低层原理是一样的)。首先{}是不能防止sql注入的,它能够通过字符串拼接的形式来任意摆弄你的sql语句,而#{}则可以很大程度上地防止sql注入,下面是关于这个的一条sql:

<mapper namespace="com.sky.dao.UserMapper">
    <select id="query" parameterType="com.sky.model.User" resultType="com.sky.model.User">
        select * from user where name = '${name}'
    </select>
</mapper>
  • 出前端页面的简略的代码:
<form action="<%=basePath%>query" method="get">
     <input type="input" placeholder="请输入姓名" name="name"/><input type="submit" value="查询"/>
</form>

前端页面通过form表单的形式输入查询条件并调用后端sql。显然对于上面这条sql语句,正常的操作应该是在前端页面输入一个名字,并查询结果,如:传入参数为:张三,则对应sql为:select * from user where name = ‘张三’;那么,其结果就是:id=1;name=’张三’;classname=’1班’;但是,如果其传入参数为:张三’ or 1=’1;则传到后台之后其对应的sql就变为:select * from user where name = ‘张三’ or 1=’1’;那么,其输出的结果就是表中所有的数据。

那么,如果我们我们将mybatis中的sql语句改为:select * from user where name = #{name} 之后又会怎样呢?如果传入的参数为:张三,则结果很显然跟上面第一次的是一样的,那如果将传入参数变为:张三’ or 1=’1 又会怎样呢?实践证明,查询结果为空,很显然它并不仅仅是给字符串两端加了单引号那么简单,否则我作为一个新手都随便就想得到的问题,那么多高智商的IT人士又怎会发现不了呢。那么它的原理又是什么呢?我带着这个问题去寻找答案,很显然,寻找答案的最好方式就是去看源代码。于是,我找到了mysql-jdbc连接的源代码,查看了PreparedStatement类的源代码,其中setString()方法的源代码如下:

/**
     * Set a parameter to a Java String value. The driver converts this to a SQL
     * VARCHAR or LONGVARCHAR value (depending on the arguments size relative to
     * the driver's limits on VARCHARs) when it sends it to the database.
     * 
     * @param parameterIndex
     *            the first parameter is 1...
     * @param x
     *            the parameter value
     * 
     * @exception SQLException
     *                if a database access error occurs
     */
    public void setString(int parameterIndex, String x) throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            // if the passed string is null, then set this column to null
            if (x == null) {
                setNull(parameterIndex, Types.CHAR);
            } else {
                checkClosed();

                int stringLength = x.length();

                if (this.connection.isNoBackslashEscapesSet()) {
                    // Scan for any nasty chars

                    boolean needsHexEscape = isEscapeNeededForString(x, stringLength);

                    if (!needsHexEscape) {
                        byte[] parameterAsBytes = null;

                        StringBuilder quotedString = new StringBuilder(x.length() + 2);
                        quotedString.append('\'');
                        quotedString.append(x);
                        quotedString.append('\'');

                        if (!this.isLoadDataQuery) {
                            parameterAsBytes = StringUtils.getBytes(quotedString.toString(), this.charConverter, this.charEncoding,
                                    this.connection.getServerCharset(), this.connection.parserKnowsUnicode(), getExceptionInterceptor());
                        } else {
                            // Send with platform character encoding
                            parameterAsBytes = StringUtils.getBytes(quotedString.toString());
                        }

                        setInternal(parameterIndex, parameterAsBytes);
                    } else {
                        byte[] parameterAsBytes = null;

                        if (!this.isLoadDataQuery) {
                            parameterAsBytes = StringUtils.getBytes(x, this.charConverter, this.charEncoding, this.connection.getServerCharset(),
                                    this.connection.parserKnowsUnicode(), getExceptionInterceptor());
                        } else {
                            // Send with platform character encoding
                            parameterAsBytes = StringUtils.getBytes(x);
                        }

                        setBytes(parameterIndex, parameterAsBytes);
                    }

                    return;
                }

                String parameterAsString = x;
                boolean needsQuoted = true;

                if (this.isLoadDataQuery || isEscapeNeededForString(x, stringLength)) {
                    needsQuoted = false; // saves an allocation later

                    StringBuilder buf = new StringBuilder((int) (x.length() * 1.1));

                    buf.append('\'');

                    //
                    // Note: buf.append(char) is _faster_ than appending in blocks, because the block append requires a System.arraycopy().... go figure...
                    //

                    for (int i = 0; i < stringLength; ++i) {
                        char c = x.charAt(i);

                        switch (c) {
                            case 0: /* Must be escaped for 'mysql' */
                                buf.append('\\');
                                buf.append('0');

                                break;

                            case '\n': /* Must be escaped for logs */
                                buf.append('\\');
                                buf.append('n');

                                break;

                            case '\r':
                                buf.append('\\');
                                buf.append('r');

                                break;

                            case '\\':
                                buf.append('\\');
                                buf.append('\\');

                                break;

                            case '\'':
                                buf.append('\\');
                                buf.append('\'');

                                break;

                            case '"': /* Better safe than sorry */
                                if (this.usingAnsiMode) {
                                    buf.append('\\');
                                }

                                buf.append('"');

                                break;

                            case '\032': /* This gives problems on Win32 */
                                buf.append('\\');
                                buf.append('Z');

                                break;

                            case '\u00a5':
                            case '\u20a9':
                                // escape characters interpreted as backslash by mysql
                                if (this.charsetEncoder != null) {
                                    CharBuffer cbuf = CharBuffer.allocate(1);
                                    ByteBuffer bbuf = ByteBuffer.allocate(1);
                                    cbuf.put(c);
                                    cbuf.position(0);
                                    this.charsetEncoder.encode(cbuf, bbuf, true);
                                    if (bbuf.get(0) == '\\') {
                                        buf.append('\\');
                                    }
                                }
                                buf.append(c);
                                break;

                            default:
                                buf.append(c);
                        }
                    }

                    buf.append('\'');

                    parameterAsString = buf.toString();
                }

                byte[] parameterAsBytes = null;

                if (!this.isLoadDataQuery) {
                    if (needsQuoted) {
                        parameterAsBytes = StringUtils.getBytesWrapped(parameterAsString, '\'', '\'', this.charConverter, this.charEncoding,
                                this.connection.getServerCharset(), this.connection.parserKnowsUnicode(), getExceptionInterceptor());
                    } else {
                        parameterAsBytes = StringUtils.getBytes(parameterAsString, this.charConverter, this.charEncoding, this.connection.getServerCharset(),
                                this.connection.parserKnowsUnicode(), getExceptionInterceptor());
                    }
                } else {
                    // Send with platform character encoding
                    parameterAsBytes = StringUtils.getBytes(parameterAsString);
                }

                setInternal(parameterIndex, parameterAsBytes);

                this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.VARCHAR;
            }
        }
    }

这段代码的作用是将java中的String字符串参数传到sql语句中,并通过驱动将其转换成sql语句并到数据库中执行。这段代码中前面一部分做了一些是否需要对字符串进行转义的判断,这里不展开讲。后面一部分则是如何有效防止sql注入的重点,代码中通过一个for循环,将字符串参数通过提取每一位上的char字符进行遍历,并通过switch()….case 条件语句进行判断,当出现换行符、引号、斜杠等特殊字符时,对这些特殊字符进行转义。那么,此时问题的答案就出来了,当我们使用PreparedStatement进行传参时,若传入参数为:张三’ or 1 = ‘1 时,经过程序后台进行转义后,真正的sql其实变成了: select * from user where name = ‘张三\’ or 1 = \’1’;显然这样查询出来的结果一定为空。

转自:https://blog.csdn.net/lisehouniao/article/details/51523497

猜你喜欢

转载自blog.csdn.net/weixin_41165867/article/details/81409650