1. Use stored procedures as much as possible and call them using the parameters set. Combine the parameters set and stored procedure
The followingCodeThe section explains the usage of the parameters set:
Sqldataadapter mycommand = new sqldataadapter ("authorlogin", Conn );
Mycommand. selectcommand. commandtype = commandtype. storedprocedure;
Sqlparameter parm = mycommand. selectcommand. Parameters. Add ("@ au_id", sqldbtype. varchar, 11 );
Parm. value = login. Text; // here, login. Text is the security protection interface.
In this example, the @ au_id parameter is considered as a text value rather than an executable code. In addition, the type and length of parameters are checked. In the preceding example, the input value cannot be longer than 11 characters. If the data does not follow the type or length defined by the parameter, an exception is generated.
Please note that,Using Stored procedures does not necessarily prevent SQL injection. It is important to combine parameters and stored procedures.If parameters are not used, they are vulnerable to SQL injection attacks when the stored procedure uses unfiltered input content. For example, the following code snippets are vulnerable to attacks:
Sqldataadapter mycommand = new sqldataadapter ("loginstoredprocedure" + login. Text + "'", Conn );
Key PointsIf you use a stored procedure, make sure that the parameters are used at the same time.
2. Use the parameters set and dynamic SQL
If you cannot use stored procedures, you can still use parameters, As shown in the following code snippet:
Sqldataadapter mycommand = new sqldataadapter ("select au_lname, au_fname from authors where au_id = @ au_id", Conn );
Sqlparameter parm = mycommand. selectcommand. Parameters. Add ("@ au_id", sqldbtype. varchar, 11 );
Parm. value = login. text;
From the example of this code, we can also think of when we call the encapsulated class method, when writing the parameters of the method, we can still use the above method for Security Testing ("@ au_id ")
3. Use a filtering routineAnother way to prevent SQL injection attacks is to develop screening routines to add escape characters to characters with special SQL meanings.
Such as the single-byte character. The following code snippet illustrates a filtering routine used to add escape characters:
Private string safesqlliteral (string inputsql)
{
Return inputsql. Replace ("'","''");
}
This type of routine has some problems, and you should not rely on them completely, because attackers can use ASCII hexadecimal characters to avoid checking. However, the input content should be filtered and used as part of the deep defense policy.
Do not rely on filtering input.
4. Use the like clause
Please note that,If you use the like clause, the wildcard still needs an escape character.. The following code snippet illustrates this technology:
S = S. Replace ("[", "[]");
S = S. Replace ("%", "[%]");
S = S. Replace ("_", "[_]");