This repository has been archived by the owner on Feb 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathacme.py
309 lines (282 loc) · 10.9 KB
/
acme.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import json
import pprint
from base64 import urlsafe_b64encode
import requests
from jwcrypto import jwk, jwt
import urllib.parse
from app.acme_directory_configuration import ACMEDirectoryConfiguration
class Acme:
url: urllib.parse.ParseResult
key = None
nonce = None
kid = None
order = None
certurl = None
finalize = {}
_directory_configuration: ACMEDirectoryConfiguration
def __init__(
self,
directory_config: ACMEDirectoryConfiguration,
):
self._directory_configuration = directory_config
def debugrequest(self, protected, payload):
print(" protected")
self.pprint(protected)
print(" payload")
self.pprint(payload)
def debugresponse(self, response):
print("- " * 40)
print(" headers")
self.pprint(self.clean_headers(response.headers))
print(" response")
self.pprint(response.json())
print("=" * 80)
def gen_key(self):
"""
This does only generate a P-256 key for use with JWT.
This key is only used during the session to request a certificate from ACME.
"""
self.key = jwk.JWK.generate(kty="EC", crv="P-256", key_ops=["verify", "sign"], alg="ES256")
def get_nonce(self):
"""
The acme protocol specifies a nonce to be used during communication
to prevent replay attacks. This is the first, a complete fresh one,
without having to use the previous nonce. This is stored in self.nonce
as with all updates, as every request answers with a new nonce.
"""
response = requests.get(
self._directory_configuration.new_nonce_url,
timeout=60,
)
self.nonce = response.headers["Replay-Nonce"]
def account_request(self, request):
"""
This is to request an account. The acme headers are pretty simple.
kid is the key registered but since this is the first request
you specify the jwk and it get's registered as the keyid.
add the nonce (see above), url and alg and tada.wav.
"""
print("Account Request")
protected = {
"alg": "ES256",
"nonce": self.nonce,
"url": self._directory_configuration.new_account_url,
"jwk": self.key.export_public(True),
}
token = jwt.JWS(payload=json.dumps(request))
token.add_signature(self.key, alg="ES256", protected=protected)
self.debugrequest(protected, request)
headers = {"Content-Type": "application/jose+json"}
response = requests.post(
self._directory_configuration.new_account_url,
data=token.serialize(),
headers=headers,
timeout=60,
)
self.debugresponse(response)
self.nonce = response.headers["Replay-Nonce"]
self.kid = response.headers["Location"]
assert response.json()["status"] == "valid"
def create_order(self, keynum, order):
"""
To let acme know you want a certificate first you have to
create an order inside the system. All other stuff hangs on
this order. This order gets a number and that gets encoded
into the most URL's. Just call the right URL which is specified
afterwards.
"""
print("Order")
new_order_url = self._directory_configuration.new_order_url
protected = {
"alg": "ES256",
"nonce": self.nonce,
"url": new_order_url,
"kid": self.kid,
}
self.debugrequest(protected, order)
token = jwt.JWS(payload=json.dumps(order))
token.add_signature(self.key, alg="ES256", protected=protected)
headers = {"Content-Type": "application/jose+json"}
response = requests.post(
new_order_url,
data=token.serialize(),
headers=headers,
timeout=60,
)
self.debugresponse(response)
self.nonce = response.headers["Replay-Nonce"]
self.order = response.headers["Location"]
self.finalize[keynum] = response.json()["finalize"]
assert response.json()["status"] == "pending"
return response.json()["authorizations"][0]
def challenge(self, challengeurl):
"""
ACME works with challenges. Normally you put them on a webserver
or in DNS for example. We just request it and it should come back
into the CSR as password. For now, just request it. #FIXME
"""
print("Challenge")
print(f" challengeurl: {challengeurl}")
protected = {
"alg": "ES256",
"nonce": self.nonce,
"url": challengeurl,
"kid": self.kid,
}
print(" protected")
self.pprint(protected)
print(" payload")
self.pprint("")
token = jwt.JWS(payload="")
token.add_signature(self.key, alg="ES256", protected=protected)
headers = {"Content-Type": "application/jose+json"}
# Request the challenge per PIV-slot from the ACME-server.
# This will return a random token, with the status of pending.
#
# Later on, these tokens from the challenges should be contained in the users' JWT.
response = requests.post(challengeurl, data=token.serialize(), headers=headers, timeout=60)
returned_json = response.json()
self.debugresponse(response)
self.nonce = response.headers["Replay-Nonce"]
assert returned_json["status"] in ["pending", "valid"]
return returned_json["challenges"], returned_json["status"]
def send_challenge_jwt(self, challenge, hw_attestation, uzi_jwt, f9_cert):
"""
We have a challenge, and a JWT to prove who we are.
This JWT is from the central identification services for UZI.
send the JWT to a jwt-v3 verify URL together with the challenge
token and continue
"""
print("Answer with JWT Challenge")
challengeurl = challenge["url"]
protected = {
"alg": "ES256",
"nonce": self.nonce,
"url": challengeurl,
"kid": self.kid,
}
payload = {}
self.debugrequest(protected, payload)
token = jwt.JWS(payload=json.dumps(payload))
token.add_signature(self.key, alg="ES256", protected=protected)
headers = {
"Content-Type": "application/jose+json",
"X-Acme-Jwt": uzi_jwt,
"X-Acme-Cert": hw_attestation,
"X-Acme-F9Cert": f9_cert,
}
print(" headers")
print(headers)
response = requests.post(challengeurl, data=token.serialize(), headers=headers, timeout=60)
self.nonce = response.headers["Replay-Nonce"]
self.debugresponse(response)
def notify(self, notifyurl):
"""
After sending the challenge and prove who we are it's within the protocol
to update ACME that we provided the challenge. With HTTP/DNS Acme will do
the lookup, with JWT it will do the lookup but internally
"""
print("Notify")
print(f" notifyurl: {notifyurl}")
protected = {
"alg": "ES256",
"nonce": self.nonce,
"url": notifyurl,
"kid": self.kid,
}
self.debugrequest(protected, {})
token = jwt.JWS(payload=json.dumps({}))
token.add_signature(self.key, alg="ES256", protected=protected)
headers = {"Content-Type": "application/jose+json"}
response = requests.post(notifyurl, data=token.serialize(), headers=headers, timeout=60)
self.nonce = response.headers["Replay-Nonce"]
self.debugresponse(response)
assert response.json()["status"] in ["pending", "valid"]
return response.json()["status"], response.json()["url"]
def final(self, keynum, csr, jwt_token: str):
"""
There is an order, we are correct. Now we get to request a certificate.
To do this we provide a CSR and that gets signed with the root/sub-CA
at the ACME service.
"""
print("Request the Certificate")
protected = {
"alg": "ES256",
"nonce": self.nonce,
"url": self.finalize[keynum],
"kid": self.kid,
}
payload = {
"csr": urlsafe_b64encode(csr).decode().rstrip("="),
}
self.debugrequest(protected, payload)
token = jwt.JWS(payload=json.dumps(payload))
token.add_signature(self.key, alg="ES256", protected=protected)
headers = {
"Content-Type": "application/jose+json",
"X-Acme-Jwt": jwt_token,
}
# This calls the finalize method, preparing the certificate
response = requests.post(self.finalize[keynum], data=token.serialize(), headers=headers, timeout=60)
self.nonce = response.headers["Replay-Nonce"]
self.debugresponse(response)
assert response.json()["status"] == "valid"
self.certurl = response.json()["certificate"]
def getcert(self):
"""
We got a URL where to download the cert.
Let's do that.
"""
print("Get Certificate")
protected = {
"alg": "ES256",
"nonce": self.nonce,
"url": self.certurl,
"kid": self.kid,
}
self.debugrequest(protected, {})
token = jwt.JWS(payload="")
token.add_signature(self.key, alg="ES256", protected=protected)
headers = {"Content-Type": "application/jose+json"}
response = requests.post(self.certurl, data=token.serialize(), headers=headers, timeout=60)
self.nonce = response.headers["Replay-Nonce"]
return response.text
def clean_headers(self, headers):
"""
We are not a webbrowser, but a demo program. This deletes all
the non-specific headers we don't want to print.
"""
headers = dict(headers)
for todel in [
"Access-Control-Allow-Origin",
"Access-Control-Expose-Headers",
"Boulder-Requester",
"Cache-Control",
"Connection",
"Content-Length",
"Content-Security-Policy",
"Content-Type",
"Date",
"Expect-CT",
"Feature-Policy",
"Keep-Alive",
"Permissions-Policy",
"Pragma",
"Referrer-Policy",
"Server",
"Strict-Transport-Security",
"X-Content-Type-Options",
"X-Dns-Prefetch-Control",
"X-Download-Options",
"X-Frame-Options",
"X-Permitted-Cross-Domain-Policies",
"X-Xss-Protection",
]:
if todel in headers:
del headers[todel]
return headers
def pprint(self, data):
"""
A simple hack to learn pprint to add some spaces upfront. Better for viewing
"""
print("\n".join([" " + x for x in pprint.pformat(data, width=80).splitlines()]))