Example #1
0
    def test_generating_totp_at_specific_clock(self):
        """
        check if the totp can be generated for a specific clock
        which is basically the same as hotp
        """
        secret = b'MFRGGZDFMZTWQ2LK'
        hotp = get_hotp(secret=secret, intervals_no=int(time.time())//30,)
        totp = get_totp(secret=secret, clock=None)
        self.assertEqual(hotp, totp)

        # hotp intervals minus 1
        hotp = get_hotp(secret=secret, intervals_no=int(time.time())//30-1,)
        #totp 30 seconds in the past
        totp = get_totp(secret=secret, clock=(int(time.time())-30))
        self.assertEqual(hotp, totp)
Example #2
0
def google(request):
    if "secret_key" not in request.POST:
        return JsonResponse({"code": 400, "message": "secret_key lack"})
    secret_key = request.POST.get("secret_key")
    time1 = time.time() - 30
    time2 = time.time() + 30
    arr = list()
    try:
        otp.get_totp(secret_key)
    except:
        return JsonResponse({"code": 401, "message": "invalid secret_key"})
    arr.append(fix_value(otp.get_totp(secret_key)))
    arr.append(fix_value(otp.get_totp(secret_key, clock=time1)))
    arr.append(fix_value(otp.get_totp(secret_key, clock=time2)))
    return JsonResponse({"code": 200, "data": arr})
Example #3
0
def get_secret_key():
    Font_tuple = ("Comic Sans MS", 15, "bold")
    value = account_id.get()
    with open('file.json', 'r') as f:
        data = json.load(f)
        a = []
        b = []
        for i in range(len(data["account"])):
            a += (data["account"][i].keys())
            b += (data["account"][i].values())
        for i in range(len(a)):
            if value == a[i]:
                global yourOTP
                my_token = ''
                my_token = otp.get_totp(b[i])
                yourOTP = Label(root, text='OTP: ', font=Font_tuple)
                yourOTP.place(x=100, y=400)
                if my_token == '':
                    onetimepassword = Label(root, text='WRONG SHARED KEY !')
                    onetimepassword.place(x=150, y=400)
                else:
                    onetimepassword = Label(root,
                                            text=my_token,
                                            font=Font_tuple)
                    onetimepassword.place(x=150, y=400)
Example #4
0
def get_otp(Ph_number,chat_id):
    my_secret = base64.b32encode(str(chat_id))
    #my_secret = 'MFRGGZDFMZTWQ2LK'
    my_token = otp.get_totp(my_secret,interval_length = 300)
    msg = "Your One-Time-Password is "+str(my_token)+". It will be valid for 3 minutes."
    phn_no = Ph_number
    sendsmses(phn_no,str(msg))
Example #5
0
 def test_validating_invalid_totp_for_same_secret(self):
     """
     Test case when the same secret is used, but the token differs
     """
     secret = b'MFRGGZDFMZTWQ2LK'
     with timecop.freeze(time.time()):
         self.assertFalse(valid_totp(get_totp(secret)+1, secret))
Example #6
0
 def test_validating_totp_for_same_secret(self):
     """
     Check if validating TOTP generated for the same secret works
     """
     secret = b'MFRGGZDFMZTWQ2LK'
     with timecop.freeze(time.time()):
         self.assertTrue(valid_totp(get_totp(secret), secret))
Example #7
0
def get_token(cfg):
    s = cfg.get('auth', 'secret')
    if s == '':
        t = getpass.getpass('OAuth Token:')
    else:
        t = onetimepass.get_totp(s)
    return t
Example #8
0
 def test_validating_correct_totp_as_hotp(self):
     """
     Check if valid TOTP will work as HOTP - should not work, unless for
     very big interval number (matching Unix epoch timestamp)
     """
     secret = b'MFRGGZDFMZTWQ2LK'
     self.assertFalse(valid_hotp(get_totp(secret), secret))
Example #9
0
def test_update_enable_2fa_invalid_token(app, client):
    utils = Utils(app, client)

    headers = {
        'Authorization': f'Bearer {utils.generate_admin_access_token()}'
    }
    # first step to enable 2fa, get secret key
    resp = client.put('/api/users/me',
                      headers=headers,
                      json={'totp_enabled': True})
    assert resp.status_code == 200
    assert not json.loads(resp.data.decode()).get('data').get('2fa')
    assert '2fa_secret' in json.loads(resp.data.decode()).get('data')
    secret = json.loads(resp.data.decode()).get('data').get('2fa_secret')

    # generate a 2fa token using the secret key, and use it to activate 2fa
    totp_token = str(onetimepass.get_totp(secret)).zfill(6)
    resp = client.post('/api/users/2fa',
                       headers=headers,
                       json={'token': '000000'})
    assert resp.status_code == 400
    assert json.loads(
        resp.data.decode()).get('message') == 'invalid token, try again'

    resp = client.post('/api/users/2fa',
                       headers=headers,
                       json={'token': str(totp_token)})
    assert resp.status_code == 200
    assert json.loads(
        resp.data.decode()).get('message') == '2fa has been enabled'
Example #10
0
def Main():
    import onetimepass as otp
    my_secret = 'ZYPRDAEJVPBMFGUA'
    my_token = otp.get_totp(my_secret)
    # print "my_token is %s"%my_token

    if len(str(my_token)) == 6:
        fin_token = my_token
    else:
        fin_token = "0" + str(my_token)
    xsh.Screen.Send(fin_token)
    ###enter token
    xsh.Screen.Send('\r')

    ###get IP addr
    IP = re.findall(r"\d+", str(xsh.Session.Path))
    if int(IP[0]) < 10:
        ###enter IP addr
        for i in range(1, 4):
            xsh.Screen.Send(abs(int(IP[i])))
            xsh.Screen.Send('.')
        xsh.Screen.Send(abs(int(IP[4])))
        xsh.Screen.Send('\r')
    else:
        ###enter ip addr
        for i in range(0, 3):
            xsh.Screen.Send(abs(int(IP[i])))
            xsh.Screen.Send('.')
        xsh.Screen.Send(abs(int(IP[3])))
        xsh.Screen.Send('\r')
    ###sudo su
    xsh.Screen.Synchronous = True
    xsh.Session.Sleep(3500)
    xsh.Screen.Send("sudo su" + '\r')
Example #11
0
def get_otp(Ph_number,chat_id):
    my_secret = base64.b32encode(str(chat_id))
    #my_secret = 'MFRGGZDFMZTWQ2LK'
    my_token = otp.get_totp(my_secret,interval_length = 300)
    msg = my_token
    phn_no = Ph_number
    sendsmses(phn_no,str(msg))
Example #12
0
def test_update_show_qr_after_2fa_has_been_enabled(app, client):
    utils = Utils(app, client)

    headers = {
        'Authorization': f'Bearer {utils.generate_admin_access_token()}'
    }
    # first step to enable 2fa, get secret key
    resp = client.put('/api/users/me',
                      headers=headers,
                      json={'totp_enabled': True})
    assert resp.status_code == 200
    assert not json.loads(resp.data.decode()).get('data').get('2fa')
    assert '2fa_secret' in json.loads(resp.data.decode()).get('data')

    # generate a 2fa token using the secret key, and use it to activate 2fa
    secret = json.loads(resp.data.decode()).get('data').get('2fa_secret')
    totp_token = str(onetimepass.get_totp(secret)).zfill(6)
    resp = client.post('/api/users/2fa',
                       headers=headers,
                       json={'token': str(totp_token)})
    assert resp.status_code == 200
    assert json.loads(
        resp.data.decode()).get('message') == '2fa has been enabled'

    # it should not be possible to generate the qr code after 2fa has been enabled
    # this would be a potential security vulnerability
    resp = client.get('/api/users/2fa', headers=headers)
    assert resp.status_code == 400
    assert json.loads(
        resp.data.decode()).get('message') == 'Unable to generate QR Code'
def get_secret_key():
    Font_tuple = ("Comic Sans MS", 15, "bold")
    value = account_id.get()
    with open('file.json', 'r') as f:
        data = json.load(f)
        a = []
        b = []
        for i in range(len(data["account"])):
            a += (data["account"][i].keys())
            b += (data["account"][i].values())
        for i in range(len(a)):
            if value == a[i]:
                global yourOTP
                my_token = ''
                my_token = otp.get_totp(b[i])
                yourOTP = Label(root,
                                text='OTP: ',
                                font=("Comic Sans MS", 12, "bold"),
                                bg='#424543',
                                fg='white')
                yourOTP.place(x=120, y=450)
                onetimepassword = Label(root,
                                        text=my_token,
                                        font=("Comic Sans MS", 12, "bold"),
                                        bg='#424543',
                                        fg='white')
                onetimepassword.place(x=170, y=450)
Example #14
0
 def test_validating_correct_totp_as_hotp(self):
     """
     Check if valid TOTP will work as HOTP - should not work, unless for
     very big interval number (matching Unix epoch timestamp)
     """
     secret = b'MFRGGZDFMZTWQ2LK'
     self.assertFalse(valid_hotp(get_totp(secret), secret))
Example #15
0
def create_otp_token(my_secret, length, interval):
    my_token = otp.get_totp(my_secret,
                            token_length=length,
                            interval_length=interval,
                            as_string=True)
    # print(my_token)
    return my_token
Example #16
0
 def test_validating_totp_for_same_secret(self):
     """
     Check if validating TOTP generated for the same secret works
     """
     secret = b'MFRGGZDFMZTWQ2LK'
     with timecop.freeze(time.time()):
         self.assertTrue(valid_totp(get_totp(secret), secret))
Example #17
0
def Main():
    ###get GoogleToken
    import onetimepass as otp
    my_secret = 'KZS774YENHNW2SVU'
    my_token = ""
    my_token1 = otp.get_totp(my_secret)
    if len(str(my_token1)) == 6:
        my_token = my_token1
        ###get IP addr
        IP_ORI = re.findall(r"\d+", str(xsh.Session.Path.split('\\')[-1]))
        IP = IP_FIN(IP_ORI)
        #result = xsh.Screen.WaitForString('OpenSSH\home\mr_ac>')
        #xsh.Screen.Send('ssh -i D:\PyCharm\Git_OPS\liuchenggong-jumpserver.pem [email protected] -p 2222\r')
        result = xsh.Screen.WaitForString('Please enter 6 digits')
        xsh.Screen.Send(str(my_token) + '\r')
        result = xsh.Screen.WaitForString('Opt>')
        xsh.Session.Sleep(100)
        xsh.Screen.Send(str(IP) + '\r')
        xsh.Session.Sleep(100)
        xsh.Screen.Send('\r')

        xsh.Session.Sleep(100)
        result = xsh.Screen.WaitForString(' ~]$ ')
        #xsh.Screen.Send('sudo su -\rsu - dig\r')
        #xsh.Session.Sleep(100)
        #result = xsh.Screen.WaitForString(' ~]$ ')
        xsh.Screen.Clear()
Example #18
0
 def test_validating_invalid_totp_for_same_secret(self):
     """
     Test case when the same secret is used, but the token differs
     """
     secret = b'MFRGGZDFMZTWQ2LK'
     with timecop.freeze(time.time()):
         self.assertFalse(valid_totp(get_totp(secret) + 1, secret))
Example #19
0
def get_otp(Ph_number, chat_id):
    my_secret = base64.b32encode(str(chat_id))
    #my_secret = 'MFRGGZDFMZTWQ2LK'
    my_token = otp.get_totp(my_secret, interval_length=300)
    msg = "Your One-Time-Password is " + str(
        my_token) + ". It will be valid for 3 minutes."
    phn_no = Ph_number
    sendsmses(phn_no, str(msg))
Example #20
0
    def test_validating_totp_with_a_window(self):
        """
        validate if a totp token falls within a certain window
        """
        secret = b'MFRGGZDFMZTWQ2LK'
        totp = get_totp(secret=secret, clock=(int(time.time()-30)))
        self.assertFalse(valid_totp(totp,secret))
        self.assertTrue(valid_totp(totp,secret,window=1))

        totp = get_totp(secret=secret, clock=(int(time.time()+30)))
        self.assertFalse(valid_totp(totp,secret))
        self.assertTrue(valid_totp(totp,secret,window=1))

        totp = get_totp(secret=secret, clock=(int(time.time()-59)))
        self.assertFalse(valid_totp(totp,secret))
        self.assertFalse(valid_totp(totp,secret,window=1))
        self.assertTrue(valid_totp(totp,secret,window=2))
Example #21
0
 def test_login_valid_mfa_login(self):
     """Tests that login with mfa works correctly."""
     # Register a user
     response = self.app.get('/register', follow_redirects=True)
     soup = beautifulsoup(response.data, 'html.parser')
     csrf_token = soup.find_all('input', id='csrf_token')[0]['value']
     response = self.register(uname='temp1234',
                              pword='temp1234',
                              csrf_token=csrf_token)
     self.assertEqual(response.status_code, 200)
     soup = beautifulsoup(response.data, 'html.parser')
     results = soup.find_all(id='success')
     self.assertGreater(len(results), 0, "No flash messages received")
     self.assertTrue(any("Registration success" in s.text for s in results))
     # Login without mfa
     csrf_token = soup.find_all('input', id='csrf_token')[0]['value']
     response = self.login(uname='temp1234',
                           pword='temp1234',
                           mfa='',
                           csrf_token=csrf_token)
     self.assertEqual(response.status_code, 200)
     # Go to account page
     response = self.app.get('/account', follow_redirects=True)
     soup = beautifulsoup(response.data, 'html.parser')
     csrf_token = soup.find_all('input', id='csrf_token')[0]['value']
     # Start MFA setup
     response = self.update_account(mfa_enabled=True, csrf_token=csrf_token)
     soup = beautifulsoup(response.data, 'html.parser')
     csrf_token = soup.find_all('input', id='csrf_token')[0]['value']
     self.assertEqual(response.status_code, 200)
     # Confirm MFA setup
     response = self.mfa_confirm(mfa_confirm=True, csrf_token=csrf_token)
     soup = beautifulsoup(response.data, 'html.parser')
     # Check that mfa was stored
     with self.base_app.app_context():
         mfa_stored = MFA.query.filter_by(username='******').first()
         self.assertFalse(mfa_stored is None)
         user_stored = Users.query.filter_by(username='******').first()
         self.assertTrue(user_stored.mfa_registered)
     # Now logout
     response = self.logout()
     self.assertEqual(response.status_code, 200)
     # And try to login with mfa
     response = self.app.get('/login', follow_redirects=True)
     soup = beautifulsoup(response.data, 'html.parser')
     csrf_token = soup.find_all('input', id='csrf_token')[0]['value']
     with self.base_app.app_context():
         mfa_stored = MFA.query.filter_by(username='******').first()
         mfa_token = onetimepass.get_totp(mfa_stored.mfa_secret)
         response = self.login(uname='temp1234',
                               pword='temp1234',
                               mfa=mfa_token,
                               csrf_token=csrf_token)
     self.assertEqual(response.status_code, 200)
     soup = beautifulsoup(response.data, 'html.parser')
     results = soup.find_all(id='result')
     self.assertGreater(len(results), 0, "No flash messages received")
     self.assertTrue(any("Login success" in s.text for s in results))
Example #22
0
    def test_validating_totp_with_a_window(self):
        """
        validate if a totp token falls within a certain window
        """
        secret = b'MFRGGZDFMZTWQ2LK'
        with timecop.freeze(time.time()):
            totp = get_totp(secret=secret, clock=(int(time.time() - 30)))
            self.assertFalse(valid_totp(totp, secret))
            self.assertTrue(valid_totp(totp, secret, window=1))

            totp = get_totp(secret=secret, clock=(int(time.time() + 30)))
            self.assertFalse(valid_totp(totp, secret))
            self.assertTrue(valid_totp(totp, secret, window=1))

            totp = get_totp(secret=secret, clock=(int(time.time() - 60)))
            self.assertFalse(valid_totp(totp, secret))
            self.assertFalse(valid_totp(totp, secret, window=1))
            self.assertTrue(valid_totp(totp, secret, window=2))
Example #23
0
File: cli.py Project: bussiere/mfa
def otp(key):
    """Generate a one-time password using TOTP."""
    password = keyring.get_password(__name__, key)
    try:
        totp = onetimepass.get_totp(password)
    except Exception as e:
        click.echo(e)
    else:
        click.echo(totp)
Example #24
0
def otp(key):
    """Generate a one-time password using TOTP."""
    password = keyring.get_password(__name__, key)
    try:
        totp = onetimepass.get_totp(password, as_string=True)
    except Exception as e:
        click.echo(e)
    else:
        click.echo(totp)
Example #25
0
 def test_generating_current_totp_and_validating(self):
     """
     Check if TOTP generated for current time is the same as manually
     created HOTP for proper interval
     """
     secret = b'MFRGGZDFMZTWQ2LK'
     hotp = get_hotp(secret=secret, intervals_no=int(time.time())//30,)
     totp = get_totp(secret=secret)
     self.assertEqual(hotp, totp)
Example #26
0
    def get_otp_window(self, user_name):
        assert (self.ByUsers.has_key(str(user_name)))
        IntLen = 15  # don't change
        window_bi_size = 10  # should be configurable later
        back_in_time = 0  #(36/60)*(60*60) #patch!! in secs
        otp_window = [otp.get_totp(self.PrivateKeys[str(user_name)], clock=(time.time() - back_in_time - d), as_string=True, \
         interval_length=IntLen) for d in range(-IntLen * window_bi_size, IntLen * window_bi_size + 1, IntLen)]

        return otp_window
Example #27
0
    def test_register_and_login(self):
        # register a new account
        g = Gender.query.filter_by(name='Male').first()
        response = self.client.post('/auth/register',
                                    data={
                                        'email': '*****@*****.**',
                                        'name': 'john',
                                        'password': '******',
                                        'password_cfm': 'cat',
                                        'gender': g.id
                                    })
        self.assertEqual(response.status_code, 302)

        # login with the new account
        response = self.client.post('/auth/login',
                                    data={
                                        'email': '*****@*****.**',
                                        'password': '******'
                                    })
        self.assertEqual(response.status_code, 302)
        url = response.headers.get('Location')
        self.assertIsNotNone(url)

        # redirect to 2FA
        response = self.client.get(url)
        self.assertTrue('Authentication Code' in response.get_data(
            as_text=True))

        # submit Authentication Code
        user = User.query.filter_by(email='*****@*****.**').first()
        totp = onetimepass.get_totp(user.otp_secret)
        response = self.client.post(url,
                                    data={'token': totp},
                                    follow_redirects=True)

        self.assertEqual(response.status_code, 200)
        self.assertTrue('<h1>Hello, john!</h1>' in response.get_data(
            as_text=True))
        self.assertTrue(
            '<h3>You have <b>NOT</b> confirmed your account yet.</h3>' in
            response.get_data(as_text=True))

        # send a confirmation token
        token = user.generate_confirmation_token()
        response = self.client.get('/auth/confirm/{}'.format(token),
                                   follow_redirects=True)
        user.confirm(token)
        self.assertEqual(response.status_code, 200)
        self.assertTrue('You have confirmed your account' in response.get_data(
            as_text=True))

        # log out
        response = self.client.get('/auth/logout', follow_redirects=True)
        self.assertEqual(response.status_code, 200)
        self.assertTrue('You have been logged out' in response.get_data(
            as_text=True))
Example #28
0
 def create_time_based_token(self):
     my_secret = self.organization.secretKey
     if my_secret is None:
         raise Exception("Error during creating time based token. The secret key of the Apigee organization %s is empty" % (self.organization.organizationName))
     print("Creating the time-based token")
     my_token = otp.get_totp(my_secret)
     self.token = my_token
     if len(str(my_token)) == 5:
         my_token = "0%s" % my_token
     return my_token
Example #29
0
 def login2(self):
     sleep(2)
     my_token = otp.get_totp(self.secret)
     data = {'step': '2', 'cktime': '0', 'oneCode': str(my_token)}
     login = self.s.post(self.loginurl, headers=self.headers, data=data)
     self.cookies = login.cookies
     login = login.text.encode('iso-8859-1').decode('gbk')
     if login.find('您已經順利登錄') != -1:
         res = '已經順利登錄'
         self.s.close()
         return res
Example #30
0
 def login2(self):
     sleep(2)
     my_token = otp.get_totp(self.secret)
     data = {'step': '2', 'cktime': '0', 'oneCode': str(my_token)}
     login = self.s.post(self.loginurl, headers=self.headers, data=data)
     self.cookies = login.cookies
     login = login.content.decode('utf-8', 'ignore')
     if login.find('您已經順利登錄') != -1:
         res = '已經順利登錄'
         self.s.close()
         return res
Example #31
0
 def totp_code(self, secret):
     """
     note - this must be called from the yielded method, not the yielding one
     if it's called from the yielding method, all the codes will be the same
     """
     global MFA_CODE
     # need to make sure we have a unique code
     new_code = otp.get_totp(secret)
     code_str = "%06d" % new_code  # need to make sure it's a 0-padded str
     num_tries = 0
     while code_str == MFA_CODE and num_tries < 12:
         time.sleep(10)
         num_tries += 1
         new_code = otp.get_totp(secret)
         code_str = "%06d" % new_code  # need to make sure it's 0-padded
     if num_tries >= 12:
         # if we timed out, return the old code but don't update the global
         return code_str
     MFA_CODE = code_str
     return code_str
 def totp_code(self, secret):
     """
     note - this must be called from the yielded method, not the yielding one
     if it's called from the yielding method, all the codes will be the same
     """
     global MFA_CODE
     # need to make sure we have a unique code
     new_code = otp.get_totp(secret)
     code_str = "%06d" % new_code  # need to make sure it's a 0-padded str
     num_tries = 0
     while code_str == MFA_CODE and num_tries < 12:
         time.sleep(10)
         num_tries += 1
         new_code = otp.get_totp(secret)
         code_str = "%06d" % new_code  # need to make sure it's 0-padded
     if num_tries >= 12:
         # if we timed out, return the old code but don't update the global
         return code_str
     MFA_CODE = code_str
     return code_str
Example #33
0
 def test_generating_current_totp_as_string(self):
     """
     Check if the TOTP also works seamlessly when generated as string
     """
     secret = b'MFRGGZDFMZTWQ2LK'
     hotp = get_hotp(
         secret=secret,
         intervals_no=int(time.time())//30,
         as_string=True,
     )
     totp = get_totp(secret=secret, as_string=True)
     self.assertEqual(hotp, totp)
Example #34
0
def okta_auth(s, domain, username, password, totp_secret, okta_mfa_default_factor_type):
    """
    Factors https://developer.okta.com/docs/api/resources/factor_admin/#factor-model
    """

    r = check(s.post(f'https://{domain}/api/v1/authn', json={'username': username, 'password': password})).json()

    if r['status'] == 'MFA_ENROLL':
        print('Please enroll in multi-factor authentication before using this tool')
        exit(1)

    if r['status'] == 'MFA_REQUIRED':
        factors = r['_embedded']['factors']

        # if only one factor enabled, use it
        if len(factors) == 1:
            factor = factors[0]
        else:
            # if multiple, use the "okta_mfa_default_factor_type"
            try:
                factor = [x for x in factors in x['factorType'] == okta_mfa_default_factor_type][0]
            except IndexError:
                factor_types = set([x['factorType'] for x in okta_mfa_default_factor_type])
                print(f"You have {len(factor_types)} factors enabled in Okta: {factor_types}.\n"
                      f"Please set the --okta-mfa-default-factor-type flag. "
                      f"Currently set or defaulted to: {okta_mfa_default_factor_type}")
                exit(1)

        if factor['factorType'] == 'push':
            url = factor['_links']['verify']['href']
            while True:
                r = check(s.post(url, json={'stateToken': r['stateToken']})).json()
                print('Push notification sent; waiting for your response', file=sys.stderr)
                if r['status'] != 'MFA_CHALLENGE':
                    break
                assert r['factorResult'] == 'WAITING'
                time.sleep(3)
            assert r['status'] == 'SUCCESS'
            return r['sessionToken']
        elif factor['factorType'] == 'token:software:totp':
            url = factor['_links']['verify']['href']
            if totp_secret:
                otp_value = onetimepass.get_totp(totp_secret)
            else:
                print('Enter your multifactor authentication token: ', file=sys.stderr, end='')
                otp_value = input()
            r = check(s.post(url, json={'stateToken': r['stateToken'], 'answer': otp_value})).json()
            assert r['status'] == 'SUCCESS'
            return r['sessionToken']
        elif factor['factorType'] in ['sms', 'question', 'call', 'token']:
            factor_type = factor['factorType']
            raise NotImplementedError(' factor not implemented')
Example #35
0
def run():
    pass_entry = get_pass_entry(sys.argv[1])

    # Remove the trailing newline or any other custom data users might have
    # saved:
    pass_entry = pass_entry.splitlines()
    secret = pass_entry[0]

    digits = get_length(pass_entry)
    token = onetimepass.get_totp(secret, as_string=True, token_length=digits)

    print(token.decode())
    copy_to_clipboard(token)
Example #36
0
    def test_generating_totp_at_specific_clock(self):
        """
        check if the totp can be generated for a specific clock
        which is basically the same as hotp
        """
        secret = b'MFRGGZDFMZTWQ2LK'
        with timecop.freeze(time.time()):
            hotp = get_hotp(
                secret=secret,
                intervals_no=int(time.time()) // 30,
            )
            totp = get_totp(secret=secret, clock=None)
            self.assertEqual(hotp, totp)

            # hotp intervals minus 1
            hotp = get_hotp(
                secret=secret,
                intervals_no=int(time.time()) // 30 - 1,
            )
            # totp 30 seconds in the past
            totp = get_totp(secret=secret, clock=(int(time.time()) - 30))
            self.assertEqual(hotp, totp)
Example #37
0
 def test_generating_current_totp_as_string(self):
     """
     Check if the TOTP also works seamlessly when generated as string
     """
     secret = b'MFRGGZDFMZTWQ2LK'
     with timecop.freeze(time.time()):
         hotp = get_hotp(
             secret=secret,
             intervals_no=int(time.time()) // 30,
             as_string=True,
         )
         totp = get_totp(secret=secret, as_string=True)
         self.assertEqual(hotp, totp)
Example #38
0
 def test_generating_current_totp_and_validating(self):
     """
     Check if TOTP generated for current time is the same as manually
     created HOTP for proper interval
     """
     secret = b'MFRGGZDFMZTWQ2LK'
     with timecop.freeze(time.time()):
         hotp = get_hotp(
             secret=secret,
             intervals_no=int(time.time()) // 30,
         )
         totp = get_totp(secret=secret)
         self.assertEqual(hotp, totp)
Example #39
0
	def handlechat(bot, update, args):
		if userdata['data']['user']==update.message.from_user.id:
			global deleteonclick
			if deleteonclick:
				try:
					del userdata['secretkeys'][update.message.text]
					deleteonclick=False;
					list(bot, update)
				except:
					print("Key doesn't exist.")
			else:
				reply=otp.get_totp(userdata['secretkeys'][update.message.text])
				bot.sendMessage(chat_id=update.message.chat_id, text=reply)
Example #40
0
    def post_fund(self, fund_type, order_id, user_id, income, notes=''):
        status = 'unknown'

        try:
            config = self.application.config.get('fund')
            secret = config.get('secret')
            operator = config.get('operator')
            url = config.get('url')

            token = otp.get_totp(secret)

            sign0 = signature(
                '{user_id}{order_id}{income}{operator}{token}'.format(
                    user_id=user_id,
                    order_id=order_id,
                    income=income,
                    operator=operator,
                    token=token))

            body = json.dumps({
                'type': fund_type,
                'order_id': order_id,
                'user_id': user_id,
                'income': income,
                'operator': operator,
                'token': token,
                'notes': notes,
                'sign': sign0
            })

            http_client = AsyncHTTPClient()

            log_request.info("FUND_URL http://%s/admin/fund", url)
            log_request.info("FUND_BODY %s", body)

            response = yield http_client.fetch(
                url,
                method='POST',
                body=body,
                headers={'Content-Type': 'application/json'},
                request_timeout=120)

            if response.code == 200:
                msg = json.loads(response.body.decode())
                status = msg.get('status')

        except:
            log_request.exception("ERROR ADD FUND")
            status = 'unknown'

        return status
 def create_time_based_token(self):
     danger_time_interval_in_seconds = 7
     my_secret = self.organization.secretKey
     if my_secret is None:
         raise Exception(
             "Error during creating time based token. The secret key of the Apigee organization %s is empty"
             % self.organization.organizationName)
     print("Creating the time-based token")
     my_token = otp.get_totp(my_secret)
     my_token = make_token_six_digits(my_token)
     self.token = my_token
     # Let's verify if the token is still valid after some seconds and we are nog switching to new interval
     my_token2 = otp.get_totp(my_secret,
                              clock=(int(time.time()) +
                                     danger_time_interval_in_seconds))
     my_token2 = make_token_six_digits(my_token2)
     if my_token == my_token2:
         return my_token
     else:
         print("Waiting for the next time interval")
         time.sleep(danger_time_interval_in_seconds)
         self.token = my_token2
         return my_token2
def login_totp():
    _id = request.forms.get('nickname')
    passw = request.forms.get('password')
    resul = db.users.find_one({"_id":_id}, {"password":1, "name":1, "salt":1, "secret":1})
    if(resul != None):
        salt = resul["salt"]
        old_pass = resul["password"]
        old_passw_in = hash_password(passw, salt)
        if(old_passw_in == old_pass):
            toptp=otp.get_totp(resul["secret"],as_string=True)
            if(otp.valid_toptp(toptp,resul["secret"])):
                return "Bienvenido "+ resul["name"]
            else: return "Usuario o contrasenia inconrrectos(totp)"
        else: return "Usuario o contrasenia inconrrectos(passw)"
    else: return "Usuario o contrasenia incorrectos(user)"
Example #43
0
def post():
    token = otp.get_totp('UWFR72OSH6B4CZCE')

    body = urllib.parse.urlencode({
        'user_id': 100001,
        'operator': 'wangtao',
        'value': 1,
        'notes': 'хКа',
        'token': token
    })

    http_client = HTTPClient()
    response = http_client.fetch('http://localhost:8899/admin/book',
                                 method='POST',
                                 body=body)
    print('OUTPUT=' + response.body.decode('utf8'))
    http_client.close()
Example #44
0
def generate_token(path, seconds=0):
    """Generate the TOTP token for the given path and the given time offset"""
    import time
    clock = time.time() + float(seconds)

    pass_entry = get_pass_entry(path)

    # Remove the trailing newline or any other custom data users might have
    # saved:
    pass_entry = pass_entry.splitlines()
    secret = normalize_secret(pass_entry[0])

    digits = get_length(pass_entry)
    token = onetimepass.get_totp(secret, as_string=True, token_length=digits,
                                 clock=clock)

    print(token.decode())
    copy_to_clipboard(token)
    def test_admins_twofactor_verify_valid(self, loggedin_client):
        test_admin = Admins().from_json({
            'username': '******',
            'password': '******',
            'name': 'Test Admin'
        })
        test_admin.generate_otp_secret()
        test_admin.otp_active = 1

        db.session.add(test_admin)
        db.session.commit()

        secret = test_admin.otp_secret
        token = onetimepass.get_totp(secret)
        assert test_admin.verify_totp(token)
        rv = loggedin_client.post("/api/v1/admins/{0}/twofactor/verify".format(test_admin.id), data=json.dumps({"code": token}))
        try:
            json.loads(rv.data.decode('utf-8'))
        except:
            assert False, "Not json"
        assert rv.status_code == 200
Example #46
0
#!/usr/bin/env python
# rikih

import onetimepass as otp

secret_key = raw_input("Secret key: ").strip()
my_token = otp.get_totp(secret_key)

print ""
print "OTP: " + str(my_token)

Example #47
0
    def show(self, name):
        if name not in self._secrets:
            raise Error("No such secret (%s)" % name)

        return otp.get_totp(self._secrets[name])
 def get_totp(self, name):
     if name not in self.config.sections():
         raise ValueError('Item {} does not exists'.format(name))
     key = self.config.get(name, 'key')
     return otp.get_totp(key)
Example #49
0
    parser.description = "Prints the TOTP auth code for the given secret. Can be either the raw secret string or a otpauth:// URI; the script will attempt to auto-detect which is given."
    parser.usage = "%prog [options] secret OR %prog [options] --stdin < secret.txt"
    parser.epilog = "Copyright (c) Mark Embling 2013"

    parser.add_option("--stdin", dest="stdin", 
                      action="store_true", default=False,
                      help="Read the secret (raw secret or otpauth:// URI) from stdin [default: %default]")
    parser.add_option("--type", dest="type", 
                      choices=["TOTP", "HOTP"], default="TOTP", 
                      help="Token type (HOTP or TOTP). If a URI is provided, the type will be determined from there. [default: %default]")
    parser.add_option("--count", dest="count", 
                      type="int", default=1,
                      help="Counter for HOTP [default: %default]")
    # parser.add_option("-d", "--digits", dest="digits", 
    #                   choices=['6','8'], default='6',
    #                   help="Number of digits to display (6 or 8) [default: %default]")

    (options, args) = parser.parse_args()

    # Get the secret and type
    data = _get_data(options, args)
    (secret, type_) = _get_secret(data)
    if type_ is None:
        type_ = options.type

    # Get the token and print
    if type_.upper() == "HOTP":
        print(otp.get_hotp(secret, intervals_no=options.count, as_string=True))
    else:
        print(otp.get_totp(secret, as_string=True))
Example #50
0
def setupclass_helper(params, auth=None, xsrf=None, params_extra=None):
    session = None

    if auth:
        if not auth.get("type", None):
            LOG.error("Auth `type` not supplied.")
            sys.exit(1)
        if auth["type"] == "firma-password":
            credentials_path = auth.get("credentials", None)
            if not credentials_path:
                LOG.error("No credentials path supplied.")
                sys.exit(1)

            credentials_path = expand_params(
                credentials_path, params_extra)

            credentials_path = os.path.join(
                os.path.dirname(os.path.realpath(CONF_PATH)),
                credentials_path
            )

            st = os.stat(credentials_path)
            if st.st_mode & stat.S_IROTH or st.st_mode & stat.S_IWOTH:
                LOG.error("%s: Credential paths may not be "
                          "readable or writable by `other`.",
                          credentials_path)
                sys.exit(1)

            with open(credentials_path, "r", encoding="utf-8") as fp:
                credentials = json.load(fp)

            account = auth.get("account", None)
            if not account:
                LOG.error("No account name supplied.")
                sys.exit(1)

            if account not in credentials:
                LOG.error("Account name %s not found in credentials.", account)
                sys.exit(1)

            account_data = credentials[account]

            email = account_data.get("email", None)
            user_id = account_data.get("user_id", None)
            password = account_data.get("password", None)
            onetime_secret = account_data.get("onetime_secret", None)

            if not (email or user_id):
                LOG.error("`email` or `user_id` not supplied in credentials.")
                sys.exit(1)

            if not password:
                LOG.error("`password` not supplied in credentials.")
                sys.exit(1)

            if not onetime_secret:
                LOG.error("`onetime_secret` not supplied in credentials.")
                sys.exit(1)

            host = params.get("host", None)
            if host == "$HOST":
                host = os.getenv(ENV_HOST, None)

            url = auth.get("url", None)
            if not url:
                LOG.error("No URL supplied.")
                sys.exit(1)

            url = params_expand_url(params, url)

            data = {
                "password": password,
                "token": get_totp(onetime_secret),
            }

            if email:
                data["email"] = email

            if user_id:
                data["user_id"] = user_id

            session = requests.Session()  # Close in `teardownclass_helper`
            try:
                r = session.get(url, data=data)
            except requests.exceptions.ConnectionError:
                LOG.error("Could not connect to host.")
                sys.exit(1)

            if r.status_code != 200:
                raise AuthenticationException(
                    "Error: %s login failed (%d)." %
                    (auth["type"], r.status_code))

            session.verify = VERIFY
        else:
            LOG.error("Unknown auth type `%s`.", auth["type"])
            sys.exit(1)

    @classmethod
    def func(cls):
        HttpTest.setUpClass()
        cls.session = session
        cls.xsrf = xsrf
        warnings.simplefilter("ignore", ResourceWarning)

    return func
Example #51
0
def main():
    args = docopt.docopt(__doc__, version='2factorcli 0.0.1')

    # Use agents?
    use_agent = True
    if args['--disable-agent']:
        use_agent = False

    # Unwritten defaults
    if args['<description>'] is None:
        args['<description>'] = ''
    if args['<padding>'] is None:
        args['<padding>'] = 6

    # Find the vault path
    vault_path = os.path.abspath(os.path.expanduser(args['--vault']))

    # Load secrets into memory
    secrets = load_vault(vault_path, use_agent)

    ###########################################################################
    # Commands!
    ###########################################################################

    if args['list']:
        data = "Name Description\n"
        data += "---- -----------\n"
        for name in sorted(secrets.keys()):
            data += "%s %s\n" % (name, secrets[name]['description'])
        print(columnize(data))
        sys.exit(0)

    ###########################################################################

    if args['add']:
        if args['<secret>'] is None:
            print("<secret> is required!")
            sys.exit(1)

        if args['<name>'] is None:
            print("<name> is required!")
            sys.exit(1)

        secrets[args['<name>']] = {
            'secret': args['<secret>'],
            'description': args['<description>'],
            'name': args['<name>'],
            'padding': args['<padding>'],
            }

        update_vault(secrets,
                     vault_path,
                     fingerprint=args['--fingerprint'],
                     use_agent=use_agent)
        sys.exit(0)

    ###########################################################################

    if args['rename']:
        secrets[args['<newname>']] = secrets[args['<name>']]
        del secrets[args['<name>']]
        update_vault(secrets,
                     vault_path,
                     fingerprint=args['--fingerprint'],
                     use_agent=use_agent)
        sys.exit(0)

    ###########################################################################

    if args['get']:
        if args['<name>'] not in secrets:
            print('%s is not a known site!' % args['<name>'])
            sys.exit(1)
        token = onetimepass.get_totp(secrets[args['<name>']]['secret'])
        token = str(token).zfill(secrets[args['<name>']]['padding'])
        print(token)
        sys.exit(0)

    ###########################################################################

    if args['set-description']:
        if args['<name>'] not in secrets:
            print('%s is not a known site!' % args['<name>'])
            sys.exit(1)
        secrets[args['<name>']]['description'] = args['<description>']
        update_vault(secrets,
                     vault_path,
                     fingerprint=args['--fingerprint'],
                     use_agent=use_agent)
        sys.exit(0)

    ###########################################################################

    if args['set-padding']:
        if args['<name>'] not in secrets:
            print('%s is not a known site!' % args['<name>'])
            sys.exit(1)
        secrets[args['<name>']]['padding'] = args['<padding>']
        update_vault(secrets,
                     vault_path,
                     fingerprint=args['--fingerprint'],
                     use_agent=use_agent)
        sys.exit(0)

    ###########################################################################

    print("Command is required!")
    sys.exit(1)
Example #52
0
    res = requests.get("https://bitskins.com/api/v1/get_price_data_for_items_on_sale/?api_key="+api
                         +"&code="+str(my_token)+"&names="+item)
    print res.url
    item_info_temp = json.loads(res.content)

    if item_info_temp["data"]["items"][0]["total_items"] == 0:
        print "Could not get item: " + item
        print "Maybe it does not exists or theres no data for the item."
        return False
    else:
        print "Lowest price for item "+ item + " --> " + str(item_info_temp["data"]["items"][0]["lowest_price"])
        return item_info_temp

item_temp = raw_input('What item(s) do you want to check? ("all" for all items on file) ')
if item_temp != 'all':
    my_token = onetimepass.get_totp(my_secret)
    item_history = get_price_history(item_temp, my_token)
    print r.set(item_temp+"_bitskins", item_history)

else:
    with open('utils/csgoitems.txt', 'r') as item_file:
        file_items_name = [line.rstrip() for line in item_file]
        for item in file_items_name:
            my_token = onetimepass.get_totp(my_secret)
            if "Case Key" in item:
                item_history = get_price_history(item, my_token)
                if item_history != False:
                    print r.set(item+"_bitskins", item_history)
                else:
                    print 'failed getting price history for ' + item
            else:
Example #53
0
def get_auth():
  return md5(primary_key + str(otp.get_totp(secret=otp_secret)))
Example #54
0
import os,sys
import onetimepass as otp
cwd = sys.path[0]
f = open(cwd + "/authentication.code.private", 'r')
my_secret = f.read().replace('\n','')
f.close()

result = str(otp.get_totp(my_secret))

while (len(result) < 6):
	result = '0' + result

print result
Example #55
0
def get_otp(otp_secret):
    """ common commands """
    return otp.get_totp(otp_secret, as_string=True).decode()
Example #56
0
import os
import onetimepass as otp

my_secret = "KJBDGZKJJIWVSVKZ"
print otp.get_totp(my_secret)
Example #57
0
def get_code():
    return str(otp.get_totp(my_secret))
Example #58
0
def twofa_code(args):
    "Returns a 2 factor authentication code."

    creds = new_credentials_config()

    print(otp.get_totp(creds.corp.seed))
Example #59
0
def totp(device, deviceId, secret):
    token = otp.get_totp(secret)
    device.write_number(deviceId, value=token)