def initialize(self): self.name = 'user' self.ensureIndices(['login', 'email', 'groupInvites.groupId', 'size', 'created']) self.prefixSearchFields = ( 'login', ('firstName', 'i'), ('lastName', 'i')) self.ensureTextIndex({ 'login': 1, 'firstName': 1, 'lastName': 1 }, language='none') self.exposeFields(level=AccessType.READ, fields=( '_id', 'login', 'public', 'firstName', 'lastName', 'admin', 'created')) self.exposeFields(level=AccessType.ADMIN, fields=( 'size', 'email', 'groups', 'groupInvites', 'status', 'emailVerified')) # To ensure compatibility with authenticator apps, other defaults shouldn't be changed self._TotpFactory = TOTP.using( # An application secret could be set here, if it existed wallet=None ) events.bind('model.user.save.created', CoreEventHandler.USER_SELF_ACCESS, self._grantSelfAccess) events.bind('model.user.save.created', CoreEventHandler.USER_DEFAULT_FOLDERS, self._addDefaultFolders)
def initialize(self): self.name = 'user' self.ensureIndices( ['login', 'email', 'groupInvites.groupId', 'size', 'created']) self.prefixSearchFields = ('login', ('firstName', 'i'), ('lastName', 'i')) self.ensureTextIndex({ 'login': 1, 'firstName': 1, 'lastName': 1 }, language='none') self.exposeFields(level=AccessType.READ, fields=('_id', 'login', 'public', 'firstName', 'lastName', 'admin', 'created')) self.exposeFields(level=AccessType.ADMIN, fields=('size', 'email', 'groups', 'groupInvites', 'status', 'emailVerified')) # To ensure compatibility with authenticator apps, other defaults shouldn't be changed self._TotpFactory = TOTP.using( # An application secret could be set here, if it existed wallet=None) events.bind('model.user.save.created', CoreEventHandler.USER_SELF_ACCESS, self._grantSelfAccess) events.bind('model.user.save.created', CoreEventHandler.USER_DEFAULT_FOLDERS, self._addDefaultFolders)
def create_totp_factory(env_var=None, file_path=None, authc_settings=None): if not authc_settings: yosai_settings = LazySettings(env_var=env_var, file_path=file_path) authc_settings = AuthenticationSettings(yosai_settings) totp_context = authc_settings.totp_context return TOTP.using(**totp_context)
def totp_factory(core_settings): authc_config = core_settings.AUTHC_CONFIG totp_settings = authc_config.get('totp') totp_context = totp_settings.get('context') totp_secrets = totp_context.get('secrets') return TOTP.using(secrets=totp_secrets, issuer="testing")
def new_user(self): self.username = input('Enter username: '******'Enter password: '******'Two factor auth (y, n)?: ') if totp.lower() == 'y': self.totp_enabled = True totp_factory = TOTP.using(secrets_path='totp_sec', issuer='sec.thelonelylands.com') totp = totp_factory.new() self.totp = json.dumps(totp.to_json()) uri = totp.to_uri(label=self.username) input('Please enlarge your screen and press enter') print(pyqrcode.create(uri).terminal(quiet_zone=1)) print("Alternatively: " + totp.pretty_key()) token = input('Enter token to verify: ') verification = self.auth_verify(token) if verification: print('Successfully created user') return self else: print('User creation failed') return else: print('Successfully created user') return self
def verifyRegistration(request): registrationId = request.args.get('registrationId') otp1 = request.args.get('otp1') otp2 = request.args.get('otp2') TotpFactory = TOTP.using(secrets_path=PATH_TO_SECRET,issuer=ISSUER) querystr = AccountAdministratorRegistration \ .query \ .filter_by(registrationId=registrationId) \ .all() if querystr: registrationObj = querystr[0] secretToken = regObj.secretToken totp = TotpFactory.from_json(secretToken) try: if not registrationObj.expired and totp.verify(otp1,secretToken) and totp.verify(otp2,secretToken, window=60) and __verifyQR__(): registrationObj.expired = True registrationObj.expiryDate = datetime.now() db.session.add(registrationObj) db.session.flush() return {"Success": True,"SuccessResponse": [{"message": "Valid Registration"}]}, 200 except: return {"Success": False,"ErrorResponse": [{"code": "12", "message": "Invalid OTP/Registration"}]}, 404 else: return {"Success": False,"ErrorResponse": [{"code": "12", "message": "No Such Id"}]}, 404
def generateOTP(request): adminId = request.args.get('adminId') # Generate OTP TotpFactory = TOTP.using(secrets_path=PATH_TO_SECRET,issuer=ISSUER) totp = TotpFactory.new(digits=8) d = datetime.now() # Insert OR Update querystr = OneTimePassword \ .query \ .filter_by(adminId=adminId) \ .all() token_obj = totp.generate() if querystr: updateqstr = querystr[0] updateqstr.adminOTP = totp.to_json() updateqstr.adminOTPCreation = d updateqstr.adminOTPValidity = token_obj.expire_time else: # Create New Record totpDBObj = OneTimePassword(adminId=adminId, adminOTP = totp.to_json(), adminOTPCreation = d, adminOTPValidity = token_obj.expire_time) print(totpDBObj) db.session.add(totpDBObj) try: safeCommit() return {"Success": True,"SuccessResponse": [{"otp": token_obj.token}]}, 200 except: return {"Success": False,"ErrorResponse": [{"code": "12", "message": "Could not Generate OTP"}]}, 404
def __init__(self, secrets, issuer): """ Initialize a totp factory. secrets are used to encrypt the per-user totp_secret on disk. """ # This should be a dict with at least one entry if not isinstance(secrets, dict) or len(secrets) < 1: raise ValueError("secrets needs to be a dict with at least one entry") self._totp = TOTP.using(issuer=issuer, secrets=secrets)
def gen_totp_qr(self): totp_factory = TOTP.using(secrets_path='totp_sec', issuer='sec.thelonelylands.com') totp = totp_factory.from_source(json.loads(self.totp)) uri = totp.to_uri(label=self.username) input('Please enlarge your screen and press enter.') print(pyqrcode.create(uri).terminal(quiet_zone=1)) print("Alternatively: " + totp.pretty_key())
def generateQRImage(request): registrationId = request.args.get('registrationId') TotpFactory = TOTP.using(secrets_path=PATH_TO_SECRET,issuer=ISSUER) totp = TotpFactory.new() uri = totp.to_uri(label=registrationId) qrurl = pyqrcode.create(uri) outputBuffer = BytesIO() qrurl.png(outputBuffer) outputBuffer.seek(0) return send_file(outputBuffer, mimetype="image/png")
def tf_setup(app): """ Initialize a totp factory. The TWO_FACTOR_SECRET is used to encrypt the per-user totp_secret on disk. """ secrets = config_value("TWO_FACTOR_SECRET", app=app) # This should be a dict with at least one entry if not isinstance(secrets, dict) or len(secrets) < 1: raise ValueError( "TWO_FACTOR_SECRET needs to be a dict with at least one" "entry") return TOTP.using(issuer=config_value("TWO_FACTOR_URI_SERVICE_NAME", app=app), secrets=secrets)
def initialize(self): self.name = 'protoUser' self.ensureIndices(['email', 'groupInvites.groupId']) self.prefixSearchFields = ('email') self.ensureTextIndex({ 'email': 1, }, language='none') self.exposeFields(level=AccessType.READ, fields=('_id', 'public', 'email', 'created')) self.exposeFields(level=AccessType.ADMIN, fields=('groupInvites', 'status')) # To ensure compatibility with authenticator apps, other defaults shouldn't be changed self._TotpFactory = TOTP.using( # An application secret could be set here, if it existed wallet=None) self._cryptContext = CryptContext(schemes=['bcrypt'])
def auth_verify(self, token): try: int(token) except ValueError: return False else: token = int(token) totp_factory = TOTP.using(secrets_path='totp_sec', issuer='sec.thelonelylands.com') source = totp_factory.from_source(json.loads(self.totp)) try: verify = TOTP.verify(token=token, source=source, last_counter=self.totp_counter, window=10) except (passlib_errors.UsedTokenError, passlib_errors.InvalidTokenError, passlib_errors.MalformedTokenError): return False else: self.totp_counter = verify.counter return True
def handleRegistration(request): email = request.args.get('email') otp = request.args.get('otp') if __getAdminIdByEmail__(email): adminId = __getAdminIdByEmail__(email) else: return {"Success": False,"ErrorResponse": [{"code": "12", "message": "Invalid Email"}]}, 404 TotpFactory = TOTP.using(secrets_path=PATH_TO_SECRET,issuer=ISSUER) querystr = OneTimePassword \ .query \ .filter_by(adminId=adminId) \ .all() if querystr: currentAdminOTPjson = querystr[0] adminOTPjson = currentAdminOTPjson.adminOTP totp = TotpFactory.from_json(adminOTPjson) try: totp.verify(otp,adminOTPjson) except: return {"Success": False,"ErrorResponse": [{"code": "12", "message": "Invalid OTP"}]}, 404 currentAdminOTPjson.adminOTPValidity = 0 totp = TotpFactory.new(digits=8) registrationObj = AccountAdministratorRegistration(adminId=adminId,secretToken=totp.to_json()) db.session.add(registrationObj) db.session.flush() return {"Success": True,"SuccessResponse": [{"registrationId": registrationObj.registrationId}]}, 200 else: return {"Success": False,"ErrorResponse": [{"code": "12", "message": "No Id Found for the email provided"}]}, 404
## import pymongo, hashlib, uuid, hashlib, pyotp, base64,qrcode, pyqrcode from pymongo import MongoClient from bottle import post, get, route, run, template, request from passlib.totp import TOTP, generate_secret from passlib.exc import TokenError, MalformedTokenError mongoclient = MongoClient() db = mongoclient.giw collection = db['usuarios'] pimienta = "c6y]s4*u#L3r?tZ{3LYM95'vLq%DfmrF{'gjv[vs:B%!_FP3L)r$-r^;~swKcUabrcapata89" secret = generate_secret() TotpFactory = TOTP.using(secrets={"1":secret}) totpCounter = 0 ############## # APARTADO 1 # ############## # MECANISMO DE PROTECCIÓN DE CONTRASEÑAS: # # Almacenar las contraseñas en la BBDD de Mongo sin cifrado expone a los usuarios. # Para almacenar la contraseña de manera segura en la BBDD guardo ésta de la siguiente manera: # El hash de la contraseña (con SHA512) + sal (generación de cadena aleatoria) + pimienta (cadena de texto estática) # Además, quiero evitar Brute Force, y para ello uso un algoritmo de ralentizado (PBKDF2) # La función de hashlib se encarga de añadir la sal #.
from trytond.i18n import gettext from trytond.model import ModelSQL, ModelView, fields from trytond.pool import Pool, PoolMeta from trytond.pyson import Eval, PYSONEncoder from trytond.transaction import Transaction from .exception import ( TOTPAccessCodeReuseError, TOTPInvalidSecretError, TOTPKeyTooShortError, TOTPLoginException) _totp_issuer = config.get( 'authentication_totp', 'issuer', default='{company} Tryton') _totp_key_length = config.get( 'authentication_totp', 'key_length', default=160) _TOTPFactory = TOTP.using(secrets_path=config.get( 'authentication_totp', 'application_secrets_file', default=None)) class User(metaclass=PoolMeta): __name__ = 'res.user' totp_key = fields.Char("TOTP Key") totp_secret = fields.Function(fields.Char( "TOTP Secret", help="Secret key used for time-based one-time password (TOTP) " "user authentication."), 'get_totp_secret', setter='set_totp_secret') totp_qrcode = fields.Function(fields.Binary( "TOTP QR Code", states={ 'invisible': ~Eval('totp_secret', '') | (not QRCode),