Welcome Guest ( Log In | Register )

Outline · [ Standard ] · Linear+

 Quote your damn SQL inputs!, Paging Bobby Tables!

views
     
TSangch
post Nov 3 2014, 08:26 PM, updated 12y ago

On my way
****
Junior Member
636 posts

Joined: Jul 2006
Sigh, have enough of seeing bad code passing by here, and people replying and fixing the wrong (IMHO) things. Topic is closed, so didn't manage to post proper reply to the original post.

Read these:

http://en.wikipedia.org/wiki/SQL_injection

http://php.net/manual/en/mysqli-stmt.bind-param.php

http://php.net/manual/en/security.database.sql-injection.php

TL/DR:

Don't do this:
CODE
$mysqli->query("UPDATE table Foo set body= '".$_POST['body']."' where id= '".$_POST['id']."'");


Do this (well, a *better* version of this):
CODE
$stmt = mysqli_prepare($link, "UPDATE table Foo set body = ? where id= ?");
mysqli_stmt_bind_param($stmt, 'sd', $_POST['body'], $_POST['id']);
mysqli_stmt_execute($stmt);


This post has been edited by angch: Nov 3 2014, 08:28 PM
matiko95
post Nov 3 2014, 08:30 PM

Enthusiast
*****
Senior Member
922 posts

Joined: Dec 2006
where the sanitized input? trim? md5 padding? aes shakehand protocol? session tucking?


wKkaY
post Nov 3 2014, 08:31 PM

misutā supākoru
Group Icon
VIP
6,008 posts

Joined: Jan 2003
Pinned FTT.... will link this thread when I come across assignment-grade code wink.gif
alien3d
post Nov 8 2014, 01:18 PM

Look at all my stars!!
*******
Senior Member
3,740 posts

Joined: Mar 2009
QUOTE(angch @ Nov 3 2014, 08:26 PM)
Sigh, have enough of seeing bad code passing by here, and people replying and fixing the wrong (IMHO) things. Topic is closed, so didn't manage to post proper reply to the original post.

Read these:

http://en.wikipedia.org/wiki/SQL_injection

http://php.net/manual/en/mysqli-stmt.bind-param.php

http://php.net/manual/en/security.database.sql-injection.php

TL/DR:

Don't do this:
CODE
$mysqli->query("UPDATE table Foo set body= '".$_POST['body']."' where id= '".$_POST['id']."'");


Do this (well, a *better* version of this):
CODE
$stmt = mysqli_prepare($link, "UPDATE table Foo set body = ? where id= ?");
mysqli_stmt_bind_param($stmt, 'sd', $_POST['body'], $_POST['id']);
mysqli_stmt_execute($stmt);

*
i dont use bind param.reason debug.better validate before putting into query.
In pass ,i try do hack E.g
username : administrator
password : OR 1
vendor : asp classic
username : forgo
password : forgo
vendor : perl

The most important sql injection more on multi query .. if you do can by is via store procedure and parameterize it or do filtering before accepting it or do parameter binding via server side.


This post has been edited by alien3d: Nov 10 2014, 04:10 PM
alien3d
post Nov 20 2014, 11:41 AM

Look at all my stars!!
*******
Senior Member
3,740 posts

Joined: Mar 2009
Some C# AND SQL Server code just i have done for quote sql.Do remind is important exception for debugging output.
** Please on SQL Profiler if want to see your code in action live for easy debug.
** Some people would said better push to store procedure to validate the parameter but it kinda hard to debug. sweat.gif sweat.gif
CODE

public void create()
       {
           if (success == true)
           {
               transaction = connection.BeginTransaction();
               sql = new StringBuilder();
               sb = new StringBuilder();
               sw = new StringWriter(sb);

               sql.Append("    INSERT INTO [country]   ");
               sql.Append("    (   ");
               sql.Append("       [countryName],   [isDefault],    [isNew],    ");
               sql.Append("       [isUpdate],      [isDelete],     [isActive], ");
               sql.Append("       [executeBy],     [executeTime] ");
               sql.Append("    ) VALUES (  ");
               sql.Append("        @countryName,   @isDefault,     @isNew, ");
               sql.Append("        @isUpdate,      @isDelete,      @isActive,  ");
               sql.Append("        @executeBy,     @executeTime  ");
               sql.Append("    );  ");
               try
               {
                   result = new SqlCommand(sql.ToString(), connection);
               }
               catch (SqlException ex)
               {
                   if (Convert.ToInt32(Session["roleId"].ToString()) == 1)
                   {
                       errorMessages = new StringBuilder();
                       for (int i = 0; i < ex.Errors.Count; i++)
                       {
                           errorMessages.Append("Index #" + i + "|" +
                               "Message: " + ex.Errors[i].Message + "|" +
                               "LineNumber: " + ex.Errors[i].LineNumber + "|" +
                               "Source: " + ex.Errors[i].Source + "|" +
                               "Procedure: " + ex.Errors[i].Procedure + "|");
                       }
                       message = " System Problem : " + errorMessages;

                   }
                   else
                   {
                       message = "Please contact administrator " + shared.administratorEmail + "Please Come Back Later.";
                   }
                   shared.errorLogging(message.ToString(),sql.ToString());
                   using (JsonTextWriter json = new JsonTextWriter(sw))
                   {
                       json.WriteStartObject();
                       json.WritePropertyName("success");
                       json.WriteValue(false);
                       json.WritePropertyName("message");
                       json.WriteValue(message);
                       json.WriteEndObject();
                   }

                   Response.Write(sw.ToString());
                   sw.Close();
                   connection.Close();
                   Response.End();
               }
               result.Parameters.Add("@companyId", SqlDbType.Int);
               result.Parameters.Add("@countryName", SqlDbType.VarChar);
               result.Parameters.Add("@isNew", SqlDbType.Bit);
               result.Parameters.Add("@isActive", SqlDbType.Bit);
               result.Parameters.Add("@executeBy", SqlDbType.VarChar);
               result.Parameters.Add("@executeTime", SqlDbType.DateTime);

               result.Parameters[0].Value = Session["companyId"];
               result.Parameters[1].Value = Request.Form["countryName"];
               result.Parameters[2].Value = true;
               result.Parameters[3].Value = true;
               result.Parameters[4].Value = Session["clientName"];
               result.Parameters[5].Value = DateTime.Now;

               try
               {
                   result.ExecuteNonQuery();
               }
               catch (SqlException ex)
               {
                   if (Convert.ToInt32(Session["roleId"].ToString()) == 1)
                   {
                       errorMessages = new StringBuilder();
                       for (int i = 0; i < ex.Errors.Count; i++)
                       {
                           errorMessages.Append("Index #" + i + "|" +
                               "Message: " + ex.Errors[i].Message + "|" +
                               "LineNumber: " + ex.Errors[i].LineNumber + "|" +
                               "Source: " + ex.Errors[i].Source + "|" +
                               "Procedure: " + ex.Errors[i].Procedure + "|");
                       }
                       message = " System Problem : " + errorMessages;
                   }
                   else
                   {
                       message = "Please contact administrator " + shared.administratorEmail + "Please Come Back Later.";
                   }
                   shared.errorLogging(message.ToString(), sql.ToString());
                   using (JsonTextWriter json = new JsonTextWriter(sw))
                   {
                       json.WriteStartObject();
                       json.WritePropertyName("success");
                       json.WriteValue(false);
                       json.WritePropertyName("message");
                       json.WriteValue(message);
                       json.WriteEndObject();
                   }

                   Response.Write(sw.ToString());
                   sw.Close();
                   connection.Close();
                   Response.End();
               }
               result.Dispose();
               transaction.Commit();

               message = "Complete";
               using (JsonTextWriter json = new JsonTextWriter(sw))
               {
                   json.WriteStartObject();
                   json.WritePropertyName("success");
                   json.WriteValue(true);
                   json.WritePropertyName("message");
                   json.WriteValue(message);
                   json.WriteEndObject();
               }
               Response.Write(sw.ToString());
               sw.Close();
               connection.Close();
               Response.End();
           }
       }

FourZeroFour
post Mar 9 2015, 07:52 PM

Getting Started
**
Junior Member
176 posts

Joined: Apr 2008
Does doing prep statement + param binding also take care of the need for escaping spec char in var? Or I still need to use mysqli_real_escape_string for that? Don't shot me please. I haven't touched db since ages lol

This post has been edited by FourZeroFour: Mar 10 2015, 10:38 AM
malleus
post Mar 10 2015, 09:39 AM

Look at all my stars!!
*******
Senior Member
2,096 posts

Joined: Dec 2011
QUOTE(FourZeroFour @ Mar 9 2015, 07:52 PM)
Does doing prep statement + param binding take care of the need for escaping spec char in var? Or I still need to use mysqli_real_escape_string for that? Don't shot me please. I haven't touched db since ages lol
*
the idea behind parameter binding is to get away from the need to validate all your inputs manually. rule of thumb is never ever build your query strings manually. too much room for mistakes.
alien3d
post Oct 27 2016, 04:45 PM

Look at all my stars!!
*******
Senior Member
3,740 posts

Joined: Mar 2009
if you want quote import an array in c#.
CODE

List<l> u = new List<l>();
           var one = new l();
           one.testName = "richat";
           one.testAge = 16;
           var two = new l();
           two.testName = "mariah";
           two.testAge = 13;
           var three = new l();
           three.testName = "mariah";
           three.testAge = 13;
           var four = new l();
           four.testName = "mariah";
           four.testAge = 13;
           var five = new l();
           five.testName = "mariah";
           five.testAge = 13;
           u.Add(one);
           u.Add(two);
           u.Add(three);
           u.Add(four);
           u.Add(five);

           string a = @" (@testName_{0},@testAge_{1}),";
           object[] x = new object[2];
           string y = string.Empty;
           for (int j = 0; j < 5; j++)
           {
               for (int i = 0; i < 2; i++)
               {
                   x[i] = (j + 1).ToString();
               }
               command.Parameters.Add("@testName_" + (j+1).ToString(), MySqlDbType.VarChar).Value = u[j].testName;
               command.Parameters.Add("@testAge_" + (j+1).ToString(), MySqlDbType.Int32).Value = u[j].testAge;

               y += string.Format(a, x);
           }
           string sql = " INSERT INTO test (testName,testAge) VALUES " + y.TrimEnd(',');
           command.CommandText = sql;
           command.Connection = connection;
           try
           {
               command.ExecuteNonQuery();
           }
           catch (MySqlException ex)
           {
               MessageBox.Show(ex.Message);
           }
           finally
           {
               command.Dispose();
           }

** warning Microsoft still give warning sql injection error

 

Change to:
| Lo-Fi Version
0.0189sec    0.30    5 queries    GZIP Disabled
Time is now: 21st December 2025 - 07:47 PM