def test_VeryFascistCheck(self): try: cracklib.VeryFascistCheck('test', dictpath=dictpath) self.fail('expected ValueError') except ValueError: pass try: cracklib.VeryFascistCheck('LhIRI6JXpKhUqBjT', dictpath=dictpath) except ValueError: self.fail('password should be good enough')
def validate_new_password(self, new_password): """ Check constraints for password + Long enough + Contain at least 1 letter in lower case + Contain at least 1 letter in upper case + Contain at least 1 number Check with function from cracklib """ icp = self.env['ir.config_parameter'] length_pw = icp.get_param('length_password', 'False') length_pw = int(length_pw) if len(new_password) < length_pw: raise ValidationError( _("Password must have at least %s characters") % (length_pw, )) if not (re.search(r'[A-Z]', new_password) and re.search( r'[a-z]', new_password) and re.search(r'\d', new_password)): raise ValidationError("Password must have: <br/> \ - at least one letter in lower case <br/> \ - at least one letter in upper case <br/> \ - at least one number") use_cracklib = icp.get_param('password_check_cracklib', 'False') if safe_eval(use_cracklib): try: cracklib.VeryFascistCheck(new_password) except ValueError, error_msg: raise ValidationError(_(error_msg))
def validate_password(text): """Validate password with cracklib""" try: password = cracklib.VeryFascistCheck(text) except ValueError as message: password = str(message) return password == text, "Error: " + password
def check(self, password): if self.min_length > 0: if len(password) < self.min_length: raise ValueError('Password is too short') else: cracklib.MIN_LENGTH = 4 # this seems to be the lowest valid value # Todo: check history if self.enableQualityCheck: for c in self.forbidden_chars: if c in password: raise ValueError('Password contains forbidden characters') if self.required_chars: for c in self.required_chars: if c in password: break else: raise ValueError( 'Password does not contain one of required characters: "%s"' % self.required_chars) cracklib.MIN_LENGTH = self.min_length if cracklib.VeryFascistCheck(password) == password: return True
def test_case_change(self): try: cracklib.VeryFascistCheck('test', 'TeSt', dictpath=dictpath) self.fail('expected ValueError') except ValueError: e = sys.exc_info()[1] self.assertEqual('case changes only', str(e))
def test_palindrome(self): try: cracklib.VeryFascistCheck('ot23#xyx#32to', dictpath=dictpath) self.fail('expected ValueError') except ValueError: e = sys.exc_info()[1] self.assertEqual('is a palindrome', str(e))
def check_pw_strength(passwd): "Check password strength" try: cracklib.VeryFascistCheck(passwd) except ValueError, message: raise validators.ValidationError(_("Password %(msg)s.") % dict(msg=str(message)[3:]))
def test_same(self): try: cracklib.VeryFascistCheck('test', 'test', dictpath=dictpath) self.fail('expected ValueError') except ValueError: e = sys.exc_info()[1] self.assertEqual('is the same as the old one', str(e))
def test_similar(self): try: cracklib.VeryFascistCheck('test12', 'test34', dictpath=dictpath) self.fail('expected ValueError') except ValueError: e = sys.exc_info()[1] self.assertEqual('is too similar to the old one', str(e))
def test_simple(self): try: cracklib.VeryFascistCheck('t3sx24', dictpath=dictpath) self.fail('expected ValueError') except ValueError: e = sys.exc_info()[1] self.assertEqual('is too simple', str(e))
def validate_pw(self, cr, uid, value): length_pw = self.pool.get('ir.config_parameter').get_param( cr, uid, 'length_password', 'False') length_pw = int(length_pw) if value: if len(value) < length_pw: raise except_osv( _("Change Password"), _("Password must have at least %s characters.") % (length_pw, )) if not (re.search(r'[A-Z]', value) and re.search(r'[a-z]', value) and re.search(r'\d', value)): raise except_osv( _("Change Password"), _("Password must have: <br/>" "- At least one letter in lower case,<br/>" "- At least one letter in upper case,<br/>" "- At least one number.")) use_cracklib = self.pool.get('ir.config_parameter').get_param( cr, uid, 'password_check_cracklib', 'False') if safe_eval(use_cracklib): try: cracklib.VeryFascistCheck(value) except ValueError, ve: # TODO: Get translations from # https://translations.launchpad.net/ubuntu/precise/+source/cracklib2/+pots/cracklib raise except_osv(_(" "), _(ve))
def __init__(self, config, logger): self.config = config self.min_length = self.get_param('min_length', 0) self.min_upper = self.get_param('min_upper', 0) self.min_lower = self.get_param('min_lower', 0) self.min_digit = self.get_param('min_digit', 0) self.min_other = self.get_param('min_other', 0) cracklib.OTH_CREDIT = self.min_other cracklib.MIN_LENGTH = self.min_length cracklib.UP_CREDIT = self.min_upper cracklib.LOW_CREDIT = self.min_lower cracklib.DIG_CREDIT = self.min_digit cracklib.simple = simple self.dict_path = self.get_param('dict_path', None) if self.dict_path is not None: try: cracklib.VeryFascistCheck('test', dictpath=self.dict_path) except ValueError as e: exstr = str(e) if exstr == 'second argument was not an absolute path!': raise Exception( 'dict_path must be absolute, or not declared') else: return except Exception as e: raise
def validate_password(username, password, strength_check=True): """Validate a password, raising a descriptive exception if problems are encountered. Optionally checks password strength.""" if strength_check: if len(password) < 8: raise ValueError('Password must be at least 8 characters.') s = difflib.SequenceMatcher() s.set_seqs(password, username) if s.ratio() > 0.6: raise ValueError('Password is too similar to username.') try: cracklib.VeryFascistCheck(password) except ValueError as e: raise ValueError('Password problem: {}.'.format(e)) # sanity check; note we don't use string.whitespace since we don't want # tabs or newlines allowed = string.digits + string.ascii_letters + string.punctuation + ' ' if not all(c in allowed for c in password): raise ValueError('Password contains forbidden characters.')
def get_input(field, required): "Get user input" prompt = "Please enter the %s:" % field while 1: if field in ['password1', 'password2']: value = getpass.getpass(prompt=prompt) else: value = raw_input(prompt) if not required: break if required and value.strip() != "": if not field in ['email', 'password1', 'password2']: break if field == 'email': if not ADDRESS_RE.match(value): print "Please provide a valid email address." else: break if field == 'password1': try: cracklib.VeryFascistCheck(value) except ValueError, message: print str(message) else: break if field == 'password2': if values['password1'] == value: break else: print 'password2 does not match password1'
def strong_check_password(self, new_password): # Check password strengh try: if CONF.spassword.enabled: cracklib.VeryFascistCheck(new_password) except ValueError, msg: LOG.debug('The password is too weak %s, ' % msg) raise exception.ValidationError(message="SPASSWORD: %s" % msg)
def check(self, password): try: cracklib.VeryFascistCheck(password, dictpath=self.dict_path) except ValueError as e: error = str(e) error = re.sub(r'^[iI][tT] ', '', error) return {'match': False, 'reason': 'Password ' + error} return {'match': True, 'reason': 'Password ok'}
def validate_password1(self, field): if (self.address.data == '' and self.username.data != '' and field.data != ''): try: cracklib.VeryFascistCheck(field.data) except ValueError, message: raise validators.ValidationError(_("Password %(msg)s.") % dict(msg=str(message)[3:]))
def check(self, password, username=None, displayname=None): if self.min_length > 0: if len(password) < self.min_length: raise CheckFailed('Password is too short') else: cracklib.MIN_LENGTH = 4 # this seems to be the lowest valid value # Workaround for users/user, which instanciates Check() without a username: # We need the username here, but if we would pass it to Check() then # _userPolicy would be run, changing the behavior in users/user. if not username: username = self.username # Todo: check history if self.enableQualityCheck: if self.mspolicy in (True, 'sufficient'): # See https://docs.microsoft.com/de-de/windows/security/threat-protection/security-policy-settings/password-must-meet-complexity-requirements if not samba_check_password_quality(password): raise CheckFailed( 'Password does not meet the password complexity requirements.' ) if username and len(username) > 3 and username.lower( ) in password.lower(): raise CheckFailed('Password contains user account name.') if displayname: for namepart in re.split('[-,._# \t]+', displayname): if len(namepart) > 3 and namepart.lower( ) in password.lower(): raise CheckFailed( 'Password contains parts of the full user name.' ) if self.mspolicy == 'sufficient': return True # skip all other checks for c in self.forbidden_chars: if c in password: raise CheckFailed('Password contains forbidden characters') if self.required_chars: for c in self.required_chars: if c in password: break else: raise CheckFailed( 'Password does not contain one of required characters: "%s"' % self.required_chars) cracklib.MIN_LENGTH = self.min_length try: if cracklib.VeryFascistCheck(password) == password: return True except ValueError as exc: raise CheckFailed(str(exc))
def _set_root_password(self, password): "Set the password to be used for root on provisioned systems, hashing if necessary" if password: if len(password.split('$')) != 4: salt = ''.join(random.choice(string.digits + string.ascii_letters) for i in range(8)) self._root_password = crypt.crypt(cracklib.VeryFascistCheck(password), "$1$%s$" % salt) else: self._root_password = password self.rootpw_changed = datetime.utcnow() else: self._root_password = None self.rootpw_changed = None
def root_password(self, password): """Set group job password Set the root password to be used by group jobs. """ if password: try: cracklib.VeryFascistCheck(password) except ValueError, msg: msg = re.sub(r'^it', 'Root password', str(msg)) raise ValueError(msg) else: self._root_password = password
def password_check(): global dictPath password = request.form["password"] dictcheck = "Ok" try: result = cracklib.VeryFascistCheck(password, None, dictPath) except ValueError as err: dictcheck = str(err) results = zxcvbn(password) return json.dumps({ "overall": dictcheck.capitalize(), "details": results }, default=timedeltaserialize)
def validate_password(): passwd = getpass.getpass() print "Again" passwd2 = getpass.getpass() if (passwd != passwd2): print "Password mismatch" return validate_password() """Check against cracklib to avoid simple passwords""" try: cracklib.VeryFascistCheck(passwd) except ValueError as msg: print msg return validate_password() return passwd
def root_password(self, password): """Set group job password Set the root password to be used by group jobs. """ if password: try: # If you change VeryFascistCheck, please also modify # bkr.server.validators.StrongPassword cracklib.VeryFascistCheck(password) except ValueError, msg: msg = re.sub(r'^it is', 'the password is', str(msg)) raise ValueError(msg) else: self._root_password = password
def assure_password_strength(configuration, password): """Make sure password fits site password policy in terms of length and number of different character classes. We split into four classes for now, lowercase, uppercase, digits and other. """ _logger = configuration.logger site_policy = configuration.site_password_policy policy_fail_msg = 'password does not fit site password policy' min_len, min_classes = parse_password_policy(configuration) if min_len < 0 or min_classes > 4: raise Exception('invalid site password policy') if len(password) < min_len: err_msg = '%s: too short, at least %d chars required' % \ (policy_fail_msg, min_len) _logger.warning(err_msg) raise ValueError(err_msg) char_class_map = {'lower': lowercase, 'upper': uppercase, 'digits': digits} base_chars = ''.join(char_class_map.values()) pw_classes = [] for i in password: if i not in base_chars and 'other' not in pw_classes: pw_classes.append('other') continue for (char_class, values) in char_class_map.items(): if i in values and not char_class in pw_classes: pw_classes.append(char_class) break if len(pw_classes) < min_classes: err_msg = '%s: too simple, at least %d character classes required' % \ (policy_fail_msg, min_classes) _logger.warning(err_msg) raise ValueError(err_msg) if configuration.site_password_cracklib: if cracklib: # NOTE: min_len does not exactly match cracklib.MIN_LENGTH meaning # but we just make sure cracklib does not directly increase # policy requirements. cracklib.MIN_LENGTH = min_len + min_classes # NOTE: this raises ValueError if password is too simple cracklib.VeryFascistCheck(password) else: _logger.warning('cracklib requested in conf but not available') _logger.debug('password compliant with site password policy (%s)' % site_policy) return True
def _set_root_password(self, password): "Set the password to be used for root on provisioned systems, hashing if necessary" if password: if len(password.split('$')) != 4: try: cracklib.VeryFascistCheck(password) except ValueError as e: msg = re.sub(r'^it', 'Root password', str(e)) raise ValueError(msg) salt = ''.join(random.choice(string.digits + string.ascii_letters) for i in range(8)) self._root_password = crypt.crypt(password, "$1$%s$" % salt) else: self._root_password = password self.rootpw_changed = datetime.utcnow() else: self._root_password = None self.rootpw_changed = None
def command(self): "run command" self.init() if self.options.username is None: print "\nProvide an username\n" print self.parser.print_help() sys.exit(2) try: user = Session\ .query(User)\ .filter(User.username == self.options.username.decode('utf-8'))\ .filter(User.local == true())\ .one() if 'BARUWA_ADMIN_PASSWD' not in os.environ or \ not os.environ['BARUWA_ADMIN_PASSWD']: pass1 = getpass.getpass(prompt="Please enter the password:"******"Please reenter the password:"******"Passwords cannot be blank" assert pass1 == pass2, "Passwords entered do not match" else: pass1 = os.environ['BARUWA_ADMIN_PASSWD'] cracklib.VeryFascistCheck(pass1) user.set_password(pass1) Session.add(user) Session.commit() print "The account password has been updated" except NoResultFound: print >> sys.stderr, ("No local user found with username %s" % self.options.username) sys.exit(2) except AssertionError, message: print >> sys.stderr, str(message) sys.exit(2)
def _to_python(self, value, state): try: cracklib.VeryFascistCheck(value) return value except ValueError, msg: raise Invalid('Invalid password: %s' % str(msg), value, state)
def validate_password(self, text): try: p = cracklib.VeryFascistCheck(text) except ValueError, message: p = str(message)
def check_password(option, opt_str, value, parser): "check the password strength" try: cracklib.VeryFascistCheck(value) except ValueError, message: raise OptionValueError("%s." % str(message)[3:])
def validate_password(text): try: p = cracklib.VeryFascistCheck(text) except ValueError as message: p = str(message) return p == text, "Error: " + p