Checking against a database using encryption - php

I want to the page 'encryptionmachine1.php' to run a query against a database to ensure that the inputted password is correct. To keep things safe, I first want the page to encrypt the password that is inputted and then check against the database field 'EncryptedPasswords' to see if it exists. At the moment when I input a correct a password (number1) only the message 'pwd does not exists' displays. I am also using the md5() function to encrypt the passwords. Any help? Thanks Dan
<?php
if(isset($_POST['submit'])){
$str=$_POST['pwd'];
md5($str);
$dblink=mysql_connect("localhost","Dan");
mysql_select_db("Dan");
$rs=mysql_query("SELECT * FROM passwords WHERE EncryptedPassword='".$str."'");
if($row = mysql_fetch_assoc($rs)){
$dbPassword=$row['EncryptedPassword'];
echo "password exists";
header('Location:http://localhost/encryptionmachine2.php?pwd='.$str);//http://194.36.155.250/POO12104368/encryptionmachine2.php
}else{
echo"pwd does not exist";
}
}
?>
<html>
<head>
<title>EncryptionMachine1</title>
</head>
<body>
<form name="myForm" action="#" method="POST">
<p>Pwd:<input type="text" name="pwd"></p>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>

There's a lot of things that need to be changed with your code to be secure. The most pressing two are:
You want to hash passwords, not encrypt them.
Furthermore, you want to use a password hashing function rather than a general-purpose hash function like MD5 (which is also insecure.
You want to use prepared statements.
This necessarily means stop using mysql_query() and mysql_fetch_assoc() in favor of PDO or mysqli.
I highly recommend starting with A Gentle Introduction to Application Security. It can seem like a lot, but I promise you this is manageable and you can do it.

Related

I am trying to implement hashing using bucket as a collision resolution technique in php. I am trying to insert the data after hashing into textfile

in this code, I am creating a hash function and trying to resolve collision using buckets.I have fixed the size of the bucket to 3. I am trying to insert values after hashing into a text file. The insertion is happening but the collision isn't being resolved.
<html>
<head>
<title>FOOD DELIVERY</title>
</head>
<body>
<form id="insert_item" action="hash_insert.php" method="post">
ID:<input type="text" name="id"><br><br>
Item Name:<input type="text" name="Item_name"><br><br>
Quantity:<input type="text" name="Quantity"><br><br>
Price:<input type="text" name="Price"><br><br>
<input type="submit">
</form>
<br>
<?php
if(isset($_POST['id'])&&isset($_POST['Item_name'])&&isset($_POST['Quantity'])&&isset($_POST['Price'])){
$id=$_POST['id'];
$i_name=$_POST['Item_name'];
$quan=$_POST['Quantity'];
$price=$_POST['Price'];
$file=fopen("Item.txt","a+");
function hash_fun($i){
$t=((($i[3]-48)*100)+(($i[4]-48)*10)+($i[5]-48))%9;
return $t*142;
}
$rec=$id."|".$i_name."|".$quan."|".$price;
while(strlen($rec)<46){
$rec=$rec."_";
}
$pos=hash_fun($id);
fseek($file,$pos,0);
$line=fgets($file);
$cnt=intval($line[0]);
if($cnt==3){
echo "Max collision 3";
}
if($cnt==0){
fseek($file,$pos,0);
fwrite($file,'1');
$pos=$pos+1;
}
else if($cnt==1){
fseek($file,$pos,0);
fwrite($file,'2');
$pos=$pos+48;
}
else if($cnt==2){
fseek($file,$pos,0);
fwrite($file,'3');
$pos=$pos+95;
}
fseek($file,$pos,0);
fwrite($file,$rec);
fwrite($file,"\n");
fclose($file);
}
?>
</body>
</html>
In summary I have into the contexts into a text file called Menu.txt and I am implementing hashing with buckets.But the collision is not being resolved but the insertion is happening.
There are several things here:
creating a safe hash function is really (REALLY) hard
serialization with separators is not safe $rec=$id."|".$i_name."|".$quan."|".$price. What if the name contains a pipe char?
to avoid race conditions an atomic operation is needed. If two requests are trying to process the same hash more or less at the same time, both requests will succeed. A database will provide mechanisms for that but you can also use the filesystem. For example making directories are atomic operations, if several processes are trying to create one, only one will succeed.
sanitize user input. What if the user send line break chars or massive payloads?
In summary, please do not use that code in production for the sake of your users.

PHP - Do I need to validate this simple form for security?

I'm building a small website where I'll be the only user (let say my credentials are "myuser" with the password "mypassword"). In the login page I have this simple form:
<form method="post">
<p>Username: <input type="text" name="usr"></p>
<p>Password: <input type="text" name="passwd"></p>
<p><input type="submit" value="Login"></p>
</form>
Is it safe to just validate the form like this?
// After checking if the request is POST...
if($_POST["usr"]=="myuser"&&$_POST["passwd"]=="mypassword") {
// Set the cookie and go to admin page...
} else {
// Show login error...
}
Or do I need to apply some security measure to the two $_POST variables (e.g. by filtering them with htmlspecialchars or something like that)? As you can see, the credentials are not saved in a database, and also these variables are never called anywhere else in the code, so I don't see any danger even if a malicious user attempts to hack the form with SQL Injection or XSS.
So, did I miss something? Is there any potential danger in leaving the code like that?
I think it is fine, you can add a hashe function & something to prevent a brute force attack to secure a little more. :)
(Sorry can't comment yet)
With php we can use mysql_real_scape_string(), this function have a parameter that modify a string deleting the special chars. This function returns a secure string, now we can execute this string into a SQL query.

Is it safe to PHP SHA256 hash user submited content without vetting first?

I want to allow users to submit input via textarea form submission and perform a SHA256 hash on the submitted text. Is the hash susceptible to attack? Should I "clean" the input before hashing? And if so what's the best way to approach this? Is it enough to use strip_tags or can I convert the input by performing an htmlspecialchars() function on the string etc.
Code example would be
<html>
<head>
<title>SHA256 on user input</title>
</head>
<body>
<?
if ($_SERVER['REQUEST_METHOD'] != 'POST' || empty($_POST['hashThis']) ):
?>
<form name="user_data" method="POST" action="">
<textarea name="hashThis"></textarea>
<input type="submit" name="submit" value="submit" />
</form>
<?
else:
echo hash('sha256', $_POST['hashThis']);
endif;
?>
</body>
</html>
So long as performing a hash is the only thing you are doing with the user's input, this is perfectly safe. You don't need to do any kind of preprocessing on data to make it safe to hash, and so long as you don't have raw output turned on (it's off by default), the output will be safe to print.

Password Protecting A Webpage

Title may be a little misleading but I'll try to explain here.
Basically, when I put my website in 'offline mode' I have a section where admins can log in with a password. (They are not logging in with their accounts) The password is 'password' for this example. When a user types in the correct password, it should redirect them to the webpage, howvever it isn't, it's just echoing 'Incorrect password' - when it is in fact correct.
The code is made up by me, as you can probably tell. I expected this not to work because I'm still in the very early stages of learning PHP
HTML:
<div class="backdroplogin">
<h2>Login to your account:</h2>
<form action="/Offline" method="GET">
<input type ="password" name="password_login" size="25" Value="" />
<input type="submit" name="login" value="Login" />
</div>
</form>
PHP:
//ADMIN LOGIN
$password = "AbCd0987connekt£*^%";
if (isset($_GET["password_login"])) {
$password_login = $_GET["password_login"];
if ($password_login == $password) {
header("Location:/Admin/Panel");
} else {
echo "Incorrect password";
}
}
Thanks for any help.
Like Svetlio said.. It is a bad habit to send passwords using the get method. So instead use method="post" in your html form and $_POST["password_login"] in your php.
In your text you say you use "password" as the password for this tool, while in your php you check if the sent password is equal to "AbCd0987connekt£*^%", so if you put in your password you should use "AbCd0987connekt£*^%"... or did you mean you use "$password"
Just another tip: for readability ability of your code try to indent :)
You could verify that the password is correct and put a flag into a session variable. Then on the admin page do a check to see if that session flag is correct to access.
if($_SESSION['IsAdmin'] === true {
//load/redirect to page
} else {
die("You aren't an admin.");
}
Also, like others said - don't use GET for passwords, and definitely don't pass them as plaintext.
I agree with comment. But just to answer your question:
Everything is working all right in your script, but I think you have a confusion when says "The password is 'password' for this example, instead the password is exactly: AbCd0987connekt£*^% as you wrote it in your code. I copied your code in my platform (changed action) and it's working as you want.

md5 returns empty string

First of all I searched on Google and didn't find any help to my problem.
I'm working on my local server with MAMP and I'm following a tutorial to try securing a php page with md5.
In my login.php page there is a form with login/password fields which calls a JS function when submitted:
<form id='log' method='post' action='templates/auth.php' onsubmit='javascript:submit_pass();'>
<input type='hidden' name='md5' />
<table align='center'>
<tr><td>Login</td><td><input name='login' /></td></tr>
<tr><td>Mot de passe</td><td><input type='password' name='passwd' /></td></tr>
<tr><td colspan='2' align='center'><input type='submit' value='Login !' /></td></tr>
</table>
</form>
The login.js script called on submit:
function submit_pass()
{
pass=document.forms['log'].passwd.value;
document.forms['log'].passwd.value="";
buf=MD5(pass);
document.forms['log'].md5.value=buf;
return true;
}
Then it sends the parameters by POST to auth.php
So I type in the fields a random login and password.
On my auth.php page I echo $_POST['login'] and $_POST['md5']
The problem is that $_POST['md5'] is empty. So I try to echo its size and it appears 0!
I don't undrestand, is something missing? Wrong?
Thanks
Do not hash the password on the client. It will not improve security, because nothing has changed: The server can only see the MD5 hash and the username now, and if I can intercept that, I have everything I need to also log in! Because the server can only check the MD5.
Additionally, Javascript does not come with a built in MD5 function.
And on top of that: An unsalted MD5 hash is as insecure as the plain text password itself - it is only marginally more effort to scan the whole password space.
If you really want to improve password security, you have to use SSL for the client-server-communication (otherwise anything is sent as clear text), and on the server you should hash with the new and shiny password_hash() function of PHP 5.5 (and there is a compatibility library that allows you to do it starting with PHP 5.3.7).
For passwords you should use crypt(). http://php.net/manual/en/function.crypt.php

Categories