5f392b3
#!/usr/bin/python
5f392b3
# vim:set et sw=4:
5f392b3
#
5f392b3
# certdata2pem.py - splits certdata.txt into multiple files
5f392b3
#
5f392b3
# Copyright (C) 2009 Philipp Kern <pkern@debian.org>
5f392b3
#
5f392b3
# This program is free software; you can redistribute it and/or modify
5f392b3
# it under the terms of the GNU General Public License as published by
5f392b3
# the Free Software Foundation; either version 2 of the License, or
5f392b3
# (at your option) any later version.
5f392b3
#
5f392b3
# This program is distributed in the hope that it will be useful,
5f392b3
# but WITHOUT ANY WARRANTY; without even the implied warranty of
5f392b3
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
5f392b3
# GNU General Public License for more details.
5f392b3
#
5f392b3
# You should have received a copy of the GNU General Public License
5f392b3
# along with this program; if not, write to the Free Software
5f392b3
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,
5f392b3
# USA.
5f392b3
5f392b3
import base64
5f392b3
import os.path
5f392b3
import re
5f392b3
import sys
5f392b3
import textwrap
5f392b3
5f392b3
objects = []
5f392b3
5f392b3
# Dirty file parser.
5f392b3
in_data, in_multiline, in_obj = False, False, False
5f392b3
field, type, value, obj = None, None, None, dict()
5f392b3
for line in open('certdata.txt', 'r'):
5f392b3
    # Ignore the file header.
5f392b3
    if not in_data:
5f392b3
        if line.startswith('BEGINDATA'):
5f392b3
            in_data = True
5f392b3
        continue
5f392b3
    # Ignore comment lines.
5f392b3
    if line.startswith('#'):
5f392b3
        continue
5f392b3
    # Empty lines are significant if we are inside an object.
5f392b3
    if in_obj and len(line.strip()) == 0:
5f392b3
        objects.append(obj)
5f392b3
        obj = dict()
5f392b3
        in_obj = False
5f392b3
        continue
5f392b3
    if len(line.strip()) == 0:
5f392b3
        continue
5f392b3
    if in_multiline:
5f392b3
        if not line.startswith('END'):
5f392b3
            if type == 'MULTILINE_OCTAL':
5f392b3
                line = line.strip()
5f392b3
                for i in re.finditer(r'\\([0-3][0-7][0-7])', line):
5f392b3
                    value += chr(int(i.group(1), 8))
5f392b3
            else:
5f392b3
                value += line
5f392b3
            continue
5f392b3
        obj[field] = value
5f392b3
        in_multiline = False
5f392b3
        continue
5f392b3
    if line.startswith('CKA_CLASS'):
5f392b3
        in_obj = True
5f392b3
    line_parts = line.strip().split(' ', 2)
5f392b3
    if len(line_parts) > 2:
5f392b3
        field, type = line_parts[0:2]
5f392b3
        value = ' '.join(line_parts[2:])
5f392b3
    elif len(line_parts) == 2:
5f392b3
        field, type = line_parts
5f392b3
        value = None
5f392b3
    else:
5f392b3
        raise NotImplementedError, 'line_parts < 2 not supported.'
5f392b3
    if type == 'MULTILINE_OCTAL':
5f392b3
        in_multiline = True
5f392b3
        value = ""
5f392b3
        continue
5f392b3
    obj[field] = value
5f392b3
if len(obj.items()) > 0:
5f392b3
    objects.append(obj)
5f392b3
5f392b3
# Read blacklist.
5f392b3
blacklist = []
5f392b3
if os.path.exists('blacklist.txt'):
5f392b3
    for line in open('blacklist.txt', 'r'):
5f392b3
        line = line.strip()
5f392b3
        if line.startswith('#') or len(line) == 0:
5f392b3
            continue
5f392b3
        item = line.split('#', 1)[0].strip()
5f392b3
        blacklist.append(item)
5f392b3
5f392b3
# Build up trust database.
5f392b3
trust = dict()
708646c
trustmap = dict()
5f392b3
for obj in objects:
37d25f7
37d25f7
    if obj['CKA_CLASS'] != 'CKO_NSS_TRUST':
5f392b3
        continue
5f392b3
    if obj['CKA_LABEL'] in blacklist:
5f392b3
        print "Certificate %s blacklisted, ignoring." % obj['CKA_LABEL']
37d25f7
    elif obj['CKA_TRUST_SERVER_AUTH'] == 'CKT_NSS_TRUSTED_DELEGATOR':
5f392b3
        trust[obj['CKA_LABEL']] = True
37d25f7
    elif obj['CKA_TRUST_EMAIL_PROTECTION'] == 'CKT_NSS_TRUSTED_DELEGATOR':
5f392b3
        trust[obj['CKA_LABEL']] = True
f098063
    elif obj['CKA_TRUST_CODE_SIGNING'] == 'CKT_NSS_TRUSTED_DELEGATOR':
f098063
        trust[obj['CKA_LABEL']] = True
f098063
    elif obj['CKA_TRUST_SERVER_AUTH'] == 'CKT_NSS_UNTRUSTED':
5f392b3
        print '!'*74
5f392b3
        print "UNTRUSTED BUT NOT BLACKLISTED CERTIFICATE FOUND: %s" % obj['CKA_LABEL']
5f392b3
        print '!'*74
708646c
        sys.exit(1)
5f392b3
    else:
5f392b3
        print "Ignoring certificate %s.  SAUTH=%s, EPROT=%s" % \
5f392b3
              (obj['CKA_LABEL'], obj['CKA_TRUST_SERVER_AUTH'],
5f392b3
               obj['CKA_TRUST_EMAIL_PROTECTION'])
37d25f7
    label = obj['CKA_LABEL']
37d25f7
    trustmap[label] = obj
37d25f7
    print " added cert", label
5f392b3
5f392b3
def label_to_filename(label):
5f392b3
    label = label.replace('/', '_')\
5f392b3
        .replace(' ', '_')\
5f392b3
        .replace('(', '=')\
5f392b3
        .replace(')', '=')\
5f392b3
        .replace(',', '_') + '.crt'
5f392b3
    return re.sub(r'\\x[0-9a-fA-F]{2}', lambda m:chr(int(m.group(0)[2:], 16)), label)
5f392b3
708646c
trust_types = {
708646c
  "CKA_TRUST_DIGITAL_SIGNATURE": "digital-signature",
708646c
  "CKA_TRUST_NON_REPUDIATION": "non-repudiation",
708646c
  "CKA_TRUST_KEY_ENCIPHERMENT": "key-encipherment",
708646c
  "CKA_TRUST_DATA_ENCIPHERMENT": "data-encipherment",
708646c
  "CKA_TRUST_KEY_AGREEMENT": "key-agreement",
708646c
  "CKA_TRUST_KEY_CERT_SIGN": "cert-sign",
708646c
  "CKA_TRUST_CRL_SIGN": "crl-sign",
708646c
  "CKA_TRUST_SERVER_AUTH": "server-auth",
708646c
  "CKA_TRUST_CLIENT_AUTH": "client-auth",
708646c
  "CKA_TRUST_CODE_SIGNING": "code-signing",
708646c
  "CKA_TRUST_EMAIL_PROTECTION": "email-protection",
708646c
  "CKA_TRUST_IPSEC_END_SYSTEM": "ipsec-end-system",
708646c
  "CKA_TRUST_IPSEC_TUNNEL": "ipsec-tunnel",
708646c
  "CKA_TRUST_IPSEC_USER": "ipsec-user",
708646c
  "CKA_TRUST_TIME_STAMPING": "time-stamping",
708646c
  "CKA_TRUST_STEP_UP_APPROVED": "step-up-approved",
708646c
}
708646c
708646c
openssl_trust = {
708646c
  "CKA_TRUST_SERVER_AUTH": "serverAuth",
708646c
  "CKA_TRUST_CLIENT_AUTH": "clientAuth",
708646c
  "CKA_TRUST_CODE_SIGNING": "codeSigning",
708646c
  "CKA_TRUST_EMAIL_PROTECTION": "emailProtection",
708646c
}
708646c
5f392b3
for obj in objects:
5f392b3
    if obj['CKA_CLASS'] == 'CKO_CERTIFICATE':
f098063
        print "producing cert file for " + obj['CKA_LABEL']
f098063
        if not obj['CKA_LABEL'] in trust or not trust[obj['CKA_LABEL']]:
f098063
            print " -> untrusted, ignoring"
f098063
            continue
5f392b3
        fname = label_to_filename(obj['CKA_LABEL'][1:-1])
5f392b3
        f = open(fname, 'w')
708646c
        trustbits = []
708646c
        openssl_trustflags = []
708646c
        tobj = trustmap[obj['CKA_LABEL']]
708646c
        for t in trust_types.keys():
37d25f7
            if tobj.has_key(t) and tobj[t] == 'CKT_NSS_TRUSTED_DELEGATOR':
708646c
                trustbits.append(t)
708646c
                if t in openssl_trust:
708646c
                    openssl_trustflags.append(openssl_trust[t])
dc70b1f
        f.write("# trust=" + " ".join(trustbits) + "\n")
708646c
        if openssl_trustflags:
708646c
            f.write("# openssl-trust=" + " ".join(openssl_trustflags) + "\n")
5f392b3
        f.write("-----BEGIN CERTIFICATE-----\n")
5f392b3
        f.write("\n".join(textwrap.wrap(base64.b64encode(obj['CKA_VALUE']), 64)))
5f392b3
        f.write("\n-----END CERTIFICATE-----\n")
f098063
        print " -> written as '%s', trust = %s, openssl-trust = %s" % (fname, trustbits, openssl_trustflags)
f098063
f098063
5f392b3