how to add md5 value in this function [closed] - php

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm Using phpfox with userplane webchat and this function is to grab sessionGuid from the database Original function is:
Function 1:
function get_current_online_session_login() {
$oSrvSec = &App::getModuleService('Account', 'Security');
$login = $oSrvSec->getCurrentUserLogin();
$aReq = getRow(App::getT('online_session'), 'online_session_user = "' . $login . '"');
// return $aReq['online_session_login'];
return $aReq['online_session_id'];
}
And i make change's in it so it return the salted hash but Chat is not working and show error that you are not authorized to enter in chat.
Here is what i make change in this code:
function get_current_online_session_login() {
$oSrvSec = &App::getModuleService('Account', 'Security');
$login = $oSrvSec->getCurrentUserLogin();
$aReq = getRow(App::getT('online_session'), 'online_session_user = "' . $login . '"');
$salt='waka_waka_shaka_laka_8342394';
// return $aReq['online_session_login'];
$umSar = $aReq['online_session_id'];
$saltedHash = md5($umSar . $salt);
return $saltedHash;
}
in this file have 2 function for session_id so i am not sure how to resolve this issue
here is the 2nd session_id function:
Function 2
function get_user_with_session_id($session_id) {
$session = getRow(App::getT('online_session'), "online_session_id = '$session_id'");
// $session = getRow(App::getT('online_session'), "online_session_login = '$session_id'");
$oSecurityService = &App::getModuleService('Account', 'Security');
$user = $oSecurityService->getUserByName($session['online_session_user']);
return isset($user) ? $user->aData['id'] : null;
}
Please i need help.
You can see function 1: and function 2: are original function in my common.php file and this function return the normal figure's for session_id and i want to return session_id as md5 salted hash or base_64.
Thanks

First you should understand, what a session-id is for. Normally the server will not recognize, that a user has already done some actions on a website, each request is like a new visit. To remember a user and his actions, the server stores them together with a random number, the session-id.
This session-id will be passed to the browser, and if the user e.g. presses a button, this session-id is handled back to the server. Now the server can look for the stored actions with this number and therefore will "remember" the user.
In your example you took the session-id, destroyed it with a one way hash function, and passed it to the browser. When the browser handles back this invalid session-id, the server has no chance to find the stored actions with this invalid number.
That said, the session-id is only a number to refind the already stored information on the server. It does in no way improve security, when you alter this number, because the browser will just send back what he gets, and the server has to recognize it, whether he previously encrypted/obfuscated it or not.
If your session-ids are predictable, like 203, 204, ..., then you should find the piece of code which generates such inappropriate numbers and modify this code, so it produces "truly" random numbers.

You first have to check if the crypt() method has MD5 support, and then pass the string to encrypt as well as the salt, beginning with $1$. See crypt() on PHP.net.
if (CRYPT_MD5 == 1) {
$saltedHash' . crypt($umSar, '$1$waka_wak$') . "\n";
}
Note that the salt must be 12 characters long for MD5.

If you're thinking of de-crypting the online-session-id you encrypted in function get_current_online_session_login() that's not not the purpose of md5 hashing.
If you want to encrypt/decrypt, u can use functions like mcrypt_decrypt,mcrypt_encrypt and base64_encode,base64_decode..
example answer: encrypt/decrypt password

Related

What part does the "token" play in password reset?

I'm using laravel's Auth password reset method and not sure i fully understand what part plays the token in all of this.
I'm sending the user an email with Password::remind('email#email.com') , which generates a token in my password_reminders table. The token is fully visible in the url.
The user goes to a url that looks something like: mywebsite.com/remindpass/xxxxxx[token] .
Then he fills out a form with his email and a new password , sending it trough post to a controller - which uses Password::reset('email','password','xxxxxx') .
The question is how is this secure? What does the generated token do to prevent someone just going to mywebsite.com/remindpass/xxxxxx[token] and change the email & password as he likes?
Can someone please clarify the proccess?
I'm sure someone could answer this question better than I could.
Short answer:
The token makes it more difficult for someone to guess the credentials needed to reset the password while making the reset link in the email available.
Long answer:
In the file vendor/laravel/framework/src/Illuminate/Auth/Guard.php, you'll see the method createRememberTokenIfDoesntExist. This method actually references another method right above it called refreshRememberToken to set your token.
It uses the laravel helper function str_random. If you trace this function back to it's source, you'll find it uses the vendor/laravel/framework/src/Illuminate/Support/Str.php class' random method.
public static function random($length = 16)
{
if (function_exists('openssl_random_pseudo_bytes'))
{
$bytes = openssl_random_pseudo_bytes($length * 2);
if ($bytes === false)
{
throw new \RuntimeException('Unable to generate random string.');
}
return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
}
return static::quickRandom($length);
}
Now we finally get down to where the token is built. This method uses the function openssl_random_pseudo_bytesto generate the token. You can read about that function in the PHP manual page for openssl_random_pseudo_bytes, but basically it generates a cryptographically strong random string.
Laravel then takes this string (still in the random method), base 64 encodes it, replaces some characters, and takes a slice of that string based on either the default setting of 16 (seen in the parameter definition $length = 16) or whatever length is passed into the method by the caller.
So, you get a string that is cryptographically strong and then manipulated as your token.
If you look at the file vendor/laravel/framework/src/Illuminate/Auth/DatabaseUserProvider.php and find the method retrieveByToken, you'll see that laravel uses both the user record ID and the token to find the user who's password needs to change.
For someone to guess that string AND the id of you user record that has that token would be incredibly difficult and would require knowledge of your application's business logic.
What does the generated token do to prevent someone just going to mywebsite.com/remindpass/xxxxxx[token] and change the email & password as he likes?
Because only you and the person you sent the email to (i.e. the account holder) know what the token is.
A strong implementation will takes steps to make it hard to guess tokens:
Long (harder to guess) tokens
Time limited tokens
IP based rate limiting for access to /remindpass/*

Using crypt () blowfish hash during login [duplicate]

This question already has an answer here:
bcrypt and randomly generated salts
(1 answer)
Closed 8 years ago.
* A REAL WORKING ANSWER is at the bottom of this page! *
This is a question about using crypt () blowfish hash during login for customer verification. I am restricted to PHP 5.3 by my web host and I know it would be better to use PHP 5.5 with password hash () and password verify() but PHP 5.3 doesn’t seem to recognize them. The problem is not hashing the password and putting it in the database the available codes on line work for that. The problem is all the codes I found (about ten so far) don’t take into consideration that the randomized salt that is highly recommended for the registration page can’t be used on login passwords because it will be different every time with no match. Is what I am trying to do not possible on PHP 5.3 or is there a way to re-hash the users password using the salt it was randomized with so it can be checked against the one stored in the database?
Codes like this work well for randomizing the salt and hashing the password for the database entry.
function better_crypt($input, $rounds = 9)
{
$salt = "";
$salt_chars = array_merge(range('A','Z'), range('a','z'), range(0,9));
for($i=0; $i < 22; $i++) {
$salt .= $salt_chars[array_rand($salt_chars)];
}
return crypt($input, sprintf('$2a$%02d$', $rounds) . $salt);
}
$password_hash = better_crypt($input);
But login codes like this don’t work and the functions from the registration page must be redefined on the login page some how. They don’t carry over like session variables. I know I must be missing something… Does anyone have a code that will work for this funtion?
$password_hash = better_crypt($db_password_hash);
if (crypt($user_password, $password_hash) == $password_hash) {
echo '<br>';
echo 'true';
}else{
echo '<br>';
echo 'false';
}
Can’t add comment at bottom of page… I don’t have permission?
The “better crypt” function is for the registration page, it could be called something else. I don’t think it is used for the login page or the PHP include page, but this is what I am asking. Is there a login function or code that can use the original salt and how do I get it out of the hashed password in the database to check it and verify the user?
About the answer (bcrypt and randomly generated salts)
How do I extract the original randomized salt from the hashed password stored in the database or do I try to separate it first during registration and save it separately to use during login? I read this not the way it is suppose to work.
Hi martinstoeckli … The link to “compatibility pack “ goes to the PHP manual on “password_hash”, I don’t see any compatibility pack. The algorithm is set by blowfish and it stays the same for every hashed password. Using crypt by itself is weaker then blowfish, but even that dose not solve the login problem I am asking about. I tried that frist.
If anyone has a working login code to use with blowfish ($2a$) algorithm and using any cost value, please post it. It needs to extract the salt from the saved hashed database password to hash the user enter password during login for comparison. Somehow... Using a fixed salt is not recommended so the randomized salt during registration must be extracted somehow from the saved hash password.
Hi deceze,
I did check the duplicate but it had no login code to try. I will try to make a new code to test using this one line below… where $passwordToCheck is the login password and $2y$10$abcdefg... is the stored hashed password in the database. I will put it in an “if statement and echo if it is true or else false”. Get back to you with the results…Thanks
crypt($passwordToCheck, '$2y$10$abcdefg...')
deceze,
I tried this code below with the “,” and “==” both return true or “worked!” with any password input into the login. Please post the code you use for your login page so I can test or modify it to use on mine .
if
(crypt($user_password == $db_password_hash)){
echo '<br>';
echo ' Worked! ';
echo '<br>';
}
else
{
echo '<br>';
echo ' Did not work ): ';
echo '<br>';
}
Also I am using “$2y$11$” now for the algorithm and cost parameter on my registration page with database input like this “$2y$11$9MUd40QqfmmtPaes91OttOlvAhkAtMvS4.mtg9LT.tazythwhRMwu”
Would someone please remove the post that this question has been answered. This will just frustrate others trying to fine an answer to this problem as I have been for days now. Again if anyone does have a working code to answer this question please post it so this problem can get resolved for others STILL NEEDING A REAL WORKING ANSWER!
//////////////////////////////////////////////////////////////////////////////
EUREKA! “I found it” or at least learned how to write the code.
This is A REAL WORKING ANSWER! , The Blowfish login code I wish I had days ago, when I sill had hair!
The "$2y$" is better for PHP 5.3.7 or higher but I must use the "$2a$" algorithm for PHP 5.3 as explained below from http://php.net/manual/en/function.crypt.php.
Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7 introduced the new prefixes to fix a security weakness in the Blowfish implementation. Please refer to » this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use "$2y$" in preference to "$2a$".
<?php
// Blowfish login code to verify user login password with the hashed password in database
// Make variables from login form on another page and use “include()” to get this PHP code
$user_name_from_login = $_POST[ 'login_user_name' ];
$user_password_from_login = $_POST[ 'login_password' ];
//Check users name for match in your database table of user names
// You must use a line like this “include(‘your_conection_name.php');”
//at the top of your page to get the database connection code or add it directly to this page for this to work
$sql = "SELECT * FROM customers WHERE user_name=:login_user_name";
$query = $db->prepare( $sql );
$query->execute( array( ':login_user_name'=>$user_name_from_login ) );
$results = $query->fetchAll( PDO::FETCH_ASSOC );
//Get hashed password in database associated with user name and make it into a php variable
foreach( $results as $row ){
$database_password_hash = $row[ 'password' ];
}
//Using the Blowfish “$2a$” algorithm with a cost of “11$” and random salt form registration page
// this one line converts login password to the original saved hashed so it can be compared with the one saved in database
$user_password_rehashed = crypt($user_password_from_login, $database_password_hash);
//Now a simple comparison can be made and verified with an “if else” using the variables above
if
($user_password_rehashed == $database_password_hash) {
echo '<br>';
echo ' User’s login password “IS A MATCH” with the one in database (:';
echo '<br>';
}
else
{
echo '<br>';
echo ' User’s login password “DOES NOT MATCH” with the one in database ):';
echo '<br>';
}
//Check your output to better understand process
echo '<br>';
echo ' $user_password_from_login = ' . $user_password_from_login;
echo '<br>';
echo ' $user_password_rehashed --- = ' . $user_password_rehashed;
echo '<br>';
echo ' $database_password_hash --- = ' . $database_password_hash;
echo '<br>';
?>
I hope this will save time and money for other web designers…
I know it would be better to use PHP 5.5 with password hash () and password verify() but PHP 5.3 doesn’t seem to recognize them…
Use the password_compat library. It provides those functions for PHP 5.3.7 and later.
The problem with your better_crypt() function is that it generates a new random salt every time it is called, so the results can't be verified. To be compatible with crypt(), it would need to take a salt from another password hash as input.
But don't do that. Use password_compat.

update PHP variable on click of html class [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to run PHP, specifically PHP I can't do it any other language, on click of a link with the class .URL
Specifically the PHP I need to run is this:
$list[4]+=10;
and the link that I need it to run on click of looks like this:
Some site's URL
I have heard about jQuery's ajax() function and its derivatives. But how can I do those to update the value of a PHP variable on click on .URL ?
First things first, most of your question is not possible in the way you want it done. Specifically incrementing a variable in PHP such that you have $list[4] += 10. I say this because when this script is run this won't exist anymore, you'd have to load it in from where ever you happen to be storing data (assuming a DB).
So, a short example of what you're trying to achieve you'll need a couple of files.
index.php - This is where your code happens that renders the page with the links on it.
link_clicked.php - This is called when a link is clicked.
You'll add need this basic Javascript in your code (it uses jQuery because you mentioned it in your question). I've broken this snippet into many pieces which is not how you'd normally write or see jQuery written to explain what is going on.
$(function() {
// Select all elements on the page that have 'URL' class.
var urls = $(".URL");
// Tell the elements to perform this action when they are clicked.
urls.click(function() {
// Wrap the current element with jQuery.
var $this = $(this);
// Fetch the 'href' attribute of the current link
var url = $this.attr("href");
// Make an AJAX POST request to the URL '/link_clicked.php' and we're passing
// the href of the clicked link back.
$.post("/link_clicked.php", {url: url}, function(response) {
if (!response.success)
alert("Failed to log link click.");
});
});
});
Now, what should our PHP look like to handle this?
<?php
// Tell the requesting client we're responding with JSON
header("Content-Type: application/json");
// If the URL was not passed back then fail.
if (!isset($_REQUEST["url"]))
die('{"success": false}');
$url = $_REQUEST["url"];
// Assume $dbHost, $dbUser, $dbPass, and $dbDefault is defined
// elsewhere. And open an connection to a MySQL database using mysqli
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbDefault);
// Escape url for security
$url = conn->real_escape_string($url);
// Try to update the click count in the database, if this returns a
// falsy value then we assume the query failed.
if ($conn->query("UPDATE `link_clicks` SET `clicks` = `clicks` + 1 WHERE url = '$url';"))
echo '{"success": true}';
else
echo '{"success": false}';
// Close the connection.
$conn->close();
// end link_clicked.php
This example is simplistic in nature and uses some unrecommended methods for performing tasks. I'll leave finding how to go about doing this properly per your requirements up to you.

How do I only allow one POST per user? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
here is the code for adding to database:
<?php
/*Config*/
Sounds like something that should be able to be easily accomplished using a PHP session variable.
Just use sessions and set a session variable (call it posted or something) and if that variable is set, don't allow the user to post (hide the submit button or use a PHP if-statement in your javascript to only perform the action when that variable is not set).
The session will be cleared when the user closes the browser.
As a possible example, in your PHP code for adding to the database, just put this at the beginning:
session_start();
if (isset($_SESSION['posted']))
die("posted");
$_SESSION['posted'] = true;
EDIT :
You just need to add another else if statement. It will look something like this:
if(response == "knownudid"){
document.getElementById('udid_message').innerHTML = '<br><i><font color="red">This UDID has already been inserted and it is valid.</font></i>' ;
}else if(response == "noudid"){
document.getElementById('udid_message').innerHTML = '<br><i><font color="orange">Please, enter your UDID.</font></i>' ;
}else if(response == "errudid"){
document.getElementById('udid_message').innerHTML = '<br><i><font color="red">It seems this UDID is not correct. Please check for typo.</font></i>' ;
}else if(response == "validatedudid"){
document.getElementById('udid_message').innerHTML = '<br><i><font color="green">This UDID has been found as an invalid one. Now it is valid.</font></i>' ;
}else if(response == "posted"){ // Here is the new one
document.getElementById('udid_message').innerHTML = '<br><i><font color="red">You have already posted a UDID for this session.</font></i>' ;
}else{
document.getElementById('udid_message').innerHTML = '<br><i><font color="green">UDID <b>'+response+'</b> successfully inserted.</font></i>';
}
With some nice jQuery or js you could hide the form after the user submit.
Having the javascript within the HTML elements is bad, move it into the <script> tags or even better, a separate .js file.
For HTML5 browsers, placeholder is a much more elegant way of providing instructions for text fields.
If you're using AJAX to submit the form, within your function insert_udid() add:
.
document.getElementById('your_button_or_form').disabled = true;
// or document.getElementById('your_form').style.visibility = 'hidden';
...otherwise, you'll need for the php code to disable or omit the form from the response HTML.

How hackers, are hacking the websites? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So basically, few days ago one of my website clients, came to me, and told me that their database and website has been hacked (hackers somehow stole the md5 hashed password from database), logged in admin panel, and changed data. Well yeah, I created that page 1 and a half year ago, so I didn't know any better hash or salts then. Anyway, how do they hack the database? Well basically, is there any protection against that, or are they using any type of JavaScript codes, that I shouldn't allow to load, or what else?
Hope you can help me about this question, so I could create more protected websites.
This was the previous login code for that site. Added per request -
public function loginUser($username, $password) {
if(isset($_POST['login'])) {
if($username != '' && $password != '') {
$sql = "SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'";
$q = mysql_query($sql);
$row = mysql_fetch_array($q);
if(mysql_num_rows($q) > 0) {
if($row['level'] == 'admin') {
$_SESSION['user_level'] = 'admin';
}
else {
$_SESSION['user_level'] = 'normal';
}
$_SESSION['logged_in'] = 1;
header('location: account.php');
}
else {
header('location: error2.php');
// Return to page and show error
}
}
else {
header('location: error1.php');
// Show error, when people have empty fields entered
}
}
It's impossible to say definitely without much more information, but the most likely case is that your appplication was vulnerable to SQL injection, which enabled the attacker to get the site to display the contents of the database. Another possibility is that a directory traversal attack allowed them to download the DB files directly.
Since MD5 is by now completely broken (whether you use salt or not hardly matters anymore with MD5), the rest was simple.
You should read about SQL Injection (maybe that's how they got the information in your database).
Then you should take a look at XSS.
The first thing you have to do is to validate every piece of input, EVERYTHING!
Against SQLi you should use prepared statements.
And against XSS you should encode everything!
But, hey, no worries, you could have googled all this!

Categories