def db_create_user(session, state, tid, request, language): request['tid'] = tid fill_localized_keys(request, models.User.localized_keys, language) if request['username']: user = session.query(models.User).filter( models.User.username == text_type(request['username']), models.UserTenant.user_id == models.User.id, models.UserTenant.tenant_id == tid).one_or_none() if user is not None: raise errors.InputValidationError('Username already in use') user = models.User({ 'tid': tid, 'username': request['username'], 'role': request['role'], 'state': u'enabled', 'name': request['name'], 'description': request['description'], 'language': language, 'password_change_needed': request['password_change_needed'], 'mail_address': request['mail_address'], 'can_edit_general_settings': request['can_edit_general_settings'] }) if not request['username']: user.username = user.id = uuid4() if request['password']: password = request['password'] else: password = u'password' user.salt = security.generateRandomSalt() user.password = security.hash_password(password, user.salt) # The various options related in manage PGP keys are used here. parse_pgp_options(state, user, request) session.add(user) session.flush() db_create_usertenant_association(session, user.id, tid) return user
def db_create_user(session, state, tid, request, language): request['tid'] = tid fill_localized_keys(request, models.User.localized_keys, language) if request['username']: user = session.query(models.User).filter( models.User.tid == tid, models.User.username == text_type( request['username'])).one_or_none() if user is not None: raise errors.InputValidationError('Username already in use') user = models.User({ 'tid': tid, 'username': request['username'], 'role': request['role'], 'state': u'enabled', 'name': request['name'], 'description': request['description'], 'name': request['name'], 'language': language, 'password_change_needed': request['password_change_needed'], 'mail_address': request['mail_address'] }) if request['password']: password = request['password'] elif user.role == 'receiver': # code necessary because the user.role for recipient is receiver password = '******' else: password = user.role user.salt = security.generateRandomSalt() user.password = security.hash_password(password, user.salt) # The various options related in manage PGP keys are used here. parse_pgp_options(state, user, request) session.add(user) session.flush() if not request['username']: user.username = user.id return user
def test_pass_hash(self): dummy_password = "******" dummy_salt = generateRandomSalt() sure_bin = scrypt.hash(dummy_password, dummy_salt) sure = binascii.b2a_hex(sure_bin) not_sure = hash_password(dummy_password, dummy_salt) self.assertEqual(sure, not_sure)
def test_check_password(self): password = '******' salt = generateRandomSalt() password_hash = binascii.b2a_hex(scrypt.hash(str(password), salt)) self.assertFalse(check_password('x', salt, password_hash)) self.assertFalse(check_password(password, 'x', password_hash)) self.assertFalse(check_password(password, salt, 'x')) self.assertTrue(check_password(password, salt, password_hash))
def test_valid_password(self): dummy_password = "******" dummy_salt = generateRandomSalt() hashed_once = binascii.b2a_hex(scrypt.hash(dummy_password, dummy_salt)) hashed_twice = binascii.b2a_hex(scrypt.hash(dummy_password, dummy_salt)) self.assertTrue(hashed_once, hashed_twice) self.assertTrue(check_password(dummy_password, dummy_salt, hashed_once))
def test_change_password_fail_with_invalid_old_password(self): dummy_salt_input = "xxxxxxxx" first_pass = helpers.VALID_PASSWORD1 second_pass = helpers.VALID_PASSWORD2 dummy_salt = generateRandomSalt() # as first we hash a "first_password" like has to be: hashed1 = binascii.b2a_hex(scrypt.hash(str(first_pass), dummy_salt)) # now emulate the change unsing the globaleaks.security module self.assertRaises(errors.InvalidOldPassword, change_password, hashed1, "invalid_old_pass", second_pass, dummy_salt_input)
def test_change_password(self): first_pass = helpers.VALID_PASSWORD1 second_pass = helpers.VALID_PASSWORD2 dummy_salt = generateRandomSalt() # as first we hash a "first_password" like has to be: hashed1 = binascii.b2a_hex(scrypt.hash(str(first_pass), dummy_salt)) # now emulate the change unsing the globaleaks.security module hashed2 = change_password(hashed1, first_pass, second_pass, dummy_salt) # verify that second stored pass is the same self.assertEqual( hashed2, binascii.b2a_hex(scrypt.hash(str(second_pass), dummy_salt)))
from globaleaks.settings import Settings from globaleaks.state import State from globaleaks.utils import security, tempdict, token, utility from globaleaks.utils.securetempfile import SecureTemporaryFile from globaleaks.utils.objectdict import ObjectDict from globaleaks.utils.structures import fill_localized_keys from globaleaks.utils.utility import datetime_null, datetime_now, datetime_to_ISO8601, \ log, sum_dicts from globaleaks.workers import process from globaleaks.workers.supervisor import ProcessSupervisor ## constants VALID_PASSWORD1 = u'ACollectionOfDiplomaticHistorySince_1966_ToThe_Pr esentDay#' VALID_PASSWORD2 = VALID_PASSWORD1 VALID_SALT1 = security.generateRandomSalt() VALID_SALT2 = security.generateRandomSalt() VALID_HASH1 = security.hash_password(VALID_PASSWORD1, VALID_SALT1) VALID_HASH2 = security.hash_password(VALID_PASSWORD2, VALID_SALT2) VALID_BASE64_IMG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQYV2NgYAAAAAMAAWgmWQ0AAAAASUVORK5CYII=' INVALID_PASSWORD = u'antani' PGPKEYS = {} DATA_DIR = os.path.join(TEST_DIR, 'data') kp = os.path.join(DATA_DIR, 'gpg') for filename in os.listdir(kp): with open(os.path.join(kp, filename)) as pgp_file: PGPKEYS[filename] = text_type(pgp_file.read())
def login(session, tid, username, password, receiver_second_login, receiver_auth_code, client_using_tor, client_ip, token=''): """ login returns a tuple (user_id, state, role, pcn, authCodePrepared) """ if token: user = session.query(User).filter(User.auth_token == token, \ User.state != u'disabled', \ User.tid == tid).one_or_none() else: user = session.query(User).filter(User.username == username, \ User.state != u'disabled', \ User.tid == tid).one_or_none() if user is None or (not token and not security.check_password( password, user.salt, user.password)): log.debug("Login: Invalid credentials") Settings.failed_login_attempts += 1 raise errors.InvalidAuthentication if not client_using_tor and not mystate.tenant_cache[tid]['https_' + user.role]: log.err("Denied login request over Web for role '%s'" % user.role) raise errors.TorNetworkRequired # Check if we're doing IP address checks today if mystate.tenant_cache[tid]['ip_filter_authenticated_enable']: ip_networks = parse_csv_ip_ranges_to_ip_networks( mystate.tenant_cache[tid]['ip_filter_authenticated']) client_ip = text_type(client_ip) client_ip_obj = ipaddress.ip_address(client_ip) # Safety check, we always allow localhost to log in success = False if client_ip_obj.is_loopback is True: success = True for ip_network in ip_networks: if client_ip_obj in ip_network: success = True if success is not True: raise errors.AccessLocationInvalid # se sono arrivato qui il primo login è andato a buon fine # il login (username, password) per un ricevente viene rieseguito anche al secondo passaggio # per motivi di sicurezza # A QUESTO PUNTO: # SE receiver2ndStepLoginState = 'N': # 1 - genero il codice # 2 - memorizzo record in ReceiverAuthCode # 3 - invio mail # ELSE: # verifico la correttenza del secondo codice if user.role == 'receiver': receiver = session.query(Receiver).filter( Receiver.id == user.id).one_or_none() if receiver.two_step_login_enabled and not user.password_change_needed: if receiver_second_login == 'first_login_to_complete': yyyy = str(datetime_now().year) mm = str(datetime_now().month).zfill(2) dd = str(datetime_now().day).zfill(2) result_query = session.query(ReceiverAuthCode).filter( ReceiverAuthCode.receiver_id == user.id, func.strftime("%Y-%m-%d", ReceiverAuthCode.creation_date) == yyyy + '-' + mm + '-' + dd).all() # genero il codice #chiamo la funzione generate_authcode_password che genera la password con l'utilizzo della funzione os.urandom #randnum = ''.join(["%s" % SystemRandom().randint(0, 9) for num in range(0, 12)]) randnum = generate_authcode_password(12) #print randnum log.debug(randnum[0:4] + ' ' + randnum[4:8] + ' ' + randnum[8:12]) # inserisco il record nel db newAuthCode = models.ReceiverAuthCode() newAuthCode.receiver_id = receiver.id newAuthCode.salt = security.generateRandomSalt() newAuthCode.auth_code = security.hash_password( randnum, newAuthCode.salt) session.add(newAuthCode) session.flush() # invio i tre pezzi del codice alle tre mail specificate nel profilo del ricevente email_prg = str(len(result_query) + 1) day = dd + '/' + mm + '/' + yyyy mystate.sendmail( 1, receiver.control_mail_1, "Receiver Auth Code #" + email_prg + " - " + day, randnum[0:4]) mystate.sendmail( 1, receiver.control_mail_2, "Receiver Auth Code #" + email_prg + " - " + day, randnum[4:8]) mystate.sendmail( 1, receiver.control_mail_3, "Receiver Auth Code #" + email_prg + " - " + day, randnum[8:12]) log.debug("Invio delle mail effettuato con successo") receiver_second_login = '******' elif receiver_second_login == 'second_login_to_complete': auth_code_item = session.query(ReceiverAuthCode).filter(ReceiverAuthCode.receiver_id == user.id) \ .order_by(ReceiverAuthCode.creation_date.desc()).first() # se non sono passati TOT minuti dall'ultimo codice emesso si può controllare la validità del codice if auth_code_item is not None and auth_code_item.is_valid and not is_expired( auth_code_item.creation_date, 0, AUTH_CODE_EXPIRATION_IN_MINUTES, 0, 0): # qui devo verificare che il codice inviato dall'utente sia uguale a una delle permutazioni dei tre blocchi # da quattro cifre che si ottengono dal codice salvato sul db firstBlock = receiver_auth_code[0:4] secondBlock = receiver_auth_code[4:8] thirdBlock = receiver_auth_code[8:12] combList = [] combList.insert(0, firstBlock + secondBlock + thirdBlock) combList.insert(1, firstBlock + thirdBlock + secondBlock) combList.insert(2, secondBlock + firstBlock + thirdBlock) combList.insert(3, secondBlock + thirdBlock + firstBlock) combList.insert(4, thirdBlock + firstBlock + secondBlock) combList.insert(5, thirdBlock + secondBlock + firstBlock) auth_code_match = False for authCode in combList: if security.check_password(authCode, auth_code_item.salt, auth_code_item.auth_code): auth_code_match = True # POSSO ANCHE FARE UNA UPDATE del campo is_valid PER IL RECORD UTILIZZATO NELLA VALIDAZIONE auth_code_item.is_valid = False session.add(auth_code_item) session.flush() #objs = session.query(ReceiverAuthCode).filter(ReceiverAuthCode.receiver_id == auth_code_item.receiver_id) \ # .order_by(ReceiverAuthCode.creation_date.desc(), ReceiverAuthCode.daily_prg.desc()) #for obj in objs: # session.delete(obj) # session.flush() #session.delete(auth_code_item) receiver_second_login = '******' break if not auth_code_match: log.debug("Login: Invalid authentication code") Settings.failed_login_attempts += 1 raise errors.InvalidAuthentication else: log.debug( "Login: authentication code is expired. Please repeat login" ) Settings.failed_login_attempts += 1 raise errors.InvalidAuthentication else: log.debug( "receiver_auth_code diverso da first_login_to_complete e second_login_to_complete" ) receiver_second_login = '******' else: receiver_second_login = '******' #da tenere sotto controllo else: receiver_second_login = '******' # da tenere sotto controllo log.debug("Login: Success (%s)" % user.role) user.last_login = datetime_now() return user.id, user.state, user.role, user.password_change_needed, receiver_second_login
# -*- coding: utf-8 import os from twisted.trial import unittest from globaleaks.rest import errors from globaleaks.utils.security import generateRandomSalt, hash_password, check_password, directory_traversal_check from globaleaks.settings import Settings from globaleaks.tests import helpers dummy_salt = generateRandomSalt() class TestPasswordManagement(unittest.TestCase): def test_pass_hash(self): dummy_password = "******" sure = hash_password(dummy_password, dummy_salt) not_sure = hash_password(dummy_password, dummy_salt) self.assertEqual(sure, not_sure) def test_valid_password(self): dummy_password = "******" hashed_once = hash_password(dummy_password, dummy_salt) hashed_twice = hash_password(dummy_password, dummy_salt) self.assertTrue(hashed_once, hashed_twice) self.assertTrue(check_password(dummy_password, dummy_salt, hashed_once))