codeigniter admin login hacked although I have used all security matters - codeigniter

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!!

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.

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
}

Related

$_SESSION variables use in queries

I have spent nearly two days going in circles on this one.
I seem to have difficulty using $_SESSION or $_POST as strings in any query or converting them to strings to use.
I am using a simple hash approach to login to a site.
Extract from script is
<?php
session_start();
echo "******Running Authenticate<br>";
echo "data submitted<br>".$_POST['site_login']."<br>".$_POST['site_password']."<br><br>";
$SiteLogin = $_POST['site_login']
$_SESSION['site_login'] = $_POST['site_login'];
$_SESSION['site_password'] = $_POST['site_password'];
$_SESSION['session_id'] = session_id();
$_SESSION['Now_val'] = date('Y-m-d H:i:s');
//include 'showallvars.php';
include 'dbconfig.php';
// Prepare our SQL
if ($stmt = $con->prepare('SELECT site_index, site_password FROM web_sites WHERE site_login = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['site_login']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
echo "account exists";
}
else
{
header('Location: badindex.php');
}
if (password_verify($_POST['site_password'], $password)) {
// Verification success! User has loggedin!
echo "password good";
}
else
{
header('Location: badindex.php');
}
}
$_SESSION['loggedin'] = TRUE;
?>
that works fine
BUT there is another field ( 'site_name') in the record which i want to carry forward.
This should be easy !!
and there is a dozen ways of doing it
for example the "standard" example is something like
$name = $mysqli->query("SELECT site_name FROM web_sites WHERE site_login = 'fred'")->fetch_object()->site_name;
That works fine
but no matter how i try - concatenating or or ... I cannot get $_SESSION['site_login'] or $_POST['site_login'] to replace 'fred'.
There seems to be white space added in.
Assistance or guidance ?
It should be possible to as easy as doing the following:
So:
if ($stmt = $con->prepare('SELECT site_index, site_password
FROM web_sites WHERE site_login = ?')) {
becomes:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $SiteLogin)) {
Do note, it is bad practice to do directly parse $SiteLogin to a query, because now someone can SQL Inject this and hack your website. All they need to do is use your form and figure out that which field is responsible for $SiteLogin. You would need to escape your $SiteLogin. Assuming Mysqli, it would become:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $con->real_escape_string($SiteLogin))) {
Thank you for that BUT the instant I saw the curly brackets in your answer - it all came flooding back to me. I had forgotten that PHP has problems with the square brackets
$sql = ("SELECT site_name FROM web_sites WHERE site_login = '". $_SESSION{'site_login'} ."' LIMIT 1");
I KNEW it was easy !
Your comments on injection are of course correct but this was an edited code excerpt and $SiteLogin was just added in as a "temporary working variable if needed"

use SELECT and SESSION to check login user doesn't work

Could you tell me why this is not working? I just want to check whether the userid is really exists. if it does exist, means the registered users are able to do anything on the website. However, my coding doesnt work for that. One for registered users and another one for admin. My coding is something like this. Any idea?
session_start();
$sql = "SELECT *
FROM tablename
WHERE userid = '".$_SESSION["userid"]."' ";
$check = mysqli_query($link,$sql);
if (mysqli_num_rows($check) == 1 && $_SESSION['username'] == 'admin') {
echo "<p> HELLO </p> ";
}
Any ideas?
I faked it and it worked for me. Make sure there is a value in session and if your database connection is ok. The mysqli_error will show possible failures (always thrown errors in your code).
$sql = "SELECT *
FROM tablename
WHERE userid = '".$_SESSION["userid"]."' ";
$check = mysqli_query($link,$sql) or die(mysqli_error($link));
if (mysqli_num_rows($check) == 1 && $_SESSION['username'] == 'admin') {
echo "<p> HELLO </p> ";
}
session_start();
$sel="select * from register where userid='$userid' and password='$pass'";
$res= mysql_query($sel);
$co= mysql_num_rows($res);
echo $co;
if($co>0) {
$row=mysql_fetch_array($res);
$_SESSION['id']=$row['userid'];
header("echo 'helloooooooo'");
} else {
echo "Invalid userid....";
}
header("location:login.php");
}

phpass not working

I'm hashing the passwords upon account creation, and that it working (with the password set to VARCHAR(60)) but when I try to do this:
$query = $this->CI->db->query("SELECT * FROM users WHERE email = ?", $email);
if ($query->num_rows() > 0) {
$user_pass = $query->row()->password;
$hasher = new PasswordHash(PHPASS_HASH_STRENGTH, PHPASS_HASH_PORTABLE);
if ($hasher->CheckPassword($user_pass, $pass)) {
return true;
} else {
return false;
}
} else {
return false;
}
it always returns false. Any ideas as to why this might be? (the password I'm providing is correct)
I think you have inverted the check password field. It has to be like this:
$hasher->CheckPassword(password which has to be checked, password from database).
This makes a difference because Check Password is going to hash the password which is to be checked.

magento saving admin details

I'm wondering if its possible to programmatically save admin user details? email, password, first name, last name and password.
This is what I have so far:
$details = Mage::getSingleton('admin/session')->getUser();
$details->setEmail($postData['email'])
->setFirstName($postData['first_name'])
->setLastName($postData['last_name']);
if($postData['password']) {
if($postData['password'] === $postData['password_confirm']) {
$details->setPassword($postData['password']);
}
}
$details->save();
However, it's not saving (it is saving other details). It is also not generating any errors.
Got it working:
$details = Mage::getSingleton('admin/session')->getUser();
$model = Mage::getModel('admin/user')->load($details2->getUserId());
$model->setEmail($postData['email'])
->setFirstname($postData['firstname'])
->setLastname($postData['lastname']);
if($postData['password']) {
if($postData['password'] === $postData['password_confirm']) {
$model->setPassword($postData['password']);
}
}
$model->save();

Twitter API - saving OAuth token in session

I am trying to find a way to keep connected with the Twitter API once authorised using OAuth but am having problems.
I get "Invalid / expired Token" when trying to connect to Twitter API using a saved Oauth token in a session or database.
Is there a way to do this? I dont want the users of my App to have to login via Twitter every time. Surely once they have authorised my App once, that should be enough?
$consumer_key = 'consumerkey';
$consumer_secret = 'consumersecret';
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
if (isset($_GET['oauth_token'])){
$oauth_token = $_GET['oauth_token'];
} else if ($_SESSION['oauth_token']){
$oauth_token = $_SESSION['oauth_token'];
echo $_SESSION['oauth_token'];
} else {
//see if authorisation already set up in DB
$query = mysql_query("SELECT oauth_token FROM PingSocialMediaUsers WHERE oauth_provider = 'twitter' AND clientID = '$clientID'");
$result = mysql_fetch_row($query);
$oauth_token = $result[0];
}
if($oauth_token == ''){
$url = $twitterObj->getAuthorizationUrl();
$twitter_login = $url;
} else {
$twitterObj->setToken($oauth_token);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$_SESSION['oauth_token'] = $token->oauth_token;
$_SESSION['oauth_secret'] = $token->oauth_token_secret;
$twitterInfo= $twitterObj->get_accountVerify_credentials();
$twitterInfo->response;
echo $twitterInfo->response['error'];
//echo '<pre>';
//print_r($twitterInfo);
$id = $twitterInfo->id;
$username = $twitterInfo->screen_name;
//add to details database
//find the user by ID
if ($id != ''){
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE oauth_provider = 'twitter' AND oauth_uid = '$id'");
$result = mysql_fetch_array($query);
// If does not exist add to database
if(empty($result)){
$query = mysql_query("INSERT INTO PingSocialMediaUsers (oauth_provider, oauth_uid, username, oauth_token, oauth_secret) VALUES ('twitter', {$id}, '{$username}', '{$_SESSION['oauth_token']}', '{$_SESSION['oauth_secret']}')");
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
//update the tokens
$query = mysql_query("UPDATE PingSocialMediaUsers SET oauth_token = '{$_SESSION['oauth_token']}', oauth_secret = '{$_SESSION['oauth_secret']}' WHERE oauth_provider = 'twitter' AND oauth_uid = {$id}");
}
$_SESSION['id'] = $result['id'];
$_SESSION['username'] = $result['username'];
$_SESSION['oauth_uid'] = $result['oauth_uid'];
$_SESSION['oauth_provider'] = $result['oauth_provider'];
$_SESSION['oauth_token'] = $result['oauth_token'];
$_SESSION['oauth_secret'] = $result['oauth_secret'];
}
$twitterAuth = TRUE;
}
I believe you are talking about access_token which you will get from the twitter as last part of OAuth handshaking after which you can go to access there services on user behalf.
Here is what they are saying in there official developer page
We do not currently expire access tokens.
Your access token will be invalid if a user explicitly
rejects your application from their settings or if a Twitter admin suspends
your application. If your application is suspended there will be
a note on your application page saying that it has been suspended.
So you can very well store that token in your database and can always use at later stage.
here is the reference to there API page
Twitter OAuth FAQ
So i suggest you to make sure that you are not changing any application setting and you are getting a valid access_token from session/database

Resources