how to edit .htpasswd using php? - apache

i have a protected directory where only user on .htpasswd can access, but sometimes it requires the user to change password or username, edit a specific username password to his username him self
sample users
kevien : kka
mike : mike
And let say i want to change kevien to XYZ
And same thing goes to password

I have modified function to use all types of crypt alghoritms. Someone may find it useful:
/*
Function change password in htpasswd.
Arguments:
$user > User name we want to change password to.
$newpass > New password
$type > Type of cryptogrphy: DES, SHA, MD5.
$salt > Option: Add your custom salt (hashing string).
Salt is applied to DES and MD5 and must be in range 0-9A-Za-z
$oldpass > Option: Add more security, user must known old password to change it.
This option is not supported for DES and MD5 without salt!!!
$path > Path to .htaccess file which contain the password protection.
Path to password file is obtained from this .htaccess file.
*/
function changePass($user, $newpass, $type="SHA", $salt="", $oldpass="", $path=".htaccess")
{
switch ($type) {
case "DES" :
$salt = substr($salt,0,2); // Salt must be 2 char range 0-9A-Za-z
$newpass = crypt($newpass,$salt);
if ($oldpass != null) {
$oldpass = crypt($oldpass,$salt);
}
break;
case "SHA" :
$newpass = '{SHA}'.base64_encode(sha1($newpass, TRUE));
if ($oldpass != null) {
$oldpass = '{SHA}'.base64_encode(sha1($oldpass, TRUE));
}
break;
case "MD5" :
$salt = substr($salt,0,8); //Salt must be max 8 char range 0-9A-Za-z
$newpass = crypt_apr1_md5($newpass, $salt);
if ($oldpass != null) {
$oldpass = crypt_apr1_md5($oldpass, $salt);
}
break;
default:
return false;
break;
}
$hta_arr = explode("\n", file_get_contents($path));
foreach ($hta_arr as $line) {
$line = preg_replace('/\s+/','',$line); // remove spaces
if ($line) {
$line_arr = explode('"', $line);
if (strcmp($line_arr[0],"AuthUserFile") == 0) {
$path_htaccess = $line_arr[1];
}
}
}
$htp_arr = explode("\n", file_get_contents($path_htaccess));
$new_file = "";
foreach ($htp_arr as $line) {
$line = preg_replace('/\s+/', '', $line); // remove spaces
if ($line) {
list($usr, $pass) = explode(":", $line, 2);
if (strcmp($user, $usr) == 0) {
if ($oldpass != null) {
if ($oldpass == $pass) {
$new_file .= $user.':'.$newpass."\n";
} else {
return false;
}
} else {
$new_file .= $user.':'.$newpass."\n";
}
} else {
$new_file .= $user.':'.$pass."\n";
}
}
}
$f = fopen($path_htaccess,"w") or die("couldn't open the file");
fwrite($f, $new_file);
fclose($f);
return true;
}
Function for generating Apache like MD5:
/**
* #param string $password
* #param string|null $salt
* #ref https://stackoverflow.com/a/8786956
*/
function crypt_apr1_md5($password, $salt = null)
{
if (!$salt) {
$salt = substr(base_convert(bin2hex(random_bytes(6)), 16, 36), 1, 8);
}
$len = strlen($password);
$text = $password . '$apr1$' . $salt;
$bin = pack("H32", md5($password . $salt . $password));
for ($i = $len; $i > 0; $i -= 16) {
$text .= substr($bin, 0, min(16, $i));
}
for ($i = $len; $i > 0; $i >>= 1) {
$text .= ($i & 1) ? chr(0) : $password[0];
}
$bin = pack("H32", md5($text));
for ($i = 0; $i < 1000; $i++) {
$new = ($i & 1) ? $password : $bin;
if ($i % 3) {
$new .= $salt;
}
if ($i % 7) {
$new .= $password;
}
$new .= ($i & 1) ? $bin : $password;
$bin = pack("H32", md5($new));
}
$tmp = '';
for ($i = 0; $i < 5; $i++) {
$k = $i + 6;
$j = $i + 12;
if ($j == 16) {
$j = 5;
}
$tmp = $bin[$i] . $bin[$k] . $bin[$j] . $tmp;
}
$tmp = chr(0) . chr(0) . $bin[11] . $tmp;
$tmp = strtr(
strrev(substr(base64_encode($tmp), 2)),
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
);
return "$" . "apr1" . "$" . $salt . "$" . $tmp;
}
Demo of crypt_apr1_md5() is available here.
Note that as of Apache 2.4, bcrypt is supported, so you can (and SHOULD) just use password_hash() on newer versions of Apache for this purpose.

Ofc this is just a sample, that will read your current file, find the given username and change either it is password of username.
Please keep in mind that this code is not safe and you would still need to parse the username and password so it does not break your file.
$username = $_POST['user'];
$password = $_POST['pass'];
$new_username = $_POST['newuser'];
$new_password = $_POST['newpass'];
$action = $_POST['action'];
//read the file into an array
$lines = explode("\n", file_get_contents('.htpasswd'));
//read the array and change the data if found
$new_file = "";
foreach($lines as $line)
{
$line = preg_replace('/\s+/','',$line); // remove spaces
if ($line) {
list($user, $pass) = split(":", $line, 2);
if ($user == $username) {
if ($action == "password") {
$new_file .= $user.':'.$new_password."\n";
} else {
$new_file .= $new_username.':'.$pass."\n";
}
} else {
$new_file .= $user.':'.$pass."\n";
}
}
}
//save the information
$f=fopen(".htpasswd","w") or die("couldn't open the file");
fwrite($f,$new_file);
fclose($f);

Don't. Store your authdb in a database instead, via e.g. mod_auth_mysql.

Googled "php generate htpasswd", got this article: How to create a password for a .htpasswd file using PHP.
The key line seems to be:
$password = crypt($clearTextPassword, base64_encode($clearTextPassword));
So I imagine you'd read in the file contents with file_get_contents, parse it into an associative array, modify the relevant entries (encrypting the password as shown above), write the array back into a string, and use file_put_contents to write the file back out.
This is most definitely not standard practice, however. Sounds like the job for a database. If you feel weird about setting up a whole database server, and your host supports it, SQLite might be a good choice.

Just in case someone is just looking for a working script, here is a solution.
It is the script published here by Kavoir with a minor change: http://www.kavoir.com/backyard/showthread.php?28-Use-PHP-to-generate-edit-and-update-htpasswd-and-htgroup-authentication-files
<?php
/*
$pairs = array(
'username' = 'password',
);
*/
// Algorithm: SHA1
class Htpasswd {
private $file = '';
public function __construct($file) {
if (file_exists($file)) {
$this -> file = $file;
} else {
return false;
}
}
private function write($pairs = array()) {
$str = '';
foreach ($pairs as $username => $password) {
$str .= "$username:{SHA}$password\n";
}
file_put_contents($this -> file, $str);
}
private function read() {
$pairs = array();
$fh = fopen($this -> file, 'r');
while (!feof($fh)) {
$pair_str = str_replace("\n", '', fgets($fh));
$pair_array = explode(':{SHA}', $pair_str);
if (count($pair_array) == 2) {
$pairs[$pair_array[0]] = $pair_array[1];
}
}
return $pairs;
}
public function addUser($username = '', $clear_password = '') {
if (!empty($username) && !empty($clear_password)) {
$all = $this -> read();
// if (!array_key_exists($username, $all)) {
$all[$username] = $this -> getHash($clear_password);
$this -> write($all);
// }
} else {
return false;
}
}
public function deleteUser($username = '') {
$all = $this -> read();
if (array_key_exists($username, $all)) {
unset($all[$username]);
$this -> write($all);
} else {
return false;
}
}
public function doesUserExist($username = '') {
$all = $this -> read();
if (array_key_exists($username, $all)) {
return true;
} else {
return false;
}
}
private function getHash($clear_password = '') {
if (!empty($clear_password)) {
return base64_encode(sha1($clear_password, true));
} else {
return false;
}
}
}
You can use this script like:
$htp = new Htpasswd('.htpasswd');
$htp -> addUser('username1', 'clearpassword1'); // this will add or edit the user
$htp -> deleteUser('username1');
// check if a certain username exists
if ($htp -> doesUserExist('username1')) {
// user exists
}

Related

PDO: My DELETE statement in the User->logout() is not executing

my errors:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '* FROM tbl_usersession WHERE BenutzerID = ?' at line 1 in C:\xampp7-4-3\htdocs\Corona\classes\db.php:52 Stack trace: #0 C:\xampp7-4-3\htdocs\Corona\classes\db.php(52): PDO->prepare('DELETE * FROM t...') #1 C:\xampp7-4-3\htdocs\Corona\classes\db.php(94): DB->query('DELETE * FROM t...', Array) #2 C:\xampp7-4-3\htdocs\Corona\classes\db.php(111): DB->action('DELETE *', 'tbl_usersession', Array) #3 C:\xampp7-4-3\htdocs\Corona\classes\user.php(135): DB->delete('tbl_usersession', Array) #4 C:\xampp7-4-3\htdocs\Corona\logout.php(5): User->logout() #5 {main} thrown in C:\xampp7-4-3\htdocs\Corona\classes\db.php on line 52
the code:
<?php
require_once 'core/init.php';
$user = new User();
$user->logout();
// Redirect::to('index.php');
?>
my user class:
<?php
class User
{
private $_db,
$_data,
$_sessionName,
$_cookieName,
$_isLoggedIn;
public function __construct($user = null)
{
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
$this->_cookieName = Config::get('remember/cookie_name');
if(!$user)
{
if(Session::exists($this->_sessionName))
{
$user = Session::get($this->_sessionName);
if($this->find($user))
{
$this->_isLoggedIn = true;
}
else
{
//process logout
}
}
}
else
{
$this->find($user);
}
}
public function create($fields = array())
{
if
(
$this->_db->insert('tbl_benutzer', $fields)
)
{
throw new Exception('Es gab einen Fehler bei der Erstellung Ihres Kontos.');
}
echo "Ihr Benutzerkonto wurde erfolgreich angelegt. Sie können sich jetzt anmelden.";
}
public function find($email = null)
{
if($email)
{
$field = (is_numeric($email)) ? 'id' : 'Email';
$data = $this->_db->get('tbl_benutzer', array($field, '=', $email));
if($data->count())
{
$this->_data = $data->first();
return true;
}
return false;
}
}
public function login($email = null, $password = null, $remember = false)
{
// echo "Remember=" . $remember . "<br>";
$user = $this->find($email);
if(!$email && !$password && $this->exists())
{
Session::put($this->_sessionName, $this->data()->ID);
}
else
{
$user = $this->find($email);
if($user)
{
if(password_verify($password, $this->data()->Hash))
{
Session::put($this->_sessionName, $this->data()->ID);
echo "Remember=" . $remember . "<br>";
if($remember)
{
$hash = Hash::unique();
echo "Hash=" . $hash . "<br>";
echo "id=" . $this->data()->ID . "<br>";
$hashCheck = $this->_db->get('tbl_usersession', array('BenutzerID', "=", $this->data()->ID));
echo "HashCheckCount= " . $hashCheck->count() . "<br>";
if(!$hashCheck->count())
{
$this->_db->insert
(
'tbl_usersession',
array
(
'BenutzerID' => $this->data()->ID,
'Hash' => $hash
)
);
}
else
{
$hash = $hashCheck->first()->Hash;
}
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
return true;
}
else return false;
}
}
return false;
}
public function exists()
{
return (!empty($this->data)) ? true : false;
}
public function logout()
{
$this->_db->delete('tbl_usersession', array('BenutzerID', '=', $this->data()->ID));
print_r($this->data());
// Wieso geht das delete nicht?
Session::delete($this->_sessionName);
Cookie::delete($this->_cookieName);
}
public function data()
{
return $this->_data;
}
public function isLoggedIn()
{
return $this->_isLoggedIn;
}
}
?>
my db class:
<?php
class DB
{
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct()
{
try
{
$this->_pdo = new PDO
(
'mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'),
Config::get('mysql/username'),
Config::get('mysql/password')
);
// Error tracking:
$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->_pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch
(
PDOException $e
)
{
die($e->getMessage());
}
}
public static function getInstance()
{
if
(
!isset(self::$_instance)
)
{
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array())
{
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql))
{
$x = 1;
if(count($params))
{
foreach($params as $param)
{
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute())
{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else
{
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = array())
{
if(count($where) === 3)
{
$operators = array('=', '<', '>', '<=', '>=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators))
{
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if($this->query($sql, array($value)))
{
return $this;
}
}
}
return false;
}
public function get($table, $where)
{
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where)
{
return $this->action('DELETE *', $table, $where);
}
public function insert($table, $fields = array())
{
if
(
count($fields)
)
{
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field)
{
$values .= '?';
if
(
$x < count($fields)
)
{
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO " . $table . " (" . implode(", ", $keys) . ") VALUES ({$values})";
if
(
$this->query($sql, $fields)->error()
)
{
return true;
}
}
}
public function update($table, $id, $fields = array())
{
$set = ' ';
$x = 1;
foreach
(
$fields as $name => $value
)
{
$set .= "{$name} = ?";
if
(
$x < count($fields)
)
{
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE ID = {$id}";
if
(
$this->query($sql, $fields)->error()
)
{
return true;
}
return false;
}
public function results()
{
return $this->_results;
}
public function first()
{
return $this->results()[0];
}
public function error()
{
return $this->_error;
}
public function count()
{
return $this->_count;
}
}
?>
It just basic syntax error for DELETE Statement shown as below:
The correct syntax is
DELETE FROM table
But your wrong syntax is
DELETE * FROM table
So debug your delete function will be solved your syntax error
public function delete($table, $where)
{
return $this->action('DELETE', $table, $where);
}

PHP PDO dynamically updating db table with multiple records to a specific user ID

/* Newbie need some help; I am creating a class to auto update my apps db record when instructed to, but I am consistently getting this message below, and for the heck of it, I just not seeing what I am doing wrong. Can someone please look at my codes for me? Thank you.
Warning: PDOStatement::bindParam() expects at least 2 parameters, 1 given in……..on line 331; that where the "else if(is_string($val)){" is located.
*/
// vars given
// DBDriver: MySQL
$myTable = 'seeYou';
$loginDate = NULL;
$ip = $_SERVER['REMOTE_ADDR'];
$date = #date('m/d/Y \a\\t h:i a');
$_id =1;
// data array
$idata = array("last_logged_in"=>$loginDate,
"login_date"=>$date,
"ip_addr"=>$ip
);
class name
{
///------------ other methods here---------///
/**
*--------------------------------------------
* Method - PDO: SET FIELD VALUE PLACEHOLDER
*--------------------------------------------
* #return fields with prefix as placeholder
*/
protected function set_fieldValPlaceHolders(array $data)
{
$set = '';
foreach($data as $field => $value)
{
$set .= $field .'= :'.$field . ',';
}
// remove the last comma
$set = substr($set, 0, -1);
return $set;
}
public function save($data=NULL, $_id = NULL, $rows= NULL, $dbTable= NULL)
{
//----------------- some other codes goes here ----------------//
$id = (int)$_id;
// update row with a specific id
if (isset($id) !== NULL && $rows === NULL)
{
$set = $this->set_fieldValPlaceHolders($data);
$sql = "UPDATE {$dbTable} SET {$set} WHERE user_id = :uid";
try
{
// Build the database statement
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindValue(':uid',$id, PDO::PARAM_INT);
foreach ($data as $field => $val)
{
if(is_int($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_INT');
}
else if(is_string($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_STR');
}
else if(is_bool($val)){
$_stmt->bindValue(':'.$field.'\', '.$val.', PDO::PARAM_BOOL');
}
else if(is_null($val)){
$_stmt->bindValue(':'.$field.'\', '.$val="null".', PDO::PARAM_NULL');
}
else {
$_stmt->bindValue(':'.$field.'\', '.$val.', NULL');
}
$result = $_stmt->execute();
$num = $_stmt->rowCount();
}
}
catch(PDOException $e)
{
die('Error! The process failed while updating your record. <br /> Line #'.__LINE__ .' '.$e);
}
if ($result === true)
{
return true;
}
}
Check your bindValue calls: You give 1 parameter (a long string). It needs at least two. Check all the '
for example, it should be:
$_stmt->bindValue(':'.$field, $val, PDO::PARAM_INT);

Authenticating plain text password against md5 hash

Hello and thank you for reading,
I have a task to authenticate a un / pw pair against a password stored in a MySQL database which has joomla serving as the CMS / frontend.
The joomla web application supports storing usernames and passwords in said database and it would appear that it goes through the following steps when storing a new user -
$salt = JUserHelper::genRandomPassword(32);
$crypt = JUserHelper::getCryptedPassword($array['password'], $salt);
$array['password'] = $crypt.':'.$salt;
genRandomPassword looks like -
/**
* Generate a random password
*
* #static
* #param int $length Length of the password to generate
* #return string Random Password
* #since 1.5
*/
public static function genRandomPassword($length = 8)
{
$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$len = strlen($salt);
$makepass = '';
$stat = #stat(__FILE__);
if (empty($stat) || !is_array($stat)) $stat = array(php_uname());
mt_srand(crc32(microtime() . implode('|', $stat)));
for ($i = 0; $i < $length; $i ++) {
$makepass .= $salt[mt_rand(0, $len -1)];
}
return $makepass;
}
Finally, getCryptedPassword and getSalt look like -
/**
* Formats a password using the current encryption.
*
* #access public
* #param string $plaintext The plaintext password to encrypt.
* #param string $salt The salt to use to encrypt the password. []
* If not present, a new salt will be
* generated.
* #param string $encryption The kind of pasword encryption to use.
* Defaults to md5-hex.
* #param boolean $show_encrypt Some password systems prepend the kind of
* encryption to the crypted password ({SHA},
* etc). Defaults to false.
*
* #return string The encrypted password.
*/
public static function getCryptedPassword($plaintext, $salt = '', $encryption = 'md5-hex', $show_encrypt = false)
{
// Get the salt to use.
$salt = JUserHelper::getSalt($encryption, $salt, $plaintext);
// Encrypt the password.
switch ($encryption)
{
case 'plain' :
return $plaintext;
case 'sha' :
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext));
return ($show_encrypt) ? '{SHA}'.$encrypted : $encrypted;
case 'crypt' :
case 'crypt-des' :
case 'crypt-md5' :
case 'crypt-blowfish' :
return ($show_encrypt ? '{crypt}' : '').crypt($plaintext, $salt);
case 'md5-base64' :
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext));
return ($show_encrypt) ? '{MD5}'.$encrypted : $encrypted;
case 'ssha' :
$encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext.$salt).$salt);
return ($show_encrypt) ? '{SSHA}'.$encrypted : $encrypted;
case 'smd5' :
$encrypted = base64_encode(mhash(MHASH_MD5, $plaintext.$salt).$salt);
return ($show_encrypt) ? '{SMD5}'.$encrypted : $encrypted;
case 'aprmd5' :
$length = strlen($plaintext);
$context = $plaintext.'$apr1$'.$salt;
$binary = JUserHelper::_bin(md5($plaintext.$salt.$plaintext));
for ($i = $length; $i > 0; $i -= 16) {
$context .= substr($binary, 0, ($i > 16 ? 16 : $i));
}
for ($i = $length; $i > 0; $i >>= 1) {
$context .= ($i & 1) ? chr(0) : $plaintext[0];
}
$binary = JUserHelper::_bin(md5($context));
for ($i = 0; $i < 1000; $i ++) {
$new = ($i & 1) ? $plaintext : substr($binary, 0, 16);
if ($i % 3) {
$new .= $salt;
}
if ($i % 7) {
$new .= $plaintext;
}
$new .= ($i & 1) ? substr($binary, 0, 16) : $plaintext;
$binary = JUserHelper::_bin(md5($new));
}
$p = array ();
for ($i = 0; $i < 5; $i ++) {
$k = $i +6;
$j = $i +12;
if ($j == 16) {
$j = 5;
}
$p[] = JUserHelper::_toAPRMD5((ord($binary[$i]) << 16) | (ord($binary[$k]) << 8) | (ord($binary[$j])), 5);
}
return '$apr1$'.$salt.'$'.implode('', $p).JUserHelper::_toAPRMD5(ord($binary[11]), 3);
case 'md5-hex' :
default :
$encrypted = ($salt) ? md5($plaintext.$salt) : md5($plaintext);
return ($show_encrypt) ? '{MD5}'.$encrypted : $encrypted;
}
}
/**
* Returns a salt for the appropriate kind of password encryption.
* Optionally takes a seed and a plaintext password, to extract the seed
* of an existing password, or for encryption types that use the plaintext
* in the generation of the salt.
*
* #access public
* #param string $encryption The kind of pasword encryption to use.
* Defaults to md5-hex.
* #param string $seed The seed to get the salt from (probably a
* previously generated password). Defaults to
* generating a new seed.
* #param string $plaintext The plaintext password that we're generating
* a salt for. Defaults to none.
*
* #return string The generated or extracted salt.
*/
public static function getSalt($encryption = 'md5-hex', $seed = '', $plaintext = '')
{
// Encrypt the password.
switch ($encryption)
{
case 'crypt' :
case 'crypt-des' :
if ($seed) {
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 2);
} else {
return substr(md5(mt_rand()), 0, 2);
}
break;
case 'crypt-md5' :
if ($seed) {
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 12);
} else {
return '$1$'.substr(md5(mt_rand()), 0, 8).'$';
}
break;
case 'crypt-blowfish' :
if ($seed) {
return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 16);
} else {
return '$2$'.substr(md5(mt_rand()), 0, 12).'$';
}
break;
case 'ssha' :
if ($seed) {
return substr(preg_replace('|^{SSHA}|', '', $seed), -20);
} else {
return mhash_keygen_s2k(MHASH_SHA1, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
}
break;
case 'smd5' :
if ($seed) {
return substr(preg_replace('|^{SMD5}|', '', $seed), -16);
} else {
return mhash_keygen_s2k(MHASH_MD5, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
}
break;
case 'aprmd5' :
/* 64 characters that are valid for APRMD5 passwords. */
$APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if ($seed) {
return substr(preg_replace('/^\$apr1\$(.{8}).*/', '\\1', $seed), 0, 8);
} else {
$salt = '';
for ($i = 0; $i < 8; $i ++) {
$salt .= $APRMD5 {
rand(0, 63)
};
}
return $salt;
}
break;
default :
$salt = '';
if ($seed) {
$salt = $seed;
}
return $salt;
break;
}
}
I'm no PHP or Joomla expert but I understand to a certain extent what is going on. I believe as far as an encryption algorithm goes, md5 is being used.
My question is -
What do I need to do to authenticate a un / pw combo against a password stored like this? Presently the salt isn't being stored along with the PW so what do I need to do here exactly? I don't need any code or pseudo-code I just need a clear list of steps to take. If you do feel like providing code I'm writing my application in Java.
EDIT -
Okay I've gotten further supplying the salt / crypto password to the authentication library I'm using however it is saying that they don't matched even after going through all the hasing / decryption. I guess I'll have to play around with this a bit more.
Using that example PW I supplied in the comment below, here's what my java code looks like :
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo("TestUser",
"564c6d2c10a7135fe0ddf0b21d1a1226", getName());
info.setCredentialsSalt(new SimpleByteSource("B9YEkhvnV8pZ8BU7fvVlIVTbEux5N17J"));
return info;
And this is the response I get -
Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - TestUser, rememberMe=false] did not match the expected credentials.
I guess I'm close but I'm still not there. Since we're not passing an algorithm name into the getCryptedPassword PHP function, I'm guessing that it's using the default which appears to be MD5. I wonder why this isn't working.
Thank you,
-Zachary Carter
Try this.
Given a user name $un and a plain text password $pw:
jimport( 'joomla.user.helper' );
$userId = JUserHelper::getUserId( $un );
$user = JUser::getInstance( $userId );
$existingPasswordParts = explode( ':', $user->password );
$salt = $existingPasswordParts[1];
$crypt = JUserHelper::getCryptedPassword( $pw, $salt );
$password = $crypt . ':' . $salt;
if ( $user->password == $password )
{
/* match */
}
The user is fetched, and the used salt is re-used to encrypt the plain text password. After that, both encrypted passwords can be compared against each other.
This should work on J1.6, J1.7 and J2.5.
Joomla was building the hash as plain-text pw + salt but when Shiro is authenticating it builds the hash as salt + plain-text pw. The solution was subclassing SimpleCredentialsMatcher and AbstractHash. I couldn't override the methods in the existing subclasses because they were all protected.

LDAP on XAMPP localhost

I am using windows XP with XAMPP 1.6.4 - php 5.2.4 with LDAP enabled
trying this script :
$server = "ldap://127.0.0.1/";
$user = "Salman";
$pass = "123";
$con = ldap_connect($server);
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($con, LDAP_OPT_REFERRALS, 0);
var_dump(ldap_bind($con, $user, $pass));
but ldap_bind always returns this error :
Warning: ldap_bind() [function.ldap-bind]: Unable to bind to server: Can't contact LDAP server in D:\xampp\htdocs\test.php on line 11
bool(false)
Hi i put a class together for this a while back:
<?php
/* USAGE:
* $ldapObj= new Ldap("HOST","PORT","USERNAME","PASSWORD","Distinguished Name"," (mailnickname=USERNAME)",array("*"));
*/
class Ldap {
enter code here
public $ldaphost;
public $ldapport;
public $ldaprdn;
public $ldappass;
public $dn;
public $filter;
public $attributes;
public $ad;
public $ldapbind;
public $ldapresults;
public $ldapentries;
public $ldaperror;
public $ldapstatus;
function __construct($ldaphost, $ldapport, $ldaprdn, $ldappass, $dn, $filter, $attributes) {
$this->ldaphost = $ldaphost;
$this->ldapport = $ldapport;
$this->ldaprdn = $ldaprdn;
$this->ldappass = $ldappass;
$this->dn = $dn;
$this->filter = $filter;
$this->attributes = $attributes;
$this->ad = ldap_connect($this->ldaphost);
if ($this->ad) {
$this->ldapbind = ldap_bind($this->ad, $this->ldaprdn, $this->ldappass);
if ($this->ldapbind) {
$this->ldapresults = ldap_search($this->ad, $this->dn, $this->filter, $this->attributes);
$this->ldapentries = ldap_get_entries($this->ad, $this->ldapresults);
$this->getSid();
$this->ldapstatus = 1;
} else {
$this->ldaperror = "Unable to authenticate user";
$this->ldapstatus = 0;
}
ldap_unbind($this->ad);
} else {
$this->ldaperror = "Could not connect to {$this->ldaphost}";
$this->ldapstatus = 0;
}
}
function getLdapEntry($entry) {
return $this->ldapentries[0][$entry][0];
}
function getLdapEntries() {
return $this->ldapentries;
}
function ldapError() {
return $this->ldaperror;
}
function getSid() {
$sid = "S-";
$entries = $this->ldapentries;
// Convert Bin to Hex and split into byte chunks
$sidinhex = str_split(bin2hex($entries[0]['objectsid'][0]), 2);
// Byte 0 = Revision Level
$sid = $sid . hexdec($sidinhex[0]) . "-";
// Byte 1-7 = 48 Bit Authority
$sid = $sid . hexdec($sidinhex[6] . $sidinhex[5] . $sidinhex[4] . $sidinhex[3] . $sidinhex[2] . $sidinhex[1]);
// Byte 8 count of sub authorities - Get number of sub-authorities
$subauths = hexdec($sidinhex[7]);
//Loop through Sub Authorities
for ($i = 0; $i < $subauths; $i++) {
$start = 8 + (4 * $i);
// X amount of 32Bit (4 Byte) Sub Authorities
$sid = $sid . "-" . hexdec($sidinhex[$start + 3] . $sidinhex[$start + 2] . $sidinhex[$start + 1] . $sidinhex[$start]);
}
$this->sid = $sid;
}
}
?>

Applying a SQL function on Zend_Db_Table_Row::save()

Is it possible, when saving a Zend_Db_Table_Row, to make ZF apply a SQL function on one column?
For example, if $row->save() generates by default this SQL query:
UPDATE table SET field = ? WHERE id = ?;
I would like it to automatically apply the GeomFromText() function on this field:
UPDATE table SET field = GeomFromText(?) WHERE id = ?;
Thanks for any hint on how to do this with Zend_Db!
Define a custom update method in your class that inherits from Zend_Db_Table (not from the Zend_Db_Table_Row) and use a Zend_Db_Expr to set the column to the function return value.
See the docs here: http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.extending.insert-update.
I am just guessing but you could try this:
<?php
class MyTable extends Zend_Db_Table_Abstract
{
protected $_name = 'my_table';
public function update(array $data, $where) {
/**
* Build "col = ?" pairs for the statement,
* except for Zend_Db_Expr which is treated literally.
*/
$set = array();
$i = 0;
foreach ($data as $col => $val) {
if ($val instanceof Zend_Db_Expr) {
$val = $val->__toString();
unset($data[$col]);
} else {
if ($this->_db->supportsParameters('positional')) {
$val = ($col == 'field') ? 'GeomFromText(?)' : '?';
} else {
if ($this->_db->supportsParameters('named')) {
unset($data[$col]);
$data[':col'.$i] = $val;
$val = ($col == 'field') ? 'GeomFromText(:col'.$i.')' : ':col'.$i;
$i++;
} else {
/** #see Zend_Db_Adapter_Exception */
require_once 'Zend/Db/Adapter/Exception.php';
throw new Zend_Db_Adapter_Exception(get_class($this) ." doesn't support positional or named binding");
}
}
}
$set[] = $this->_db->quoteIdentifier($col, true) . ' = ' . $val;
}
$where = $this->_whereExpr($where);
/**
* Build the UPDATE statement
*/
$sql = "UPDATE "
. $this->_db->quoteIdentifier($this->_name , true)
. ' SET ' . implode(', ', $set)
. (($where) ? " WHERE $where" : '');
/**
* Execute the statement and return the number of affected rows
*/
if ($this->_db->supportsParameters('positional')) {
$stmt = $this->_db->query($sql, array_values($data));
} else {
$stmt = $this->_db->query($sql, $data);
}
$result = $stmt->rowCount();
return $result;
}
protected function _whereExpr($where)
{
if (empty($where)) {
return $where;
}
if (!is_array($where)) {
$where = array($where);
}
foreach ($where as $cond => &$term) {
// is $cond an int? (i.e. Not a condition)
if (is_int($cond)) {
// $term is the full condition
if ($term instanceof Zend_Db_Expr) {
$term = $term->__toString();
}
} else {
// $cond is the condition with placeholder,
// and $term is quoted into the condition
$term = $this->quoteInto($cond, $term);
}
$term = '(' . $term . ')';
}
$where = implode(' AND ', $where);
return $where;
}
}
?>