forked from sigstore/sigstore-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
375 lines (305 loc) · 11.6 KB
/
client.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# Copyright 2022 The Sigstore Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Client implementation for interacting with Fulcio.
"""
from __future__ import annotations
import base64
import datetime
import json
import logging
import struct
from abc import ABC
from dataclasses import dataclass
from enum import IntEnum
from typing import List
from urllib.parse import urljoin
import requests
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.x509 import (
Certificate,
CertificateSigningRequest,
PrecertificateSignedCertificateTimestamps,
load_pem_x509_certificate,
)
from cryptography.x509.certificate_transparency import (
LogEntryType,
SignatureAlgorithm,
SignedCertificateTimestamp,
Version,
)
from pydantic import BaseModel, Field, validator
from sigstore._utils import B64Str
from sigstore.oidc import IdentityToken
logger = logging.getLogger(__name__)
DEFAULT_FULCIO_URL = "https://fulcio.sigstore.dev"
STAGING_FULCIO_URL = "https://fulcio.sigstage.dev"
SIGNING_CERT_ENDPOINT = "/api/v2/signingCert"
TRUST_BUNDLE_ENDPOINT = "/api/v2/trustBundle"
class SCTHashAlgorithm(IntEnum):
"""
Hash algorithms that are valid for SCTs.
These are exactly the same as the HashAlgorithm enum in RFC 5246 (TLS 1.2).
See: https://datatracker.ietf.org/doc/html/rfc5246#section-7.4.1.4.1
"""
NONE = 0
MD5 = 1
SHA1 = 2
SHA224 = 3
SHA256 = 4
SHA384 = 5
SHA512 = 6
def to_cryptography(self) -> hashes.HashAlgorithm:
"""
Converts this `SCTHashAlgorithm` into a `cryptography.hashes` object.
"""
if self != SCTHashAlgorithm.SHA256:
raise FulcioSCTError(f"unexpected hash algorithm: {self!r}")
return hashes.SHA256()
class FulcioSCTError(Exception):
"""
Raised on errors when constructing a `FulcioSignedCertificateTimestamp`.
"""
pass
class DetachedFulcioSCT(BaseModel):
"""
Represents a "detached" SignedCertificateTimestamp from Fulcio.
"""
version: Version = Field(..., alias="sct_version")
log_id: bytes = Field(..., alias="id")
timestamp: datetime.datetime
digitally_signed: bytes = Field(..., alias="signature")
extension_bytes: bytes = Field(..., alias="extensions")
class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
@validator("digitally_signed", pre=True)
def _validate_digitally_signed(cls, v: bytes) -> bytes:
digitally_signed = base64.b64decode(v)
if len(digitally_signed) <= 4:
raise ValueError("impossibly small digitally-signed struct")
return digitally_signed
@validator("log_id", pre=True)
def _validate_log_id(cls, v: bytes) -> bytes:
return base64.b64decode(v)
@validator("extension_bytes", pre=True)
def _validate_extensions(cls, v: bytes) -> bytes:
return base64.b64decode(v)
@property
def entry_type(self) -> LogEntryType:
"""
Returns the kind of CT log entry this detached SCT is signing for.
"""
return LogEntryType.X509_CERTIFICATE
@property
def signature_hash_algorithm(self) -> hashes.HashAlgorithm:
"""
Returns the hash algorithm used in this detached SCT's signature.
"""
hash_ = SCTHashAlgorithm(self.digitally_signed[0])
return hash_.to_cryptography()
@property
def signature_algorithm(self) -> SignatureAlgorithm:
"""
Returns the signature algorithm used in this detached SCT's signature.
"""
return SignatureAlgorithm(self.digitally_signed[1])
@property
def signature(self) -> bytes:
"""
Returns the raw signature inside the detached SCT.
"""
(sig_size,) = struct.unpack("!H", self.digitally_signed[2:4])
if len(self.digitally_signed[4:]) != sig_size:
raise FulcioSCTError(
f"signature size mismatch: expected {sig_size} bytes, "
f"got {len(self.digitally_signed[4:])}"
)
return self.digitally_signed[4:]
# SignedCertificateTimestamp is an ABC, so register our DetachedFulcioSCT as
# virtual subclass.
SignedCertificateTimestamp.register(DetachedFulcioSCT)
class ExpiredCertificate(Exception):
"""An error raised when the Certificate is expired."""
@dataclass(frozen=True)
class FulcioCertificateSigningResponse:
"""Certificate response"""
cert: Certificate
chain: List[Certificate]
sct: SignedCertificateTimestamp
@dataclass(frozen=True)
class FulcioTrustBundleResponse:
"""Trust bundle response, containing a list of certificate chains"""
trust_bundle: List[List[Certificate]]
class FulcioClientError(Exception):
"""
Raised on any error in the Fulcio client.
"""
pass
class _Endpoint(ABC):
def __init__(self, url: str, session: requests.Session) -> None:
self.url = url
self.session = session
def _serialize_cert_request(req: CertificateSigningRequest) -> str:
data = {
"certificateSigningRequest": B64Str(
base64.b64encode(req.public_bytes(serialization.Encoding.PEM)).decode()
)
}
return json.dumps(data)
class FulcioSigningCert(_Endpoint):
"""
Fulcio REST API signing certificate functionality.
"""
def post(
self, req: CertificateSigningRequest, identity: IdentityToken
) -> FulcioCertificateSigningResponse:
"""
Get the signing certificate, using an X.509 Certificate
Signing Request.
"""
headers = {
"Authorization": f"Bearer {identity}",
"Content-Type": "application/json",
"Accept": "application/pem-certificate-chain",
}
resp: requests.Response = self.session.post(
url=self.url, data=_serialize_cert_request(req), headers=headers
)
try:
resp.raise_for_status()
except requests.HTTPError as http_error:
try:
text = json.loads(http_error.response.text)
raise FulcioClientError(text["message"]) from http_error
except (AttributeError, KeyError):
raise FulcioClientError from http_error
if resp.json().get("signedCertificateEmbeddedSct"):
sct_embedded = True
try:
certificates = resp.json()["signedCertificateEmbeddedSct"]["chain"][
"certificates"
]
except KeyError:
raise FulcioClientError("Fulcio response missing certificate chain")
else:
sct_embedded = False
try:
certificates = resp.json()["signedCertificateDetachedSct"]["chain"][
"certificates"
]
except KeyError:
raise FulcioClientError("Fulcio response missing certificate chain")
# Cryptography doesn't have chain verification/building built in
# https://github.com/pyca/cryptography/issues/2381
if len(certificates) < 2:
raise FulcioClientError(
f"Certificate chain is too short: {len(certificates)} < 2"
)
cert = load_pem_x509_certificate(certificates[0].encode())
chain = [load_pem_x509_certificate(c.encode()) for c in certificates[1:]]
if sct_embedded:
# Try to retrieve the embedded SCTs within the cert.
precert_scts_extension = cert.extensions.get_extension_for_class(
PrecertificateSignedCertificateTimestamps
).value
if len(precert_scts_extension) != 1:
raise FulcioClientError(
f"Unexpected embedded SCT count in response: {len(precert_scts_extension)} != 1"
)
sct = precert_scts_extension[0]
else:
# If we don't have any embedded SCTs, then we might be dealing
# with a Fulcio instance that provides detached SCTs.
# The detached SCT is a base64-encoded payload, which in turn
# is a JSON representation of the SignedCertificateTimestamp
# in RFC 6962 (subsec. 3.2).
try:
sct_b64 = resp.json()["signedCertificateDetachedSct"][
"signedCertificateTimestamp"
]
except KeyError:
raise FulcioClientError(
"Fulcio response did not include a detached SCT"
)
try:
sct_json = json.loads(base64.b64decode(sct_b64).decode())
except ValueError as exc:
raise FulcioClientError from exc
try:
sct = DetachedFulcioSCT.parse_obj(sct_json)
except Exception as exc:
# Ideally we'd catch something less generic here.
raise FulcioClientError from exc
return FulcioCertificateSigningResponse(cert, chain, sct)
class FulcioTrustBundle(_Endpoint):
"""
Fulcio REST API trust bundle functionality.
"""
def get(self) -> FulcioTrustBundleResponse:
"""Get the certificate chains from Fulcio"""
resp: requests.Response = self.session.get(self.url)
try:
resp.raise_for_status()
except requests.HTTPError as http_error:
raise FulcioClientError from http_error
trust_bundle_json = resp.json()
chains: List[List[Certificate]] = []
for certificate_chain in trust_bundle_json["chains"]:
chain: List[Certificate] = []
for certificate in certificate_chain["certificates"]:
cert: Certificate = load_pem_x509_certificate(certificate.encode())
chain.append(cert)
chains.append(chain)
return FulcioTrustBundleResponse(chains)
class FulcioClient:
"""The internal Fulcio client"""
def __init__(self, url: str = DEFAULT_FULCIO_URL) -> None:
"""Initialize the client"""
logger.debug(f"Fulcio client using URL: {url}")
self.url = url
self.session = requests.Session()
def __del__(self) -> None:
"""
Destroys the underlying network session.
"""
self.session.close()
@classmethod
def production(cls) -> FulcioClient:
"""
Returns a `FulcioClient` for the Sigstore production instance of Fulcio.
"""
return cls(DEFAULT_FULCIO_URL)
@classmethod
def staging(cls) -> FulcioClient:
"""
Returns a `FulcioClient` for the Sigstore staging instance of Fulcio.
"""
return cls(STAGING_FULCIO_URL)
@property
def signing_cert(self) -> FulcioSigningCert:
"""
Returns a model capable of interacting with Fulcio's signing certificate endpoints.
"""
return FulcioSigningCert(
urljoin(self.url, SIGNING_CERT_ENDPOINT), session=self.session
)
@property
def trust_bundle(self) -> FulcioTrustBundle:
"""
Returns a model capable of interacting with Fulcio's trust bundle endpoints.
"""
return FulcioTrustBundle(
urljoin(self.url, TRUST_BUNDLE_ENDPOINT), session=self.session
)