Laravel Auth Failed? - php

I am creating a simple login page for my application but my auth always says i'm failed?
$email = Input::get('email');
//echo = matchesmyemail
$password = Input::get('password');
//echo = matchesmydbpassword
$auth = Auth::attempt(array(
'email' => $email,
'password' => $password
));
if($auth){
die('logged in');
}else{
die('failed');
}
Any ideas what i'm doing incorrect?

Is your password hashed in the database?
$password = Hash::make('password');
If you have a plain text password in the database table than that is the problem. The password will be hashed and the hashes will be compared.

Related

Why OWASP ZAP detect SQL injection?

I'd like to know why OWASP ZAP detect potential SQL injection on my login page. I call an API to connect my users.
PHP slim API code:
$sql = "SELECT id, idGroup, idTeam,lastName, firstName, isLogged, login, phoneNumber, webrtc FROM users WHERE enable = 1 AND login = :login AND password = :password";
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$userPass = md5($password);
$stmt->bindParam(':login', $login);
$stmt->bindParam(':password', $userPass);
$stmt->execute();
$user = $stmt->fetchAll(PDO::FETCH_OBJ);
Login page:
$login = $_POST['username'];
$password = $_POST['password'];
$client = new GuzzleHttp\Client();
$response = $client->request('POST', $apiUrl . 'agent/login', [
'form_params' => [
'login' => $login,
'password' => $password,
'ipAddress' => $_SERVER['REMOTE_ADDR'],
]
]);
$data = json_decode($response->getBody(), true);
if (isset($data[0]['id']) && $data[0]['id'] > 0) {
$_SESSION['fullName'] = $data[0]['firstName'] . ' ' . $data[0]['lastName'];
$_SESSION['idGroup'] = $data[0]['idGroup'];
$_SESSION['idTeam'] = $data[0]['idTeam'];
$_SESSION['idUser'] = $data[0]['id'];
$_SESSION['login'] = $data[0]['login'];
$_SESSION['phoneNumber'] = $data[0]['phoneNumber'];
$_SESSION['webrtc'] = $data[0]['webrtc'];
//Get roles for user
$response = $client->request('GET', $apiUrl . 'web/permissions/' . $login);
$data = json_decode($response->getBody(),true);
foreach ($data as $roles) {
$_SESSION['roles'][$roles['bit']] = $roles['name'];
}
echo "<script>window.open('index.php','_self')</script>";
}
All my APIs use prepared statements and parameterized queries.
Here's the OWASP ZAP alert:
The page results were successfully manipulated using the boolean
conditions [ZAP" AND "1"="1" -- ] and [ZAP" AND "1"="2" -- ] The
parameter value being modified was NOT stripped from the HTML output
for the purposes of the comparison Data was returned for the original
parameter.
This may happen if the response page for the form submission contains the value of a form field as it was specified by a user. For instance if you are logging in your user and use the value of 'username' field to greet the user but pull it not from the DB but from the request variables. SQL injection does not take place but the scanning script assumes that you stored the value unsanitized in the DB while you just using the value provided by a user and not the value that you have stored in the DB. Hope this makes sense.

different value when retrieving data from database

i am a beginner in PHP & MySQL development, I am following a tutorial. I am trying to make login system, after inserting data to Mysql in registration. I want to validate the password from the database and the password from user in login page, if it is match, then login is successful.
here is the password from the database, as we can see, for username=admin the password is 3462623.....
The data type of this database is like this
as we can see, the data type for password and salt is Binary.
when I tried to var_dump the variable which stores the value from the database, the password and salt is different from what appears in the database.
the password should be : 3462623.....
but from var_dump, the password is : 4bb5d8229634bf5 .....
other data like id,username,email are correct. just password and salt are different.
I suspect this is because the return value data type from var_dump is String, but when i stored to database, the datatype is Binary, how do I fix that ? it seems that from tutorial I saw, the login system still OK even though the password in string data type.
to be honest I don't understand why it has to be Binary data type. but I guess it because it will be encrypted.
so what went wrong in here?
here is the code :
Registration Process
$username = htmlentities($_REQUEST["username"]);
$password = htmlentities($_REQUEST["password"]);
$fullname = htmlentities($_REQUEST["fullname"]);
$email = htmlentities($_REQUEST["email"]);
if (empty($username) || empty($password) || empty($fullname) || empty($email)) {
$returnArray = [
"status" => "400",
"message" => "missing required information"
];
echo json_encode($returnArray);
return;
}
//encrypt the password
$salt=openssl_random_pseudo_bytes(20);
$securedPassword = sha1($password.$salt);
// Create Connection
$file = parse_ini_file("../../../twitter.ini");
$dbhost = trim($file["host"]);
$dbusername = trim($file["username"]);
$dbpassword = trim($file["password"]);
$dbname = trim($file["dbname"]);
$access = new access($dbhost,$dbusername,$dbpassword,$dbname);
$access->connect();
function registerUser($username,$password,$salt,$email,$fullname) {
$query = "INSERT INTO users SET username=?, password=?,salt=?,email=?,fullname=?";
$statement = $this->conn->prepare($query);
if (!$statement) {
throw new Exception($statement->error);
}
$statement-> bind_param('sssss',$username,$password,$salt,$email,$fullname);
$returnValue = $statement -> execute();
return $returnValue;
}
// Insert data to database
$result = $access->registerUser($username,$securedPassword,$salt,$email,$fullname);
if ($result) {
// get data from database
$user = $access->selectUser($username);
$resultArray = [
"status" => "200",
"message" => "Sucessfully registered",
"id" => $user["id"],
"username" => $user["username"],
"email" => $user["email"],
"avatar" => $user["avatar"],
"fullname" => $user["fullname"]
];
login process
$username = htmlentities($_REQUEST["username"]);
$password = htmlentities($_REQUEST["password"]);
if (empty($username) || empty($password)) {
$returnArray = [
"status" => "400",
"message" => "missing required information"
];
echo json_encode($returnArray);
return;
}
// make connection
$file = parse_ini_file("../../../twitter.ini");
$dbhost = trim($file["host"]);
$dbusername = trim($file["username"]);
$dbpassword = trim($file["password"]);
$dbname = trim($file["dbname"]);
$access = new access($dbhost,$dbusername,$dbpassword,$dbname);
$access->connect();
$user = $access -> getUserData($username);
if (empty($user)) {
$returnArray = [
"status" => "403",
"message" => "User is not found"
];
echo json_encode($returnArray);
return;
} else {
// password validation
$securedPassword = $user["password"];
$salt = $user["salt"];
if ($securedPassword === sha1($password.$salt)) {
$resultArray = [
"status" => "200",
"message" => "Login Success!",
"id" => $user["id"],
"username" => $user["username"],
"email" => $user["email"],
"avatar" => $user["avatar"],
"fullname" => $user["fullname"]
];
} else {
$returnArray = [
"status" => "403",
"message" => "Password didn't match"
];
}
}
$access ->disconnect();
echo json_encode($returnArray);
As pointed out by other users, password and salt should be char or varchar or even text, but not binary.
The reason you see a difference between them is based on the method of access and character sets used in retrieval and display.
In one case you are retrieving using PHP and then displaying using (likely) a PRE tag and showing it on a web page. In the other case you are viewing it in phpMyAdmin or some other MySQL desk system. Each one of these requires several translations before viewing and as binary data they will not display the same way reliably when retrieved with two different pathways (phpMyAdmin will translate the character set differently, and then display the result differently).
A simple solution to this is to switch to a non-binary (TEXT/VARCHAR) field definition.
Alternately, you could attempt to retrieve them as HEX or some other Binary Friendly display method in both your MySQL desk (using a query, not just displaying in the table) and in the php/mysqli query as well. In essence, then, you'd be converting the binary to a known text display set.

Facebook Login with Sentry, A password is required for user [email], none given

I'm trying to allow users to login using facebook but my user management is based on sentry
as you know if you connect from facebook, you wont need a password unless you are creating a account normally. Is there a way to tell sentry(http://docs.cartalyst.com/sentry-2/installation/laravel-4) that this is a facebook login and it doesnt require a "password"
I tried giving the account a temp password but i receive
A hasher has not been provided for the user , even when i hash it.
Any advice on this?
I'm also using http://maxoffsky.com/code-blog/integrating-facebook-login-into-laravel-application/ as a guide
Route::get('login/fb/callback', function() {
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
$facebook = new Facebook(Config::get('facebook'));
$uid = $facebook->getUser();
if ($uid == 0) return Redirect::to('/')->with('message', 'There was an error');
$me = $facebook->api('/me');
$profile = Profile::whereUid($uid)->first();
if (empty($profile)) {
$user = new User;
$user->name = $me['first_name'].' '.$me['last_name'];
$user->email = $me['email'];
$user->photo = 'https://graph.facebook.com/'.$me['username'].'/picture?type=large';
$user->save();
$profile = new Profile();
$profile->uid = $uid;
$profile->username = $me['username'];
$profile = $user->profiles()->save($profile);
}
$profile->access_token = $facebook->getAccessToken();
$profile->save();
$user = $profile->user;
Auth::login($user);
return Redirect::to('/')->with('message', 'Logged in with Facebook');
});
I think that when you create the user you need to use Sentry::createUser()
$user = Sentry::createUser(array(
'name' => $me['first_name'].' '.$me['last_name'],
'email' => $me['email'],
'password' => 'test',
'photo' => 'https://graph.facebook.com/'.$me['username'].'/picture?type=large',
));
And then use Sentry::login($user, false); to force a login for the user without a password.
You probably also want to put something in the password field other than test if you also have a regular non-facebook login.
Also you may have to activate the user depending on what your plans were with that email:
//You could email this to the user from here.
$activationCode = $user->getActivationCode();
//OR just activate immediately.
$user->attemptActivation($activationCode);
I'm looking at doing something similar, and was thinking of using the facebook uid as the password. Would this not work?
Edit:
I can confirm the following works for me:
function callback()
{
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
$facebook = new Facebook(Config::get('facebook'));
$uid = $facebook->getUser();
if ($uid == 0) return Redirect::to('/')->with('message', 'There was an error');
$me = $facebook->api('/me');
//dd($me);
//Check if user profile exists
$profile = Profile::whereUid($uid)->first();
if (empty($profile)) {
// Create the user
$user = Sentry::createUser(array(
'email' => $me['email'],
'password' => $uid,
'first_name' => $me['first_name'],
'last_name' => $me['last_name'],
'photo' => 'https://graph.facebook.com/'.$me['username'].'/picture?type=large',
'activated' => 1
));
// Find the group using the group id
$registered = Sentry::findGroupById(2);
// Assign the group to the user
$user->addGroup($registered);
$profile = new Profile();
$profile->uid = $uid;
$profile->username = $me['username'];
$profile = $user->profiles()->save($profile);
}
$profile->access_token = $facebook->getAccessToken();
$profile->save();
$user = $profile->user;
Sentry::login($user, false);
$user = Sentry::getUser();
echo $user->first_name . " logged in.";
//return Redirect::to('/')->with('message', 'Logged in with Facebook');
}
Also note that you'll need customize the model sentry uses using this method (http://forums.laravel.io/viewtopic.php?pid=48274#p48274) in order to specify the relationship with profiles

Laravel 4 Authentication

I'm having trouble getting the Authentication to work with laravel 4. This is my whole sign in function when a user enters their email and password into the form.
public function getSignin() {
$return_arr = array();
$email = Input::get('email');
$password = Input::get('password');
$validation = Validator::make(
array(
'Email' => $email,
'Password' => $password
), array(
'Email' => 'required|Email',
'Password' => 'required'
)
);
if ($validation->passes()) {
$pass = base64_encode($password);
$details = array ('email' => $email, 'password' => $pass);
if (Auth::attempt($details)) {
$return_arr['frm_check'] = 'success';
$return_arr['msg'] = 'logged in';
} else {
$return_arr['frm_check'] = 'error';
$return_arr['msg'] = 'log in failed';
}
} else {
$errors = $validation->messages();
$return_arr['frm_check'] = 'error';
$return_arr['msg'] = $errors->first();
}
echo json_encode($return_arr);
$this->layout = null;
return;
}
Even though the email and password are in the same row in the database, it still returns log in failed, was wondering if anyone could shed some light on to this situation?
If I've missed off any other crucial details let me know and I'll post them right away. Thanks in advance.
Based on your comments...
When you're creating your $user, use Hash::make($password) to hash the password using BCrypt, before saving it in your db.
Then, when the user's logging in just use Auth::attempt($credentials) as you are, but don't use base_64 to encrypt it, the Auth method does it all for you!
Much more on the excellent Laravel docs: http://laravel.com/docs/security
Unless you have base64 encoded your password on save(), remove this line from your code:
$pass = base64_encode($password);
And edit this one to:
$details = array ('email' => $email, 'password' => $password);
Auth::attempt() will hash it for you, using something safer than base64.
EDIT:
To correctly save your passwords you have to do something like this:
$user = new User;
$user->email = 'me#me.com';
$user->password = Hash::make('mySuperSecretPassword');
$user->save();
Then you can user attempt just passing it unhashed.
Here's a tutorial I wrote; which might help!
https://medium.com/on-coding/e8d93c9ce0e2

Joomla manual login with controller

I am developing a component for Joomla. It has integrations with popular social websites. I retrieve user information from database via given social profile. Then, I try to make this user login with the following code:
$fbuser = $facebook->api(
'/me',
'GET',
array(
'access_token' => $_SESSION['active']['access_token']
)
);
// Get a database object
$db =& JFactory::getDBO();
$query = "SELECT * FROM #__users WHERE email = '".$fbuser['email']."';";
$db->setQuery($query);
$row = $db->loadRow();
if(isset($row))
{
$app = JFactory::getApplication();
$user =& JUser::getInstance($row[0]);
$credentials = array();
$credentials['username'] = $user->get('username');
$credentials['password'] = $user->get('password'); // When I change this to related users plain password then it works
$options = array();
$options['remember'] = true;
$options['silent'] = true;
$app->login($credentials, $options);
}
else
{
return 'There is no account associated with facebook';
}
The problem is database return encoded password and this doesn't work. When I give decoded password to $credentials it works. What can be the problem?
One option is to create your own authentication plugin (quite simple task) that would log in any user with a specific password known only to you and the site.
Then you can supply that password along with known username.
For the sake of security, only allow that plugin to log in ordinary users, and not admins.
You need to MD5 hash the pwd (the way it's stored in the DB).
try this:
$salt = '19IQYkelXrqVH1Eht6PFOIZRe5T1SQHs';
$pwd = md5_hex($pwd . $salt) .":$salt";
$query = "select name,username,email,password from jos_users where password = $pwd;";
...
// --- login mamanam.com
$app = JFactory::getApplication();
$credentials = array();
$credentials['username'] = $username;
$credentials['password'] = $password;
$app->login($credentials);
Necessary parameters in array $credentials=array() for logon function Joomla! $app->login($credentials)
*Sorry my English is not so good

Categories