Coverage for admin/x509_utils.py: 100%
30 statements
« prev ^ index » next coverage.py v7.5.3, created at 2025-10-30 06:22 +0000
« prev ^ index » next coverage.py v7.5.3, created at 2025-10-30 06:22 +0000
1# The MIT License (MIT)
2#
3# Copyright (c) 2021 RSK Labs Ltd
4#
5# Permission is hereby granted, free of charge, to any person obtaining a copy of
6# this software and associated documentation files (the "Software"), to deal in
7# the Software without restriction, including without limitation the rights to
8# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9# of the Software, and to permit persons to whom the Software is furnished to do
10# so, subject to the following conditions:
11#
12# The above copyright notice and this permission notice shall be included in all
13# copies or substantial portions of the Software.
14#
15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21# SOFTWARE.
23import re
24import requests
25from cryptography import x509
26from urllib.parse import unquote as url_unquote
29def split_pem_certificates(pem_data):
30 pattern = r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----"
31 certs = re.findall(pattern, pem_data, flags=re.DOTALL)
32 return certs
35def get_intel_pcs_x509_crl(url):
36 ra_res = requests.get(url)
37 if ra_res.status_code != 200:
38 raise RuntimeError(f"Error fetching CRL from {url}")
40 try:
41 # Parse CRL
42 ctype = ra_res.headers["Content-Type"]
43 if ctype in ["application/x-pem-file"]:
44 crl = x509.load_pem_x509_crl(ra_res.content)
45 elif ctype in ["application/pkix-crl", "application/x-x509-ca-cert"]:
46 crl = x509.load_der_x509_crl(ra_res.content)
47 else:
48 raise RuntimeError(f"Unknown CRL encoding: {ctype}")
50 # Parse certification chain (if any)
51 issuer_chain = ra_res.headers.get("SGX-PCK-CRL-Issuer-Chain")
52 if issuer_chain is not None:
53 issuer_chain = split_pem_certificates(url_unquote(issuer_chain))
54 issuer_chain = list(map(
55 lambda pem: x509.load_pem_x509_certificate(pem.encode()), issuer_chain))
57 warning = ra_res.headers.get("warning")
58 if warning is not None:
59 warning = f"Getting {url}: {warning}"
61 response = {
62 "crl": crl,
63 "issuer_chain": issuer_chain,
64 "warning": warning,
65 }
67 return response
68 except Exception as e:
69 raise RuntimeError(f"While fetching CRL from {url}: {e}")