-
Notifications
You must be signed in to change notification settings - Fork 0
/
dpa-acme2.py
executable file
·274 lines (243 loc) · 10.8 KB
/
dpa-acme2.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env python3
import re, sys, json, base64, copy, os, errno, subprocess, hashlib, time, argparse, textwrap
from OpenSSL import crypto
from urllib.request import Request, urlopen
from urllib.error import URLError
defaults = {
"CA": "https://acme-staging-v02.api.letsencrypt.org/directory"
}
moddir = os.path.abspath(os.path.dirname(sys.argv[0]) or '.')
def base64url(o):
if isinstance(o, dict):
o = json.dumps(o)
if isinstance(o, str):
o = o.encode('utf-8')
return base64.urlsafe_b64encode(o).replace(b"=", b"").decode('utf-8')
def JWK_Thumbprint(jwk):
sjwk = json.dumps(
{ 'e': jwk['e'], 'kty': jwk['kty'], 'n': jwk['n'] },
sort_keys=True, separators=(',', ':')
)
return base64url(hashlib.sha256(sjwk.encode('utf-8')).digest())
def int_to_bytes(x):
return x.to_bytes((x.bit_length() + 7) // 8, 'big')
class ChallengeSolver:
def __init__(self, ctype, exe, args=[], id_val=None, id_type='dns'):
self.ctype = ctype
self.args = args
self.id_val = id_val
self.id_type = id_type
if exe.find('/') == -1:
exe = os.path.join(moddir, 'challenge_solvers', ctype or 'any', exe)
self.exe = os.path.abspath(exe)
if not os.access(self.exe, os.X_OK):
raise OSError(errno.EPERM,'File "{}" isn\'t executable'.format(self.exe))
def solve(self, challenge, completition_func):
args = [self.exe] + self.args
proc = subprocess.Popen(args,stdout=subprocess.PIPE, stdin=subprocess.PIPE)
proc.stdin.write((json.dumps(challenge)+'\n').encode('utf-8'))
proc.stdin.flush()
line = proc.stdout.readline().decode('utf-8')
if line[:6] != 'ready ':
raise Exception("Challenge solver failed")
proc.stdout.close()
update = json.loads(line[6:])
try:
completition_func(challenge, update)
finally:
proc.stdin.close()
if proc.wait() != 0:
print("Process exited with non-zero exit code {}".format(args))
class ACME2:
def __init__(self, CA, account_key):
self.CA = CA
self.account_key = crypto.load_privatekey(crypto.FILETYPE_PEM, account_key)
ac_pub_numbers = self.account_key.to_cryptography_key().public_key().public_numbers()
self.jws_jwk = {
"kty": "RSA",
"e": base64url(int_to_bytes(ac_pub_numbers.e)),
"n": base64url(int_to_bytes(ac_pub_numbers.n))
}
self.nonce = None
self.account = None
self.account_url = None
self.contact = []
self.directory = json.loads(self.request(CA)[0])
def request(self, url, payload=None, headers={}):
if isinstance(payload, str):
payload = payload.encode('utf-8')
# print((url, payload, headers))
response = urlopen(Request(url, payload, headers))
if 'Replay-Nonce' in response.headers:
self.nonce = response.headers['Replay-Nonce']
return response.read().decode("utf-8"), response.status, response.headers
def newNonce(self):
self.nonce = urlopen(self.directory['newNonce']).headers['Replay-Nonce']
def requestJWS(self, url, payload=None):
if not self.nonce:
self.newNonce()
protected = {
"alg": "RS256",
"url": url
}
if url in [self.directory['newAccount'],self.directory['revokeCert']]:
protected["jwk"] = self.jws_jwk
else:
self.createAccount()
protected['kid'] = self.account_url
protected["nonce"] = self.nonce
request = {
"protected": base64url(protected),
"payload": base64url(payload) if payload != None else ""
}
request['signature'] = base64url(crypto.sign(self.account_key, (request['protected'] + '.' + request['payload']).encode('utf-8'), 'sha256'))
return self.request(url, json.dumps(request), {"Content-Type":"application/jose+json"})
def createAccount(self):
if not self.account_url:
payload = {"termsOfServiceAgreed": True}
if len(self.contact):
payload["contact"] = self.contact
account, status, headers = self.requestJWS(self.directory['newAccount'], payload)
self.account_url = headers['Location']
if account.strip(): # This should always happen
self.account = json.loads(account)
else: # But if not, we need to get it from the returned location field :(
self.account = json.loads(self.requestJWS(self.account_url,payload)[0])
return self.account
def makeOrder(self, domains):
payload = {
'identifiers': [ {'type':'dns', 'value': domain} for domain in domains ]
}
body, status, headers = self.requestJWS(self.directory['newOrder'],payload)
return json.loads(body), headers['Location']
def getAuthorization(self,url):
auth = json.loads(self.request(url)[0])
auth['url'] = url
return auth
def resolveChallenges(self, authorizations, challengeSolvers):
challengeSolvers = sorted( challengeSolvers,
key = lambda x: (x.id_val is None)*4 + (x.ctype is None)*2 + (x.id_type is None)
)
challenges = []
for authorization in authorizations:
if authorization['status'] == 'valid':
continue
aauth = copy.deepcopy(authorization)
chs = aauth['challenges']
del aauth['challenges']
def findMatch():
for solver in challengeSolvers:
for ch in chs:
if ( ( solver.id_val is None or aauth['identifier']['value'] == solver.id_val )
and ( solver.id_type is None or aauth['identifier']['type'] == solver.id_type )
and ( solver.ctype is None or ch['type'] == solver.ctype )
): return ( solver, {
"authorization": aauth,
"challenge": ch,
"account": {'jwk':self.jws_jwk, "jwk_thumb": JWK_Thumbprint(self.jws_jwk)}
})
raise Exception("No solver for any challenge of authorization found: {}".format(authorization))
challenges += [findMatch()]
for challenge in challenges:
challenge[0].solve(challenge[1],self.completeChallenge)
def completeChallenge(self, challenge, update):
url = challenge['challenge']['url']
challenge_result = json.loads(self.requestJWS(url,update)[0])
attemps = 10
while ( challenge_result['status'] in ['pending','processing'] ) and 0<--attemps:
time.sleep(1)
challenge_result = json.loads(self.request(url)[0])
if not attemps:
raise Exception("Timeout, challenge still pending or processing after about 10 seconds")
if challenge_result['status'] == 'invalid':
raise Exception('Challenge failed: '+challenge_result['error']['detail'])
if challenge_result['status'] != 'valid':
raise Exception('Unexpected challenge status: '+challenge_result['status'])
def getOrder(self, url):
return json.loads(self.requestJWS(url)[0])
def finalizeOrder(self, location, scsr, order=None):
csr = crypto.load_certificate_request(crypto.FILETYPE_PEM, scsr)
der = crypto.dump_certificate_request(crypto.FILETYPE_ASN1,csr)
attemps = 10
while ( (not order) or (order['status'] in ['pending','processing']) ) and 0<--attemps:
time.sleep(1)
order = self.getOrder(location)
if order['status'] != 'ready':
raise ValueError("Unexpected order status: "+order['status'])
order = json.loads(self.requestJWS(order['finalize'], {'csr': base64url(der)})[0])
attemps = 10
while order['status'] == 'ready' and 0<--attemps:
time.sleep(1)
order = self.getOrder(location)
return order
def getCertificat(self, scsr, challengeSolvers):
csr = crypto.load_certificate_request(crypto.FILETYPE_PEM, scsr)
domains = [x[1].decode('utf-8') for x in csr.get_subject().get_components() if x[0] == b'CN']
for extension in csr.get_extensions():
if extension.get_short_name() == b'subjectAltName':
domains += [san[4:] for san in extension._subjectAltNameString().split(', ') if san[:4] == 'DNS:']
order, location = self.makeOrder(domains)
if order['status'] == 'pending' or order['status'] == 'ready':
authorizations = [ self.getAuthorization(url) for url in order['authorizations'] ]
self.resolveChallenges(authorizations, challengeSolvers)
order = self.finalizeOrder(location, scsr, order)
if order['status'] != 'valid':
raise ValueError("Unexpected order status: "+order['status'])
return self.request(order['certificate'])[0].encode('utf-8')
def main(argv):
arg_parts = []
arg_part = []
for arg in argv:
if arg == '--':
arg_parts += [arg_part]
arg_part = []
else:
arg_part += [arg]
arg_parts += [arg_part]
del arg_part
solver_parser = argparse.ArgumentParser( allow_abbrev=False, prog='CHALLENGE_TYPE SOLVER_PROGRAM' )
solver_parser.add_argument("--identifier", help="The Identifier for which this solver shall be used, or any identifier. Usually a domain name.")
solver_parser.add_argument("--identifier-type", default="dns", help="The Identifier type. Usually a domain name.")
parser = argparse.ArgumentParser(
allow_abbrev = False,
epilog = '<challenge solver> ' + solver_parser.format_help(),
formatter_class = argparse.RawDescriptionHelpFormatter,
description = textwrap.dedent("""\
Small ACME v2 client. DPA-ACME2 doesn't implement any challenges by itself.
Just tell it which program it shall use to solve which challenge types for
which identifiers (usually domains). You can specify programs using an
absolute path, a relative path, or using it's name. If the program name is
used, it should be located in "challenge_solvers/${CHALLENGE_TYPE}/${PROGRAM_NAME}"
""")
)
parser.add_argument("--account-key", required=True, help="path to account private key")
parser.add_argument("--csr", required=True, help="path to certificate signing request")
parser.add_argument("--output", required=True, help="Where shall the certificate be written to?")
parser.add_argument("--ca", default=defaults['CA'], help="URL to ACME directory of certificate authority, default is Let's Encrypt")
parser.add_argument("--contact", action='append', help="A contact URI. Usually an E-Mail as mailto URI, like 'mailto:[email protected]'")
parser.usage = '\n '.join(textwrap.wrap(' '.join(parser.format_usage().split())[7:] + ' -- <challenge solver> [-- <challenge solver> ...]\n'))
args = parser.parse_args(arg_parts.pop(0))
if len(arg_parts) < 1 or True in [len(x)<2 for x in arg_parts]:
parser.print_help()
exit(2)
solvers = []
for params in arg_parts:
ctype = params.pop(0)
exe = params.pop(0)
sargs, remaining = solver_parser.parse_known_args(params)
solvers += [ChallengeSolver(ctype, exe, args=remaining, id_type=sargs.identifier_type, id_val=sargs.identifier)]
with open(args.account_key,'rb') as key:
acme = ACME2(args.ca, key.read())
acme.contact = args.contact or []
with open(args.csr,'rb') as csr:
certificate = acme.getCertificat(csr.read(), solvers)
with open(args.output,'wb') as output:
output.write(certificate)
if __name__ == "__main__":
try:
main(sys.argv[1:])
except URLError as e:
print(e.code,e.msg)
print(e.headers)
print(e.fp.read())
raise