Symfony security.password_encoder isPasswordValid is returning empty - security

In Symfony 2.6, I am using the following method to encode my password. The password is successfully encoded and saved in the DB.
$encoder = $this->container->get('security.password_encoder');
$encodedPwd = $encoder->encodePassword($adminUser, $plainPassword);
When I try to validate the user supplied password provided in the login form as follows:
$adminUser = $this->getDoctrine()->getManager()->getRepository("AcmeUserBundle:AdminUser")->findOneBy(array('username' => $_username));
$_password = $request->request->get('_password');
$encoder = $this->container->get('security.password_encoder');
echo $encoder->isPasswordValid($adminUser, $_password))
The last line is always returning empty, which means that the password is not getting validated.
I have gotten this from Symfony documentation and have searched if anyone has encountered similar problem, but doesn't seem to find any.
Can any one please provide some insights please?
Thanks!
Sharad

Ok I found a solution like this and it is working. Hope it helps anybody encountering similar problem.
For encoding the password, I am doing the following:
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$encodedPwd = $encoder->encodePassword($plainPassword, $user->getSalt());
For validating the password, I am doing the following:
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
echo $encoder->isPasswordValid($user->getPassword(), $_password, $user->getSalt())
While encoding the password, I wasn't using the salt, but it is important,
It all works now.
Thank you
Sharad

Related

password_verify() with generated hash from Myth-auth returns false

I know that Myth-auth is not stable yet, but it's okay that's not my point.
I want to make a change password feature so I wrote this in my controller:
$oldPass=$this->request->getPost('oldPass');
$check=password_verify($oldPass, user()->password_hash);
//Myth-auth has helper to get field data in database using user()->column_name function
var_dump($check);die;
I don't know what's wrong with my code, but it returns false.
so I checked again using a hardcoded password like this:
$check=password_verify('bayusetiaji14', user()->password_hash);
//using double qoutes
$check2=password_verify("bayusetiaji14", user()->password_hash);
but it's still returning false, is this a Myth-auth bug when hashing password or anything else?
enter image description here
because they used base64 encode to manipulate string on they password, you should look on auth->src->entities->user.php
it seems that the library is using double hashes. use this
if(!password_verify(base64_encode(hash('sha384', service('request')->getPost('newPasswords'), true)), $oldpassword)){
echo 'password not match'
} else {
echo 'password matched';
}

how to encrypt password text input using script mode in Katalon ?

I have a csv with a list of users and passwords that I need check the login.
Is there any way to encrypt password text input using script mode in
Katalon ?
I found an answer on katalon forums but they do that manually using a a tool of the IDE like you can see here Working with Sensitive Text
I would like to create an script that for every (user,password) encrypt the password and login using encrypted password.
#Keyword
def login(user, password, url){
WebUI.navigateToUrl(url)
WebUI.setText(findTestObject('Object Repository/Page_Sign in My Page/input_SigninFormemail'),user)
def password_encript = Encrypt(password)// Fictitious method that I would like to get
WebUI.setEncryptedText(findTestObject('Object Repository/Page_Sign in My Page/input_SigninFormpassword'), password_encript)
WebUI.click(findTestObject('Object Repository/Page_Sign in My Page/input_yt0'))
}
Is there a method like Encrypt(password) in Katalon?
Is there a way to do that in code?
Thanks in advance.
I came across this question while investigating other Katalon encryption questions, and thought I may offer some late insight.
The "setEncryptedText(TestObject, encryptedText)" method is to allow you to store sensitive text in an encrypted form, which is then decrypted when entered into the web application.
Since your method is being passed 'password' as a string in cleartext, then why not just have the function do:
WebUI.setText(findTestObject('Object Repository/Page_Sign in My Page/input_SigninFormpassword'), password)
So to use Java Encryption : Blowfish with Text and Key.
Here is my solution :
public static String encrypt(String strClearText,String strKey) throws Exception{
String strData="";
// streData - here you put your data
try {
SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
Cipher cipher=Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, skeyspec);
byte[] encrypted=cipher.doFinal(strClearText.getBytes());
strData=new String(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}

Issue in web.EnsureUser for FBA users programatically

I am trying to ensure user through web.EnsureUser for FBA users. Here is my code snipplet.
as an example :
string fbUsername = "i:0#.f|ie-fbamembership|userlogin";
SPUser userSP = site.RootWeb.EnsureUser(fbUsername);
But i get an error user does not exists. But i can surely add this user to the site collection manually.
But could not add the user through code (programatically).
Any ideas? i could not find a solution for this in the net.
S.R.G
SharePoint Developer
I'm very late to this question, but I had the same problem today and a colleague of mine finally found a solution.
I just use the AllowUnsafeUpdates property of my SPWeb object and write :
web.AllowUnsafeUpdates = true;
oUser = web.EnsureUser(userId);
In my case, userId is from a PeoplePicker, I construct it like this :
PickerEntity selectedEntity = (PickerEntity)peEditor.ResolvedEntities[i];
string userId = selectedEntity.Key;
Hope it can helps someone !

Noob way to login the user in Prestashop

This is a walkthrough on how to make a user login on prestashop without passing through the login screen. This is helpful if you do not want the user to login again like when you want to transfer his session from one website to prestashop.
Step 1 Eliminate the need for password salting. Under config/settings.inc.php, set _COOKIE_KEY_ to blank. Note this also means that you must create a new customer. Or you can delete the old md5 password from DB and add your own.
Step 2 In the authentication.php file paste the following lines after line 6:
$customer = new Customer();
//$authentication = $customer->getByEmail(trim($email), trim($passwd));
$authentication = $customer->getByMd5(trim($email), trim($passwd)); //modified version of getByEmail if we are not accepting $passwd in cleartext but in md5.
/* Handle brute force attacks */
sleep(1);
if (!$authentication OR !$customer->id)
$errors[] = Tools::displayError('authentication failed');
else
{
$cookie->id_customer = intval($customer->id);
$cookie->customer_lastname = $customer->lastname;
$cookie->customer_firstname = $customer->firstname;
$cookie->logged = 1;
$cookie->passwd = $customer->passwd;
$cookie->email = $customer->email;
if (Configuration::get('PS_CART_FOLLOWING') AND (empty($cookie->id_cart) OR Cart::getNbProducts($cookie->id_cart) == 0))
$cookie->id_cart = intval(Cart::lastNoneOrderedCart(intval($customer->id)));
Module::hookExec('authentication');
if ($back = Tools::getValue('back'))
Tools::redirect($back);
//Tools::redirect('my-account.php'); //cut redirection to break infinite loop
}
The above code is what makes the user login using $email as username and $passwd as password in plaintext. The original code comes from the if (Tools::isSubmit('SubmitLogin')) function inside the authentication.php file.
Step 3 Paste the above code in the products.php file just under line 5
Step 4 In case you are sending $passwd directly in md5 format, here is the modified version of getByEmail()(customer.php):
public function getByMd5($email, $passwd = NULL)
{
$result = Db::getInstance()->GetRow('SELECT * FROM `'._DB_PREFIX_ .'customer` WHERE `active` = 1 AND `email` = \''.pSQL($email).'\' '.(isset($passwd) ? 'AND `passwd` = \''.pSQL(_COOKIE_KEY_.$passwd).'\'' : '').' AND `deleted` = 0');
if (!$result)
return false;
$this->id = $result['id_customer'];
foreach ($result AS $key => $value)
if (key_exists($key, $this))
$this->{$key} = $value;
return $this;
}
You can get access to the username/passwd either through the $_COOKIE[] function or through $_GET[]. Either way its a big security risk. Cookie reading can be placed in the index.php file.
This approach you have proposed is extremely insecure. A salt is required for password safety and should never be removed. Further more by authenticating a user with their MD5 hash you effectively voiding all protection that hashing passwords provides you. People hash passwords because attacks like SQL injection allow an attacker to obtain this hash which then needs to be cracked. In this scenario the attacker can grab the admin's hash and just login right away.
The correct way to do session sharing:
Create a simple table to store session state. In this case the Cryptgoraphic Nonce is a large random value used to reference the data.
'insert into session_state (sess,token) value ('.pSQL(serialize($_SESSION)).', '.$cryptographic_nonce.')'
When the browser is redirected to another shop give them a redirect like this:
header('location: https://some_other_shop/landing.php?token=$cryptographic_nonce');
When the new server gets this landing request it fetches the session state from the previous server:
$sess=http_get($_SERVER['HTTP_REFERER']."?token=$_GET[token]");
$_SESSION=unserialize($sess);
Note you might have to transfer the user's data in the database as well.

MODX - Making multiple snippet calls on a page returning differeny output

I've created a snippet that pulls data from a databse table and displays it in tabular format. The snippet takes an id as parameter, and this is added to the sql query.
My problem is that if I've got more than 1 snippet call (sometimes need the tabular data for different id's displayed on a page) on the same page, all table data is the same as the last database call that's been made by the last snippet.
What do I need to do to kinda not cache the snippet database calls and have them all display their own content?
I've tried setting the page to no cache-able. Also used the [! !] brackets for the snippet calls, and even used the function_exists() method, but none of them helped.
Please can someone help me?
thanks
Try this at the end of the snippet:
mysql_connect('host', 'user', 'pass');
mysql_select_db('db_name');
You need to specify the connection parameters ofcourse.
It would help to answer if you can post your snippet. I do this with multiple calls on the page without issue, so there is either something wrong inside the snippet, or you need to output to unique placeholder names.
You have encountered a glitch of ModX, and it took me a long time to solve. ModX does a lot of caching by using hashing and apparently, when multiple connections are made from within one page divided over multiple snippets, this erratic behaviour can be seen. This is most likely very unwanted behaviour, it can be solved easily but gives you terrible headache otherways.
One sympton is that $modx->getObject($classname, $id)returns null (often).
The solution is very simple:
either use a static class with a single db instance, or
use $modx->setPlaceholder($instance, $tag);, or a combination.
My solution has been:
class dt__xpdo {
private function __construct() {}
public function __destruct() {
$this->close();
}
static public function db($modx = null) {
if ($modx->getPlaceholder('dt_xpdo') == '') {
$dt_user = 'xxxxxxxxx';
$dt_pw = 'xxxxxxxxx';
$dt_host = 'localhost';
$dt_dbname = 'xxxxxxxxx';
$dt_port = '3306';
$dt_dsn = "mysql:host=$dt_host;dbname=$dt_dbname;port=$dt_port;charset=utf8";
$dt_xpdo = new xPDO($dt_dsn, $dt_user, $dt_pw);
$dt_xpdo->setPackage('mymodel', MODX_CORE_PATH.'components/mymodel/'.'model/', '');
//$modx->log(modX::LOG_LEVEL_DEBUG, 'mymodel.config.php');
//$modx->log(modX::LOG_LEVEL_DEBUG, 'Could not addPackage for mymodel!');
$modx->setPlaceholder('dt_xpdo', $dt_xpdo);
}
return $modx->getPlaceholder('dt_xpdo');
}
}
Now you can use in your code:
require_once 'above.php';
and use something like
$xpdo = dt__xpdo::db($modx);
and continue flawlessly!

Resources