|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +# |
| 4 | +# Copyright (c) 2023 Project CHIP Authors |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | +# |
| 18 | + |
| 19 | +# Generates a basic RevocationSet from TestNet |
| 20 | +# Usage: |
| 21 | +# python ./credentials/generate-revocation-set.py --help |
| 22 | + |
| 23 | +import base64 |
| 24 | +import json |
| 25 | +import subprocess |
| 26 | +import sys |
| 27 | +from enum import Enum |
| 28 | + |
| 29 | +import click |
| 30 | +import requests |
| 31 | +from click_option_group import RequiredMutuallyExclusiveOptionGroup, optgroup |
| 32 | +from cryptography import x509 |
| 33 | + |
| 34 | + |
| 35 | +class RevocationType(Enum): |
| 36 | + CRL = 1 |
| 37 | + |
| 38 | + |
| 39 | +OID_VENDOR_ID = x509.ObjectIdentifier("1.3.6.1.4.1.37244.2.1") |
| 40 | +OID_PRODUCT_ID = x509.ObjectIdentifier("1.3.6.1.4.1.37244.2.2") |
| 41 | + |
| 42 | +PRODUCTION_NODE_URL = "https://on.dcl.csa-iot.org:26657" |
| 43 | +PRODUCTION_NODE_URL_REST = "https://on.dcl.csa-iot.org" |
| 44 | +TEST_NODE_URL_REST = "https://on.test-net.dcl.csa-iot.org" |
| 45 | + |
| 46 | + |
| 47 | +def use_dcld(dcld, production, cmdlist): |
| 48 | + return [dcld] + cmdlist + (['--node', PRODUCTION_NODE_URL] if production else []) |
| 49 | + |
| 50 | + |
| 51 | +def extract_single_integer_attribute(subject, oid): |
| 52 | + attribute_list = subject.get_attributes_for_oid(oid) |
| 53 | + |
| 54 | + if len(attribute_list) == 1: |
| 55 | + if attribute_list[0].value.isdigit(): |
| 56 | + return int(attribute_list[0].value) |
| 57 | + |
| 58 | + return None |
| 59 | + |
| 60 | + |
| 61 | +@click.command() |
| 62 | +@click.help_option('-h', '--help') |
| 63 | +@optgroup.group('Input data sources', cls=RequiredMutuallyExclusiveOptionGroup) |
| 64 | +@optgroup.option('--use-main-net-dcld', type=str, default='', metavar='PATH', help="Location of `dcld` binary, to use `dcld` for mirroring MainNet.") |
| 65 | +@optgroup.option('--use-test-net-dcld', type=str, default='', metavar='PATH', help="Location of `dcld` binary, to use `dcld` for mirroring TestNet.") |
| 66 | +@optgroup.option('--use-main-net-http', is_flag=True, type=str, help="Use RESTful API with HTTPS against public MainNet observer.") |
| 67 | +@optgroup.option('--use-test-net-http', is_flag=True, type=str, help="Use RESTful API with HTTPS against public TestNet observer.") |
| 68 | +@optgroup.group('Optional arguments') |
| 69 | +@optgroup.option('--output', default='sample_revocation_set_list.json', type=str, metavar='FILEPATH', help="Output filename (default: sample_revocation_set_list.json)") |
| 70 | +def main(use_main_net_dcld, use_test_net_dcld, use_main_net_http, use_test_net_http, output): |
| 71 | + """DCL PAA mirroring tools""" |
| 72 | + |
| 73 | + production = False |
| 74 | + dcld = use_test_net_dcld |
| 75 | + |
| 76 | + if len(use_main_net_dcld) > 0: |
| 77 | + dcld = use_main_net_dcld |
| 78 | + production = True |
| 79 | + |
| 80 | + use_rest = use_main_net_http or use_test_net_http |
| 81 | + if use_main_net_http: |
| 82 | + production = True |
| 83 | + |
| 84 | + rest_node_url = PRODUCTION_NODE_URL_REST if production else TEST_NODE_URL_REST |
| 85 | + |
| 86 | + # TODO: Extract this to a helper function |
| 87 | + if use_rest: |
| 88 | + revocation_point_list = requests.get(f"{rest_node_url}/dcl/pki/revocation-points").json()["PkiRevocationDistributionPoint"] |
| 89 | + else: |
| 90 | + cmdlist = ['config', 'output', 'json'] |
| 91 | + subprocess.Popen([dcld] + cmdlist) |
| 92 | + |
| 93 | + cmdlist = ['query', 'pki', 'all-revocation-points'] |
| 94 | + |
| 95 | + cmdpipe = subprocess.Popen(use_dcld(dcld, production, cmdlist), stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 96 | + |
| 97 | + revocation_point_list = json.loads(cmdpipe.stdout.read())["PkiRevocationDistributionPoint"] |
| 98 | + |
| 99 | + revocation_set = [] |
| 100 | + |
| 101 | + for revocation_point in revocation_point_list: |
| 102 | + # 1. Validate Revocation Type |
| 103 | + if revocation_point["revocationType"] != RevocationType.CRL: |
| 104 | + continue |
| 105 | + |
| 106 | + # 2. Parse the certificate |
| 107 | + crl_signer_certificate = x509.load_pem_x509_certificate(revocation_point["crlSignerCertificate"]) |
| 108 | + |
| 109 | + vid = revocation_point["vid"] |
| 110 | + pid = revocation_point["pid"] |
| 111 | + is_paa = revocation_point["isPAA"] |
| 112 | + |
| 113 | + # 3. && 4. Validate VID/PID |
| 114 | + # TODO: Need to support alternate representation of VID/PID (see spec "6.2.2.2. Encoding of Vendor ID and Product ID in subject and issuer fields") |
| 115 | + crl_vid = extract_single_integer_attribute(crl_signer_certificate.subject, OID_VENDOR_ID) |
| 116 | + crl_pid = extract_single_integer_attribute(crl_signer_certificate.subject, OID_PRODUCT_ID) |
| 117 | + |
| 118 | + if is_paa: |
| 119 | + if crl_vid is not None: |
| 120 | + if vid != crl_vid: |
| 121 | + # TODO: Need to log all situations where a continue is called |
| 122 | + continue |
| 123 | + else: |
| 124 | + if crl_vid is None or vid != crl_vid: |
| 125 | + continue |
| 126 | + if crl_pid is not None: |
| 127 | + if pid != crl_pid: |
| 128 | + continue |
| 129 | + |
| 130 | + # 5. Validate the certification path containing CRLSignerCertificate. |
| 131 | + crl_signer_issuer_name = base64.b64encode(crl_signer_certificate.issuer.public_bytes()).decode('utf-8') |
| 132 | + |
| 133 | + crl_signer_authority_key_id = crl_signer_certificate.extensions.get_extension_for_oid( |
| 134 | + x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier |
| 135 | + |
| 136 | + paa_certificate = None |
| 137 | + |
| 138 | + # TODO: Extract this to a helper function |
| 139 | + if use_rest: |
| 140 | + response = requests.get( |
| 141 | + f"{rest_node_url}/dcl/pki/certificates/{crl_signer_issuer_name}/{crl_signer_authority_key_id}").json()["approvedCertificates"]["certs"][0] |
| 142 | + paa_certificate = response["pemCert"] |
| 143 | + else: |
| 144 | + cmdlist = ['query', 'pki', 'x509-cert', '-u', crl_signer_issuer_name, '-k', crl_signer_authority_key_id] |
| 145 | + cmdpipe = subprocess.Popen(use_dcld(dcld, production, cmdlist), stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 146 | + paa_certificate = json.loads(cmdpipe.stdout.read())["approvedCertificates"]["certs"][0]["pemCert"] |
| 147 | + |
| 148 | + if paa_certificate is None: |
| 149 | + continue |
| 150 | + |
| 151 | + paa_certificate_object = x509.load_pem_x509_certificate(paa_certificate) |
| 152 | + |
| 153 | + try: |
| 154 | + crl_signer_certificate.verify_directly_issued_by(paa_certificate_object) |
| 155 | + except Exception: |
| 156 | + continue |
| 157 | + |
| 158 | + # 6. Obtain the CRL |
| 159 | + r = requests.get(revocation_point["dataURL"]) |
| 160 | + crl_file = x509.load_der_x509_crl(r.content) |
| 161 | + |
| 162 | + # 7. Perform CRL File Validation |
| 163 | + crl_authority_key_id = crl_file.extensions.get_extension_for_oid(x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier |
| 164 | + crl_signer_subject_key_id = crl_signer_certificate.extensions.get_extension_for_oid( |
| 165 | + x509.OID_SUBJECT_KEY_IDENTIFIER).value.key_identifier |
| 166 | + if crl_authority_key_id != crl_signer_subject_key_id: |
| 167 | + continue |
| 168 | + |
| 169 | + issuer_subject_key_id = ''.join('{:02X}'.format(x) for x in crl_authority_key_id) |
| 170 | + |
| 171 | + same_issuer_points = None |
| 172 | + |
| 173 | + # TODO: Extract this to a helper function |
| 174 | + if use_rest: |
| 175 | + response = requests.get( |
| 176 | + f"{rest_node_url}/dcl/pki/revocation-points/{issuer_subject_key_id}").json()["pkiRevocationDistributionPointsByIssuerSubjectKeyID"] |
| 177 | + same_issuer_points = response["points"] |
| 178 | + else: |
| 179 | + cmdlist = ['query', 'pki', 'revocation-points', '--issuer-subject-key-id', issuer_subject_key_id] |
| 180 | + cmdpipe = subprocess.Popen(use_dcld(dcld, production, cmdlist), stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 181 | + same_issuer_points = json.loads(cmdpipe.stdout.read())[ |
| 182 | + "pkiRevocationDistributionPointsByIssuerSubjectKeyID"]["points"] |
| 183 | + |
| 184 | + matching_entries = False |
| 185 | + for same_issuer_point in same_issuer_points: |
| 186 | + if same_issuer_point["vid"] == vid: |
| 187 | + matching_entries = True |
| 188 | + break |
| 189 | + |
| 190 | + if matching_entries: |
| 191 | + try: |
| 192 | + issuing_distribution_point = crl_file.extensions.get_extension_for_oid( |
| 193 | + x509.OID_ISSUING_DISTRIBUTION_POINT).value |
| 194 | + except Exception: |
| 195 | + continue |
| 196 | + |
| 197 | + uri_list = issuing_distribution_point.full_name |
| 198 | + if len(uri_list) == 1 and isinstance(uri_list[0], x509.UniformResourceIdentifier): |
| 199 | + if uri_list[0].value != revocation_point["dataURL"]: |
| 200 | + continue |
| 201 | + else: |
| 202 | + continue |
| 203 | + |
| 204 | + # 9. Assign CRL File Issuer |
| 205 | + certificate_authority_name = base64.b64encode(crl_file.issuer.public_bytes()).decode('utf-8') |
| 206 | + |
| 207 | + serialnumber_list = [] |
| 208 | + # 10. Iterate through the Revoked Certificates List |
| 209 | + for revoked_cert in crl_file: |
| 210 | + try: |
| 211 | + revoked_cert_issuer = revoked_cert.extensions.get_extension_for_oid( |
| 212 | + x509.CRLEntryExtensionOID.CERTIFICATE_ISSUER).value.get_values_for_type(x509.DirectoryName).value |
| 213 | + |
| 214 | + if revoked_cert_issuer is not None: |
| 215 | + if revoked_cert_issuer != certificate_authority_name: |
| 216 | + continue |
| 217 | + except Exception: |
| 218 | + pass |
| 219 | + |
| 220 | + # b. |
| 221 | + try: |
| 222 | + revoked_cert_authority_key_id = revoked_cert.extensions.get_extension_for_oid( |
| 223 | + x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier |
| 224 | + |
| 225 | + if revoked_cert_authority_key_id is None or revoked_cert_authority_key_id != crl_signer_subject_key_id: |
| 226 | + continue |
| 227 | + except Exception: |
| 228 | + continue |
| 229 | + |
| 230 | + # c. and d. |
| 231 | + serialnumber_list.append(bytes(str('{:02X}'.format(revoked_cert.serial_number)), 'utf-8').decode('utf-8')) |
| 232 | + |
| 233 | + issuer_name = base64.b64encode(crl_file.issuer.public_bytes()).decode('utf-8') |
| 234 | + |
| 235 | + revocation_set.append({"type": "revocation_set", |
| 236 | + "issuer_subject_key_id": issuer_subject_key_id, |
| 237 | + "issuer_name": issuer_name, |
| 238 | + "revoked_serial_numbers": serialnumber_list}) |
| 239 | + |
| 240 | + with open(output, 'w+') as outfile: |
| 241 | + json.dump(revocation_set, outfile, indent=4) |
| 242 | + |
| 243 | + |
| 244 | +if __name__ == "__main__": |
| 245 | + if len(sys.argv) == 1: |
| 246 | + main.main(['--help']) |
| 247 | + else: |
| 248 | + main() |
0 commit comments