summaryrefslogtreecommitdiff
path: root/tools/convertdb.py
blob: c036843b36de161418643c1f2f9e07ce9f3fd443 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2014, NORDUnet A/S.
# See LICENSE for licensing information.

import argparse
import urllib2
import urllib
import json
import base64
import sys
import struct
import hashlib
import itertools
from certtools import *
from mergetools import *
import zipfile
import os
import time
import shutil

def write_file(fn, contents):
    tempname = fn + ".new"
    open(tempname, 'w').write(contents)
    shutil.move(tempname, fn)

def unpack_entry(entry):
    pieces = []
    while len(entry):
        (length,) = struct.unpack(">I", entry[0:4])
        data = entry[4:4+length]
        entry = entry[4+length:]
        pieces.append(data)
    return pieces

def read_old_entry(entry, hash):
    unpacked = unpack_entry(entry)
    mtl = unpacked[0]
    assert hash == get_leaf_hash(mtl)
    (leafcert, timestamp, issuer_key_hash) = unpack_mtl(mtl)
    certchain = decode_certificate_chain(unpacked[1])
    if issuer_key_hash:
        leafcert = certchain[0]
        certchain = certchain[1:]
        certtype = "PRC1"
    else:
        certtype = "EEC1"
    return (mtl, leafcert, certtype, certchain)

def convertentry(entry, hash):
    (mtl, leafcert, certtype, chain) = read_old_entry(entry, hash)
    entry = tlv_encodelist([("MTL1", mtl),
                            (certtype, leafcert),
                            ("CHN1", tlv_encodelist([("X509", cert) for cert in chain]))])
    return wrap_entry(entry)

parser = argparse.ArgumentParser(description='')
parser.add_argument('path', help="Path to database to convert")
args = parser.parse_args()

for (dirpath, dirnames, filenames) in os.walk(args.path):
    for filename in filenames:
        fullpath = dirpath + "/" + filename
        entry = open(fullpath).read()
        entry = convertentry(entry, base64.b16decode(filename.upper()))
        if entry != None:
            print "writing new entry for", filename
            write_file(fullpath, entry)
        else:
            print "not writing new entry for", filename