ungleich-otp/ungleichotpclient.py

82 lines
2.4 KiB
Python
Raw Normal View History

2018-11-18 14:41:47 +00:00
import pyotp
import json
2018-12-24 19:28:21 +00:00
import urllib.request
import urllib.error
2018-11-18 14:41:47 +00:00
2018-12-24 19:28:21 +00:00
class UngleichOTPClient(object):
2018-11-18 14:41:47 +00:00
token_name = 'token'
name_name = 'name'
realm_name = 'realm'
2018-12-24 19:28:21 +00:00
def __init__(self, name, realm, seed, serverurl):
2018-11-18 14:41:47 +00:00
self.name = name
self.realm = realm
self.seed = seed
self.serverurl = serverurl
2018-12-24 19:28:21 +00:00
def verify(self, name, realm, token):
2018-11-18 14:41:47 +00:00
to_send = {}
# Client credentials to be verified
2018-12-24 19:28:21 +00:00
to_send['verifyname'] = name
to_send['verifyrealm'] = realm
to_send['verifytoken'] = token
2018-11-18 14:41:47 +00:00
# Our credentials
2018-12-24 19:28:21 +00:00
to_send['token'] = pyotp.TOTP(self.seed).now()
2018-11-18 14:41:47 +00:00
to_send['name'] = self.name
to_send['realm'] = self.realm
data = json.dumps(to_send).encode("utf-8")
2018-12-24 19:28:21 +00:00
req = urllib.request.Request(url=self.serverurl,
2018-11-18 14:41:47 +00:00
data=data,
headers={'Content-Type': 'application/json'},
method='POST')
f = urllib.request.urlopen(req)
2018-12-24 19:28:21 +00:00
if f.status == 200:
return True
return False
if __name__ == '__main__':
import argparse
import os
import sys
parser = argparse.ArgumentParser(description='ungleichotp-client')
parser.add_argument('-n', '--name', help="Name (for verification)", required=True)
parser.add_argument('-r', '--realm', help="Realm (for verification)", required=True)
2018-12-24 19:46:54 +00:00
g = parser.add_mutually_exclusive_group(required=True)
g.add_argument('--token', help="Token (for verification)")
g.add_argument('--seed', help="Seed (for verification)")
2018-12-24 19:28:21 +00:00
args = parser.parse_args(sys.argv[1:])
UNGLEICHOTP={}
for env in ['UNGLEICHOTPREALM', 'UNGLEICHOTPNAME', 'UNGLEICHOTPSEED', 'UNGLEICHOTPSERVER' ]:
if not env in os.environ:
raise Exception("Required environment variable missing: {}".format(env))
2018-11-18 14:41:47 +00:00
2018-12-24 19:28:21 +00:00
client = UngleichOTPClient(os.environ['UNGLEICHOTPNAME'],
os.environ['UNGLEICHOTPREALM'],
os.environ['UNGLEICHOTPSEED'],
os.environ['UNGLEICHOTPSERVER'])
2018-11-18 14:41:47 +00:00
2018-12-24 19:46:54 +00:00
if args.seed:
token = pyotp.TOTP(args.seed).now()
else:
token = args.token
2018-11-18 13:33:30 +00:00
2018-12-24 19:28:21 +00:00
try:
2018-12-24 19:46:54 +00:00
if client.verify(args.name, args.realm, token) == True:
2018-12-24 19:30:12 +00:00
print("Verify ok")
2018-12-24 19:28:21 +00:00
except urllib.error.HTTPError as e:
print("Failed to verify: {}".format(e))