-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathduo.py
executable file
·245 lines (200 loc) · 7.77 KB
/
duo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/env python3
"""Duo HOTP
Usage:
duo_hotp new <qr_url> [-s <secret.json>]
duo_hotp next [-s <secret.json>]
duo_hotp -h | --help
Options:
-h --help Show this screen.
-s PATH provide PATH of secret.json file
Large parts of code copied from
https://github.com/simonseo/nyuad-spammer/tree/master/spammer/duo
"""
import base64
import inspect
import json
import os
from os.path import abspath, dirname, isfile, join
from urllib import parse
import pyotp
import requests
from Crypto.PublicKey import RSA
from docopt import docopt
def b32_encode(key):
return base64.b32encode(key.encode("utf-8"))
def find_secret(path=None, must_exist=True):
"""use input, env, or script directory
>>> os.path.basename(find_secret(must_exist=False)) # default
'secrets.json'
>>> os.environ["DUO_SECRETFILE"] = "a/b"
>>> find_secret(must_exist=False) # env
'a/b'
>>> find_secret("foobar", False) # explicit
'foobar'
"""
if path is None and os.environ.get("DUO_SECRETFILE", None) is not None:
path = os.environ["DUO_SECRETFILE"]
if path is None:
bin_dir = dirname(abspath(inspect.stack()[0][1]))
path = join(bin_dir, "secrets.json")
if not isfile(path) and must_exist:
print(f"'{path}' does not exist!")
raise Exception("Cannot find secret json file")
return path
def qr_url_to_activation_url(qr_url):
"""Create request URL
>>> eg_url = 'https://blah.duosecurity.com/frame/qr?value=c53Xoof7cFSOHGxtm69f-YXBpLWU0Yzk4NjNlLmR1b3NlY3VyaXR5LmNvbQ'
>>> res = qr_url_to_activation_url(eg_url)
https://api-e4c9863e.duosecurity.com/push/v2/activation/c53Xoof7cFSOHGxtm69f?customer_protocol=1
"""
# get ?value=XXX
data = parse.unquote(qr_url.split("?value=")[1])
# first half of value is the activation code
code = data.split("-")[0].replace("duo://", "")
# second half of value is the hostname in base64
hostb64 = data.split("-")[1]
# Same as "api-e4c9863e.duosecurity.com"
host = base64.b64decode(hostb64 + "=" * (-len(hostb64) % 4))
host = host.decode("utf-8")
# this api is not publicly known
activation_url = f"https://{host}/push/v2/activation/{code}?customer_protocol=1"
print(activation_url)
return activation_url
def activate_params():
"""
Generate paramaters for activiating a device.
>>> p = activate_params()
>>> len(p['pubkey'])
450
"""
# publickey not public_key in python3-pycryptodomex-3.20.0 (Fedora 40)
# fix from @gsomlo, see
# https://github.com/WillForan/duo-hotp/issues/3#issuecomment-2176260202
# 'pip install pycryptodome==3.20.0' has both publickey and public_key
try:
pubkey = RSA.generate(2048).public_key().export_key("PEM").decode()
except AttributeError:
pubkey = RSA.generate(2048).publickey().exportKey("PEM").decode()
params = {
"pkpush": "rsa-sha512",
"pubkey": pubkey,
"jail broken": "false",
"Architecture": "arm64",
"Legion": "US",
"App_id": "com.duosecurity.duomobile",
"full_disk_encryption": "true",
"passcode_status": "true",
"platform": "Android",
"app_version": "3.49.0",
"app_build_number": "323001",
"version": "11",
"manufacturer": "unknown",
"language": "en",
"model": "Pixel 3a",
"security_patch_level": "2021-02-01",
}
return params
def activate_device(activation_url):
"""Activates through activation url and returns HOTP key"""
# --- Get response which will be a JSON of secret keys, customer names, etc
# --- Expected Response:
# {'response': {'hotp_secret': 'blahblah123', ...}, 'stat': 'OK'}
# --- Expected Error:
# {'code': 40403, 'message': 'Unknown activation code', 'stat': 'FAIL'}
params = activate_params()
response = requests.post(activation_url, params=params, timeout=300)
response_dict = json.loads(response.text)
if response_dict["stat"] == "FAIL":
raise Exception("Activation failed! Try a new QR/Activation URL")
print(response_dict)
hotp_secret = response_dict["response"]["hotp_secret"]
return hotp_secret
class HOTP:
"""read and write from json file to generate HMAC-based one time password
using pyotp
>>> if isfile('example.json'): os.unlink('example.json') # cleanup
HOTP can create and immedately use a secret
>>> hotp = HOTP('example.json', "7e1c0372fec015ac976765ef4bb5c3f3")
>>> isfile('example.json')
True
>>> hotp.count
0
>>> passcode = hotp.generate()
>>> hotp.count
1
But wont over write an existing file
>>> fail = HOTP('example.json', "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
Traceback (most recent call last):
...
Exception: Not overwritting existing file
Instead, reload the last settings
>>> hotp_again = HOTP('example.json')
>>> hotp_again.count
1
"""
def __init__(self, path, hotp_secret=None):
"""load for secret file
or if given a secret, make the file
"""
self.secret_file = path # where to save
self.count = None # number of hits on this secret
self.hotp_secret = None # like "7e1c0372fec015ac976765ef4bb5c3f3"
self.pyhotp = None # pyotp
# if we are initializing with a secret
# we should create a new file
if hotp_secret is not None:
self.init_secret(hotp_secret)
self.load_secret()
def init_secret(self, hotp_secret):
"""create file with 0 counter"""
if isfile(self.secret_file):
print(f"'{self.secret_file}' already exits. not overwriting!")
print(f"MANUALLY EDIT: counter to 0 and htop to {hotp_secret}")
raise Exception("Not overwritting existing file")
self.hotp_secret = hotp_secret
self.count = 0
self.save_secret()
def save_secret(self):
"""Save to secrets.json
hotp_secret should look like "7e1c0372fec015ac976765ef4bb5c3f3"
count should be an int"""
secrets = {"hotp_secret": self.hotp_secret, "count": self.count}
with open(self.secret_file, "w") as f:
json.dump(secrets, f)
def load_secret(self):
"""sets self.pyhotp to a pyotp.HOTP object using secret.json"""
with open(self.secret_file, "r") as f:
secret_dict = json.load(f)
self.count = secret_dict.get("count", -1)
self.hotp_secret = secret_dict.get("hotp_secret", None)
if self.count < 0 or self.hotp_secret is None:
print("Missing values in '{self.secret_file}")
raise Exception("Bad secret input")
encoded_secret = b32_encode(self.hotp_secret)
self.pyhotp = pyotp.HOTP(encoded_secret)
return self.pyhotp
def generate(self):
"generate and update counter in secret_file"
if self.pyhotp is None or self.count is None:
raise Exception("cannot generate without first loading a secret")
passcode = self.pyhotp.at(self.count)
self.count += 1
self.save_secret()
return passcode
def mknew(qr_url, secret_file):
"""load QR code, send activation request, generate first code"""
activation_url = qr_url_to_activation_url(qr_url)
hotp_secret = activate_device(activation_url)
print("HOTP Secret (B32):", b32_encode(hotp_secret))
hotp = HOTP(secret_file, hotp_secret)
print("first key")
print(hotp.generate())
if __name__ == "__main__":
args = docopt(__doc__, version="Duo HOTP 2021.01")
if args["new"]:
secret_file = find_secret(args["-s"], must_exist=False)
mknew(args["<qr_url>"], secret_file)
elif args["next"]:
secret_file = find_secret(args["-s"])
hotp = HOTP(secret_file)
print(hotp.generate())