Пример #1
0
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
Пример #2
0
 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
Пример #3
0
    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
Пример #4
0
    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)
Пример #5
0
 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
Пример #6
0
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
Пример #7
0
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
Пример #8
0
 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'])
Пример #9
0
    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
Пример #10
0
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
Пример #11
0
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
Пример #12
0
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
Пример #13
0
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()
Пример #14
0
    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)
Пример #15
0
def get_client():
    return Yubico(YUBICO_AUTH_CLIENT_ID, YUBICO_AUTH_SECRET_KEY)
Пример #16
0
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
Пример #17
0
 def prepare(self):
     self.yubico = Yubico(options.yubico_api_id, options.yubico_api_key)
Пример #18
0
 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
Пример #19
0
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
Пример #20
0
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)
Пример #21
0
#!/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:
Пример #22
0
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)
Пример #23
0
	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
Пример #24
0
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')