1. Introduction to SQL Injection
SQL injection is one of the more common network attack methods. It does not use the BUG of the operating system to implement the attack, but targets programmersProgramming Negligence, through SQL statements, login without an account, or even tampering with the database.
2. The general idea of SQL injection attack
1. Find the location of SQL injection
2. Determine the server type and background database type
3. Conduct SQL injection attacks based on different server and database characteristics
3. SQL injection attack examples
For example, in a login interface, requiring input Username and password:
You can enter it like this to log in without an account:
Username: 'or 1 = 1 –
Password:
Click to log in, If no special treatment is done, then the illegal user will log in very proudly. (Of course, some language databasesAPI have already dealt with these problems)
Why is this? Let’s analyze it below:
Theoretically, there will be the following SQL statement in the background authentication program:
String sql = "select * from user_table where username= ' "+userName+" ' and password=' "+password+" '";
When the above user name and password are entered, the above SQL statement becomes:
SELECT * FROM user_table WHERE username= '’or 1 = 1 -- and password='’
Analyze the SQL statement:
After the condition username="or 1=1 username is equal to" or 1=1 then this condition will definitely succeed;
Then add after Two -, which means Comment, it will comment the following statements so that they will not work, so that the statements can always be executed correctly, and the user can easily deceive the system and obtain legal identity.
This is relatively gentle. If
SELECT * FROM user_table WHERE username='' ;DROP DATABASE (DB Name) --' and password=''
is executed...the consequences can be imagined...
4. Coping methods
Let me talk about the countermeasures for JSP:
1. (Simple and effective method) PreparedStatement
uses a precompiled statement set, which has built-in To handle SQL injection, just use its setXXX method to pass the value.
Benefits of use:
(1). Code readability and maintainability.
(2).PreparedStatement improves performance as much as possible.
(3). The most important point is that it greatly improves security.
Principle:
sql injection only affects the preparation (compilation) process of sql statements It has a destructive effect
The PreparedStatement is already prepared. The execution phase only processes the input string as data,
and no longer parses and prepares the sql statement, thus avoiding sql injection. Question.
2. Use regular expression to filter the incoming parameters
Package to be imported:
import java.util.regex.*;
正则表达式:
private String CHECKSQL = “^(.+)\\sand\\s(.+)|(.+)\\sor(.+)\\s$”;
判断是否匹配:
Pattern.matches(CHECKSQL,targerStr);
下面是具体的正则表达式:
检测SQL meta-characters的正则表达式 :
/(\%27)|(\’)|(\-\-)|(\%23)|(#)/ix
修正检测SQL meta-characters的正则表达式 :
/((\%3D)|(=))[^\n]*((\%27)|(\’)|(\-\-)|(\%3B)|(:))/i
典型的SQL 注入攻击的正则表达式 :
/\w*((\%27)|(\’))((\%6F)|o|(\%4F))((\%72)|r|(\%52))/ix
检测SQL注入,UNION查询关键字的正则表达式
:/((\%27)|(\’))union/ix(\%27)|(\’)
检测MS SQL Server SQL注入攻击的正则表达式:
/exec(\s|\+)+(s|x)p\w+/ix
等等…..
3.字符串过滤
比较通用的一个方法:
(||之间的参数可以根据自己程序的需要添加)
public static boolean sql_inj(String str){ String inj_str = "'|and|exec|insert|select|delete|update| count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,"; String inj_stra[] = split(inj_str,"|"); for (int i=0 ; i < inj_stra.length ; i++ ){ if (str.indexOf(inj_stra[i])>=0){ return true; } } return false; }
4.jsp中调用该函数检查是否包函非法字符
防止SQL从URL注入:
sql_inj.java代码:
package sql_inj; import java.net.*; import java.io.*; import java.sql.*; import java.text.*; import java.lang.String; public class sql_inj{ public static boolean sql_inj(String str){ String inj_str = "'|and|exec|insert|select|delete|update| count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,";
//这里的东西还可以自己添加
String[] inj_stra=inj_str.split("\\|"); for (int i=0 ; i < inj_stra.length ; i++ ){ if (str.indexOf(inj_stra[i])>=0){ return true; } } return false; } }
5.JSP页面判断代码:
使用javascript在客户端进行不安全字符屏蔽
功能介绍:检查是否含有”‘”,”\\”,”/”
参数说明:要检查的字符串
返回值:0:是1:不是
函数名是
function check(a){ return 1; fibdn = new Array (”‘” ,”\\”,”/”); i=fibdn.length; j=a.length; for (ii=0; ii<i; ii++) { for (jj=0; jj<j; jj++) { temp1=a.charAt(jj); temp2=fibdn[ii]; if (tem’; p1==temp2) { return 0; } } } return 1; }
===================================
总的说来,防范一般的SQL注入只要在代码规范上下点功夫就可以了。
凡涉及到执行的SQL中有变量时,用JDBC(或者其他数据持久层)提供的如:PreparedStatement就可以 ,切记不要用拼接字符串的方法就可以了。
【相关推荐】
1. 特别推荐:“php程序员工具箱”V0.1版本下载
The above is the detailed content of How to prevent sql injection? Introducing 5 ways to prevent SQL injection. For more information, please follow other related articles on the PHP Chinese website!

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver Mac version
Visual web development tools
