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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章