Exemplo n.º 1
0
function addNewUser($dbHandler, $username, $password, $permission)
{
    $thisUserPasswordSalt = generateSalt(5);
    $thisUserPasswordHash = md5($password . $thisUserPasswordSalt);
    // create table and insert first root user
    $dbHandler->query("INSERT INTO users (username, salt, password, permissions) VALUES('{$username}', '{$thisUserPasswordSalt}', '{$thisUserPasswordHash}', {$permission});");
}
Exemplo n.º 2
0
 /**
  * Register Admin
  */
 function register()
 {
     initiateSession();
     $this->set("title", "Sevasetu | New Admin");
     if (isset($_SESSION['admin_hash'])) {
         header("LOCATION: /admins/dashboard");
     }
     $name = sqlSafe($_POST['name']);
     $username = sqlSafe($_POST['username']);
     $password = sqlSafe($_POST['password']);
     $password2 = sqlSafe($_POST['password2']);
     $salt = generateSalt();
     $email = sqlSafe($_POST['email']);
     if ($password === $password2) {
         $password = generateHash($password . $salt);
     } else {
         $this->set("message", "Password doesn't match");
         return false;
     }
     if ($this->Admin->insertAdmin($name, $username, $email, $salt, $password) == true) {
         $this->set("message", "Administrator Registered.");
     } else {
         $this->set("message", "Unable to register admin");
     }
 }
function registreerNieuweUser($login, $pasw)
{
    $_SESSION["msg"] = "Registratie niet gelukt. Probeer later opnieuw.";
    //default message
    //controleren of de login reeds gebruikt is....
    $connection = new W_DatabaseHelper("cms");
    $querystring = "SELECT * \n\t\t\t\t\t\t FROM users \n\t\t\t\t\t\t WHERE naam LIKE :login \n\t\t\t\t\t\t";
    $bindValues = [":login" => $login];
    $resultset = $connection->query($querystring, $bindValues);
    //$resultset = $connection->query($querystring);
    //var_dump($resultset);
    if (sizeof($resultset) > 0) {
        $_SESSION["msg"] = "Deze naam is reeds in gebruik. Gelieve een andere login te kiezen.";
    } else {
        $querystring = "INSERT INTO users(naam, paswoord, salt) \n\t\t\t\t\t\t\tVALUES (:login, :pasw, :newsalt) \n\t\t\t\t\t\t\t";
        ///// SECURITY voor paswoord...
        //salt aanmaken
        $newsalt = generateSalt();
        //parameter 5 in onderstaande lijn betekent dat we kiezen voor algoritme SHA256...
        $pasw = hash("sha256", $pasw . $newsalt);
        var_dump($pasw);
        $bindValues = [":login" => $login, ":pasw" => $pasw, ":newsalt" => $newsalt];
        $resultset = $connection->query($querystring, $bindValues);
        $validatedUser = checklogin($login, $pasw);
        $_SESSION["msg"] = "Proficiat met uw registratie. U bent meteen ook ingelogd met uw nieuwe login en paswoord.";
        /// get the new user's userid...
        $querystring = "SELECT userid FROM users\n\t\t\t\t\t\t\tWHERE naam LIKE :login \n\t\t\t\t\t\t\tAND paswoord LIKE :pasw \n\t\t\t\t\t\t\tAND salt LIKE :newsalt\n\t\t\t\t\t\t\t";
        $bindValues = [":login" => $login, ":pasw" => $pasw, ":newsalt" => $newsalt];
        $resultset = $connection->query($querystring, $bindValues);
        var_dump($resultset);
        $_SESSION["user"] = $resultset[0];
        $_SESSION["username"] = $login;
    }
    //return $resultmessage;
}
Exemplo n.º 4
0
 public function createAdmin($username, $email, $password)
 {
     if ($this->input->is_cli_request()) {
         $saltkey = generateSalt();
         $salt_password = crypt($password, $saltkey);
         $this->setup_model->generateAdmin($username, $saltkey, $salt_password, $email);
     }
 }
Exemplo n.º 5
0
function adduser($username, $password, $level, $email = "", $realname = "", $can_modify_passwd = '1', $description = "")
{
    if (!user_exists($username)) {
        $encrypted = crypt($password, '$1$' . generateSalt(8) . '$');
        return dbInsert(array('username' => $username, 'password' => $encrypted, 'level' => $level, 'email' => $email, 'realname' => $realname, 'can_modify_passwd' => $can_modify_passwd, 'descr' => $description), 'users');
    } else {
        return FALSE;
    }
}
Exemplo n.º 6
0
function hashUserID($ID)
{
    $salt1 = generateSalt($ID);
    // reverse the $ID and generate another salt
    $salt2 = generateSalt(strrev((string) $ID));
    $salted = $salt1 . $ID . $salt2;
    $hashUserID = hash("sha256", $salted);
    //    $hashUserID = $ID;
    return $hashUserID;
}
Exemplo n.º 7
0
function passwordEncrypt($password)
{
    // use Blowfish with a "cost" of 10
    $hash_format = "\$2y\$10\$";
    $salt_length = 22;
    $salt = generateSalt($salt_length);
    $format_and_salt - $hash_format . $salt;
    $hash = crypt($password, $format_and_salt);
    return $hash;
}
Exemplo n.º 8
0
 public function testGenerateSalt()
 {
     // each salt is unique, so we test length of salt generated
     $this->assertEquals(22, strlen(generateSalt(22)));
     $this->assertEquals(1, strlen(generateSalt(1)));
     $this->assertEquals(0, strlen(generateSalt(0)));
     $this->assertEquals(40, strlen(generateSalt(40)));
     // test that no two salts are identical
     $this->assertFalse(generateSalt(22) == generateSalt(22));
     $this->assertFalse(generateSalt(4) == generateSalt(4));
     // salts of length 0 are identical
     $this->assertEquals(generateSalt(0), generateSalt(0));
 }
Exemplo n.º 9
0
/**
 * This function compares the submitted email & password to those in the user
 * table for a match and starts a session with ['loggedIn'} = TRUE if found.
 * @return boolean
 */
function userIsLoggedIn()
{
    $salt = generateSalt($_POST['email']);
    $password = generateHash($salt, $_POST['password']);
    if (databaseContainsUser($_POST['email'], $password)) {
        $_SESSION['loggedIn'] = TRUE;
        $_SESSION['email'] = $_POST['email'];
        $_SESSION['password'] = $password;
        return TRUE;
    } else {
        unset($_SESSION['loggedIn']);
        unset($_SESSION['email']);
        unset($_SESSION['password']);
        return FALSE;
    }
}
Exemplo n.º 10
0
 /**
  * Sets the contents for the processing of user registration form
  */
 function register()
 {
     initiateSession();
     $this->set("title", "IEEE NIEC | New User Registration");
     if (isset($_SESSION['user_id'])) {
         header("LOCATION: /indexs/home");
     }
     $name = sqlSafe($_POST['name']);
     $username = sqlSafe($_POST['username']);
     $password = sqlSafe($_POST['password']);
     $password2 = sqlSafe($_POST['password2']);
     $salt = generateSalt();
     $email = sqlSafe($_POST['email']);
     $dor = date("Y-m-d H:i:s");
     $dob = sqlSafe($_POST['dob']);
     $profilepicPath = ROOT . DS . 'public' . DS . 'uploads' . DS . 'dp' . DS . 'default.jpg';
     if ($password === $password2) {
         $password = generateHash($password . $salt);
     } else {
         $this->set("message", "Password doesn't match");
     }
     $profilepic = new Image($_FILES['profile_picture']);
     $profilepic->setUploadPath(ROOT . DS . 'public' . DS . 'uploads' . DS . 'dp');
     if ($profilepic->validate() == false) {
         $this->set("message", "Unsupported Image Format for profile picture. Try again.");
     } else {
         if ($profilepic->moveUploadedImage() == true) {
             $profilepicPath = $profilepic->getUploadLocation();
             $profilepic = null;
         } else {
             $this->set("message", "Error uploading profile picture. Try again after some time.");
         }
     }
     if ($this->User->insertUser($name, $username, $password, $salt, $email, $dob, $dor, $profilepicPath) == -1) {
         $this->set("message", "There was some error processing your request. Try again later.");
     } else {
         $this->sendActivationMail($username);
         $this->set("message", "Registration Successful. Please check your mail to activate your account.");
     }
 }
Exemplo n.º 11
0
function recoverSendMail($db, $sEmail)
{
    global $config;
    $row = getUserFromEmail($db, $sEmail);
    if (!$row) {
        echo json_encode(array("success" => false));
        return;
    }
    $sRecoverCode = generateSalt();
    $query = "UPDATE `user` SET `recoverCode` = ? WHERE `ID` = ?";
    $stmt = $db->prepare($query);
    $stmt->execute(array($sRecoverCode, $row->ID));
    if ($sEmail !== "") {
        $link = $config->teacherInterface->sCoordinatorFolder . "/recover.php?action=recover&email=" . urlencode($sEmail) . "&recoverCode=" . urlencode($sRecoverCode);
        $sBody = "Bonjour,\r\n\r\nPour définir un nouveau mot de passe, ouvrez le lien suivant dans votre navigateur  : \r\n\r\n" . $link . "\r\n\r\nN'hésitez pas à nous contacter si vous rencontrez des difficultés.\r\n\r\nCordialement,\r\n--\r\nL'équipe du Castor Informatique";
        $sTitle = "Réinitialisation de mot de passe Coordinateur Castor Informatique";
        sendMail($sEmail, $sTitle, $sBody, $config->email->sEmailSender);
        //$params = array('recoverCode' => $recoverCode, 'email' => $email);
        //http_post("eval01.france-ioi.org", 80, "/castor/sendMail2.php", $params);
    }
    echo json_encode(array("success" => true));
}
Exemplo n.º 12
0
/**
 * @param $username
 * @param $userpass
 * @return bool|object
 * Login.
 */
function login($username, $userpass)
{
    if ($username == "" || $userpass == "") {
        return false;
    }
    $salt = "";
    $sql = "SELECT Salt, UserID FROM tbl_users WHERE Email = " . convertForInsert($username);
    $mysqli = new mysqli(Database::dbserver, Database::dbuser, Database::dbpass, Database::dbname);
    $rs = $mysqli->query($sql);
    while ($row = $rs->fetch_assoc()) {
        $userid = $row['UserID'];
        $salt = $row['Salt'] == "" ? generateSalt($userid) : $row['Salt'];
    }
    $salted = encryptPassword($userpass, $salt);
    $rs->free();
    $mysqli->close();
    $sql = "SELECT UserID, FirstName FROM tbl_users WHERE Email = " . convertForInsert($username) . " AND Password = "******"success" => true, "usertoken" => generateToken($row['UserID']), "userfirstname" => $row['FirstName']);
            return json_encode($data);
        }
        //return true;
    }
}
Exemplo n.º 13
0
function createUsers($IDs, $role, $dbConn, $isIDsHashed = false, $firstName = null, $lastName = null)
{
    global $AES_key, $DEPLOYMENT_NAME;
    $userIDs = null;
    // deal with null firstname & lastname, convert to "NULL" for SQL
    $firstName = $firstName == null ? "NULL" : $firstName;
    $lastName = $lastName == null ? "NULL" : $lastName;
    // convert to array
    if (!is_array($IDs)) {
        $IDs = (array) $IDs;
    }
    foreach ($IDs as $ID) {
        //TODO: add DB contraint unique per user
        // This function can be called either with a pre-hashed ID or an unhashed userID
        // situations for calling with a pre-hashed ID include updating a class list, or
        // giving existing users permissions (student or instructor) to a new class
        $isIDsHashed ? $hashUserID = $ID : ($hashUserID = hashUserID($ID));
        // Check to see if the user already existed
        $query = "SELECT id FROM users WHERE hash_user_id LIKE '{$hashUserID}'";
        $result = mysql_query($query, $dbConn);
        $resultText = $result == false ? "<div style=\"color:red;\">failed, error: " . mysql_error($dbConn) . "</div>" : "<div style=\"color:green;\">ok, retVal: " . mysql_result($result, 0) . "</div>";
        print "<br/>Debug Info: {$query} - Result: {$resultText}<br/>";
        // get the OVAL userID of the last insert of this hashed university ID
        if (1 == mysql_num_rows($result)) {
            $userID = mysql_result($result, 0);
        } else {
            $saltedID = $ID . generateSalt($ID);
            if ($DEPLOYMENT_NAME === "dev") {
                $query = "INSERT INTO users VALUES (NULL, '{$hashUserID}', AES_ENCRYPT('{$saltedID}', '{$AES_key}'), '{$firstName}', '{$lastName}', {$role}, NULL)";
            } else {
                $query = "INSERT INTO users VALUES (NULL, '{$hashUserID}', '', '{$firstName}', '{$lastName}', {$role}, NULL)";
            }
            $result = mysql_query($query, $dbConn);
            $resultText = $result == false ? "<div style=\"color:red;\">failed, error: " . mysql_error($dbConn) . "</div>" : "<div style=\"color:green;\">ok, retVal: " . mysql_result($result, 0) . "</div>";
            $query = str_replace($AES_key, "", $query);
            print "<br/>Debug Info: {$query} - Result: {$resultText}<br/>";
            // user already exists so query id
            $userID = mysql_insert_id();
        }
        //print "userID:$userID<br />";
        // collect users.id
        $userIDs[] = $userID;
    }
    return $userIDs;
}
Exemplo n.º 14
0
function password_reset_by_token($username, $token, $password, $repeat_password)
{
    $userid = is_simplerisk_user($username);
    // Verify that the passwords match
    if ($password == $repeat_password) {
        // If the username exists
        if ($userid != 0) {
            // If the reset token is valid
            if (is_valid_reset_token($username, $token)) {
                // Open the database connection
                $db = db_open();
                // Create the new password hash
                $salt = generateSalt($username);
                $hash = generateHash($salt, $password);
                // Update the password
                $stmt = $db->prepare("UPDATE user SET password=:hash WHERE username=:username");
                $stmt->bindParam(":hash", $hash, PDO::PARAM_STR, 60);
                $stmt->bindParam(":username", $username, PDO::PARAM_STR, 20);
                $stmt->execute();
                // Close the database connection
                db_close($db);
                return true;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}
Exemplo n.º 15
0
     if ($QR === 'NONE') {
         $mypage->leaf('p', 'Couldn\'t find a user named ' . $EscapedAccountName . '. Please check that you spelled the account name correctly.');
     } else {
         if (!$QR['UserValidated']) {
             $mypage->leaf('p', 'That user account isn\'t validated yet. If you haven\'t received your validation email, you can visit <a href="resendvalemail.php">this page</a> to re-send it (although you will need your password to do so).');
         } else {
             if ($QR['Email'] == '') {
                 $mypage->leaf('p', 'There was a problem sending the email. Either the account email address is blank, or the email could not be sent for some other reason. You might want to try again; if it still doesn\'t work, you can ask the Administrator to investigate, but be aware that the Administrator will only go so far as to check for problems with this script and with the site\'s ability to send emails, not give you access to your account.');
             } else {
                 $CharArray = 'abcdefghijklmnopqrstuvwxyz0123456789';
                 $thevstring = '';
                 for ($i = 0; $i < 20; $i++) {
                     $j = rand(0, 35);
                     $thevstring .= $CharArray[$j];
                 }
                 $encryptedthevstring = crypt($thevstring, generateSalt());
                 $QueryResult = dbquery(DBQUERY_WRITE, 'UPDATE "User" SET "ScrambleKey" = :scramblekey: WHERE "UserID" = :user:'******'scramblekey', $encryptedthevstring, 'user', $QR['UserID']);
                 $subject = 'Account Recovery Email for Brass';
                 $body = '<p>Account recovery has been requested for your account ' . $EscapedAccountName . ' for Brass. If it was not you who submitted the request, please ignore this email.</p><p>Please click on the url on the next line, or copy and paste it into your browser\'s address bar.</p><p><a href="' . SITE_ADDRESS . 'recoveraccountb.php?UserID=' . $QR['UserID'] . '&amp;VString=' . $thevstring . '">' . SITE_ADDRESS . 'recoveraccountb.php?UserID=' . $QR['UserID'] . '&amp;VString=' . $thevstring . '</a></p>' . EMAIL_FOOTER;
                 if (send_email($subject, $body, $QR['Email'], null)) {
                     $mypage->leaf('p', 'An account recovery email for ' . $EscapedAccountName . ' has been sent.');
                     $mypage->finish();
                 } else {
                     $mypage->leaf('p', 'There was a problem sending the email. Either the account email address is blank, or the email could not be sent for some other reason. You might want to try again; if it still doesn\'t work, you can ask the Administrator to investigate, but be aware that the Administrator will only go so far as to check for problems with this script and with the site\'s ability to send emails, not give you access to your account.');
                 }
             }
         }
     }
 } else {
     $EscapedAccountName = '';
     $mypage->leaf('p', 'This page may be used to attempt to recover access to an account for which you have forgotten the password. Use this feature if you are the owner of the account and you cannot remember your password. You will need to know your Secret Answer, and have access to your email address.');
Exemplo n.º 16
0
 function newPass($pass, $verify)
 {
     global $lang;
     global $db;
     $id = 0;
     $sql = "SELECT `id` FROM `teams` WHERE `id`=? AND `verification`=?";
     $stmt = $db->prepare($sql);
     $stmt->bind_param("is", $this->id, $verify);
     $stmt->bind_result($id);
     $stmt->execute();
     $stmt->store_result();
     $stmt->fetch();
     if ($stmt->num_rows != 1 || $id !== $this->id) {
         throw new Exception($lang['team'][11]);
     }
     $stmt->close();
     if (strlen($pass) < 1) {
         throw new Exception($lang['register'][3]);
     }
     $salt = generateSalt();
     $hash = hashPass($salt, $pass);
     $salt = base64_encode($salt);
     $sql = "UPDATE `teams` SET `pass`=?, `salt`=? WHERE `id`=?";
     $stmt = $db->prepare($sql);
     $stmt->bind_param("ssi", $hash, $salt, $this->id);
     $stmt->execute();
     $stmt->close();
     return true;
 }
Exemplo n.º 17
0
function print_assertation($cid, $badgetext, $badgename, $descr, $userid, $email)
{
    global $badgeid, $installname, $imasroot;
    header('Content-Type: application/json');
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
        $urlmode = 'https://';
    } else {
        $urlmode = 'http://';
    }
    $urlbase = $urlmode . $_SERVER['HTTP_HOST'];
    $salt = generateSalt();
    $hash = 'sha256$' . hash('sha256', $email . $salt);
    $bs = substr($badgetext, 0, 7);
    if ($bs == 'http://' || $bs == 'https:/') {
        $img = $badgetext;
    } else {
        $img = "{$imasroot}/img/badge.php?text=" . urlencode($badgetext);
    }
    /*$query = "SELECT imas_courses.name AS cname, imas_users.LastName, imas_users.FirstName, imas_users.email, imas_groups.name FROM imas_courses JOIN imas_teachers ON imas_courses.id=imas_teachers.courseid ";
    	$query .= "JOIN imas_users ON imas_teachers.userid=imas_users.id LEFT JOIN imas_groups ON imas_users.groupid=imas_groups.id WHERE imas_courses.id='$cid' LIMIT 1";
    	$result = mysql_query($query) or die("Query failed : " . mysql_error());
    	if (mysql_num_rows($result)==0) {
    		$org = ' ';
    		$email = ' ';
    	} else {
    		$t = array();
    		$e = array();
    		$cname = '';
    		while ($row = mysql_fetch_row($result)) {
    			$cname = $row[0];
    			if ($row[4]==null) {
    				$t[] = $row[1].', '.$row[0];
    			} else {
    				$t[0] = $row[1].', '.$row[2] . ' ('.$row[4].')';
    			}
    			$e[] = $row[3];
    		}
    		$org = 'Course: '.$cname.'. Instructor'.((count($t)>1)?'s':'').': '.implode(', ',$t);
    		$contact = implode(', ', $e);
    	}*/
    echo <<<END
{
\t"recipient": "{$hash}",
\t"salt": "{$salt}",
\t"badge": {
\t\t"version": "0.5.0",
\t\t"name": "{$badgename}",
\t\t"image": "{$img}",
\t\t"description": "{$descr}",
\t\t"criteria": "{$imasroot}/course/verifybadge.php?badgeid={$badgeid}",
\t\t"issuer": {
\t\t\t"origin": "{$urlbase}",
\t\t\t"name": "{$installname}"
\t\t}
\t}
}\t\t
END;
    //  can't include because of FERPA :(
    // "evidence": "$imasroot/course/verifybadge.php?badgeid=$badgeid&userid=$userid",
    //
    //too long, so don't bother
    // 			"org": "$org",
    //			"email": "$contact"
}
Exemplo n.º 18
0
<?php

/**
 * This function generates a password salt as a string of x (default = 15) characters
 * in the a-zA-Z0-9!@#$%&*? range.
 * @param $max integer The number of characters in the string
 * @return string
 * @author AfroSoft <*****@*****.**>
 */
function generateSalt($max = 15)
{
    $characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%&*?";
    $i = 0;
    $salt = "";
    while ($i < $max) {
        $salt .= $characterList[mt_rand(0, strlen($characterList) - 1)];
        $i++;
    }
    return $salt;
}
echo generateSalt();
Exemplo n.º 19
0
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    session_start();
    $errorFlag = false;
    // let us know further down if there was a problem
    $passwordcorrect = false;
    $dbh = db_connect();
    // from login.php:33
    $sql = "SELECT id, \"user\", hash, salt, name FROM users WHERE \"user\" = :username";
    $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    $sth->execute(array(":username" => $_SESSION["username"]));
    $data = $sth->fetch(PDO::FETCH_ASSOC);
    if ($data && hash("sha256", $_POST["oldpass"] . $data["salt"]) == $data["hash"]) {
        // password was correct.
        if ($_POST["newpass"] != "" && $_POST["newpass"] == $_POST["confirmpass"]) {
            // update password
            $salt = generateSalt(40);
            $hash = hash("sha256", $_POST["newpass"] . $salt);
            $sql = "UPDATE users SET (hash, salt, name) = (:hash, :salt, :name) WHERE id = :id";
            $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
            $sth->execute(array(":id" => $_SESSION["userid"], ":hash" => $hash, ":salt" => $salt, ":name" => $_POST["name"]));
            $data = $sth->fetch(PDO::FETCH_ASSOC);
        } else {
            if ($_POST["newpass"] != "" && $_POST["newpass"] != $_POST["confirmpass"]) {
                // new passwords do not match
                echo '<div class="alert alert-error">
                          <button type="button" class="close" data-dismiss="alert">&times;</button>
                          <strong>New passwords do not match.</strong> Please try again.
                        </div>';
                $errorFlag = true;
            } else {
                // just update settings
Exemplo n.º 20
0
<?php

require_once "team.php";
require_once "utility.php";
require_once "en.php";
$teams = array();
#NULL POINTER
$teams[] = array("name" => "NULLPOINTER", "members" => "Mehmet Can Demirel", "email" => "*****@*****.**");
$t = new Teams();
foreach ($teams as $team) {
    $pass = base64_encode(generateSalt(10));
    $t->register($team["name"], $pass, $team["email"], explode("<%#:#%>", $team["members"]));
}
Exemplo n.º 21
0
     }
     if (!$errors and ($SendDataPW or $SendDataAns)) {
         if ($SendDataPW and $SendDataAns) {
             $Query = 'UPDATE "User" SET "Password" = :password:, "SecretAnswer" = :answer:, "SecretQuestion" = :question: WHERE "UserID" = :user:'******'Password and Secret Question / Secret Answer';
         } else {
             if ($SendDataPW) {
                 $Query = 'UPDATE "User" SET "Password" = :password: WHERE "UserID" = :user:'******'Password';
             } else {
                 $Query = 'UPDATE "User" SET "SecretAnswer" = :answer:, "SecretQuestion" = :question: WHERE "UserID" = :user:'******'Secret Question / Secret Answer';
             }
         }
         $EscapedPassword = crypt($EscapedPassword, generateSalt());
         $EscapedAnswer = crypt($EscapedAnswer, generateSalt());
         $QueryResult = dbquery(DBQUERY_WRITE, $Query, 'password', $EscapedPassword, 'answer', $EscapedAnswer, 'question', $EscapedQuestion, 'user', $_SESSION['MyUserID']);
     } else {
         if (!$errors) {
             $errors = true;
             $errorlist->leaf('li', 'Your old password was correct, but you have not entered a new password nor a new Secret Question / Secret Answer, so nothing has been changed.');
         }
     }
     $QArray[$EscapedQuestion] = ' selected';
 } else {
     $errors = false;
     for ($i = 0; $i < 20; $i++) {
         if ($row['SecretQuestion'] == $i) {
             $QArray[$i] = ' selected';
         }
     }
Exemplo n.º 22
0
 public function createPerson($data)
 {
     if (!checkClearanceLevel(ORGANIZER)) {
         return false;
     }
     // Sanitize input data
     foreach ($data as $column => $value) {
         switch ($column) {
             case 'firstname':
             case 'lastname':
                 if (strlen($value) == 0 || strlen($value) > 40) {
                     return false;
                 }
                 $data[$column] = sanitizeInput($value, 40);
                 break;
             case 'sign':
                 if (strlen($value) == 0 || strlen($value) > 4) {
                     return false;
                 }
                 $data[$column] = sanitizeInput($value, 4);
                 break;
             case 'password':
                 if (strlen($value) < 5) {
                     // Password too short
                     return false;
                 } else {
                     // Generate hashed password
                     $salt = generateSalt();
                     $data[$column] = sanitizeInput(crypt($value, "\$5\$" . $salt . "\$"));
                 }
                 break;
             default:
                 $data[$column] = sanitizeInput($value);
         }
     }
     // Add last change date
     $data['datelastchange'] = "CURRENT_TIMESTAMP";
     // Select columns and build query
     $columns = array('firstname', 'lastname', 'sign', 'password', 'type', 'datelastchange');
     $insert = $this->generateSQLInsertClauses($data, $columns);
     $query = "INSERT INTO person ({$insert['columns']}) VALUES ({$insert['values']})";
     $result = mysql_query($query, $this->dbConn);
     if (!$result) {
         ErrorLog(mysql_error($this->dbConn));
     }
     return $result;
 }
Exemplo n.º 23
0
         $errors = true;
         $errorlist->leaf('li', 'The new password you entered is too long.');
     }
     if ($EscapedPassword != $EscapedConfirmPassword) {
         $errors = true;
         $errorlist->leaf('li', 'The passwords in the two fields do not match.');
     }
     if (!$errors) {
         $CharArray = 'abcdefghijklmnopqrstuvwxyz0123456789';
         $thevstring = '';
         for ($i = 0; $i < 20; $i++) {
             $j = rand(0, 35);
             $thevstring .= $CharArray[$j];
         }
         $encryptedthevstring = crypt($thevstring, generateSalt());
         $EscapedPassword = crypt($EscapedPassword, generateSalt());
         dbquery(DBQUERY_WRITE, 'UPDATE "User" SET "ScrambleKey" = :scramblekey:, "Password" = :password: WHERE "UserID" = :user:'******'scramblekey', $encryptedthevstring, 'password', $EscapedPassword, 'user', $EscapedUserID);
         $_SESSION['AllowUse'] = 0;
         $mypage->title_body('Password successfully changed');
         $mypage->leaf('p', 'Your password has been successfully changed. Please click <a href="index.php">here</a> to go to the main page.');
         $mypage->finish();
     }
 } else {
     if (!isset($_GET['UserID']) or !isset($_GET['VString'])) {
         $_SESSION['AllowUse'] = 0;
         $mypage->title_body('Invalid URL');
         $mypage->leaf('p', 'The URL you used to get here is not valid. If you copied and pasted the URL from the email, you may not have copied the entire line. Please try again.');
         $mypage->finish();
     } else {
         $EscapedUserID = sanitise_int($_GET['UserID']);
         $row = dbquery(DBQUERY_READ_SINGLEROW, 'SELECT "ScrambleKey", "SecretQuestion", "UserValidated" FROM "User" WHERE "UserID" = :user:'******'user', $EscapedUserID);
Exemplo n.º 24
0
    echo "16";
}
?>
" autofocus>
            <input type="submit" value="Get Salt">
        </form>
        <p style="font-family: monospace; word-wrap: break-word;">
			<?php 
// Default is to generate a 16 character long salt
function generateSalt($max = 16)
{
    // You can customise the character set here:
    $characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%*&?";
    $i = 0;
    $salt = "";
    while ($i < $max) {
        $salt .= $characterList[mt_rand(0, strlen($characterList) - 1)];
        $i++;
    }
    return $salt;
}
// Check to see if we've been passed a GET parameter
if (isset($_GET['length'])) {
    $length = $_GET['length'];
    // Call the generate salt function, convert any special HTML characters, and print to page:
    echo htmlentities(generateSalt($length));
}
?>
  		</p>
    </body>
</html>
Exemplo n.º 25
0
<?
function generateSalt() {
    $salt = '';
    $length = rand(5,10); // длина соли (от 5 до 10 сомволов)
    for($i=0; $i<$length; $i++) {
         $salt .= chr(rand(33,126)); // символ из ASCII-table
    }
    return $salt;
}
if($_POST['send_data']){
	$salt = generateSalt();
	$pass = md5(md5($_POST['pass_gen']).$salt);
	echo '<p>Пароль: <b>'.$pass.'</b></p>';
	echo '<p>Соль: <b>'.$salt.'</b></p>';
}else{
?>
<h1>Получить соль и пароль</h1>
<form action="<?php 
echo $DOCUMENT_ROOT['PHP_SELF'];
?>
" method="POST">
	<label>Пароль</label><br>
	<input type="text" name="pass_gen"><br><br>
	<input type="submit" name="send_data" value="получить">
</form>
<?
}
?>
Exemplo n.º 26
0
 fwrite(STDOUT, "4.) Please tell me the name of the database you wish to create for vulnDB (default 'vulnDB') : \n");
 $dbname = trim(fgets(STDIN));
 if (!empty($dbname)) {
     $conf['database']['dbname'] = $dbname;
 } else {
     $conf['database']['dbname'] = "vulnDB";
 }
 fwrite(STDOUT, "5.) If you wish to have an alias in front of the table names, please tell me that now : \n");
 $t_alias = trim(fgets(STDIN));
 if (!empty($t_alias)) {
     $conf['database']['table_alias'] = $t_alias . "_";
 } else {
     $conf['database']['table_alias'] = "";
 }
 $conf['database']['dbuser'] = "******";
 $conf['database']['dbpass'] = generateSalt(25);
 $dbh = mysql_connect($conf['database']['dbhost'], $db_root, $db_root_pass);
 echo "Creating database: {$conf['database']['dbname']}.\n";
 $vdb_create = mysql_query("CREATE DATABASE IF NOT EXISTS " . $conf['database']['dbname'] . ";", $dbh) or die(mysql_error());
 echo "Created database {$conf['database']['dbname']}\n";
 $vdb_user_create = mysql_query("GRANT ALL PRIVILEGES ON " . $conf['database']['dbname'] . ".* TO " . $conf['database']['dbuser'] . "@" . $conf['database']['dbhost'] . " IDENTIFIED BY '" . $conf['database']['dbpass'] . "';", $dbh) or die(mysql_error());
 echo "Created user {$conf['database']['dbuser']}\n";
 // Select our new DB
 mysql_select_db($conf['database']['dbname']);
 echo "Creating Tables\n";
 $d = dir($ddl_dir);
 while (FALSE !== ($entry = $d->read())) {
     if ($entry == ".." | $entry == ".") {
         continue;
     }
     $table_short_name = str_replace(".sql", "", $entry);
Exemplo n.º 27
0
    }
});
$app->post('/login/', function () use($app, $em, $urls) {
    $env = $app->environment();
    if (!$env['ulogovan']['status']) {
        try {
            $ds = ldap_connect("localhost");
            ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
            ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
            $user_data = explode('@', $_POST['email']);
            $user = $user_data[0];
            $pass = $_POST['pass'];
            $r = ldap_bind($ds, "cn={$user},ou=users,dc=db,dc=etf,dc=lab,dc=ba", $pass);
            $sr = ldap_search($ds, "dc=db,dc=etf,dc=lab,dc=ba", "cn={$user}");
            $info = ldap_get_entries($ds, $sr);
            $r = ['korisnik' => $info[0]['cn'][0], 'ime' => $info[0]['givenname'][0], 'prezime' => $info[0]['sn'][0], 'kljuc' => generateSalt(), 'lozinka' => $pass, 'rola' => $info[0]['gidnumber'][0]];
            $s = new Sesija();
            $s->setKorisnik($r['korisnik']);
            $s->setIme($r['ime']);
            $s->setPrezime($r['prezime']);
            $s->setKljuc($r['kljuc']);
            $s->setLozinka($r['lozinka']);
            $s->setRola($r['rola']);
            $em->persist($s);
            $em->flush();
            $sesija_kljuc = $r['kljuc'] . ':' . $s->getId();
            setcookie('session', $sesija_kljuc, time() + 60 * 60 * 24 * 30, $urls['rootUri'] . '/');
            //            header('Location: /');
            //            die();
            echo json_encode(array('session' => $sesija_kljuc));
        } catch (Exception $e) {
Exemplo n.º 28
0
function better_crypt($input, $rounds = 7)
{
    $salt = generateSalt();
    return crypt($input, sprintf('$2a$%02d$', $rounds) . $salt);
}
Exemplo n.º 29
0
function hashPassword($password)
{
    return crypt($password, generateSalt());
}
Exemplo n.º 30
0
 /**
  * Добавляем пользователя с текущими данными
  * @global type $sqlcn
  */
 function Add()
 {
     global $sqlcn;
     // хешируем пароль
     $this->salt = generateSalt();
     $this->password = sha1(sha1($this->pass) . $this->salt);
     $sql = "INSERT INTO users (id, randomid, orgid, login, pass, `password`, salt,\n\t\t\temail, mode, lastdt, active) VALUES (NULL, '{$this->randomid}'," . " '{$this->orgid}', '{$this->login}', '{$this->pass}'," . " '{$this->password}', '{$this->salt}', " . " '{$this->email}', '{$this->mode}', NOW(), 1)";
     $sqlcn->ExecuteSQL($sql) or die('Неверный запрос Tusers.Add (1): ' . mysqli_error($sqlcn->idsqlconnection));
     $fio = $this->fio;
     $code = $this->tab_num;
     $telephonenumber = $this->telephonenumber;
     $homephone = $this->homephone;
     $jpegphoto = $this->jpegphoto;
     $rid = $this->randomid;
     $post = $this->post;
     $zx = new Tusers();
     if ($zx->GetByRandomIdNoProfile($rid)) {
         // добавляю профиль
         $sql = "INSERT INTO users_profile (id, usersid, fio, code,\n\t\t\t\ttelephonenumber, homephone, jpegphoto, post, faza, enddate,\n\t\t\t\tres1) VALUES (NULL, '{$zx->id}', '{$fio}', '{$code}'," . " '{$telephonenumber}', '{$homephone}', '{$jpegphoto}'," . " '{$post}', '', NOW(), '')";
         $sqlcn->ExecuteSQL($sql) or die('Неверный запрос Tusers.Add(2): ' . mysqli_error($sqlcn->idsqlconnection));
     } else {
         die('Не найден пользователь по randomid Tusers.Add');
     }
 }