views:

440

answers:

3

hi friends,

how come have the code before hacked with SQL Injection :(

$query = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?", array(mysql_real_escape_string($this->input->post('username')), mysql_real_escape_string(MD5($this->input->post('password')))));  

appreciate helps!!

A: 

Try using the Active Record Class within the database library of codeigniter. It allows for safer queries, since the values are escaped automatically by the system.

http://codeigniter.com/user_guide/database/active_record.html

Sylvio
Using the query() method this way is exactly the same as passing it through ActiveRecord. Notice he is passing an array which is mapped to the ? in the query.
Phil Sturgeon
thanks Phil, did not know that, I just found it in the CI user guide
Sylvio
A: 

You don't need to use mysql_real_escape_string() as CodeIgniter Database driver does that for you. Double escaping your string could well cause some problems.

Phil Sturgeon
I had same hacking problem when I didnt have that mysql_real_escape_string() , and I was suggested to use that. than I added that, and I added MD5 to password, but again got hacked :(
artmania
"got hacked" is not very descriptive. Are you entirely sure it was SQL Injection, as that is very tricky to sneak through the driver class. There may well be a number of other ways to hack your system but we can't tell just from this code.
Phil Sturgeon
Indeed. Could have been anything - left the admin account with a default password? Set admin password to "letmein"? Virtual host hypervisor got compromised? (That's a bit over the top, I admit).
Piskvor
A: 

Use like this for more safer queries:

    $query_username = $this->db->query("SELECT COUNT(username) AS count_username FROM users WHERE username=?", $this->input->post('username'));
$row_username = $query_username->row_array();
if ($row_username['count_username'] > 0) {
  $query_password = $this->db->query("SELECT password FROM users WHERE username=?", $this->input->post('username'));
  $row_password = $query_password->row_array();
  if ($row_password['password'] == MD5($this->input->post('password')) {
    // LOGIN SUCCESS 
  } else {
    // LOGIN FAILED
  }
} else {
  // LOGIN FAILED
}
Arnas Risqianto