Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am building a website with a user page. Currently it is set up in the following way:
The user types their username and password into corresponding fields then the user pressed submit.
The js code sends a get request to a php script with the password and username in plain text.
The php returns a randomly generated session token to the js code if the credentials are correct and an error message otherwise.
All future interactions the user engages in while logged on will now require the session token to be provided in any get requests. The php will then check that the session token is correct.
In the back end, the user name is stored in a database along side a salt and the hash (sha256) of the salted password. (the salt is randomly generated upon account creation).
My question is as follows: Is there anything in the description above that seems insecure? If so, what should be done instead. More broadly, what are the best practices around setting up a user login page or account system for a website. Thanks
Why are you trying to re-invent the wheel.
Php already has builting password encryption functions so why using Sha256 + Salt.
Again they are two type of authentication
1.) Session Based Login
2.) Token Based Login.
From your write-up you are combining session login with token login. You will need to decide which one that you want to apply.
Consequently they are alot of php validation or sanitization functions that you need to know to keep your code more secured.
1.) use strip_tags()
This will strips out all html elements from form inputs or variables
Eg
$email = strip_tags($_POST['email']);
2.) use htmlentities or htmlspecialchars to prevent XSS Attack.
This converts htmls tags to their respective entities. its only used when printing or echoing result to html page to
You will see how i used it in the welcome.php page
See Applications:
$email = htmlentities($_POST['email']);
3.) escaping variables against sql injection Attack
If you are using Mysqli, the best sql method to be used is prepared Statement.
Alternatively you can still escape variables using mysqli_real_escape_string() functions
See Application
// escape variables Against sql injections
$email = mysqli_real_escape_string($conn, $_POST['email']);
4.) If you are using session based login, You need to use sessionId regenerate method. This will help to regenerate new session
Id as user login thus preventing session fixation attack. do not worry you will need how to use it in the login.php code below
See Application:
// first you will need to initialize sessions
session_start();
session_regenerate_id();
This are just few among other security measures
Lets have a look at Session based login using php password verify functions
Assume this is your
registeration.php
<?php
$conn = mysqli_connect("localhost","root","","demo");
if(!$conn){
die("Connection error: " . mysqli_connect_error());
}
if(isset($_POST['submit'])){
$firstName = mysqli_real_escape_string($conn,$_POST['first_name']);
$surName = mysqli_real_escape_string($conn,$_POST['surname']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$options = array("cost"=>4);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into users (first_name, last_name,email, password) value('".$firstName."', '".$surName."', '".$email."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}
}
?>
This is now how your login.php code will look like
<?php
$conn = mysqli_connect("localhost","root","","demo");
if(!$conn){
die("Connection error: " . mysqli_connect_error());
}
if(isset($_POST['submit'])){
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$sql = "select * from users where email = '".$email."'";
$rs = mysqli_query($conn,$sql);
$numRows = mysqli_num_rows($rs);
if($numRows == 1){
$row = mysqli_fetch_assoc($rs);
if(password_verify($password,$row['password'])){
echo "Password verified and ok";
// initialize session if things where ok.
session_start();
session_regenerate_id();
$_SESSION['surname'] = $row['surname'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['email'] = $row['email'];
// take me to welcome.php page
header('Location: welcome.php');
}
else{
echo "Wrong Password details";
}
}
else{
echo "User does not exist";
}
}
?>
Welcome.php will now look like code below to show authenticated users session info.
//use htmlentities or htmlspecialchars to prevent XSS Attack.
<?php echo htmlentities($_SESSION['surname'], ENT_QUOTES, "UTF-8"); ?>
<?php echo htmlspecialchars($_SESSION['first_name'], ENT_QUOTES, "UTF-8"); ?>
<?php echo htmlentities($_SESSION['email'], ENT_QUOTES, "UTF-8"); ?>
Now in your post I Saw where you wrote sending a generated token with every http request. In this case I guess you are
trying to mitigate CSRF Attack.
Here is the best and most secured way to do once you logged in
To prevent CSRF you'll want to validate a one-time token, POST'ed and associated with the current session.
Something like the following . . .
On the page where the user requests eg to insert a record for payments:
payment.php
<?php
session_start();
$token= md5(uniqid());
$_SESSION['payment_token']= $token;
session_write_close();
?>
<html>
<body>
<form method="post" action="payment_save.php">
<input type="hidden" name="token" value="<?php echo $token; ?>" />
Amount: <input type="hidden" name="token" value="100 usd" />
<input type="submit" value="submit" />
</form>
</body>
</html>
Then when it comes to actually inserting the record:
payment_save.php
<?php
session_start();
$token = $_SESSION['payment_token'];
unset($_SESSION['payment_token']);
session_write_close();
if ($token && $_POST['token']==$token) {
// Insert the record for payment
} else {
// log message. You are vulnerable to CSRF attack.
}
?>
The token should be hard to guess, unique for each insert request, accepted via $_POST only and expire after a few minutes
(expiration not shown in this illustrations).
Related
I have a table in my php that shows the data of a table in my database: username, email, etc. and I have also added an option to delete. The delete option works correctly and also shows a confirmation message with a necessary password before deleting.
I have the passwords saved in a table in the database but not encrypted.
The problem is that if a user explores the content of the page they can see what’s the password, so anyone can be able to delete data from the database. Therefore, a more or less skilled user can easily explore that content.
What can I do to prevent this from happening? Should I copy the same JavaScript code in another script and delete it from index.php? For more security, I tried to use a hash on the same index.php page but you can also see what the password is.
This is my code:
index.php
<table id="professorsRegistered" border="1px">
<tr>
<th colspan="3"><h2>Users</h2></th>
</tr>
<tr>
<th> Name </th>
<th> Email </th>
<th> Delete </th>
</tr>
<?php
$sql = "SELECT * FROM users"; /*Select from table name: users*/
$result = $conn->query($sql); /*Check connection*/
if ($result->num_rows==0){
echo "No users";
}else{
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["username"]."</td><td>".$row["email"]."</td><td><a class='eliminate' onClick=\"getPass(".$row['id'].");\">X</a></td></tr>";
}
}
?>
</table>
<?php
$sql = "SELECT password FROM passwords WHERE passwords_id = '1';"; /*Select from table name: passwords*/
$result = $conn->query($sql); /*Check connection*/
$row = $result->fetch_assoc();
$password = $row["password"];
$hash = sha1($password);
/*echo "<p>".$hash."</p>";*/
?>
<script type = "text/javascript">
function getPass(user) {
var securePass = "<?php echo $password ?>";
var pass = prompt("Introduce password to delete: ", "Password");
if (pass!=securePass) {
return confirm('Incorrect Password');
}
else if (pass==securePass) {
window.location='delete.php?id='+user;
}
}
</script>
Delete.php
<?php
include('Conexion.php'); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id']; // $id is defined
mysqli_query($conn,"DELETE FROM users WHERE id='".$id."'");
mysqli_close($conn);
header("Location: index.php");
?>
To make this more secure you should look at doing the following:
Ensure that the credentials are validated in the server-side code (PHP), not the client side code. As malicious user can very easily either edit the JavaScript or post data directly to your server and totally bypass your code.
Passwords should be hashed with a appropriate password hashing algorithm. SHA1 is not a good algorithm for password hashing as it is too fast, which makes brute force and dictionary attacks easier. A better choice would be something like bcrypt or pbkdf2 these are much slower making the above attacks much more difficult. You should also salt your password. This means just adding some randomness to the password before it is hashed. This will help prevent an attack known as a rainbow table attack in which an attacker uses a set of pre-hashed values and corresponding plain text to speed up the brute force process.
Do not build SQL query stings by string contactination as this leaves your application vulnerable to SQL injection attacks. If a malicious user was to send up 1' OR 1=1 -- as the id parameter then all the users would be deleted, this technique could also be used dump all of the data from the database or even delete the database altogether. Look in to using parameterized queries instead.
Luckily there is already loads of information on how to do this the right way. I would recommend looking at the OWASP website which has plenty of examples.
There are a couple of things which are very wrong about this design. You need to fix them.
Do not store cleartext passwords in your database. Hash passwords using a password hash function (like PHP's password_hash() or sodium_crypto_pwhash()) before storing them in the database. (SHA1 is not a password hash, and should not be used for this purpose.)
Do not construct SQL queries with string interpolation or concatenation. You're already using PDO, so you can easily use parameter placeholders to prevent SQL injection.
Do not expose password hashes to the browser in any form. If you need to verify a password, submit it to the server as part of the request to perform a password-protected action, so that a user cannot bypass the password check by typing a URL in manually.
I am setting up a login page to take a users username and password then check that against a local database, however nothing is echoing form the database connection and there is no redirecting to the next page 'welcome.php' happening.
I have already tried many different ways of connecting to the local database and redirecting to different pages with different methods, none of which gave any error message or worked. using XAMPP Apache and mySQL modules to provide the local server.
<?php
if (isset($_POST['Login']))
{
$link = mysql_connect('localhost','root','password','budget');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
session_start();
$username= $_POST['username'];
$password= sha1($_POST['password']);
$_SESSION['login_user']=$username;
$query = mysql_query("SELECT accounts.username, passwords.password_hash
FROM accounts
INNER JOIN passwords ON accounts.account_id = passwords.account_id
WHERE accounts.username = '$username' AND password_hash = '$password';");
if (mysql_num_rows($query) != 0){
?>
<script type="text/javascript">window.location.replace(welcome.php);
</script>;
<?php
mysql_close($link);
}
}
?>
I expect it to redirect to 'welcome.php' but instead it just refreshes the same page and nothing is echoed or given as an error
What isn't working?
Your JavaScript location.replace method needs a string as an input, you're not giving it that (as the input value is not quoted). It would be window.location.replace('welcome.php'); instead.
How to solve it?
The better solution is to redirect in PHP instead of in JavaScript, using header().
Additional remarks
I took the liberty of converting your code to use mysqli_ instead of the old, outdated and deprecated mysqli_ library. With this, you can use a prepared statement, as I have shown below. Use this approach for all your queries, bind the parameters through placeholders.
session_start();
if (isset($_POST['Login'])) {
$link = mysqli_connect('localhost','root','password','budget');
if ($link->connection_errno) {
die('Could not connect: ' . $con->error);
}
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $link->prepare("SELECT a.username, p.password_hash
FROM accounts a
INNER JOIN passwords p
ON a.account_id = a.account_id
WHERE a.username = ?
AND p.password_hash = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->bind_result($resultUsername, $resultPassword);
$stmt->execute();
if ($stmt->num_rows) {
$_SESSION['login_user'] = $username;
header("Location: welcome.php");
}
$stmt->close();
}
What's next?
Fix your passwords. Using sha1() is highly insecure for passwords, look into using passwords_hash()/password_verify() instead.
You need to add single quote around welcome.php
As welcome.php is neither a JavaScript keyword like this nor a number, single quote is mandatory also it is not a variable/object.
JS considers welcome as object and php as its method in welcome.php
Without it, a JavaScript error will be displayed:
ReferenceError: welcome is not defined
<script type="text/javascript">window.location.replace(welcome.php);
</script>
Also, there is no need of semi-colon ;.
JavaScript redirect without any condition.
I am new on PHP and trying to do get the user agent from the visitor of the website then send this information to the MySQL.
Home.html (this page has a button where the user should click on it to take him to another page where he will see his device information
<div id="TestMe_img">
<a href="Result.php">
<input type="submit" value="Test Your Device">
</a>
</div>
Result.php (the result page contain 2 things: 1- php code. 2- html code)
PHP
<?php
$server = "localhost";
$user = "root";
$pass = "";
$dbname = "user_data";
$userAgent = $_POST['userAgent'];
// Create connection
$conn = new mysqli($server,$user, $pass, $dbname);
// Check connection
if($conn -> connect_error) {
die("Conneciton Failed: " . $conn -> connect_error);
}
if (empty($userAgent)) {
echo "User Agent is blank";
die();
}
$sql = "INSERT INTO UserData (UserAgent) VALUES ('$userAgent')";
if ($conn -> query($sql) === TRUE) {
echo "Thank you! Hana is stupid";
}
else
echo "Unfortunately Hana is smart";
$conn -> close();
?>
HTML Part
<body onload="userAgent();">
<table>
<tr>
<td>user agent</td>
<td id="userAgent"></td>
</tr>
</table>
</body>
JavaScript
function userAgent(){
var userAgent = navigator.userAgent;
document.getElementById('userAgent').innerHTML = userAgent;
}
However, there is a mistake that I can not find because every time I click on the button it takes me to the result.php and show me the code on the browser with no result appear on the database!
OK, this is going to be slightly longer, but bear with me.
1st: You will be getting a "User Agent is blank" message, because the user agent is not actually submitted to the PHP page. You need to put an input (hidden or text) into a form, push the data inside and then submit that form. Change your HTML like this, then at least your date will be submitted:
<form method="post" action="Result.php">
<input type="hidden" id="userAgent">
<input type="submit" value="Test Your Device">
</form>
2nd: You don't even need to do that, because the userAgent is available to PHP already, even without submitting it manually. Just use this variable:
$_SERVER['HTTP_USER_AGENT']
3rd: You should NEVER put unsanitized input into an SQL string. This will lead to SQL injections and your server will be hacked.
Instead of:
$sql = "INSERT INTO UserData (UserAgent) VALUES ('$userAgent')";
$conn->query($sql);
You have to use a prepared statement (for pretty much any query that accepts variables), so that nobody can manipulate your query. Otherwise if your $userAgent variable contained a single quote, you could break out of your query and the attacker could inject any SQL code he wanted. So do this to fix your security issue:
$statement = $conn->prepare("INSERT INTO UserData (UserAgent) VALUES (?)");
$statement->bind_param('s', $userAgent);
$statement->execute();
The 's' parameter is actually one letter per each parameter you want to prepare in the statement. In this case it indicates you want to pass a string. "i" would be an integer, "d" a double, see here for more: http://php.net/manual/de/mysqli-stmt.bind-param.php
4th: Your question has absolutely nothing to do with phpMyAdmin, so you should probably change the title.
I hope this helps you get started.
I have a login.html webpage that lets user enter his username and password. When he clicks on submit I collect the entered value using Javascript and then make a Ajax POST Call to the php file and send the username and password.
My concern here is that is this a safe way of sending username and password ? If not how can i secure this transaction of sending data from html file to php running the backend?
The php file then connects to the MySql Db and checks if the user exits and if the password is correct If Yes it simply sends a Valid text back to the ajax calls to the javascript function if not I determine it is an invalid user ?
I am not quite happy with this logic ? Is there a better way to implement this process ? Since i am putting my code to production I want to secure it as much as possible.
The below code works fine i just need tips to secure it.
login.html
<div>
<h3>Login information</h3>
<input type="text" name="user" id="usrnm" placeholder="Username/Email">
<input type="password" name="pswdlogin" id="pswdlogin" placeholder="Password">
<input type="checkbox" name="keepmeloggedin" id="keepmeloggedin" value="1" data-mini="true">
<input type="submit" data-inline="false" onclick="logmein()" value="Log in">
<div id="loginstatus"> </div>
</div>
logmein.js
function logmein() {
var usrnm = document.getElementById("usrnm").value;
var pswdlogin = document.getElementById("pswdlogin").value;
$.post("http://xyz/mobile/php/logmein.php",
{
usrnm: usrnm,
pswdlogin: pswdlogin
},
function(data, status) {
if (data == 'Valid') {
window.open("http://xyz/mobile/home.html?email=" + usrnm + "", "_parent");
} else {
alert(data);
document.getElementById("loginstatus").innerHTML = data;
}
});
}
logmein.php
<?php
$usrnm_original = $_POST['usrnm'];
$pswdlogin_original = $_POST['pswdlogin'];
$con = mysqli_connect("localhost", "cSDEqLj", "4GFU7vT", "dbname", "3306");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con, "dbname");
$usrnm = mysqli_real_escape_string($con, $usrnm_original);
$pswdlogin = mysqli_real_escape_string($con, $pswdlogin_original);
$result = mysqli_query($con, "SELECT * FROM registration WHERE email = '" . $usrnm . "' AND password='" . $pswdlogin . "' ");
$rows = mysqli_num_rows($result);
if ($rows == 1)
{
echo "Valid";
}
else
{
echo "In Valid Credentials Entered";
}
mysqli_close($con);
?>
This really belongs on codereview.stackexchange.com, but I'll give it a shot anyway.
Firstly, I'd add a csrf token to your form to stop those types of attacks.
//the most simple type of csrf token
if (!isset($_SESSION['token'])):
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
else:
$token = $_SESSION['token'];
endif;
Then in your form, include a hidden input field:
<input type="hidden" name="token" id="token" value="<?php echo $token; ?>"/>
Then in your ajax, add the token.
var usrnm = $('#usrnm').val();
var pswdlogin = $('#pswdlogin').val();
var token = $('#token').val();
{
usrnm: usrnm,
pswdlogin: pswdlogin,
token: token
}
Then in your php, let's stop the undefined index errors on access of that page directly.
$usrnm_original = isset($_POST['usrnm'])?$_POST['usrnm']:false;
$pswdlogin_original = isset($_POST['pswdlogin'])?$_POST['pswdlogin']:false;
$token = isset($_POST['token'])$_POST['token']:false;
Then we need to check if the token that was passed is the same as our token
if(!$_SESSION['token'] == $token):
die('CSRF Attacks are not allowed.');
endif;
Then we need to stop using mysqli_query when accepting user data, even if sanitizing with mysqli_real_escape_string and instead use prepared statements. Also, procedural style code makes me cry, so we'll be changing that. Furthermore, let's return an array with a status and a message, so it's easier to handle the error and success reporting.
$ret = array();
$mysqli = new mysqli("localhost", "cSDEqLj", "4GFU7vT", "dbname");
if($sql = $mysqli->prepare('SELECT * FROM registration WHERE email = ? and password = ?')):
$sql->bind_param('ss', $usrnm_original, $pswd_original);
if($sql->execute()):
$sql->fetch();
if($sql->num_rows > 0):
$ret['status'] = true;
$ret['msg'] = 'You have successfully logged in! Redirecting you now';
else:
$ret['status'] = false;
$ret['msg'] = 'The credentials supplied were incorrect. Please try again';
endif;
endif;
$sql->close();
return json_encode($ret);
endif;
Now we need to modify your post function.
$.post("http://xyz/mobile/php/logmein.php",
{
usrnm: usrnm,
pswdlogin: pswdlogin,
token:token
},
function(data) {
if (data.status == true) {
window.open("http://xyz/mobile/home.html?email=" + usrnm + "", "_parent");
} else {
alert(data.msg);
$('#loginstatus').text(data.msg);
}
}, 'json');
Finally, and most importantly, you have a plain text method of passwords being used, which makes no sense from a security perspective. This is precisely how you get hacked. Instead, you should be using at least the sha256 hashing method. Change how the passwords are stored in the database to use sha256 then make a comparison by passing that into the SQL selector, example:
$pswdlogin_original = isset($_POST['pswdlogin'])? hash('sha256', $_POST['pswdlogin']):false;
And when saved in the database, the password will look like fcec91509759ad995c2cd14bcb26b2720993faf61c29d379b270d442d92290eb for instance.
My answer has been for clarity sake, but in reality, you shouldn't even be reinventing things. There's plenty of applications and framework's out there that have placed countless hours into securing their authentication systems. I would recommend having a look into all of these, as they'll help build your core programming skills and teach fundamental OOP practices
Lararvel 4.x
Zend 2
Phalcon
Yi
Hopefully this has been helpful.
First of all, if you want "top" security you should use HTTPS with a valid certificate, otherwise any attacker may be able to create a Man in the middle attack and intercept your data (I guess this is your main concern). Doing the HTTPS on the login page only is meaningless as the same attacker could do a Session Hijacking attack and impersonate other users without knowing the password.
Be aware that there is no difference of using AJAX or an HTML form, the data is sent though the wire in the same way.
If you don't want to spent more resources (usually HTTPS cerficates costs money), you can go the "not that good route": pass a hashed version of the password, but this has its downsides too (if you don't hash at server side, then the password becomes the hash itself...)
As adviced, don't try to reinvent the wheel, try using a well known framework like Laravel, or one smaller like Slim or Silex, it might be easier to migrate your code to them.
At the end you must ask yourself, what is the worst case scenario if some user gets access to another account? If you're deploying a trivial app with no personal data, maybe your current solution is good enough on the other hand if you're dealing with sensitive information you must pay good attention securing your website.
Further reading:
About session hijacking
About Man In the Middle
Storing passwords "the good way" (TM)
1.How can i login in same form for admin and user?
Here is my code
<?php
include('config.php');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email=$_POST['email'];
$password=$_POST['password'];
$salt = sha1(md5($password));
$password = md5($password.$salt);
$sql="SELECT email FROM registered_members WHERE email='$email' and password='$password'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
$sql1="SELECT email,password FROM admin WHERE email='$email' and password='$password'";
$result1=mysql_query($sql1);
$row1=mysql_fetch_array($result1);
$active1=$row1['active'];
$count_admin=mysql_num_rows($result1);
if($count==1){
session_register("email");
session_register("password");
$_SESSION['login_user']=$email;
header("location:member.php");
}
elseif($count_admin==1){
session_register("email");
session_register("password");
$_SESSION['login_admin']=$email;
header("location:admincp/admin-panel.php");
}
else {
echo "Wrong email or Password";
}}
?>
2.Please help me how can i resolve this??
Please use some indentation before post. It's hard and hardly someone will answer you with a dirty code
As the comment said, SQL Injections. Prevent them and learn about prepared statements:
http://php.net/pdo.prepared-statements
Before your answer, is it really need two tables to have the same content? Wouldn't be easier to create a single column that could mark if user has administrator rights or not? It would prevent you to run two queries, faster code, faster performance, less memory consumption.
Now, your question:
Code removed
Please have in mind your code structure and safety.