def validateotp(uri): print("validating uri") result = False client_id = config.get('system', 'yubico_client_id') secret_key = config.get('system', 'yubico_secret_key') #token = raw_input('Enter OTP token: ') token = uri if not secret_key: secret_key = None client = Yubico(client_id, secret_key) try: status = client.verify(token) except yubico_exceptions.InvalidClientIdError: #e = sys.exc_info()[1] print('Client with id %s does not exist' % (e.client_id)) #sys.exit(1) except yubico_exceptions.SignatureVerificationError: print('Signature verification failed') #sys.exit(1) except yubico_exceptions.StatusCodeError: #e = sys.exc_info()[1] print('Negative status code was returned: %s' % (e.status_code)) #sys.exit(1) if status: print('Success, the provided OTP is valid') result = True else: print('No response from the servers or received other negative ' 'status code') return result
def validate_yubikey_otp(self, value): value = value.strip() if settings.ALLOWED_SECOND_FACTORS and 'yubikey_otp' not in settings.ALLOWED_SECOND_FACTORS: # TODO Replace with SERVER_NOT_SUPPORT_YUBIKEY msg = _('The server does not allow Yubikeys.') raise exceptions.ValidationError(msg) if settings.YUBIKEY_CLIENT_ID is None or settings.YUBIKEY_SECRET_KEY is None: # TODO Replace with SERVER_NOT_SUPPORT_YUBIKEY msg = _('Server does not support Yubikeys') raise exceptions.ValidationError(msg) client = Yubico(settings.YUBIKEY_CLIENT_ID, settings.YUBIKEY_SECRET_KEY) try: yubikey_is_valid = client.verify(value) except: yubikey_is_valid = False if not yubikey_is_valid: # TODO Replace with YUBICO_TOKEN_INVALID msg = _('Yubikey token invalid') raise exceptions.ValidationError(msg) return value
def post(self, request): key = request.POST.get('key', None) if key is None: response = JsonResponse({'error': _('No YubiKey found')}, status=400) return response # Make sure only acceptable characters in the key pattern = r'[^0-9a-zA-Z]' key = re.sub(pattern, '', key) if len(key) != 44: return JsonResponse({'error': _('Does not appear to be a valid YubiKey')}, status=400) try: client = Yubico(settings.YUBIKEY_CLIENT_ID, settings.YUBIKEY_CLIENT_SECRET) verify = client.verify(key) if verify: public_id = key[:12] yubikey = Yubikey.objects.get(public_id=public_id) user = yubikey.user request.session['yubikey_user_id'] = user.id request.session['incorrect_user'] = False except ObjectDoesNotExist: return JsonResponse({'error': _('That YubiKey is unrecognized.')}, status=400) except Exception as e: return JsonResponse({'error': str(e)}, status=400) output = { "verify": verify, } return JsonResponse(output)
def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') otp = self.cleaned_data.get('otp') # lifted from django.contrib.auth admin field if username and password and otp: self.user_cache = authenticate(username=username, password=password, otp=otp) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) # verify the yubikey try: client = Yubico(settings.YUBIKEY_CLIENT_ID, settings.YUBIKEY_SECRET_KEY) client.verify(otp) except: raise forms.ValidationError(_("Yubikey confirmation failed.")) return self.cleaned_data
def userLogin(args): user = args[USERNAME] # Yubikey OTP is 44-characters so if there's not at least 45 chars then # we assume there's only a single factor and fail them out of spite # also fail out of spite if the user does not have a yubikey in their password entry if user not in p.users: print(FAILED) logit("User not in table") return if (len(args['password']) < 45): print(FAILED) logit("Password too short to have yubi token") return if p.users[user]['yubikeyid'] is None: print(FAILED) logit("User has no yubi token in the passwd file") return # Otherwise split the first and second factors apart password = args['password'][0:-44] yubiotp = args['password'][-44:] userobject = p.users[user] # Check the first factor against the hash if not sha512_crypt.verify(password, userobject['hash']): print(FAILED) logit("First factor failed") return # does the yubikey belong to this user? # We should have pretty good assurance at this point that the userobject has a yubikeyid # value. Our check above should have promised that if yubiotp[0:12] != userobject['yubikeyid']: print(FAILED) logit( "Yubi token presented %s does not match what is on file %s" % (yubiotp[0:12], userobject['yubikeyid'])) return try: # Now FINALLY we go to yubicloud and ask yubi = Yubico(yubicloud_client_id, yubicloud_secret_key) if yubi.verify(yubiotp): print(SUCCESS) return except Exception as e: logging.error("Exception in yubi verify", e) print(FAILED) return # If we fall all the way out logit("Fell out the bottom") print(FAILED)
def __init__(self, client_id, secret_key, yubikey_id): Authenticator.__init__(self) try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass from yubico_client import Yubico self._client = Yubico(client_id, secret_key) if len(yubikey_id) != 12: raise ValueError("invalid yubikey_id") self._yubikey_id = yubikey_id
def post(self): args = self.reqparse.parse_args() client = Yubico('1851', 'oBVbNt7IZehZGR99rvq8d6RZ1DM=') response = {'response': 'success'} #import ipdb; ipdb.set_trace() # BREAKPOINT try: client.verify(args['yubikey']) except: response = {'response': 'fail'} return {'content': response}, 401 return {'content': response}, 200
def __init__(self): self.db = DBH(db='yubiauth') self.pwd_context = CryptContext(**settings['CRYPT_CONTEXT']) if settings['USE_NATIVE_YKVAL']: # Native verify from .ykval import Verifyer self.ykval_client = Verifyer() else: # Using yubico_client to verify against remote server from yubico_client import Yubico self.ykval_client = Yubico(settings['YKVAL_CLIENT_ID'], settings['YKVAL_CLIENT_SECRET'], api_urls=settings['YKVAL_SERVERS'])
def __init__(self): self.db = DBHandler(db='yubiauth') self.pwd_context = CryptContext(**settings['CRYPT_CONTEXT']) if settings['USE_NATIVE_YKVAL']: # Native verify from .ykval import Validator self.ykval_client = Validator() else: # Using yubico_client to verify against remote server from yubico_client import Yubico self.ykval_client = Yubico(settings['YKVAL_CLIENT_ID'], settings['YKVAL_CLIENT_SECRET'], api_urls=settings['YKVAL_SERVERS'])
def auth(username, password): ''' Authenticate against yubico server ''' _cred = __get_yubico_users(username) client = Yubico(_cred['id'], _cred['key']) try: return client.verify(password) except yubico_exceptions.StatusCodeError as e: log.info('Unable to verify YubiKey `%s`', e) return False
def auth(username, password): """ Authenticate against yubico server """ _cred = __get_yubico_users(username) client = Yubico(_cred["id"], _cred["key"]) try: return client.verify(password) except yubico_exceptions.StatusCodeError as e: log.info("Unable to verify YubiKey `%s`", e) return False
def post(self): data = parser.parse_args() print(data) current_user = User.find_by_username(data['username']) if not current_user: return { 'message': 'User {} Does Not Exist'.format(data['username']) } if current_user.check_password(data['password']): otp = data['yubikey'] if current_user.yubikey_id != otp[0:12]: return { 'message': 'Yubikey OTP ID not affiliated with user.' }, 403 client = Yubico(33781, None) status = False try: status = client.verify(otp) except yubico_exceptions.InvalidClientIdError: e = sys.exc_info()[1] print('Client with id %s does not exist' % (e.client_id)) sys.exit(1) except yubico_exceptions.SignatureVerificationError: print('Signature verification failed') sys.exit(1) except yubico_exceptions.StatusCodeError: e = sys.exc_info()[1] print('Negative status code was returned: %s' % (e.status_code)) sys.exit(1) if status: print('OTP: ' + str(status)) access_token = create_access_token(identity=data['username']) refresh_token = create_refresh_token(identity=data['username']) return { 'message': 'Logged in as {}'.format(data['username']), 'access_token': access_token, 'refresh_token': refresh_token } else: return {'message': "Invalid OTP"}, 403 else: return {'message': 'Invalid Credentials'}, 403
def auth(username, password): ''' Authentcate against yubico server ''' _cred = __get_yubico_users(username) client = Yubico(_cred['id'], _cred['key']) try: if client.verify(password): return True else: return False except yubico_exceptions.StatusCodeError, e: log.info('Unable to verify YubiKey `{0}`'.format(e)) return False
def _validate_yubikey_otp(self, code: str) -> bool: try: return Yubico(self._config[YUBICLOUD_CLIENT_ID]).verify( code, timestamp=True) except (YubicoError, Exception) as cause: logging.error(cause, exc_info=True) return False
def auth(username, password): ''' Authenticate against yubico server ''' _cred = __get_yubico_users(username) client = Yubico(_cred['id'], _cred['key']) try: if client.verify(password): return True else: return False except yubico_exceptions.StatusCodeError as e: log.info('Unable to verify YubiKey `{0}`'.format(e)) return False
def verify_otp(token): yubikey_owner = read_from_s3(bucket='taybird-birdnest-creds', key='yubikey_key_id') yubico_creds = read_from_s3(bucket='taybird-birdnest-creds', key='yubico').split(',') yubikey_client = Yubico(yubico_creds[0], yubico_creds[1]) if not token[:12] == yubikey_owner: logging.warn('Denied unknown token: "{}"'.format(token)) raise ValueError if not yubikey_client.verify(token): logging.warn('Token failed to validate: "{}"'.format(token)) raise ValueError
def yubikey_authenticate(yubikey_otp): """ Checks a YubiKey OTP :param yubikey_otp: Yubikey OTP :type yubikey_otp: :return: True or False or None :rtype: bool """ if settings.YUBIKEY_CLIENT_ID is None or settings.YUBIKEY_SECRET_KEY is None: return None client = Yubico(settings.YUBIKEY_CLIENT_ID, settings.YUBIKEY_SECRET_KEY) try: yubikey_is_valid = client.verify(yubikey_otp) except: yubikey_is_valid = False return yubikey_is_valid
async def authenticate_code(code): # Check the code is in the correct length # 32 character OTP + 2-16 character identifier if len(code) < 34 or len(code) > 48: display.print('-NO-') display.show() await asyncio.sleep(2) launch_control.auth_failure() return # Grab config with open(CONFIG_FILE) as f: config = json.load(f) try: display.print('YUBI') client = Yubico(config['client_id'], config['api_secret']) status = client.verify(code) except yubico_exceptions.InvalidClientIdError: e = sys.exc_info()[1] logger.info('Client with id %s does not exist', (e.client_id)) except yubico_exceptions.SignatureVerificationError: logger.info('Signature verification failed') except yubico_exceptions.StatusCodeError: e = sys.exc_info()[1] logger.info('Negative status code was returned: %s', (e.status_code)) if status: global authenticated_user authenticated_user = code[1:-32] logger.debug("Successful authentication for user %s", authenticated_user) launch_control.authenticate() else: display.print('FAIL') display.show() await asyncio.sleep(2) launch_control.auth_failure()
def post(self, request): key = request.POST.get('key', None) if key is None: response = JsonResponse({'error': _('No YubiKey found')}, status=400) return response # Make sure only acceptable characters in the key pattern = r'[^0-9a-zA-Z]' key = re.sub(pattern, '', key) if len(key) != 44: return JsonResponse( {'error': _('Does not appear to be a valid YubiKey')}, status=400) try: client = Yubico(settings.YUBIKEY_CLIENT_ID, settings.YUBIKEY_CLIENT_SECRET) verify = client.verify(key) if verify: public_id = key[:12] yubikey = Yubikey.objects.get(public_id=public_id) user = yubikey.user request.session['yubikey_user_id'] = user.id request.session['incorrect_user'] = False except ObjectDoesNotExist: return JsonResponse({'error': _('That YubiKey is unrecognized.')}, status=400) except Exception as e: return JsonResponse({'error': str(e)}, status=400) output = { "verify": verify, } return JsonResponse(output)
class AuthenticatorYUBI(Authenticator): def __init__(self, client_id, secret_key, yubikey_id): Authenticator.__init__(self) try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass from yubico_client import Yubico self._client = Yubico(client_id, secret_key) if len(yubikey_id) != 12: raise ValueError("invalid yubikey_id") self._yubikey_id = yubikey_id def verify_impl(self, token): if token[:12] != self._yubikey_id: return False return self._client.verify(token, timeout=5)
from yubico_client import Yubico from yubico_client import yubico_exceptions from yubico_client.py3 import PY3 if PY3: raw_input = input client_id = raw_input('Enter your client id: ') secret_key = raw_input('Enter your secret key (optional): ') token = raw_input('Enter OTP token: ') if not secret_key: secret_key = None client = Yubico(client_id, secret_key) try: status = client.verify(token) except yubico_exceptions.InvalidClientIdError: e = sys.exc_info()[1] print('Client with id %s does not exist' % (e.client_id)) sys.exit(1) except yubico_exceptions.SignatureVerificationError: print('Signature verification failed') sys.exit(1) except yubico_exceptions.StatusCodeError: e = sys.exc_info()[1] print('Negative status code was returned: %s' % (e.status_code)) sys.exit(1)
import os import re import base64 from flask import Flask, render_template, request, redirect, session, flash from mysqlconnection import connectToMySQL from flask_bcrypt import Bcrypt from yubico_client import Yubico, otp, yubico_exceptions from yubico_client.py3 import b EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') yubi_client_id = "51542" yubi_secret_key = "B2Q6oZvOHQIAMxxEDVXM+XaN5D8=" rand_str = b(os.urandom(30)) nonce = base64.b64encode(rand_str, b('xz'))[:25].decode('utf-8') yubi_client = Yubico(yubi_client_id, yubi_secret_key) app = Flask(__name__) app.secret_key = 'keep it secret, keep it safe' bcrypt = Bcrypt(app) @app.route('/') def index(): return render_template("index.html") @app.route('/create_user', methods=['POST']) def create(): is_valid = True # assume True if len(request.form['fname']) < 1: is_valid = False
class Client: """ Authentication Client """ def __init__(self): self.db = DBHandler(db='yubiauth') self.pwd_context = CryptContext(**settings['CRYPT_CONTEXT']) if settings['USE_NATIVE_YKVAL']: # Native verify from .ykval import Validator self.ykval_client = Validator() else: # Using yubico_client to verify against remote server from yubico_client import Yubico self.ykval_client = Yubico(settings['YKVAL_CLIENT_ID'], settings['YKVAL_CLIENT_SECRET'], api_urls=settings['YKVAL_SERVERS']) def _get_user_info(self, username): """ Get user from DB Args: username Returns: dictionary of user data Raises: AuthFail if user does not exist """ user = self.db.get_user(username) if not user: raise YKAuthError('UNKNOWN_USER') logger.debug('[%s] Found user: %s', username, user) return user def _check_token(self, user, token_id): """ Check Token association with user Args: user: User data dict as recieved from _get_user_info() token_id: Token prefix (aka. publicname) Returns: None Raises: AuthFail if token is not associated with the user AithFail if token is disabled """ token = self.db.get_token(user['users_id'], token_id) if not token: logger.error('[%s] Token %s is not associated with user', user['users_name'], token_id) raise YKAuthError('INVALID_TOKEN') logger.debug('[%s] Found token: %s', user['users_name'], token) if not token.get('yubikeys_enabled'): logger.error('[%s] Token %s is disabled for %s', user['users_name'], token_id, user['users_name']) raise YKAuthError('DISABLED_TOKEN') def _validate_password(self, user, password): """ Validate password against the hash in SQL """ valid, new_hash = self.pwd_context.verify_and_update(str(password), user['users_auth']) if not valid: logger.error('[%(users_name)s] Invalid password', user) raise YKAuthError('BAD_PASSWORD') if new_hash: # TODO: update user's hash with new_hash logger.warning('[%(users_name)s] User password hash needs update', user) return True def authenticate(self, username, password, otp): """ Yubistack user authentication Args: username: Username of the user password: Password/PIN of the user otp: Yubikey one time password Returns: dict of authentication data Authentication process: 1. Check if token is enabled 2. Check if token is associated with the user & enabled 3. Validate users password 4. Validate OTP (YKVal) """ token_id = otp[:-TOKEN_LEN] # STEP 1: Check if token is enabled user = self._get_user_info(username) # STEP 2: Check if token is associated with the user & enabled self._check_token(user, token_id) # STEP 3: Validate users password self._validate_password(user, password) # STEP 4: Validate OTP self.ykval_client.verify(otp) return True
import lock, shelve ids = { "interncccccc": 1, "interncccccd": 2, "internccccch": 3, "internccccci": 4, "internccccce": 5, "interncccccg": 6, "interncccccf": 7, "interncccccb": 8, "internccccck": 9, "interncccccj": 10 } while True: try: inp = input(">") id = ids[inp[:12]] with shelve.open("Settings.conf") as settings: client = Yubico(id, settings["keys"][id], api_urls=('http://localhost/wsapi/2.0/verify', )) client.verify(inp) except KeyboardInterrupt: break except: pass else: lock.switch(id)
def check_otp(self, otp): client = Yubico(client_id, secret_key) return (get_public_id(otp) == self.yubikey_id and client.verify(otp))
class Client: """ Authentication Client """ def __init__(self): self.db = DBHandler(db='yubiauth') self.pwd_context = CryptContext(**settings['CRYPT_CONTEXT']) if settings['USE_NATIVE_YKVAL']: # Native verify from .ykval import Validator self.ykval_client = Validator() else: # Using yubico_client to verify against remote server from yubico_client import Yubico self.ykval_client = Yubico(settings['YKVAL_CLIENT_ID'], settings['YKVAL_CLIENT_SECRET'], api_urls=settings['YKVAL_SERVERS']) def _get_user_info(self, username): """ Get user from DB Args: username Returns: dictionary of user data Raises: AuthFail if user does not exist """ user = self.db.get_user(username) if not user: raise YKAuthError('UNKNOWN_USER') logger.debug('[%s] Found user: %s', username, user) return user def _check_token(self, user, token_id): """ Check Token association with user Args: user: User data dict as recieved from _get_user_info() token_id: Token prefix (aka. publicname) Returns: None Raises: AuthFail if token is not associated with the user AithFail if token is disabled """ token = self.db.get_token(user['users_id'], token_id) if not token: logger.error('[%s] Token %s is not associated with user', user['users_name'], token_id) raise YKAuthError('INVALID_TOKEN') logger.debug('[%s] Found token: %s', user['users_name'], token) if not token.get('yubikeys_enabled'): logger.error('[%s] Token %s is disabled for %s', user['users_name'], token_id, user['users_name']) raise YKAuthError('DISABLED_TOKEN') def _validate_password(self, user, password): """ Validate password against the hash in SQL """ valid, new_hash = self.pwd_context.verify_and_update( str(password), user['users_auth']) if not valid: logger.error('[%(users_name)s] Invalid password', user) raise YKAuthError('BAD_PASSWORD') if new_hash: # TODO: update user's hash with new_hash logger.warning('[%(users_name)s] User password hash needs update', user) return True def authenticate(self, username, password, otp): """ Yubistack user authentication Args: username: Username of the user password: Password/PIN of the user otp: Yubikey one time password Returns: dict of authentication data Authentication process: 1. Check if token is enabled 2. Check if token is associated with the user & enabled 3. Validate users password 4. Validate OTP (YKVal) """ token_id = otp[:-TOKEN_LEN] # STEP 1: Check if token is enabled user = self._get_user_info(username) # STEP 2: Check if token is associated with the user & enabled self._check_token(user, token_id) # STEP 3: Validate users password self._validate_password(user, password) # STEP 4: Validate OTP self.ykval_client.verify(otp) return True
from yubico_client import yubico_exceptions client_id = raw_input('Enter your client id: ') secret_key = raw_input('Enter your secret key (optional): ') use_https = raw_input('Use secure connection (https)? [y/n]: ') token = raw_input('Enter OTP token: ') if not secret_key: secret_key = None if use_https == 'n': https = False else: https = True client = Yubico(client_id, secret_key, https) try: status = client.verify(token) except yubico_exceptions.InvalidClientIdError, e: print 'Client with id %s does not exist' % (e.client_id) sys.exit(1) except yubico_exceptions.SignatureVerificationError: print 'Signature verification failed' sys.exit(1) except yubico_exceptions.StatusCodeError, e: print 'Negative status code was returned: %s' % (e.status_code) sys.exit(1) if status: print 'Success, the provided OTP is valid'
#!/usr/bin/env python from yubico_client import Yubico from yubico_client import yubico_exceptions import sys otp = raw_input("Enter OTP token: ") valid_token = 'ccccccfgictv' #API-KEY MDVNPrFH6JyXgc+6DvsMA7RxQ2g= is depricated. Get a new key from yubico.com. client = Yubico('32945', 'MDVNPrFH6JyXgc+6DvsMA7RxQ2g=') status = False try: status = client.verify(otp) except yubico_exceptions.InvalidClientIdError: e = sys.exc_info()[1] print('Client with id %s does not exist' % (e.client_id)) sys.exit(1) except yubico_exceptions.SignatureVerificationError: print('Signature verification failed') sys.exit(1) except yubico_exceptions.StatusCodeError: e = sys.exc_info()[1] print('Negative status code was returned: %s' % (e.status_code)) sys.exit(1) if status: #Key exists, check access base status = (otp[:12]==valid_token)
class BaseRequestHandler(RequestHandler): def prepare(self): self.yubico = Yubico(options.yubico_api_id, options.yubico_api_key) def get(self, **kwargs): raise NotImplementedError() def response_invalid_login(self): self.set_status(401) self.set_header('WWW-Authenticate', 'Basic realm=Restricted') self._transforms = [] self.finish() def set_session_cookie(self, cookie_name=None): """Set the session cookies.""" # Note that secure cookie implements it's own timestamp checking but # does so by days. check yubicoauth date so we can be more specific if not cookie_name: cookie_name = options.session_cookie_name cookiedata = { "nonce": base64.b64encode(os.urandom(12)), "timestamp": time.time() } self.set_secure_cookie(cookie_name, cPickle.dumps(cookiedata, 0)) def get_session_cookie(self, cookie_name=None): """Get the cookie data if exists. Typically depickling a cookie received from client is a bad idea. This is a special case as get_secure_cookie() contains a HMAC that is verified before returning anything. :return: Returns the contents of session cookie in whatever type it was when saved (ie dictionary) """ if not cookie_name: cookie_name = options.session_cookie_name if not self.get_secure_cookie(cookie_name): return None else: return cPickle.loads(self.get_secure_cookie(cookie_name)) def clear_session_cookie(self, cookie_name=None): """Clear session cookie While there is an existing clear_cookie() it doesn't seem to work so instead set it to blank value """ if not cookie_name: cookie_name = options.session_cookie_name self.set_secure_cookie(cookie_name, cPickle.dumps({}, 0)) def verify_yubikey(self, yubikey_otp): """Verify a given OTP is valid.""" yubikey_id = get_yubikey_id(yubikey_otp) if yubikey_id not in options.yubikeys: logging.info( "yubikey id not specified in auth_yubico options: %s" % yubikey_id) result = False else: try: result = self.yubico.verify(yubikey_otp) except YubicoError as exc: logging.error("YubicoError: %s" % exc) result = False else: self.set_header("X-Yubikey-Id", yubikey_id) result = True return result def verify_session_cookie(self): session_cookie = self.get_session_cookie() if session_cookie: if 'timestamp' in session_cookie: timedelta = time.time() - session_cookie['timestamp'] if timedelta < options.session_timeout: logging.info("Previously logged in, not checking again") result = True else: logging.info("expired session (age: %f)" % timedelta) result = False else: logging.warn("session cookie missing timestamp param") result = False else: result = False return result def authenticate(self, username, password): """Do actual authentication.""" logging.info("authenticate: user=%s password=HIDDEN" % username) # This was used to test thread concurrency #time.sleep(5) auth_ok = None if self.verify_session_cookie(): auth_ok = True elif self.verify_yubikey(password): auth_ok = True if auth_ok: logging.info("successful authentication, setting session cookie") self.set_session_cookie() else: logging.info("unsuccessful authentication, send back to login") self.response_invalid_login() return auth_ok
def _validate_yubikey_otp(self, code): client = Yubico(self.conf['YUBICLOUD_CLIENT_ID']) try: return client.verify(code, timestamp=True) except (YubicoError, Exception): return False
def AuthUser(username, password): # Extract the token from the encoded password if password.startswith('SCRV1:'): # Extract the actual password and token passwordSplit = password.split(':') password = b64decode(passwordSplit[1]) token = b64decode(passwordSplit[2]) else: # Invalid data return False # Check username and password are valid using PAM try: loginValid = pam.authenticate(username, password) except: loginValid = False if not loginValid: return False # The first 12 characters of the token is the unique public ID tokenId = token[:12] # Only accept the token assigned to the user. If this is the first time # a token has been used for a user, assign it to the user. if os.path.exists(self.dbPath): try: file = open(self.dbPath,'rb') tokenDb = pickle.load(file) file.close() except: tokenDb = {} else: tokenDb = {} updateDb = False if username in tokenDb.keys() and tokenDb[username] != tokenId: # The token being used does not match the token for the user return False else: tokenDb[username] = tokenId updateDb = True # Check that the token is valid using the Yubico Cloud service yubico = Yubico(self.clientID, self.secretKey) try: tokenValid = yubico.verify(token) except: tokenValid = False if not tokenValid: return False # Save the token database if necessary if updateDb: file = open(self.dbPath,'wb') pickle.dump(tokenDb, file, -1) file.close() return True
def prepare(self): self.yubico = Yubico(options.yubico_api_id, options.yubico_api_key)
def get_client(): return Yubico(YUBICO_AUTH_CLIENT_ID, YUBICO_AUTH_SECRET_KEY)
kwargs = {} urls_no_proto = [ url[8:] if url.startswith('https://') else url[7:] if url.startswith('http://') else url for url in settings['ykval'] ] use_https = all(url.startswith('https://') for url in settings['ykval']) if version < (1, 8, 0): # No URL passing, except through hack. yubico_constants.API_URLS = urls_no_proto elif version < (1, 9, 0): # 1.8.0 introduces URL passing, without protocol. kwargs['api_urls'] = urls_no_proto else: # 1.9.0 or later kwargs['api_urls'] = settings['ykval'] if version < (1, 9, 0): # 1.9.0 removes use_https parameter. kwargs['use_https'] = use_https yubico = Yubico(settings['ykval_id'], settings['ykval_secret'], **kwargs) MODHEX = 'cbdefghijklnrtuv' def validate_otp(otp): try: return yubico.verify(otp) except: pass return False
import nfc import nfc.ndef from yubico_client import Yubico from subprocess import call with nfc.ContactlessFrontend('usb') as clf: tag = clf.connect(rdwr={'on-connect': None}) # print tag.ndef.message if tag.ndef else "Sorry, no NDEF" message = tag.ndef.message # pprint(record) print tag.ndef.readable for index, record in enumerate(message): rcount = " [record {0}]".format(index+1) try: if record.type == "urn:nfc:wkt:U": print("URI Record" + rcount) record = nfc.ndef.UriRecord(record) else: print("Unknown Record Type" + rcount) except nfc.ndef.FormatError as e: print(record.pretty(indent=2)) # print nfc.ndef.Message(record) # print record #now verify this client = Yubico('client id', 'secret key') #get this from https://upgrade.yubico.com/getapikey/ if client.verify(record): call ("gpio","-g mode 23 out") call ("gpio","-g write 23 1")#opened relais else print "failed to verify" call ("gpio","-g mode 23 out") call ("gpio","-g write 23 0")#closed relais
class Client(object): """ Authentication Client """ def __init__(self): self.db = DBH(db='yubiauth') self.pwd_context = CryptContext(**settings['CRYPT_CONTEXT']) if settings['USE_NATIVE_YKVAL']: # Native verify from .ykval import Verifyer self.ykval_client = Verifyer() else: # Using yubico_client to verify against remote server from yubico_client import Yubico self.ykval_client = Yubico(settings['YKVAL_CLIENT_ID'], settings['YKVAL_CLIENT_SECRET'], api_urls=settings['YKVAL_SERVERS']) def _get_token_info(self, username, token_id): """ 1. Check user 2. Check token """ user = self.db.get_user(username) if not user: raise YKAuthError("No such user: %s" % username) logger.debug('Found user: %s', user) token = self.db.get_token(user['users_id'], token_id) if not token: logger.error('Token %s is not associated with %s', token_id, username) raise YKAuthError("Token %s is not associated with %s" % (token_id, username)) logger.debug('Found token: %s', token) if not token.get('yubikeys_enabled'): logger.error('Token %s is disabled for %s', token_id, username) raise YKAuthError("Token is disabled for %s" % username) return user def _validate_password(self, user, password): """ Validate password against the hash in SQL """ valid, new_hash = self.pwd_context.verify_and_update(str(password), user['users_auth']) if not valid: logger.error('Invalid password for %(users_name)s', user) raise YKAuthError("Invalid password for %(users_name)s" % user) if new_hash: # TODO: update user's hash with new_hash logger.warning("User %(users_name)s's hash needs update", user) return True def _validate_otp(self, otp): """ Use Yubico client to validate OTP """ try: if self.ykval_client.verify(otp): return True return False except Exception as err: logger.error('OTP Validation failed: %r', err) return False def authenticate(self, username, password, otp): """ 1. Check if token is enabled 2. Check if token is associated with the user 3. Validate users password 4. Validate OTP (YKVal) """ token_id = otp[:-32] user = self._get_token_info(username, token_id) self._validate_password(user, password) return self._validate_otp(otp)
#!/usr/bin/env python # -*- coding: utf-8 -*- import hashlib import os import sqlite3 import sys from yubico_client import Yubico from config import DB_PATH, HASH_ALGORITHM, YUBICO_CLIENT_ID, YUBICO_SECRET yubi_client = Yubico(YUBICO_CLIENT_ID, YUBICO_SECRET) hash_func = getattr(hashlib, HASH_ALGORITHM) conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() yubi_otp = os.environ['password'][-44:] sent_password = os.environ['password'][:-44] cursor.execute( 'SELECT username, password FROM users WHERE username = ? AND yubi_public_id = ?;', ( os.environ['username'], yubi_otp[:12], )) result = cursor.fetchone() if result is None: sys.exit(1) username, password = result if hash_func(sent_password.encode("utf-8")).hexdigest() != password:
import requests r = requests.get("http://192.168.1.2:8080/ccapi/ver100/contents/sd/100CANON") r.json()["url"][-1] from PIL import Image from io import BytesIO i = Image.open(BytesIO(r.content)) i from simple_websocket_server import WebSocketServer, WebSocket import sys import yubico from yubico_client import Yubico try: yubikey = yubico.find_yubikey(debug=False) print( "Version : %s " % yubikey.version()) except yubico.yubico_exception.YubicoError as e: print( "ERROR: %s" % e.reason) sys.exit(1) client = Yubico('client id', 'secret key') client.verify('otp')