Blame SOURCES/certdata2pem.py

13173e
#!/usr/bin/python
13173e
# vim:set et sw=4:
13173e
#
13173e
# certdata2pem.py - splits certdata.txt into multiple files
13173e
#
13173e
# Copyright (C) 2009 Philipp Kern <pkern@debian.org>
13173e
# Copyright (C) 2013 Kai Engert <kaie@redhat.com>
13173e
#
13173e
# This program is free software; you can redistribute it and/or modify
13173e
# it under the terms of the GNU General Public License as published by
13173e
# the Free Software Foundation; either version 2 of the License, or
13173e
# (at your option) any later version.
13173e
#
13173e
# This program is distributed in the hope that it will be useful,
13173e
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13173e
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13173e
# GNU General Public License for more details.
13173e
#
13173e
# You should have received a copy of the GNU General Public License
13173e
# along with this program; if not, write to the Free Software
13173e
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,
13173e
# USA.
13173e
13173e
import base64
13173e
import os.path
13173e
import re
13173e
import sys
13173e
import textwrap
13173e
import urllib.request, urllib.parse, urllib.error
13173e
import subprocess
13173e
13173e
objects = []
13173e
13173e
def printable_serial(obj):
13173e
  return ".".join([str(x) for x in obj['CKA_SERIAL_NUMBER']])
13173e
13173e
# Dirty file parser.
13173e
in_data, in_multiline, in_obj = False, False, False
13173e
field, ftype, value, binval, obj = None, None, None, bytearray(), dict()
13173e
for line in open('certdata.txt', 'r'):
13173e
    # Ignore the file header.
13173e
    if not in_data:
13173e
        if line.startswith('BEGINDATA'):
13173e
            in_data = True
13173e
        continue
13173e
    # Ignore comment lines.
13173e
    if line.startswith('#'):
13173e
        continue
13173e
    # Empty lines are significant if we are inside an object.
13173e
    if in_obj and len(line.strip()) == 0:
13173e
        objects.append(obj)
13173e
        obj = dict()
13173e
        in_obj = False
13173e
        continue
13173e
    if len(line.strip()) == 0:
13173e
        continue
13173e
    if in_multiline:
13173e
        if not line.startswith('END'):
13173e
            if ftype == 'MULTILINE_OCTAL':
13173e
                line = line.strip()
13173e
                for i in re.finditer(r'\\([0-3][0-7][0-7])', line):
13173e
                    integ = int(i.group(1), 8)
13173e
                    binval.extend((integ).to_bytes(1, sys.byteorder))
13173e
                obj[field] = binval
13173e
            else:
13173e
                value += line
13173e
                obj[field] = value
13173e
            continue
13173e
        in_multiline = False
13173e
        continue
13173e
    if line.startswith('CKA_CLASS'):
13173e
        in_obj = True
13173e
    line_parts = line.strip().split(' ', 2)
13173e
    if len(line_parts) > 2:
13173e
        field, ftype = line_parts[0:2]
13173e
        value = ' '.join(line_parts[2:])
13173e
    elif len(line_parts) == 2:
13173e
        field, ftype = line_parts
13173e
        value = None
13173e
    else:
13173e
        raise NotImplementedError('line_parts < 2 not supported.\n' + line)
13173e
    if ftype == 'MULTILINE_OCTAL':
13173e
        in_multiline = True
13173e
        value = ""
13173e
        binval = bytearray()
13173e
        continue
13173e
    obj[field] = value
13173e
if len(list(obj.items())) > 0:
13173e
    objects.append(obj)
13173e
13173e
# Build up trust database.
13173e
trustmap = dict()
13173e
for obj in objects:
13173e
    if obj['CKA_CLASS'] != 'CKO_NSS_TRUST':
13173e
        continue
13173e
    key = obj['CKA_LABEL'] + printable_serial(obj)
13173e
    trustmap[key] = obj
13173e
    print(" added trust", key)
13173e
13173e
# Build up cert database.
13173e
certmap = dict()
13173e
for obj in objects:
13173e
    if obj['CKA_CLASS'] != 'CKO_CERTIFICATE':
13173e
        continue
13173e
    key = obj['CKA_LABEL'] + printable_serial(obj)
13173e
    certmap[key] = obj
13173e
    print(" added cert", key)
13173e
13173e
def obj_to_filename(obj):
13173e
    label = obj['CKA_LABEL'][1:-1]
13173e
    label = label.replace('/', '_')\
13173e
        .replace(' ', '_')\
13173e
        .replace('(', '=')\
13173e
        .replace(')', '=')\
13173e
        .replace(',', '_')
13173e
    labelbytes = bytearray()
13173e
    i = 0
13173e
    imax = len(label)
13173e
    while i < imax:
13173e
        if i < imax-3 and label[i] == '\\' and label[i+1] == 'x':
13173e
            labelbytes.extend(bytes.fromhex(label[i+2:i+4]))
13173e
            i += 4
13173e
            continue
13173e
        labelbytes.extend(str.encode(label[i]))
13173e
        i = i+1
13173e
        continue
13173e
    label = labelbytes.decode('utf-8')
13173e
    serial = printable_serial(obj)
13173e
    return label + ":" + serial
13173e
13173e
def write_cert_ext_to_file(f, oid, value, public_key):
13173e
    f.write("[p11-kit-object-v1]\n")
13173e
    f.write("label: ");
13173e
    f.write(tobj['CKA_LABEL'])
13173e
    f.write("\n")
13173e
    f.write("class: x-certificate-extension\n");
13173e
    f.write("object-id: " + oid + "\n")
13173e
    f.write("value: \"" + value + "\"\n")
13173e
    f.write("modifiable: false\n");
13173e
    f.write(public_key)
13173e
13173e
trust_types = {
13173e
  "CKA_TRUST_DIGITAL_SIGNATURE": "digital-signature",
13173e
  "CKA_TRUST_NON_REPUDIATION": "non-repudiation",
13173e
  "CKA_TRUST_KEY_ENCIPHERMENT": "key-encipherment",
13173e
  "CKA_TRUST_DATA_ENCIPHERMENT": "data-encipherment",
13173e
  "CKA_TRUST_KEY_AGREEMENT": "key-agreement",
13173e
  "CKA_TRUST_KEY_CERT_SIGN": "cert-sign",
13173e
  "CKA_TRUST_CRL_SIGN": "crl-sign",
13173e
  "CKA_TRUST_SERVER_AUTH": "server-auth",
13173e
  "CKA_TRUST_CLIENT_AUTH": "client-auth",
13173e
  "CKA_TRUST_CODE_SIGNING": "code-signing",
13173e
  "CKA_TRUST_EMAIL_PROTECTION": "email-protection",
13173e
  "CKA_TRUST_IPSEC_END_SYSTEM": "ipsec-end-system",
13173e
  "CKA_TRUST_IPSEC_TUNNEL": "ipsec-tunnel",
13173e
  "CKA_TRUST_IPSEC_USER": "ipsec-user",
13173e
  "CKA_TRUST_TIME_STAMPING": "time-stamping",
13173e
  "CKA_TRUST_STEP_UP_APPROVED": "step-up-approved",
13173e
}
13173e
13173e
legacy_trust_types = {
13173e
  "LEGACY_CKA_TRUST_SERVER_AUTH": "server-auth",
13173e
  "LEGACY_CKA_TRUST_CODE_SIGNING": "code-signing",
13173e
  "LEGACY_CKA_TRUST_EMAIL_PROTECTION": "email-protection",
13173e
}
13173e
13173e
legacy_to_real_trust_types = {
13173e
  "LEGACY_CKA_TRUST_SERVER_AUTH": "CKA_TRUST_SERVER_AUTH",
13173e
  "LEGACY_CKA_TRUST_CODE_SIGNING": "CKA_TRUST_CODE_SIGNING",
13173e
  "LEGACY_CKA_TRUST_EMAIL_PROTECTION": "CKA_TRUST_EMAIL_PROTECTION",
13173e
}
13173e
13173e
openssl_trust = {
13173e
  "CKA_TRUST_SERVER_AUTH": "serverAuth",
13173e
  "CKA_TRUST_CLIENT_AUTH": "clientAuth",
13173e
  "CKA_TRUST_CODE_SIGNING": "codeSigning",
13173e
  "CKA_TRUST_EMAIL_PROTECTION": "emailProtection",
13173e
}
13173e
13173e
for tobj in objects:
13173e
    if tobj['CKA_CLASS'] == 'CKO_NSS_TRUST':
13173e
        key = tobj['CKA_LABEL'] + printable_serial(tobj)
13173e
        print("producing trust for " + key)
13173e
        trustbits = []
13173e
        distrustbits = []
13173e
        openssl_trustflags = []
13173e
        openssl_distrustflags = []
13173e
        legacy_trustbits = []
13173e
        legacy_openssl_trustflags = []
13173e
        for t in list(trust_types.keys()):
13173e
            if t in tobj and tobj[t] == 'CKT_NSS_TRUSTED_DELEGATOR':
13173e
                trustbits.append(t)
13173e
                if t in openssl_trust:
13173e
                    openssl_trustflags.append(openssl_trust[t])
13173e
            if t in tobj and tobj[t] == 'CKT_NSS_NOT_TRUSTED':
13173e
                distrustbits.append(t)
13173e
                if t in openssl_trust:
13173e
                    openssl_distrustflags.append(openssl_trust[t])
13173e
13173e
        for t in list(legacy_trust_types.keys()):
13173e
            if t in tobj and tobj[t] == 'CKT_NSS_TRUSTED_DELEGATOR':
13173e
                real_t = legacy_to_real_trust_types[t]
13173e
                legacy_trustbits.append(real_t)
13173e
                if real_t in openssl_trust:
13173e
                    legacy_openssl_trustflags.append(openssl_trust[real_t])
13173e
            if t in tobj and tobj[t] == 'CKT_NSS_NOT_TRUSTED':
13173e
                raise NotImplementedError('legacy distrust not supported.\n' + line)
13173e
13173e
        fname = obj_to_filename(tobj)
13173e
        try:
13173e
            obj = certmap[key]
13173e
        except:
13173e
            obj = None
13173e
13173e
        # optional debug code, that dumps the parsed input to files
13173e
        #fulldump = "dump-" + fname
13173e
        #dumpf = open(fulldump, 'w')
13173e
        #dumpf.write(str(obj));
13173e
        #dumpf.write(str(tobj));
13173e
        #dumpf.close();
13173e
13173e
        is_legacy = 0
13173e
        if 'LEGACY_CKA_TRUST_SERVER_AUTH' in tobj or 'LEGACY_CKA_TRUST_EMAIL_PROTECTION' in tobj or 'LEGACY_CKA_TRUST_CODE_SIGNING' in tobj:
13173e
            is_legacy = 1
13173e
            if obj == None:
13173e
                raise NotImplementedError('found legacy trust without certificate.\n' + line)
13173e
13173e
            legacy_fname = "legacy-default/" + fname + ".crt"
13173e
            f = open(legacy_fname, 'w')
13173e
            f.write("# alias=%s\n"%tobj['CKA_LABEL'])
13173e
            f.write("# trust=" + " ".join(legacy_trustbits) + "\n")
13173e
            if legacy_openssl_trustflags:
13173e
                f.write("# openssl-trust=" + " ".join(legacy_openssl_trustflags) + "\n")
13173e
            f.write("-----BEGIN CERTIFICATE-----\n")
13173e
            temp_encoded_b64 = base64.b64encode(obj['CKA_VALUE'])
13173e
            temp_wrapped = textwrap.wrap(temp_encoded_b64.decode(), 64)
13173e
            f.write("\n".join(temp_wrapped))
13173e
            f.write("\n-----END CERTIFICATE-----\n")
13173e
            f.close()
13173e
13173e
            if 'CKA_TRUST_SERVER_AUTH' in tobj or 'CKA_TRUST_EMAIL_PROTECTION' in tobj or 'CKA_TRUST_CODE_SIGNING' in tobj:
13173e
                legacy_fname = "legacy-disable/" + fname + ".crt"
13173e
                f = open(legacy_fname, 'w')
13173e
                f.write("# alias=%s\n"%tobj['CKA_LABEL'])
13173e
                f.write("# trust=" + " ".join(trustbits) + "\n")
13173e
                if openssl_trustflags:
13173e
                    f.write("# openssl-trust=" + " ".join(openssl_trustflags) + "\n")
13173e
                f.write("-----BEGIN CERTIFICATE-----\n")
13173e
                f.write("\n".join(textwrap.wrap(base64.b64encode(obj['CKA_VALUE']), 64)))
13173e
                f.write("\n-----END CERTIFICATE-----\n")
13173e
                f.close()
13173e
13173e
            # don't produce p11-kit output for legacy certificates
13173e
            continue
13173e
13173e
        pk = ''
13173e
        cert_comment = ''
13173e
        if obj != None:
13173e
            # must extract the public key from the cert, let's use openssl
13173e
            cert_fname = "cert-" + fname
13173e
            fc = open(cert_fname, 'w')
13173e
            fc.write("-----BEGIN CERTIFICATE-----\n")
13173e
            temp_encoded_b64 = base64.b64encode(obj['CKA_VALUE'])
13173e
            temp_wrapped = textwrap.wrap(temp_encoded_b64.decode(), 64)
13173e
            fc.write("\n".join(temp_wrapped))
13173e
            fc.write("\n-----END CERTIFICATE-----\n")
13173e
            fc.close();
13173e
            pk_fname = "pubkey-" + fname
13173e
            fpkout = open(pk_fname, "w")
13173e
            dump_pk_command = ["openssl", "x509", "-in", cert_fname, "-noout", "-pubkey"]
13173e
            subprocess.call(dump_pk_command, stdout=fpkout)
13173e
            fpkout.close()
13173e
            with open (pk_fname, "r") as myfile:
13173e
                pk=myfile.read()
13173e
            # obtain certificate information suitable as a comment
13173e
            comment_fname = "comment-" + fname
13173e
            fcout = open(comment_fname, "w")
13173e
            comment_command = ["openssl", "x509", "-in", cert_fname, "-noout", "-text"]
13173e
            subprocess.call(comment_command, stdout=fcout)
13173e
            fcout.close()
13173e
            sed_command = ["sed", "--in-place", "s/^/#/", comment_fname]
13173e
            subprocess.call(sed_command)
13173e
            with open (comment_fname, "r", errors = 'replace') as myfile:
13173e
                cert_comment=myfile.read()
13173e
13173e
        fname += ".tmp-p11-kit"
13173e
        f = open(fname, 'w')
13173e
13173e
        if obj != None:
13173e
            is_distrusted = False
13173e
            has_server_trust = False
13173e
            has_email_trust = False
13173e
            has_code_trust = False
13173e
13173e
            if 'CKA_TRUST_SERVER_AUTH' in tobj:
13173e
                if tobj['CKA_TRUST_SERVER_AUTH'] == 'CKT_NSS_NOT_TRUSTED':
13173e
                    is_distrusted = True
13173e
                elif tobj['CKA_TRUST_SERVER_AUTH'] == 'CKT_NSS_TRUSTED_DELEGATOR':
13173e
                    has_server_trust = True
13173e
13173e
            if 'CKA_TRUST_EMAIL_PROTECTION' in tobj:
13173e
                if tobj['CKA_TRUST_EMAIL_PROTECTION'] == 'CKT_NSS_NOT_TRUSTED':
13173e
                    is_distrusted = True
13173e
                elif tobj['CKA_TRUST_EMAIL_PROTECTION'] == 'CKT_NSS_TRUSTED_DELEGATOR':
13173e
                    has_email_trust = True
13173e
13173e
            if 'CKA_TRUST_CODE_SIGNING' in tobj:
13173e
                if tobj['CKA_TRUST_CODE_SIGNING'] == 'CKT_NSS_NOT_TRUSTED':
13173e
                    is_distrusted = True
13173e
                elif tobj['CKA_TRUST_CODE_SIGNING'] == 'CKT_NSS_TRUSTED_DELEGATOR':
13173e
                    has_code_trust = True
13173e
13173e
            if is_distrusted:
13173e
                trust_ext_oid = "1.3.6.1.4.1.3319.6.10.1"
13173e
                trust_ext_value = "0.%06%0a%2b%06%01%04%01%99w%06%0a%01%04 0%1e%06%08%2b%06%01%05%05%07%03%04%06%08%2b%06%01%05%05%07%03%01%06%08%2b%06%01%05%05%07%03%03"
13173e
                write_cert_ext_to_file(f, trust_ext_oid, trust_ext_value, pk)
13173e
13173e
            trust_ext_oid = "2.5.29.37"
13173e
            if has_server_trust:
13173e
                if has_email_trust:
13173e
                    if has_code_trust:
13173e
                        # server + email + code
13173e
                        trust_ext_value = "0%2a%06%03U%1d%25%01%01%ff%04 0%1e%06%08%2b%06%01%05%05%07%03%04%06%08%2b%06%01%05%05%07%03%01%06%08%2b%06%01%05%05%07%03%03"
13173e
                    else:
13173e
                        # server + email
13173e
                        trust_ext_value = "0 %06%03U%1d%25%01%01%ff%04%160%14%06%08%2b%06%01%05%05%07%03%04%06%08%2b%06%01%05%05%07%03%01"
13173e
                else:
13173e
                    if has_code_trust:
13173e
                        # server + code
13173e
                        trust_ext_value = "0 %06%03U%1d%25%01%01%ff%04%160%14%06%08%2b%06%01%05%05%07%03%01%06%08%2b%06%01%05%05%07%03%03"
13173e
                    else:
13173e
                        # server
13173e
                        trust_ext_value = "0%16%06%03U%1d%25%01%01%ff%04%0c0%0a%06%08%2b%06%01%05%05%07%03%01"
13173e
            else:
13173e
                if has_email_trust:
13173e
                    if has_code_trust:
13173e
                        # email + code
13173e
                        trust_ext_value = "0 %06%03U%1d%25%01%01%ff%04%160%14%06%08%2b%06%01%05%05%07%03%04%06%08%2b%06%01%05%05%07%03%03"
13173e
                    else:
13173e
                        # email
13173e
                        trust_ext_value = "0%16%06%03U%1d%25%01%01%ff%04%0c0%0a%06%08%2b%06%01%05%05%07%03%04"
13173e
                else:
13173e
                    if has_code_trust:
13173e
                        # code
13173e
                        trust_ext_value = "0%16%06%03U%1d%25%01%01%ff%04%0c0%0a%06%08%2b%06%01%05%05%07%03%03"
13173e
                    else:
13173e
                        # none
13173e
                        trust_ext_value = "0%18%06%03U%1d%25%01%01%ff%04%0e0%0c%06%0a%2b%06%01%04%01%99w%06%0a%10"
13173e
13173e
            # no 2.5.29.37 for neutral certificates
13173e
            if (is_distrusted or has_server_trust or has_email_trust or has_code_trust):
13173e
                write_cert_ext_to_file(f, trust_ext_oid, trust_ext_value, pk)
13173e
13173e
            pk = ''
13173e
            f.write("\n")
13173e
13173e
            f.write("[p11-kit-object-v1]\n")
13173e
            f.write("label: ");
13173e
            f.write(tobj['CKA_LABEL'])
13173e
            f.write("\n")
13173e
            if is_distrusted:
13173e
                f.write("x-distrusted: true\n")
13173e
            elif has_server_trust or has_email_trust or has_code_trust:
13173e
                f.write("trusted: true\n")
13173e
            else:
13173e
                f.write("trusted: false\n")
13173e
13173e
            # requires p11-kit >= 0.23.4
13173e
            f.write("nss-mozilla-ca-policy: true\n")
13173e
            f.write("modifiable: false\n");
13173e
13173e
            f.write("-----BEGIN CERTIFICATE-----\n")
13173e
            temp_encoded_b64 = base64.b64encode(obj['CKA_VALUE'])
13173e
            temp_wrapped = textwrap.wrap(temp_encoded_b64.decode(), 64)
13173e
            f.write("\n".join(temp_wrapped))
13173e
            f.write("\n-----END CERTIFICATE-----\n")
13173e
            f.write(cert_comment)
13173e
            f.write("\n")
13173e
13173e
        else:
13173e
            f.write("[p11-kit-object-v1]\n")
13173e
            f.write("label: ");
13173e
            f.write(tobj['CKA_LABEL']);
13173e
            f.write("\n")
13173e
            f.write("class: certificate\n")
13173e
            f.write("certificate-type: x-509\n")
13173e
            f.write("modifiable: false\n");
13173e
            f.write("issuer: \"");
13173e
            f.write(urllib.parse.quote(tobj['CKA_ISSUER']));
13173e
            f.write("\"\n")
13173e
            f.write("serial-number: \"");
13173e
            f.write(urllib.parse.quote(tobj['CKA_SERIAL_NUMBER']));
13173e
            f.write("\"\n")
13173e
            if (tobj['CKA_TRUST_SERVER_AUTH'] == 'CKT_NSS_NOT_TRUSTED') or (tobj['CKA_TRUST_EMAIL_PROTECTION'] == 'CKT_NSS_NOT_TRUSTED') or (tobj['CKA_TRUST_CODE_SIGNING'] == 'CKT_NSS_NOT_TRUSTED'):
13173e
              f.write("x-distrusted: true\n")
13173e
            f.write("\n\n")
13173e
        f.close()
13173e
        print(" -> written as '%s', trust = %s, openssl-trust = %s, distrust = %s, openssl-distrust = %s" % (fname, trustbits, openssl_trustflags, distrustbits, openssl_distrustflags))