What are the best practices for password submission? [closed]How to protect against Log Injection attacks in PHP?How can I safely link and use MySQL databases with a webpage using PHP?What is the most efficient way to deep clone an object in JavaScript?Secure hash and salt for PHP passwordsJavaScript closure inside loops – simple practical exampleWhat is the !! (not not) operator in JavaScript?What does “use strict” do in JavaScript, and what is the reasoning behind it?What is the difference between call and apply?How should I ethically approach user password storage for later plaintext retrieval?What is the best way to detect a mobile device in jQuery?Reference — What does this symbol mean in PHP?Why is char[] preferred over String for passwords?

Piano - What is the notation for a double stop where both notes in the double stop are different lengths?

Finding files for which a command fails

Ideas for colorfully and clearly highlighting graph edges according to weights

Does it makes sense to buy a new cycle to learn riding?

What is GPS' 19 year rollover and does it present a cybersecurity issue?

Prime joint compound before latex paint?

What happens when a metallic dragon and a chromatic dragon mate?

Is "plugging out" electronic devices an American expression?

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

Shall I use personal or official e-mail account when registering to external websites for work purpose?

What are the advantages and disadvantages of running one shots compared to campaigns?

Add an angle to a sphere

Why was the "bread communication" in the arena of Catching Fire left out in the movie?

How to create a consistent feel for character names in a fantasy setting?

How would photo IDs work for shapeshifters?

Mapping arrows in commutative diagrams

How to move the player while also allowing forces to affect it

COUNT(id) or MAX(id) - which is faster?

Why do we use polarized capacitors?

When blogging recipes, how can I support both readers who want the narrative/journey and ones who want the printer-friendly recipe?

How can I add custom success page

Are objects structures and/or vice versa?

Deciding between multiple birth names and dates?

How can I fix this gap between bookcases I made?



What are the best practices for password submission? [closed]


How to protect against Log Injection attacks in PHP?How can I safely link and use MySQL databases with a webpage using PHP?What is the most efficient way to deep clone an object in JavaScript?Secure hash and salt for PHP passwordsJavaScript closure inside loops – simple practical exampleWhat is the !! (not not) operator in JavaScript?What does “use strict” do in JavaScript, and what is the reasoning behind it?What is the difference between call and apply?How should I ethically approach user password storage for later plaintext retrieval?What is the best way to detect a mobile device in jQuery?Reference — What does this symbol mean in PHP?Why is char[] preferred over String for passwords?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-1















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










share|improve this question















closed as too broad by Phil, yivi, Adriaan, tripleee, E_net4 Mar 8 at 10:57


Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.


















  • Use https for all the pages which makes sure complete data transmits in encrypted format.

    – Saji
    Mar 8 at 6:04











  • how can I ensure this will happen? is there something I can add in the php or js code? Thanks

    – fred
    Mar 8 at 6:06






  • 1





    I wouldn't send any user data over GET, it will appear in the URL

    – Phil
    Mar 8 at 7:31

















-1















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










share|improve this question















closed as too broad by Phil, yivi, Adriaan, tripleee, E_net4 Mar 8 at 10:57


Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.


















  • Use https for all the pages which makes sure complete data transmits in encrypted format.

    – Saji
    Mar 8 at 6:04











  • how can I ensure this will happen? is there something I can add in the php or js code? Thanks

    – fred
    Mar 8 at 6:06






  • 1





    I wouldn't send any user data over GET, it will appear in the URL

    – Phil
    Mar 8 at 7:31













-1












-1








-1


0






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










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







javascript php security






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 7:05









Jodast

7551725




7551725










asked Mar 8 at 5:54









fredfred

459318




459318




closed as too broad by Phil, yivi, Adriaan, tripleee, E_net4 Mar 8 at 10:57


Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.









closed as too broad by Phil, yivi, Adriaan, tripleee, E_net4 Mar 8 at 10:57


Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.














  • Use https for all the pages which makes sure complete data transmits in encrypted format.

    – Saji
    Mar 8 at 6:04











  • how can I ensure this will happen? is there something I can add in the php or js code? Thanks

    – fred
    Mar 8 at 6:06






  • 1





    I wouldn't send any user data over GET, it will appear in the URL

    – Phil
    Mar 8 at 7:31

















  • Use https for all the pages which makes sure complete data transmits in encrypted format.

    – Saji
    Mar 8 at 6:04











  • how can I ensure this will happen? is there something I can add in the php or js code? Thanks

    – fred
    Mar 8 at 6:06






  • 1





    I wouldn't send any user data over GET, it will appear in the URL

    – Phil
    Mar 8 at 7:31
















Use https for all the pages which makes sure complete data transmits in encrypted format.

– Saji
Mar 8 at 6:04





Use https for all the pages which makes sure complete data transmits in encrypted format.

– Saji
Mar 8 at 6:04













how can I ensure this will happen? is there something I can add in the php or js code? Thanks

– fred
Mar 8 at 6:06





how can I ensure this will happen? is there something I can add in the php or js code? Thanks

– fred
Mar 8 at 6:06




1




1





I wouldn't send any user data over GET, it will appear in the URL

– Phil
Mar 8 at 7:31





I wouldn't send any user data over GET, it will appear in the URL

– Phil
Mar 8 at 7:31












1 Answer
1






active

oldest

votes


















1














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).






share|improve this answer


















  • 1





    Why even mention escaping SQL strings in a best-practice / security related post, let alone provide an example of it (and no prepared statement example)?

    – Phil
    Mar 8 at 20:56


















1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














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).






share|improve this answer


















  • 1





    Why even mention escaping SQL strings in a best-practice / security related post, let alone provide an example of it (and no prepared statement example)?

    – Phil
    Mar 8 at 20:56
















1














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).






share|improve this answer


















  • 1





    Why even mention escaping SQL strings in a best-practice / security related post, let alone provide an example of it (and no prepared statement example)?

    – Phil
    Mar 8 at 20:56














1












1








1







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).






share|improve this answer













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).







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 8 at 10:32









Nancy MooreeNancy Mooree

679139




679139







  • 1





    Why even mention escaping SQL strings in a best-practice / security related post, let alone provide an example of it (and no prepared statement example)?

    – Phil
    Mar 8 at 20:56













  • 1





    Why even mention escaping SQL strings in a best-practice / security related post, let alone provide an example of it (and no prepared statement example)?

    – Phil
    Mar 8 at 20:56








1




1





Why even mention escaping SQL strings in a best-practice / security related post, let alone provide an example of it (and no prepared statement example)?

– Phil
Mar 8 at 20:56






Why even mention escaping SQL strings in a best-practice / security related post, let alone provide an example of it (and no prepared statement example)?

– Phil
Mar 8 at 20:56






Popular posts from this blog

AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

Алба-Юлія

Захаров Федір Захарович