Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
BCrypt/PDO Registration (Outdated)
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / Torrent Trader / v3 Mods Completed

2020-06-03 12:49:14
I've made BCrypt and PDO registration script I'm staging to redo my signup page and get rid 90% of the current file size.

So I forgot to include a form last time, i've included one this time. It works as it is. Next will be a stand-alone login form supporting this script. PDO Edition does the same thing, only different code.
This is about as simple as it gets. This bypasses TT entirely this time.. as do all my mods, just for kicks ?

In this release, I transferred over my avatar upload feature with thumbnail resizing (image_thumb.ext) and original (original filename). It's saved me many GB's worth of bandwidth alone since February. Its a must-have for high traffic and a lot of users.

Add to backend/functions.php


function imageResize($imageSrc, $imageWidth, $imageHeight)
{
   $newImageWidth  = 200;
   $newImageHeight = 200;
   $newImageLayer  = imagecreatetruecolor($newImageWidth, $newImageHeight);
   imagecopyresampled($newImageLayer, $imageSrc, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $imageWidth, $imageHeight);
   return $newImageLayer;
}


Now create register.php


<?
require_once 'backend/functions.php';
if (isset($_POST['submit'], $_POST['username'], $_POST['password'])) {
   if (is_array($_FILES)) {
       $uploadedFile     = $_FILES['avatar']['tmp_name'];
       $sourceProperties = getimagesize($uploadedFile);
       $newFileName      = sha1_file($uploadedFile);
       $dirPath          = "images/avatars/";
       $ext              = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);
       $imageType        = $sourceProperties[2];
       switch ($imageType) {
           case IMAGETYPE_PNG:
               $imageSrc = imagecreatefrompng($uploadedFile);
               $tmp      = imageResize($imageSrc, $sourceProperties[0], $sourceProperties[1]);
               imagepng($tmp, $dirPath . $newFileName . "_thumb." . $ext);
               break;
           case IMAGETYPE_JPEG:
               $imageSrc = imagecreatefromjpeg($uploadedFile);
               $tmp      = imageResize($imageSrc, $sourceProperties[0], $sourceProperties[1]);
               imagejpeg($tmp, $dirPath . $newFileName . "_thumb." . $ext);
               break;
           case IMAGETYPE_GIF:
               $imageSrc = imagecreatefromgif($uploadedFile);
               $tmp      = imageResize($imageSrc, $sourceProperties[0], $sourceProperties[1]);
               imagegif($tmp, $dirPath . $newFileName . "_thumb." . $ext);
               break;
           default:
               echo "Invalid avatar image. Please <a href='" . $site_config['SITEURL'] . "/signup/'>go back</a> and try again.";
               exit;
               break;
       }
       move_uploaded_file($uploadedFile, $dirPath . $newFileName . "." . $ext);
   }
   try {
       $dsn      = 'mysql:dbname=database;host=localhost';
       $user     = 'username';
       $password = 'password';
       $conn     = new PDO($dsn, $user, $password);
       if (function_exists("filter_var")) {
           $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
           $email    = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
       } else {
           echo "Filter extension for PHP " . phpversion() . " not found. Using unsafe instead.";
           $username = $_POST["username"];
           $email    = $_POST["email"];
       }
       $avatar          = $dirPath . $newFileName . "." . $ext;
       $avatar_thumb    = $dirPath . $newFileName . "_thumb." . $ext;
       $password        = $_POST["password"];
       $saltstr         = '_salt56789012345678901';
       $salt            = password_hash($password, PASSWORD_BCRYPT, array(
           'salt' => $saltstr
       ));
       $cryptedPassword = password_hash($password, PASSWORD_BCRYPT, array(
           'cost' => 11
       ));
       $sql             = "INSERT INTO users (username, password, secret, email, status, added, last_access, age, country, gender, client, stylesheet, language, class, avatar, avatar_thumb) VALUES (:username, :cryptedPassword, :secret, :email, 'confirmed', NOW(), NOW(), 29, 1, 'Male', 'uTorrent', 1, 1, 1, :avatar, :avatar_thumb)";
       $stmt            = $conn->prepare($sql);
       if ($stmt) {
           $stmt->bindParam(":username", $username);
           $stmt->bindParam(":cryptedPassword", $cryptedPassword);
           $stmt->bindParam(":email", $email);
           $stmt->bindParam(":secret", $salt);
           $stmt->bindParam(":avatar", $avatar);
           $stmt->bindParam(":avatar_thumb", $avatar_thumb);
           $result = $stmt->execute();
           echo $result ? 'ok' : 'Query successful';
       } else {
           throw new Exception('Preparing Query Failed');
       }
   }
   catch (Exception $e) {
       echo $e->getMessage();
   }
}
?>


Now create images/avatars and CHMOD 777.

Create as account-register.php


<?
require_once("backend/functions.php");
dbconn(true); stdhead("Sign Up"); begin_frame("Register");
?>

<form method="POST" enctype="multipart/form-data" action="/register.php" autocomplete="off">
   <input type="text" name="username" placeholder="Your Username" /><br><br>
   <input type="email" name="email" placeholder="Your E-mail" /><br><br>
   <input type="password" name="password" placeholder="Your Password" /><br><br>
   <input type="file" name="avatar" accept="image/*"><br><br>
   <button type="submit" name="submit">Sign Up</button>
</form>

<? end_frame(); stdfoot(); ?>


I added the filter module check, and fallback to unsafe vars if not installed.
Just a working basic skeleton that needs a dress. I don't know bootstrap, and it breaks everything I use so I'll leave that up to you.
NOTE: The salt attribute for BCrypt are depreciated as of PHP 7.0 and is encouraged to let password_hash() do it instead. I've put it in anyway for compatibility.

[ATTACH type="full" alt="Register.png"]5574[/ATTACH]
Register.png
Register.png
Unknown User
2020-06-04 22:27:14
Do not create your own salt. It is very concerning and can be brute forced via time based attacks with new amd and intel processors.


Since 2017, NIST recommends using a secret input when hashing memorized secrets such as passwords. By mixing in a secret input (commonly called a "pepper"), one prevents an attacker from brute-forcing the password hashes altogether, even if they have the hash and salt. For example, an SQL injection typically affects only the database, not files on disk, so a pepper stored in a config file would still be out of reach for the attacker. A pepper must be randomly generated once and can be the same for all users. Many password leaks could have been made completely useless if site owners had done this.

Since there is no pepper parameter for password_hash (even though Argon2 has a "secret" parameter, PHP does not allow to set it), the correct way to mix in a pepper is to use hash_hmac(). The "add note" rules of php.net say I can't link external sites, so I can't back any of this up with a link to NIST, Wikipedia, posts from the security stackexchange site that explain the reasoning, or anything... You'll have to verify this manually. The code:

// config.conf
pepper=c1isvFdxMDdmjOlvxpecFw

<?php
// register.php
$pepper = getConfigVariable("pepper");
$pwd = $_POST['password'];
$pwd_peppered = hash_hmac("sha256", $pwd, $pepper);
$pwd_hashed = password_hash($pwd_peppered, PASSWORD_ARGON2ID);
add_user_to_database($username, $pwd_hashed);
?>

<?php
// login.php
$pepper = getConfigVariable("pepper");
$pwd = $_POST['password'];
$pwd_peppered = hash_hmac("sha256", $pwd, $pepper);
$pwd_hashed = get_pwd_from_db($username);
if (password_verify($pwd_peppered, $pwd_hashed)) {
echo "Password matches.";
}
else {
echo "Password incorrect.";
}
?>

Note that this code contains a timing attack that leaks whether the username exists. But my note was over the length limit so I had to cut this paragraph out.

Also note that the pepper is useless if leaked or if it can be cracked. Consider how it might be exposed, for example different methods of passing it to a docker container. Against cracking, use a long randomly generated value (like in the example above), and change the pepper when you do a new install with a clean user database. Changing the pepper for an existing database is the same as changing other hashing parameters: you can either wrap the old value in a new one and layer the hashing (more complex), you compute the new password hash whenever someone logs in (leaving old users at risk, so this might be okay depending on what the reason is that you're upgrading).

Why does this work? Because an attacker does the following after stealing the database:

password_verify("a", $stolen_hash)
password_verify("b", $stolen_hash)
...
password_verify("z", $stolen_hash)
password_verify("aa", $stolen_hash)
etc.

(More realistically, they use a cracking dictionary, but in principle, the way to crack a password hash is by guessing. That's why we use special algorithms: they are slower, so each verify() operation will be slower, so they can try much fewer passwords per hour of cracking.)

Now what if you used that pepper? Now they need to do this:

password_verify(hmac_sha256("a", $secret), $stolen_hash)

Without that $secret (the pepper), they can't do this computation. They would have to do:

password_verify(hmac_sha256("a", "a"), $stolen_hash)
password_verify(hmac_sha256("a", "b"), $stolen_hash)
...
etc., until they found the correct pepper.

If your pepper contains 128 bits of entropy, and so long as hmac-sha256 remains secure (even MD5 is technically secure for use in hmac: only its collision resistance is broken, but of course nobody would use MD5 because more and more flaws are found), this would take more energy than the sun outputs. In other words, it's currently impossible to crack a pepper that strong, even given a known password and salt.
2020-06-04 23:58:08
This is being taken down in place of a new user class, offering sessions and bcrypt that will be posted soon.
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 9
  • Members: 0
  • Guests online: 9
  • Comments: 3
  • Messages: 1,728