MongoDB findOne with regex (security flaw?) - regex

Before i insert the email into the database -> i validate the adress with
if (filter_var($emailAdress, FILTER_VALIDATE_EMAIL))
{
....
}
.. but is this maybe a security flaw?
$userAccObj = $db->user->findOne( array('email' => array('$regex' => '^'.$emailAdress.'$', '$options' => 'i') ));
Schould i do this? or is it not necessary?
$emailAdress= preg_replace("/\#/", '\#', $emailAdress);
$emailAdress= preg_replace("/\-/", '\-', $emailAdress);
$emailAdress= preg_replace("/\./", '\.', $emailAdress);

if (filter_var($emailAdress, FILTER_VALIDATE_EMAIL))
Is a good way to vlaidate an email address in PHP, however, it does use regexes but so far, those have proven to be the best.
$userAccObj = $db->user->findOne( array('email' => array('$regex' => '^'.$emailAdress.'$', '$options' => 'i') ));
The only real problem with that is the . which is a special character which will effect how the regex works, but do you really need to do a regex here? You have checked it is a full email address as such you just need to check for where that exact email address exists (or better yet make a unique index on the field).
As I such I think you can take out the regex and do an exact match.

Related

Regex email vaildation in Zend

I'm using email validation of zend framework and when I give email address as abcde#gester.tech and it responded with invalid validation. Then I modifed the validation as below.
$emailValidator= new Validator\EmailAddress(Validator\Hostname::ALLOW_DNS | Validator\Hostname::ALLOW_LOCAL);
$emailRegex= new Validator\Regex(
array(
'pattern' => '/^(?:(?:[^<>()\[\]\\.,;:\s#"]+(?:\.[^<>()\[\]\\.,;:\s#"]+)*)|(?:".+"))#(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/',
'messages'=>array(
'regexNotMatch'=>'Make sure your email pattern is correct'
)
)
);
$emailInp->getValidatorChain()->addValidator($emailValidator)->addValidator($emailRegex);
Now am able to pass the email address (abcde#gester.tech) with out validation error. But if I give the input as abcde#gester it also take as valid input. But I want to restrict that and I think this can be implemented by adding regex to this validation. May I know how to implement that.
$emailValidator= new Validator\EmailAddress(
Validator\Hostname::ALLOW_DNS |
Validator\Hostname::ALLOW_LOCAL);
$emailRegex= Validator\Regex(array('pattern' => '/^(?:(?:[^<>()\[\]\\.,;:\s#"]+(?:\.[^<>()\[\]\\.,;:\s#"]+)*)|(?:".+"))#(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'));
$emailInp->getValidatorChain()->addValidator($emailValidator->addValidator($emailRegex));
There is a Regex Validator support in Zend framework which facilitates matching the user-defined regex pattern. There is a pattern option which sets the regular expression pattern for the given validator.
You can use it to match the user-defined validator i.e. the pattern that suits your need.
SYNTAX:
$validator = new Zend\Validator\Regex(array('pattern' => '/your_desired_regex_pattern_here/'));
For matching the valid email address that suits your need you can fill in the pattern with available regex validators for email addresses. Also as per the Zend docs; the regex validator uses PCRE(php) syntax, so you can use PCRE regex flavor.
A sample example:
$validator = new Zend\Validator\Regex(array('pattern' => '/^(?:(?:[^<>()\[\]\\.,;:\s#"]+(?:\.[^<>()\[\]\\.,;:\s#"]+)*)|(?:".+"))#(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'));
$validator->isValid("abcde#gester.tech"); // returns true
$validator->isValid("abcde#gester"); // returns false
$validator->isValid("Someemail#someDomain.com"); // returns true
If you want to chain multiple validators on a single input data you can also use the below syntax:
$validatorChain = new Zend_Validate();
$validatorChain->addValidator(
new Zend\Validator\Regex(array('pattern' => '/^(?:(?:[^<>()\[\]\\.,;:\s#"]+(?:\.[^<>()\[\]\\.,;:\s#"]+)*)|(?:".+"))#(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'))
->addValidator(new Zend_Validate_Alnum()); // Second validator...You can chain multiple
if ($validatorChain->isValid($input_email)) {
// email passed validation
} else {
// email failed validation; print reasons
foreach ($validatorChain->getMessages() as $message) {
echo "$message\n";
}
}
You can find the demo of the above regex in here.
Reference: The regex for validating email address is taken from this answer.

Regex Negative look ahead in ADFS claim rule

I need to grant a claim to everyone not matching a particular LDAP attribute. I want to use a regex with a negative look ahead to perform this "not" clause
c1:[Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", Value =~ "^(?!Test User).*$"]
=> issue(Type = "http://goofyclaim", Value = "youre not a tester");
the above rule doesn't seem to get satisfied by my test users. Something wrong with the regex? or does ADFS4.0 not support it. I don't see any errors in the ADFS event logs.
this is a win2016srv on a win2012r2 AD domain.
for reference, this rule does work:
c1:[Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", Value =~ "(?i)^Test User1"]
=> issue(Type = "http://somethignelseentreily", Value = "imispellwhendriving");
first I need to use (found here ADFS rules language terminals) for REGEXP_NOT_MATCH
!~
Next, I had to restructure the regex mode modifier a little, by having the case insensitivity inside the ^ idenifier
c1:[Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", Value !~ "^(?i)Test User"]
=> issue(Type = "http://somethignelseentreily", Value = "imispellwhendriving");
(leaving my other answer so other can see its not the right answer)
NOT EXISTS([Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", Value =~ "^Test User"])
=> issue(Type = "http://somethignelseentreily", Value = "all");

Enforcing strong passwords in Kohana Auth

I am trying to enforce strong(er) passwords in my Kohana application using Auth, by using the following regex to require at least one upper case letter, one lower case, one number, one non-alphanum (special character), and a minimum of 8 characters.
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).{8,}$
The regex is working, as can be seen on Rubular. Here's the code I'm using in Kohana's Model_Auth_User, which extends ORM.
public function rules() {
return array(
'password' => array(
array('not_empty'),
array('min_length', array(':value', 8)),
array('regex', array(':value', '/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).{8,}$/'))
)
);
}
However, when creating a new user account, or changing the password of an existing one, this regex seems to be completely ignored. The min_length from the line above is working fine though!
It will stop me from using test as a password because it's less than 8 characters, but testing123 doesn't give any sort of error message.
Any ideas why this is happening and a way around it?
Figured it out - you have to add the regex to the get_password_validation function (in the same Model) or it doesn't output any error message.
public static function get_password_validation($values) {
return Validation::factory($values)
->rule('password', 'min_length', array(':value', 8))
->rule('password', 'regex', array(':value', '/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).{8,}$/'))
->rule('password_confirm', 'matches', array(':validation', ':field', 'password'));
}
If added, the regex in the rules() function needs to be removed or it's not possible to login as it runs the regex check on the hashed string, which doesn't contain any special characters.
Hope this helps someone.

CakePHP reading Cookie with multiple dots

I am using CakePHP to develop a website and currently struggling with cookie.
The problem is that when I write cookie with multiple dots,like,
$this->Cookie->write("Figure.1.id",$figureId);
$this->Cookie->write("Figure.1.name",$figureName);`
and then read, cakePHP doesn't return nested array but it returns,
array(
'1.id' => '82',
'1.name' => '1'
)
I expected something like
array(
(int) 1 => array(
'id'=>'82',
'name'=>'1'
)
)
Actually I didn't see the result for the first time when I read after I write them. But from second time, result was like that. Do you know what is going on?
I'm afraid it doesn't look as if multiple dots are supported. If you look at the read() method of the CookieComponent (http://api.cakephp.org/2.4/source-class-CookieComponent.html#256-289), you see this:
277: if (strpos($key, '.') !== false) {
278: $names = explode('.', $key, 2);
279: $key = $names[0];
280: }
and that explode() method is being told to explode the name of your cookie into a maximum of two parts around the dot.
You might be best serializing the data you want to store before saving and then deserializing after reading as shown here: http://abakalidis.blogspot.co.uk/2011/11/cakephp-storing-multi-dimentional.html

symfony form validation clean with regex before validate with regex

I'm using Symfony 1.4 and am a little stuck regarding form validation. I have a validator like the one below:
$this->setValidator('mobile_number', new sfValidatorAnd(array(
new sfValidatorString(array('max_length' => 13)),
new sfValidatorRegex(array('pattern' => '/^07\d{9}$/'),
array('invalid' => 'Invalid mobile number.')),
)
));
That is a simple regex for matching a UK mobile phone number.
However my problem is that if someone submitted a string like this: "07 90 44 65 48 1" the regex would fail but they have given a valid number if a the string was cleaned to remove whitespace first.
My problem is that I don't know where within the symfony form framework I would accomplish this.
I need to strip everything but numbers from the user input and then use my mobile_number validator.
Any ideas would be greatly appreciated. Thanks.
You may be able to do this with a combination of standard validators, but it might well be easiest to construct your own custom validator. There is a guide to this on the symfony website: http://www.symfony-project.org/more-with-symfony/1_4/en/05-Custom-Widgets-and-Validators#chapter_05_building_a_simple_widget_and_validator
I think it should probably look something like this:
class sfValidatorMobilePhone extends sfValidatorBase
{
protected function doClean($value)
{
$value = preg_replace('/\s/','',$value);
if (
(0 !== strpos($value, '07')) ||
(13 < strlen($value)) ||
(0 !== preg_match('/[^\d]/', $value))
)
{
throw new sfValidatorError($this, 'invalid', array('value' => $value));
}
else
{
return $value;
}
}
}
Save this as lib/validator/sfValidatorMobilePhone.class.php. You could then call it as
$this->setValidator('mobile_number', new sfValidatorMobilePhone());
I don't know Symfony, so I don't know how you would go about cleaning the input. If you can do a regex-based search-and-replace somehow, you can search for /\D+/ and replace that with nothing - this will remove everything except digits from your string. Careful, it would also remove a leading + which might be relevant (?).
If you can't do a "cleaning step" before the validation, you could try validating it like this:
/^\D*07(?:\d*\d){9}\D*$/
This will match any string that contains exactly 11 numbers (and arbitrarily many non-number characters), the first two of which need to be 07.