简体   繁体   中英

How to escape special characters like " in the SQL query in order to avoid Injection

Using delphi 2010, i am wondering if there someway to escape the following string to make it safe from sql injection attacks :

my string :

    SQLQuery1.SQL.Text := 'SELECT * FROM registered WHERE email="'+
      email+'" and login_pass="'+password+'"';

How to rewrite this string, to make it safer than it is when someone type " in my TEditbox as his email or password !

Use parameters, and let the database drivers handle that stuff.

SQLQuery1.SQL.Text := 'SELECT * FROM registered WHERE email= :email'+
  ' and login_pass = :password';
SQLQuery1.ParamByName('email').AsString := EMail;
SQLQuery1.ParamByName('password').AsString := Password;

the basic replacement of ' with '' should make sure that you won't get injected in textual fields.

As a rule of thumb, make sure all inputs you add to the database are in the pattern you expect them to be. in the case of email addresses, zip codes and passwords- you can define a simple regex to verify the validity.

keep in mind, that numeric fields can be also injected and should be verified as well.

If for whatever reason you can't use parameters, you can use a function like this:

USES SysUtils;

FUNCTION QuotedStr(CONST S : STRING) : STRING;
  BEGIN
    Result:='"'+ReplaceStr(S,'"','""')+'"'
  END;

and then

SQLQuery1.SQL.Text := 'SELECT * FROM registered WHERE email='+
  QuotedStr(email)+' and login_pass='+QuotedStr(password);

(this assumes that your database provider uses double quotes to delimit strings with and that two consecutive double quotes in a quoted string is really a single double quote, ie. one double quote).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM