Blame SOURCES/certdata2pem.py

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