什麼是SQL注入?如何進行SQL注入攻擊?如何避免SQL注入攻擊?

比如說我的DaoImp是這樣寫的

package com.xatu.dao.imp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.xatu.dao.UserDao;
import com.xatu.domain.User;
import com.xatu.utils.JDBC;

public class UserDaoImp implements UserDao {
	
	private Connection conn;
	@Override
	public User userLogin(String username,String password){
		JDBC jdbc = new JDBC();
		User u = null;
		try {
			conn = jdbc.getConn();
			Statement createStatement = conn.createStatement();
			ResultSet set = createStatement.executeQuery("select * from usertab where username = '" + username + 
					"' and password = " + "'" + password + "'");
			
			while(set.next()) {
				u = new User();
				u.setUsername(set.getString(1));
				u.setPasswordString(set.getString(2));
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return u;
	}
}

ResultSet set = createStatement.executeQuery(“select * from usertab where username = '” + username +
"’ and password = " + “’” + password + “’”);
注意這個sql查詢語句 這個會導致我們收到SQL注入攻擊!

如何攻擊?

很簡單

“select * from usertab where username = '” + username +
"’ and password = " + “’” + password + “’”

因爲我們拿的是這個sql語句去做業務的,username和password是用戶可以輸入的參數 只要在password處加入一些可以直接影響結果的語句就可以了

如何影響結果?

比如 在密碼輸入框內加 or ‘1’=‘1’ 這樣的字樣 因爲1絕對等於1,所以針對那條查詢語句會直接讓你成功進入數據庫

如何避免

使用預處理sql語句的方式即可,因爲預處理機制是把用戶的輸入完整的當作參數處理了。

PreparedStatement statement = conn.prepareStatement
					("select * from usertab where username = ? AND password = ?");
			statement.setString(1, username);
			statement.setString(2, password);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章