Example #1
0
 public function register()
 {
     check_if_already_logged_in();
     $data["page"] = "register";
     if (isset($_POST['btnRegister'])) {
         $input = array("username" => $_POST['username'], "password" => $_POST['password'], "confirmpass" => $_POST['password_confirm'], "firstname" => $_POST['firstname'], "middlename" => $_POST['middlename'], "lastname" => $_POST['lastname'], "email" => $_POST['email'], "gender" => isset($_POST['gender']) ? $_POST['gender'] : "", "occupation" => $_POST['occupation'], "otherinfo" => $_POST['otherinfo']);
         $data["error"] = verify_data($input);
         if ($data["error"]["count"] == 0) {
             $salt = generate_salt();
             $userdata["username"] = $input["username"];
             $userdata["salt"] = encrypt_salt($salt, 'enElpiPUP1516');
             $userdata["password"] = hash_password($input["password"], $salt);
             $userdata["type"] = "member";
             $other["first_name"] = $input["firstname"];
             $other["middle_name"] = $input["middlename"];
             $other["last_name"] = $input["lastname"];
             $other["email"] = $input["email"];
             $other["gender"] = $input["gender"];
             $other["occupation"] = $input["occupation"];
             $other["about"] = $input["otherinfo"];
             $user = $this->Users_model->insert($userdata, $other);
             header('Location: register');
         }
     }
     $this->load->view('templates/header');
     $this->load->view('users/register', $data);
     $this->load->view('templates/footer');
 }
Example #2
0
function add_user($username, $password, $email)
{
    global $conn;
    $salt = generate_salt();
    $password_hash = hash("sha256", $password . $salt);
    $query = "INSERT INTO login_data (username, password_hash, salt, email) VALUES ('{$username}', '{$password_hash}', '{$salt}', '{$email}');";
    mysqli_query($conn, $query) or die(mysqli_error($conn));
}
Example #3
0
function user_register($username, $password, $email)
{
    $salt = generate_salt();
    $encrypted = md5(md5($password) . $salt);
    //	$query = "INSERT into users (username, password, salt) values ('$username', '$encrypted', '$salt')";
    $query = "INSERT into users (username, password, salt, email) values ('{$username}', '{$encrypted}', '{$salt}', '{$email}')";
    mysql_query($query) or die('Could not create user.');
}
Example #4
0
function new_user($firstName, $lastName, $email, $password, $userType)
{
    $salt = generate_salt();
    $encPassword = encrypt_password($password, $salt);
    $user = create_user_object($firstName, $lastName, $email, $encPassword, $salt, $userType);
    save_user_object($user);
    return $user;
}
Example #5
0
function password_encrypt($password)
{
    $hash_format = "\$2y\$10\$";
    $salt_length = 22;
    $salt = generate_salt($salt_length);
    $format_and_salt = $hash_format . $salt;
    $hash = crypt($password, $format_and_salt);
    return $hash;
}
Example #6
0
 function convert_data($data)
 {
     $insert_data = array();
     // phpBB 2 values
     $insert_data['usergroup'] = $this->board->get_group_id($data, array("not_multiple" => true));
     $insert_data['additionalgroups'] = str_replace($insert_data['usergroup'], '', $this->board->get_group_id($data));
     $insert_data['displaygroup'] = $this->board->get_group_id($data, array("not_multiple" => true));
     $insert_data['import_usergroup'] = $this->board->get_group_id($data, array("not_multiple" => true, "original" => true));
     $insert_data['import_additionalgroups'] = $this->board->get_group_id($data, array("original" => true));
     $insert_data['import_displaygroup'] = $data['group_id'];
     $insert_data['import_uid'] = $data['user_id'];
     $insert_data['username'] = encode_to_utf8($data['username'], "users", "users");
     $insert_data['email'] = $data['user_email'];
     $insert_data['regdate'] = $data['user_regdate'];
     $insert_data['lastactive'] = $data['user_lastvisit'];
     $insert_data['lastvisit'] = $data['user_lastvisit'];
     $insert_data['website'] = $data['user_website'];
     $insert_data['avatar'] = $data['user_avatar'];
     list($width, $height) = @getimagesize($data['user_avatar']);
     $insert_data['avatardimensions'] = $width . '|' . $height;
     if ($insert_data['avatar'] == '') {
         $insert_data['avatartype'] = "";
     } else {
         $insert_data['avatartype'] = 'remote';
     }
     $last_post = $this->get_last_post($data['user_id']);
     $insert_data['lastpost'] = intval($last_post['post_time']);
     $insert_data['icq'] = $data['user_icq'];
     $insert_data['aim'] = $data['user_aim'];
     $insert_data['yahoo'] = $data['user_yim'];
     $insert_data['msn'] = $data['user_msnm'];
     $insert_data['hideemail'] = $data['hideEmail'];
     $insert_data['invisible'] = int_to_01($data['user_allow_viewonline']);
     $insert_datar['allownotices'] = $data['user_notify'];
     if ($data['user_notify'] == 1) {
         $subscription_method == 2;
     } else {
         $subscription_method = 0;
     }
     $insert_data['subscriptionmethod'] = $subscription_method;
     $insert_data['receivepms'] = $data['user_allow_pm'];
     $insert_data['pmnotice'] = $data['user_popup_pm'];
     $insert_data['pmnotify'] = $data['pm_email_notify'];
     $insert_data['showsigs'] = $data['user_attachsig'];
     $insert_data['showavatars'] = $data['user_allowavatar'];
     $insert_data['timeformat'] = $data['user_dateformat'];
     $insert_data['timezone'] = $data['user_timezone'];
     $insert_data['regip'] = $last_post['poster_ip'];
     $insert_data['totalpms'] = $this->get_private_messages($data['user_id']);
     $insert_data['unreadpms'] = $data['user_unread_privmsg'];
     $insert_data['salt'] = generate_salt();
     $insert_data['signature'] = encode_to_utf8(str_replace(':' . $data['user_sig_bbcode_uid'], '', utf8_unhtmlentities($data['user_sig'])), "users", "users");
     $insert_data['password'] = salt_password($data['user_password'], $insert_data['salt']);
     $insert_data['loginkey'] = generate_loginkey();
     return $insert_data;
 }
function password_encrypt($password)
{
    $hash_format = "\$2y\$10\$";
    $length = 22;
    //generate salt function of length 22
    $salt = generate_salt($length);
    $format_and_salt = $hash_format . $salt;
    $hashed_password = crypt($password, $format_and_salt);
    return $hashed_password;
}
function password_encrypt($password)
{
    $hash_format = "\$2a\$05\$";
    //blowfish
    $salt = generate_salt();
    $format_and_salt = $hash_format . $salt;
    //crypt using password and 22 characters (salt and blowfish)
    $hash = crypt($password, $format_and_salt);
    return $hash;
}
Example #9
0
function user_register($username, $password, $email, $youtubeUserName)
{
    // Get a salt using our function
    $salt = generate_salt();
    // Now encrypt the password using that salt
    $encrypted = md5(md5($password) . $salt);
    // And lastly, store the information in the database
    $ref = $_SESSION['ref'];
    $query = "insert into user (username, password, salt, email, youtubeUserName, video, refferal) values ('{$username}', '{$encrypted}', '{$salt}', '{$email}', '{$youtubeUserName}', '', '{$ref}')";
    mysql_query($query) or die('Could not create user. Refresh the page to try again.');
}
Example #10
0
 public function change_password(IChangePasswordInput $input)
 {
     // Prepare data
     $this->load->helper('crypto');
     $passwordsalt = generate_salt();
     $passwordhash = generate_hash($input->get_password(), $passwordsalt);
     $this->db->where('email', $input->get_email());
     $this->db->where('passwordresetcode', $input->get_resetcode());
     $this->db->update("users", array("passwordresetcode" => NULL, "passwordhash" => $passwordhash, "passwordsalt" => $passwordsalt));
     return $this->db->affected_rows() > 0;
 }
Example #11
0
function password_encrypt($password)
{
    $hash_format = "\$2y\$10\$";
    // Blowfish with a "cost" of 10
    $salt_length = 22;
    // Blowfish salts
    $salt = generate_salt($salt_length);
    $format_and_salt = $hash_format . $salt;
    $hash = crypt($password, $format_and_salt);
    return $hash;
}
Example #12
0
function password_encrypt($password)
{
    $hash_format = "\$2y\$10\$";
    // Tells PHP to use Blowfish with a "cost" of 10
    $salt_length = 22;
    // Blowfish salts should be 22-characters or more
    $salt = generate_salt($salt_length);
    $format_and_salt = $hash_format . $salt;
    $hash = crypt($password, $format_and_salt);
    return $hash;
}
Example #13
0
function verify_password($password, $salt, $uid = false)
{
    $correct = false;
    if (substr($salt, 0, 1) == '$') {
        // new-style crypt()
        $correct = crypt($password, $salt) == $salt;
    } elseif (substr($salt, 0, 7) == '{crypt}') {
        // old-style crypt() with DES and static salt - not used anymore
        $correct = crypt($password, '77') == $salt;
    } elseif (strlen($salt) == 32) {
        // old-style md5 without salt - not used anymore
        $correct = md5($password) == $salt;
    }
    if ($correct && substr($salt, 0, strlen(CRYPT_ALG)) != CRYPT_ALG && $uid) {
        // this password is stored in another format than we want it to be.
        // let's update it!
        // we duplicate the query from the above set_password() function to have the extra safety of checking the old hash
        sql_query("UPDATE `User` SET `Passwort` = '" . sql_escape(crypt($password, CRYPT_ALG . '$' . generate_salt() . '$')) . "' WHERE `UID` = " . intval($uid) . " AND `Passwort` = '" . sql_escape($salt) . "' LIMIT 1");
    }
    return $correct;
}
Example #14
0
function loginconvert_convert(&$login)
{
    global $mybb, $valid_login_types, $db, $settings;
    $options = array("fields" => array('username', "password", "salt", 'loginkey', 'coppauser', 'usergroup', "passwordconvert", "passwordconverttype", "passwordconvertsalt"), "username_method" => (int) $settings['username_method']);
    if ($login->username_method !== null) {
        $options['username_method'] = (int) $login->username_method;
    }
    $user = get_user_by_username($login->data['username'], $options);
    // There's nothing to check for, let MyBB do everything
    // This fails also when no user was found above, so no need for an extra check
    if (!isset($user['passwordconvert']) || $user['passwordconvert'] == '') {
        return;
    }
    if (!array_key_exists($user['passwordconverttype'], $valid_login_types)) {
        // TODO: Is there an easy way to make the error translatable without adding a new language file?
        redirect($mybb->settings['bburl'] . "/member.php?action=lostpw", "We're sorry but we couldn't convert your old password. Please select a new one", "", true);
    } else {
        $function = "check_" . $valid_login_types[$user['passwordconverttype']];
        $check = $function($login->data['password'], $user);
        if (!$check) {
            // Yeah, that function is called later too, but we need to know whether the captcha is right
            // If we wouldn't call that function the error would always be shown
            $login->verify_attempts($mybb->settings['captchaimage']);
            $login->invalid_combination(true);
        } else {
            // The password was correct, so use MyBB's method the next time (even if the captcha was wrong we can update the password)
            $salt = generate_salt();
            $update = array("salt" => $salt, "password" => salt_password(md5($login->data['password']), $salt), "loginkey" => generate_loginkey(), "passwordconverttype" => "", "passwordconvert" => "", "passwordconvertsalt" => "");
            $db->update_query("users", $update, "uid='{$user['uid']}'");
            // Make sure the password isn't tested again
            unset($login->data['password']);
            // Also make sure all data is available when creating the session (otherwise SQL errors -.-)
            $login->login_data = array_merge($user, $update);
        }
    }
}
Example #15
0
/**
 * Process information given to new/edit account form
 *
 * @global array $SUPPORTED_LANGS Languages that are supported by the AUR
 * @param string $TYPE Either "edit" for editing or "new" for registering an account
 * @param string $A Form to use, either UpdateAccount or NewAccount
 * @param string $U The username for the account
 * @param string $T The account type for the user
 * @param string $S Whether or not the account is suspended
 * @param string $E The e-mail address for the user
 * @param string $H Whether or not the e-mail address should be hidden
 * @param string $P The password for the user
 * @param string $C The confirmed password for the user
 * @param string $R The real name of the user
 * @param string $L The language preference of the user
 * @param string $I The IRC nickname of the user
 * @param string $K The PGP fingerprint of the user
 * @param string $PK The list of public SSH keys
 * @param string $J The inactivity status of the user
 * @param string $UID The user ID of the modified account
 * @param string $N The username as present in the database
 *
 * @return array Boolean indicating success and message to be printed
 */
function process_account_form($TYPE, $A, $U = "", $T = "", $S = "", $E = "", $H = "", $P = "", $C = "", $R = "", $L = "", $I = "", $K = "", $PK = "", $J = "", $UID = 0, $N = "")
{
    global $SUPPORTED_LANGS;
    $error = '';
    $message = '';
    if (is_ipbanned()) {
        $error = __('Account registration has been disabled ' . 'for your IP address, probably due ' . 'to sustained spam attacks. Sorry for the ' . 'inconvenience.');
    }
    $dbh = DB::connect();
    if (isset($_COOKIE['AURSID'])) {
        $editor_user = uid_from_sid($_COOKIE['AURSID']);
    } else {
        $editor_user = null;
    }
    if (empty($E) || empty($U)) {
        $error = __("Missing a required field.");
    }
    if ($TYPE != "new" && !$UID) {
        $error = __("Missing User ID");
    }
    if (!$error && !valid_username($U)) {
        $length_min = config_get_int('options', 'username_min_len');
        $length_max = config_get_int('options', 'username_max_len');
        $error = __("The username is invalid.") . "<ul>\n" . "<li>" . __("It must be between %s and %s characters long", $length_min, $length_max) . "</li>" . "<li>" . __("Start and end with a letter or number") . "</li>" . "<li>" . __("Can contain only one period, underscore or hyphen.") . "</li>\n</ul>";
    }
    if (!$error && $P && $C && $P != $C) {
        $error = __("Password fields do not match.");
    }
    if (!$error && $P != '' && !good_passwd($P)) {
        $length_min = config_get_int('options', 'passwd_min_len');
        $error = __("Your password must be at least %s characters.", $length_min);
    }
    if (!$error && !valid_email($E)) {
        $error = __("The email address is invalid.");
    }
    if (!$error && $K != '' && !valid_pgp_fingerprint($K)) {
        $error = __("The PGP key fingerprint is invalid.");
    }
    if (!$error && !empty($PK)) {
        $ssh_keys = array_filter(array_map('trim', explode("\n", $PK)));
        $ssh_fingerprints = array();
        foreach ($ssh_keys as &$ssh_key) {
            if (!valid_ssh_pubkey($ssh_key)) {
                $error = __("The SSH public key is invalid.");
                break;
            }
            $ssh_fingerprint = ssh_key_fingerprint($ssh_key);
            if (!$ssh_fingerprint) {
                $error = __("The SSH public key is invalid.");
                break;
            }
            $tokens = explode(" ", $ssh_key);
            $ssh_key = $tokens[0] . " " . $tokens[1];
            $ssh_fingerprints[] = $ssh_fingerprint;
        }
        /*
         * Destroy last reference to prevent accidentally overwriting
         * an array element.
         */
        unset($ssh_key);
    }
    if (isset($_COOKIE['AURSID'])) {
        $atype = account_from_sid($_COOKIE['AURSID']);
        if ($atype == "User" && $T > 1 || $atype == "Trusted User" && $T > 2) {
            $error = __("Cannot increase account permissions.");
        }
    }
    if (!$error && !array_key_exists($L, $SUPPORTED_LANGS)) {
        $error = __("Language is not currently supported.");
    }
    if (!$error) {
        /*
         * Check whether the user name is available.
         * TODO: Fix race condition.
         */
        $q = "SELECT COUNT(*) AS CNT FROM Users ";
        $q .= "WHERE Username = "******"edit") {
            $q .= " AND ID != " . intval($UID);
        }
        $result = $dbh->query($q);
        $row = $result->fetch(PDO::FETCH_NUM);
        if ($row[0]) {
            $error = __("The username, %s%s%s, is already in use.", "<strong>", htmlspecialchars($U, ENT_QUOTES), "</strong>");
        }
    }
    if (!$error) {
        /*
         * Check whether the e-mail address is available.
         * TODO: Fix race condition.
         */
        $q = "SELECT COUNT(*) AS CNT FROM Users ";
        $q .= "WHERE Email = " . $dbh->quote($E);
        if ($TYPE == "edit") {
            $q .= " AND ID != " . intval($UID);
        }
        $result = $dbh->query($q);
        $row = $result->fetch(PDO::FETCH_NUM);
        if ($row[0]) {
            $error = __("The address, %s%s%s, is already in use.", "<strong>", htmlspecialchars($E, ENT_QUOTES), "</strong>");
        }
    }
    if (!$error && count($ssh_keys) > 0) {
        /*
         * Check whether any of the SSH public keys is already in use.
         * TODO: Fix race condition.
         */
        $q = "SELECT Fingerprint FROM SSHPubKeys ";
        $q .= "WHERE Fingerprint IN (";
        $q .= implode(',', array_map(array($dbh, 'quote'), $ssh_fingerprints));
        $q .= ")";
        if ($TYPE == "edit") {
            $q .= " AND UserID != " . intval($UID);
        }
        $result = $dbh->query($q);
        $row = $result->fetch(PDO::FETCH_NUM);
        if ($row) {
            $error = __("The SSH public key, %s%s%s, is already in use.", "<strong>", htmlspecialchars($row[0], ENT_QUOTES), "</strong>");
        }
    }
    if ($error) {
        $message = "<ul class='errorlist'><li>" . $error . "</li></ul>\n";
        return array(false, $message);
    }
    if ($TYPE == "new") {
        /* Create an unprivileged user. */
        $salt = generate_salt();
        if (empty($P)) {
            $send_resetkey = true;
            $email = $E;
        } else {
            $send_resetkey = false;
            $P = salted_hash($P, $salt);
        }
        $U = $dbh->quote($U);
        $E = $dbh->quote($E);
        $P = $dbh->quote($P);
        $salt = $dbh->quote($salt);
        $R = $dbh->quote($R);
        $L = $dbh->quote($L);
        $I = $dbh->quote($I);
        $K = $dbh->quote(str_replace(" ", "", $K));
        $q = "INSERT INTO Users (AccountTypeID, Suspended, ";
        $q .= "InactivityTS, Username, Email, Passwd, Salt, ";
        $q .= "RealName, LangPreference, IRCNick, PGPKey) ";
        $q .= "VALUES (1, 0, 0, {$U}, {$E}, {$P}, {$salt}, {$R}, {$L}, ";
        $q .= "{$I}, {$K})";
        $result = $dbh->exec($q);
        if (!$result) {
            $message = __("Error trying to create account, %s%s%s.", "<strong>", htmlspecialchars($U, ENT_QUOTES), "</strong>");
            return array(false, $message);
        }
        $uid = $dbh->lastInsertId();
        account_set_ssh_keys($uid, $ssh_keys, $ssh_fingerprints);
        $message = __("The account, %s%s%s, has been successfully created.", "<strong>", htmlspecialchars($U, ENT_QUOTES), "</strong>");
        $message .= "<p>\n";
        if ($send_resetkey) {
            send_resetkey($email, true);
            $message .= __("A password reset key has been sent to your e-mail address.");
            $message .= "</p>\n";
        } else {
            $message .= __("Click on the Login link above to use your account.");
            $message .= "</p>\n";
        }
    } else {
        /* Modify an existing account. */
        $q = "SELECT InactivityTS FROM Users WHERE ";
        $q .= "ID = " . intval($UID);
        $result = $dbh->query($q);
        $row = $result->fetch(PDO::FETCH_NUM);
        if ($row[0] && $J) {
            $inactivity_ts = $row[0];
        } elseif ($J) {
            $inactivity_ts = time();
        } else {
            $inactivity_ts = 0;
        }
        $q = "UPDATE Users SET ";
        $q .= "Username = "******", AccountTypeID = " . intval($T);
        }
        if ($S) {
            /* Ensure suspended users can't keep an active session */
            delete_user_sessions($UID);
            $q .= ", Suspended = 1";
        } else {
            $q .= ", Suspended = 0";
        }
        $q .= ", Email = " . $dbh->quote($E);
        if ($H) {
            $q .= ", HideEmail = 1";
        } else {
            $q .= ", HideEmail = 0";
        }
        if ($P) {
            $salt = generate_salt();
            $hash = salted_hash($P, $salt);
            $q .= ", Passwd = '{$hash}', Salt = '{$salt}'";
        }
        $q .= ", RealName = " . $dbh->quote($R);
        $q .= ", LangPreference = " . $dbh->quote($L);
        $q .= ", IRCNick = " . $dbh->quote($I);
        $q .= ", PGPKey = " . $dbh->quote(str_replace(" ", "", $K));
        $q .= ", InactivityTS = " . $inactivity_ts;
        $q .= " WHERE ID = " . intval($UID);
        $result = $dbh->exec($q);
        $ssh_key_result = account_set_ssh_keys($UID, $ssh_keys, $ssh_fingerprints);
        if ($result === false || $ssh_key_result === false) {
            $message = __("No changes were made to the account, %s%s%s.", "<strong>", htmlspecialchars($U, ENT_QUOTES), "</strong>");
        } else {
            $message = __("The account, %s%s%s, has been successfully modified.", "<strong>", htmlspecialchars($U, ENT_QUOTES), "</strong>");
        }
    }
    return array(true, $message);
}
function gen_mix_salt($pass)
{
    $salt = generate_salt();
    return mix_salt($salt, $pass);
}
Example #17
0
        }
        $langs .= '<option ' . $sel . ' value="' . $larray . '" >' . $larray . '</option>';
        $sel = '';
        $count++;
    }
    $langs .= '</select><br />';
} else {
    $langs = '<b>' . i18n_r('LANGUAGE') . '</b>: &nbsp;<code style="color:red;">' . i18n_r('NONE') . '</code> &nbsp;&nbsp;';
}
# salt value generation
$api_file = GSDATAOTHERPATH . GSAUTHFILE;
if (!file_exists($api_file)) {
    if (getDef('GSUSECUSTOMSALT')) {
        $saltval = sha1(GSUSECUSTOMSALT);
    } else {
        $saltval = generate_salt();
    }
    $xml = new SimpleXMLExtended('<item></item>');
    $note = $xml->addChild('apikey');
    $note->addCData($saltval);
    if (!XMLsave($xml, $api_file)) {
        $kill = i18n_r('CHMOD_ERROR');
    }
}
# get salt value
$data = getXML($api_file);
$APIKEY = $data->apikey;
if (empty($APIKEY)) {
    $kill = i18n_r('CHMOD_ERROR');
}
$pagetitle = $site_full_name . ' &middot; ' . i18n_r('INSTALLATION');
/**
 * Updates a user's salt in the database (does not update a password).
 *
 * @param int $uid The uid of the user to update.
 * @return string The new salt.
 */
function update_salt($uid)
{
    global $db;
    $salt = generate_salt();
    $sql_array = array("salt" => $salt);
    $db->update_query("users", $sql_array, "uid='{$uid}'");
    return $salt;
}
Example #19
0
 /**
  * Insert a new provider record into the database.
  *  
  * @param array $provider Contains the provider data (must be already validated).
  * @return int Returns the new record id.
  * @throws Exception When the insert operation fails.
  */
 public function insert($provider)
 {
     $this->load->helper('general');
     // Get provider role id.
     $provider['id_roles'] = $this->get_providers_role_id();
     // Store provider settings and services (must not be present on the $provider array).
     $services = $provider['services'];
     unset($provider['services']);
     $settings = $provider['settings'];
     unset($provider['settings']);
     // Insert provider record and save settings.
     if (!$this->db->insert('ea_users', $provider)) {
         throw new Exception('Could not insert provider into the database');
     }
     $settings['salt'] = generate_salt();
     $settings['password'] = hash_password($settings['salt'], $settings['password']);
     $provider['id'] = $this->db->insert_id();
     $this->save_settings($settings, $provider['id']);
     $this->save_services($services, $provider['id']);
     // Return the new record id.
     return intval($provider['id']);
 }
Example #20
0
function mod_user_new()
{
    global $pdo, $config;
    if (!hasPermission($config['mod']['createusers'])) {
        error($config['error']['noaccess']);
    }
    if (isset($_POST['username'], $_POST['password'], $_POST['type'])) {
        if ($_POST['username'] == '') {
            error(sprintf($config['error']['required'], 'username'));
        }
        if ($_POST['password'] == '') {
            error(sprintf($config['error']['required'], 'password'));
        }
        if (isset($_POST['allboards'])) {
            $boards = array('*');
        } else {
            $_boards = listBoards();
            foreach ($_boards as &$board) {
                $board = $board['uri'];
            }
            $boards = array();
            foreach ($_POST as $name => $value) {
                if (preg_match('/^board_(' . $config['board_regex'] . ')$/u', $name, $matches) && in_array($matches[1], $_boards)) {
                    $boards[] = $matches[1];
                }
            }
        }
        $type = (int) $_POST['type'];
        if (!isset($config['mod']['groups'][$type]) || $type == DISABLED) {
            error(sprintf($config['error']['invalidfield'], 'type'));
        }
        $salt = generate_salt();
        $password = hash('sha256', $salt . sha1($_POST['password']));
        $query = prepare('INSERT INTO ``mods`` VALUES (NULL, :username, :password, :salt, :type, :boards)');
        $query->bindValue(':username', $_POST['username']);
        $query->bindValue(':password', $password);
        $query->bindValue(':salt', $salt);
        $query->bindValue(':type', $type);
        $query->bindValue(':boards', implode(',', $boards));
        $query->execute() or error(db_error($query));
        $userID = $pdo->lastInsertId();
        modLog('Created a new user: '******'username']) . ' <small>(#' . $userID . ')</small>');
        header('Location: ?/users', true, $config['redirect_http']);
        return;
    }
    mod_page(_('New user'), 'mod/user.html', array('new' => true, 'boards' => listBoards(), 'token' => make_secure_link_token('users/new')));
}
Example #21
0
function LostPassword($email)
{
    $objResponse = new xajaxResponse();
    $q = $GLOBALS['db']->GetRow("SELECT * FROM `" . DB_PREFIX . "_admins` WHERE `email` = ?", array($email));
    if (!$q[0]) {
        $objResponse->addScript("ShowBox('Error', 'The email address you supplied is not registered on the system', 'red', '');");
        return $objResponse;
    } else {
        $objResponse->addScript("\$('msg-red').setStyle('display', 'none');");
    }
    $validation = md5(generate_salt(20) . generate_salt(20)) . md5(generate_salt(20) . generate_salt(20));
    $query = $GLOBALS['db']->Execute("UPDATE `" . DB_PREFIX . "_admins` SET `validate` = ? WHERE `email` = ?", array($validation, $email));
    $message = "";
    $message .= "Hello " . $q['user'] . "\n";
    $message .= "You have requested to have your password reset for your SourceBans account.\n";
    $message .= "To complete this process, please click the following link.\n";
    $message .= "NOTE: If you didnt request this reset, then simply ignore this email.\n\n";
    $message .= "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "?p=lostpassword&email=" . RemoveCode($email) . "&validation=" . $validation;
    $headers = 'From: lostpwd@' . $_SERVER['HTTP_HOST'] . "\n" . 'X-Mailer: PHP/' . phpversion();
    $m = mail($email, "SourceBans Password Reset", $message, $headers);
    $objResponse->addScript("ShowBox('Check E-Mail', 'Please check your email inbox (and spam) for a link which will help you reset your password.', 'blue', '');");
    return $objResponse;
}
Example #22
0
function password_encrypt($password)
{
    /* specify $blowfish encryption with $cost of 10 */
    $hash_format = "\$2y\$10\$";
    /* set salt length */
    $salt_length = 22;
    $salt = generate_salt($salt_length);
    $format_and_salt = $hash_format . $salt;
    $hash = crypt($password, $format_and_salt);
    return $hash;
}
Example #23
0
function change_password($user_id, $new_pass)
{
    global $DB_CONN;
    $conn = $DB_CONN;
    $salt = generate_salt(32);
    $hash = hash_pbkdf2('sha256', $new_pass, $salt, 1000, 0);
    if ($result = mysqli_query($conn, "UPDATE `Users` SET `Salt` = '{$salt}', `Password` = '{$hash}' WHERE `UserId` = {$user_id} LIMIT 1;")) {
        return true;
    } else {
        write_log("mysqli", "change_password: MySQLi Query failed with error #" . mysqli_errno($conn) . ": '" . mysqli_error($conn) . "'.");
        return false;
    }
}
function password_encrypt($password)
{
    $hash_format = "\$2y\$10\$";
    // tell php to use blowfish with cost of 10
    $salt_lenght = 22;
    // what blowfish expects to see everytime
    $salt = generate_salt($salt_lenght);
    $format_and_salt = $hash_format . $salt;
    $hash = crypt($password, $format_and_salt);
    return $hash;
}
Example #25
0
// ------------------------------------------------------------------
// handles user login creation process
// creates or include salt file
if (file_exists($auto_restrict['path_to_files'] . '/auto_restrict_salt.php')) {
    include $auto_restrict['path_to_files'] . '/auto_restrict_salt.php';
} else {
    $auto_restrict['system_salt'] = generate_salt(512);
    file_put_contents($auto_restrict['path_to_files'] . '/auto_restrict_salt.php', '<?php $auto_restrict["system_salt"]=' . var_export($auto_restrict['system_salt'], true) . '; ?>');
}
// creates auto_restrict_pass.php with secured login pass data
if (file_exists($auto_restrict['path_to_files'] . '/auto_restrict_pass.php')) {
    include $auto_restrict['path_to_files'] . '/auto_restrict_pass.php';
}
if (!isset($auto_restrict['pass'])) {
    if (isset($_POST['pass']) && isset($_POST['login']) && $_POST['pass'] != '' && $_POST['login'] != '') {
        $salt = generate_salt(512);
        $auto_restrict['encryption_key'] = md5(uniqid('', true));
        file_put_contents($auto_restrict['path_to_files'] . '/auto_restrict_pass.php', '<?php $auto_restrict["login"]="******";$auto_restrict["encryption_key"]=' . var_export($auto_restrict['encryption_key'], true) . ';$auto_restrict["salt"] = ' . var_export($salt, true) . '; $auto_restrict["pass"] = '******'sha512', $salt . $_POST['pass']), true) . '; $auto_restrict["tokens_filename"] = "tokens_' . var_export(hash('sha512', $salt . uniqid('', true)), true) . '.php";$auto_restrict["banned_ip_filename"] = "banned_ip_' . var_export(hash('sha512', $salt . uniqid('', true)), true) . '.php";?>');
        include 'login_form.php';
        exit;
    } else {
        include 'login_form.php';
        exit;
    }
}
// ------------------------------------------------------------------
// load banned ip
// ------------------------------------------------------------------
if (is_file($auto_restrict['path_to_files'] . '/' . $auto_restrict["banned_ip_filename"])) {
    include $auto_restrict['path_to_files'] . '/' . $auto_restrict["banned_ip_filename"];
}
Example #26
0
             error(_("Cannot create board with banned word {$w}"));
         }
     } else {
         if (preg_match($w, $uri)) {
             error(_("Cannot create board matching banned pattern {$w}"));
         }
     }
 }
 $query = prepare('SELECT ``username`` FROM ``mods`` WHERE ``username`` = :username');
 $query->bindValue(':username', $username);
 $query->execute() or error(db_error($query));
 $users = $query->fetchAll(PDO::FETCH_ASSOC);
 if (sizeof($users) > 0) {
     error(_('The username you\'ve tried to enter already exists!'));
 }
 $salt = generate_salt();
 $password = hash('sha256', $salt . sha1($password));
 $query = prepare('INSERT INTO ``mods`` VALUES (NULL, :username, :password, :salt, :type, :boards, :email)');
 $query->bindValue(':username', $username);
 $query->bindValue(':password', $password);
 $query->bindValue(':salt', $salt);
 $query->bindValue(':type', 20);
 $query->bindValue(':boards', $uri);
 $query->bindValue(':email', $email);
 $query->execute() or error(db_error($query));
 $query = prepare('INSERT INTO ``boards`` (`uri`, `title`, `subtitle`) VALUES (:uri, :title, :subtitle)');
 $query->bindValue(':uri', $_POST['uri']);
 $query->bindValue(':title', $_POST['title']);
 $query->bindValue(':subtitle', $_POST['subtitle']);
 $query->execute() or error(db_error($query));
 $query = Element('posts.sql', array('board' => $uri));
Example #27
0
 /**
  * Verifies if a new password is valid or not.
  *
  * @return boolean True when valid, false when invalid.
  */
 function verify_password()
 {
     global $mybb;
     $user =& $this->data;
     // Always check for the length of the password.
     if (my_strlen($user['password']) < $mybb->settings['minpasswordlength'] || my_strlen($user['password']) > $mybb->settings['maxpasswordlength']) {
         $this->set_error('invalid_password_length', array($mybb->settings['minpasswordlength'], $mybb->settings['maxpasswordlength']));
         return false;
     }
     // Has the user tried to use their email address or username as a password?
     if ($user['email'] === $user['password'] || $user['username'] === $user['password']) {
         $this->set_error('bad_password_security');
         return false;
     }
     // See if the board has "require complex passwords" enabled.
     if ($mybb->settings['requirecomplexpasswords'] == 1) {
         // Complex passwords required, do some extra checks.
         // First, see if there is one or more complex character(s) in the password.
         if (!preg_match("/^.*(?=.{" . $mybb->settings['minpasswordlength'] . ",})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*\$/", $user['password'])) {
             $this->set_error('no_complex_characters', array($mybb->settings['minpasswordlength']));
             return false;
         }
     }
     // If we have a "password2" check if they both match
     if (isset($user['password2']) && $user['password'] !== $user['password2']) {
         $this->set_error("passwords_dont_match");
         return false;
     }
     // MD5 the password
     $user['md5password'] = md5($user['password']);
     // Generate our salt
     $user['salt'] = generate_salt();
     // Combine the password and salt
     $user['saltedpw'] = salt_password($user['md5password'], $user['salt']);
     // Generate the user login key
     $user['loginkey'] = generate_loginkey();
     return true;
 }
function LostPassword($email)
{
    $objResponse = new xajaxResponse();
    $q = $GLOBALS['db']->GetRow("SELECT * FROM `" . DB_PREFIX . "_admins` WHERE `email` = ?", array($email));
    if (!$q[0]) {
        $objResponse->addScript("ShowBox('Ошибка', 'Введенный Вами адрес e-mail не найден в базе', 'red', '');");
        return $objResponse;
    } else {
        $objResponse->addScript("\$('msg-red').setStyle('display', 'none');");
    }
    $validation = md5(generate_salt(20) . generate_salt(20)) . md5(generate_salt(20) . generate_salt(20));
    $query = $GLOBALS['db']->Execute("UPDATE `" . DB_PREFIX . "_admins` SET `validate` = ? WHERE `email` = ?", array($validation, $email));
    $message = "";
    $message .= "Привет " . $q['user'] . "\n";
    $message .= "Вы запросили смену пароля в системе Sourcebans.\n";
    $message .= "Для завершения процедуры смены пароля перейдите по ссылке ниже.\n";
    $message .= "ПРИМЕЧАНИЕ: если Вы не запрашивали смену пароля, просто проигнорируйте это сообщение.\n\n";
    $message .= "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "?p=lostpassword&email=" . RemoveCode($email) . "&validation=" . $validation;
    $headers = 'From: lostpwd@' . $_SERVER['HTTP_HOST'] . "\n" . 'X-Mailer: PHP/' . phpversion();
    $m = mail($email, "Сброс пароля SourceBans", $message, $headers);
    $objResponse->addScript("ShowBox('Проверьте почту', 'На Ваш электронный ящик было отправлено письмо с ссылкой для сброса пароля.', 'blue', '');");
    return $objResponse;
}
 /**
  * Insert a new sercretary record into the database.
  * 
  * @param array $secretary Contains the secretary data.
  * @return int Returns the new record id.
  * @throws Exception When the insert operation fails.
  */
 public function insert($secretary)
 {
     $this->load->helper('general');
     $providers = $secretary['providers'];
     unset($secretary['providers']);
     $settings = $secretary['settings'];
     unset($secretary['settings']);
     $secretary['id_roles'] = $this->get_secretary_role_id();
     if (!$this->db->insert('ea_users', $secretary)) {
         throw new Exception('Could not insert secretary into the database.');
     }
     $secretary['id'] = intval($this->db->insert_id());
     $settings['salt'] = generate_salt();
     $settings['password'] = hash_password($settings['salt'], $settings['password']);
     $this->save_providers($providers, $secretary['id']);
     $this->save_settings($settings, $secretary['id']);
     return $secretary['id'];
 }
Example #30
0
# ------------------------------------------------------------------
if (!empty($_POST['pass']) && !empty($_POST['confirm']) && isset($_POST['creation']) && !empty($_POST['login']) && empty($_POST['admin_password'])) {
    if (!isset($auto_restrict['users'])) {
        $auto_restrict['users'] = array();
    }
    $index = count($auto_restrict['users']);
    $login = strip_tags($_POST['login']);
    if (login_exists($login)) {
        safe_redirect('index.php?p=login&newuser&error=1&token=' . returnToken());
    }
    if ($_POST['pass'] != $_POST['confirm']) {
        safe_redirect('index.php?p=login&newuser&error=3&token=' . returnToken());
    }
    $auto_restrict['users'][$index]['login'] = $login;
    $auto_restrict['users'][$index]['encryption_key'] = md5(uniqid('', true));
    $auto_restrict['users'][$index]['salt'] = generate_salt(512);
    $auto_restrict['users'][$index]['lang'] = $_SESSION['language'];
    $auto_restrict['users'][$index]['status'] = '';
    $auto_restrict['users'][$index]['pass'] = hash('sha512', $auto_restrict['users'][$index]['salt'] . $_POST['pass']);
    if (!save_users()) {
        exit('<div class="error">auto_restrict: problem saving users</div>');
    }
    safe_redirect('index.php?p=admin&msg=' . e('Account created:', false) . $login . '&token=' . returnToken());
    exit;
}
# ------------------------------------------------------------------
# Change password request
# ------------------------------------------------------------------
if (!empty($_POST['pass']) && !empty($_POST['confirm']) && !empty($_POST['admin_password'])) {
    if ($auto_restrict['users'][$_SESSION['login']]['pass'] !== hash('sha512', $auto_restrict['users'][$_SESSION['login']]['salt'] . $_POST['admin_password'])) {
        safe_redirect('index.php?p=login&change_password&error=4&token=' . returnToken());