summaryrefslogtreecommitdiff
path: root/tools/merge.py
blob: 9904b84d44e9d5086ecbbdb63471a46f709ad92e (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2014, NORDUnet A/S.
# See LICENSE for licensing information.

import argparse
import json
import base64
import urllib
import urllib2
import sys
import time
import ecdsa
import hashlib
import urlparse
import os
import yaml
import select
import struct
from certtools import build_merkle_tree, create_sth_signature, \
    check_sth_signature, get_eckey_from_file, timing_point, http_request, \
    get_public_key_from_file, get_leaf_hash, decode_certificate_chain, \
    create_ssl_context
from mergetools import parselogrow, get_logorder, read_chain, unpack_entry, \
    verify_entry

parser = argparse.ArgumentParser(description="")
parser.add_argument('--config', help="System configuration", required=True)
parser.add_argument('--localconfig', help="Local configuration", required=True)
parser.add_argument("--nomerge", action='store_true', help="Don't actually do merge")
parser.add_argument("--timing", action='store_true', help="Print timing information")
args = parser.parse_args()

config = yaml.load(open(args.config))
localconfig = yaml.load(open(args.localconfig))

ctbaseurl = config["baseurl"]
frontendnodes = config["frontendnodes"]
storagenodes = config["storagenodes"]
secondaries = localconfig.get("secondary", [])
paths = localconfig["paths"]
mergedb = paths["mergedb"]

signingnodes = config["signingnodes"]
create_ssl_context(cafile=paths["https_cacertfile"])

chainsdir = mergedb + "/chains"
logorderfile = mergedb + "/logorder"

own_key = (localconfig["nodename"], "%s/%s-private.pem" % (paths["privatekeys"], localconfig["nodename"]))

logpublickey = get_public_key_from_file(paths["logpublickey"])

hashed_dir = True

def write_chain(key, value):
    filename = base64.b16encode(key)
    if hashed_dir:
        path = chainsdir + "/" + filename[0:2] + "/" + filename[2:4] + "/" + filename[4:6]
        try:
            os.makedirs(path)
        except Exception, e:
            pass
    else:
        path = chainsdir
    f = open(path + "/" + filename, "w")
    f.write(value)
    f.close()

def add_to_logorder(key):
    f = open(logorderfile, "a")
    f.write(base64.b16encode(key) + "\n")
    f.close()

def fsync_logorder():
    f = open(logorderfile, "a")
    os.fsync(f.fileno())
    f.close()

def get_new_entries(node, baseurl):
    try:
        result = http_request(baseurl + "ct/storage/fetchnewentries", key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        parsed_result = json.loads(result)
        if parsed_result.get(u"result") == u"ok":
            return [base64.b64decode(entry) for entry in parsed_result[u"entries"]]
        print >>sys.stderr, "ERROR: fetchnewentries", parsed_result
        sys.exit(1)
    except urllib2.HTTPError, e:
        print >>sys.stderr, "ERROR: fetchnewentries", e.read()
        sys.exit(1)

def get_entries(node, baseurl, hashes):
    try:
        params = urllib.urlencode({"hash":[base64.b64encode(hash) for hash in hashes]}, doseq=True)
        result = http_request(baseurl + "ct/storage/getentry?" + params, key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        parsed_result = json.loads(result)
        if parsed_result.get(u"result") == u"ok":
            entries = dict([(base64.b64decode(entry["hash"]), base64.b64decode(entry["entry"])) for entry in parsed_result[u"entries"]])
            assert len(entries) == len(hashes)
            assert set(entries.keys()) == set(hashes)
            return entries
        print >>sys.stderr, "ERROR: getentry", parsed_result
        sys.exit(1)
    except urllib2.HTTPError, e:
        print >>sys.stderr, "ERROR: getentry", e.read()
        sys.exit(1)

def get_curpos(node, baseurl):
    try:
        result = http_request(baseurl + "ct/frontend/currentposition", key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        parsed_result = json.loads(result)
        if parsed_result.get(u"result") == u"ok":
            return parsed_result[u"position"]
        print >>sys.stderr, "ERROR: currentposition", parsed_result
        sys.exit(1)
    except urllib2.HTTPError, e:
        print >>sys.stderr, "ERROR: currentposition", e.read()
        sys.exit(1)

def sendlog(node, baseurl, submission):
    try:
        result = http_request(baseurl + "ct/frontend/sendlog",
            json.dumps(submission), key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        return json.loads(result)
    except urllib2.HTTPError, e:
        print >>sys.stderr, "ERROR: sendlog", e.read()
        sys.stderr.flush()
        return None
    except ValueError, e:
        print >>sys.stderr, "==== FAILED REQUEST ===="
        print >>sys.stderr, submission
        print >>sys.stderr, "======= RESPONSE ======="
        print >>sys.stderr, result
        print >>sys.stderr, "========================"
        sys.stderr.flush()
        raise e

def sendentry(node, baseurl, entry, hash):
    try:
        result = http_request(baseurl + "ct/frontend/sendentry",
            json.dumps({"entry":base64.b64encode(entry), "treeleafhash":base64.b64encode(hash)}), key=own_key,
            verifynode=node, publickeydir=paths["publickeys"])
        return json.loads(result)
    except urllib2.HTTPError, e:
        print >>sys.stderr, "ERROR: sendentry", e.read()
        sys.exit(1)
    except ValueError, e:
        print >>sys.stderr, "==== FAILED REQUEST ===="
        print >>sys.stderr, hash
        print >>sys.stderr, "======= RESPONSE ======="
        print >>sys.stderr, result
        print >>sys.stderr, "========================"
        sys.stderr.flush()
        raise e

def sendsth(node, baseurl, submission):
    try:
        result = http_request(baseurl + "ct/frontend/sendsth",
            json.dumps(submission), key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        return json.loads(result)
    except urllib2.HTTPError, e:
        print >>sys.stderr, "ERROR: sendsth", e.read()
        sys.exit(1)
    except ValueError, e:
        print >>sys.stderr, "==== FAILED REQUEST ===="
        print >>sys.stderr, submission
        print >>sys.stderr, "======= RESPONSE ======="
        print >>sys.stderr, result
        print >>sys.stderr, "========================"
        sys.stderr.flush()
        raise e

def get_missingentries(node, baseurl):
    try:
        result = http_request(baseurl + "ct/frontend/missingentries", key=own_key, verifynode=node, publickeydir=paths["publickeys"])
        parsed_result = json.loads(result)
        if parsed_result.get(u"result") == u"ok":
            return parsed_result[u"entries"]
        print >>sys.stderr, "ERROR: missingentries", parsed_result
        sys.exit(1)
    except urllib2.HTTPError, e:
        print >>sys.stderr, "ERROR: missingentries", e.read()
        sys.exit(1)

def chunks(l, n):
    return [l[i:i+n] for i in range(0, len(l), n)]

timing = timing_point()

logorder = get_logorder(logorderfile)

timing_point(timing, "get logorder")

certsinlog = set(logorder)

new_entries_per_node = {}
new_entries = set()
entries_to_fetch = {}

for storagenode in storagenodes:
    print >>sys.stderr, "getting new entries from", storagenode["name"]
    sys.stderr.flush()
    new_entries_per_node[storagenode["name"]] = set(get_new_entries(storagenode["name"], "https://%s/" % storagenode["address"]))
    new_entries.update(new_entries_per_node[storagenode["name"]])
    entries_to_fetch[storagenode["name"]] = []

import subprocess

timing_point(timing, "get new entries")

new_entries -= certsinlog

print >>sys.stderr, "adding", len(new_entries), "entries"
sys.stderr.flush()

if args.nomerge:
    sys.exit(0)

for hash in new_entries:
    for storagenode in storagenodes:
        if hash in new_entries_per_node[storagenode["name"]]:
            entries_to_fetch[storagenode["name"]].append(hash)
            break

verifycert = subprocess.Popen([paths["verifycert_bin"], paths["known_roots"]],
                              stdin=subprocess.PIPE, stdout=subprocess.PIPE)

added_entries = 0
for storagenode in storagenodes:
    print >>sys.stderr, "getting %d entries from %s:" % (len(entries_to_fetch[storagenode["name"]]), storagenode["name"]),
    sys.stderr.flush()
    for chunk in chunks(entries_to_fetch[storagenode["name"]], 100):
        entries = get_entries(storagenode["name"], "https://%s/" % storagenode["address"], chunk)
        for hash in chunk:
            entry = entries[hash]
            verify_entry(verifycert, entry, hash)
            write_chain(hash, entry)
            add_to_logorder(hash)
            logorder.append(hash)
            certsinlog.add(hash)
            added_entries += 1
        print >>sys.stderr, added_entries,
        sys.stderr.flush()
    print >>sys.stderr
    sys.stderr.flush()
fsync_logorder()
timing_point(timing, "add entries")
print >>sys.stderr, "added", added_entries, "entries"
sys.stderr.flush()

verifycert.communicate(struct.pack("I", 0))

tree = build_merkle_tree(logorder)
tree_size = len(logorder)
root_hash = tree[-1][0]
timestamp = int(time.time() * 1000)

for secondary in secondaries:
    remotehost = secondary["host"]
    remotedir = remotehost + ":" + secondary["mergedir"]
    localdir = mergedb
    if localdir[:-1] != '/':
        localdir = localdir + "/"

    print >>sys.stderr, "copying database to secondary:", remotehost
    sys.stderr.flush()
    rsyncstatus = subprocess.call(["rsync", "-r", "--append", "--rsh=ssh", localdir, remotedir])
    if rsyncstatus:
        print >>sys.stderr, "rsync failed:", rsyncstatus
        sys.exit(1)

    print >>sys.stderr, "verifying database at secondary:", remotehost
    sys.stderr.flush()
    verifysecondary = subprocess.Popen(["ssh", remotehost, secondary["verifycommand"], secondary["mergedir"]],
                                    stdout=subprocess.PIPE)

    (verifysecondaryresult, _) = verifysecondary.communicate()

    if root_hash != base64.b16decode(verifysecondaryresult.strip()):
        print >>sys.stderr, "secondary root hash was", verifysecondaryresult.strip()
        print >>sys.stderr, "  expected", base64.b16encode(root_hash)
        sys.exit(1)

tree_head_signature = None
for signingnode in signingnodes:
    try:
        tree_head_signature = create_sth_signature(tree_size, timestamp,
                                                   root_hash, "https://%s/" % signingnode["address"], key=own_key)
        break
    except urllib2.URLError, e:
        print >>sys.stderr, e
        sys.stderr.flush()
if tree_head_signature == None:
    print >>sys.stderr, "Could not contact any signing nodes"
    sys.exit(1)

sth = {"tree_size": tree_size, "timestamp": timestamp,
       "sha256_root_hash": base64.b64encode(root_hash),
       "tree_head_signature": base64.b64encode(tree_head_signature)}

check_sth_signature(ctbaseurl, sth, publickey=logpublickey)

timing_point(timing, "build sth")

if args.timing:
    print >>sys.stderr, timing["deltatimes"]
    sys.stderr.flush()

print base64.b16encode(root_hash)
sys.stdout.flush()

for frontendnode in frontendnodes:
    nodeaddress = "https://%s/" % frontendnode["address"]
    nodename = frontendnode["name"]
    timing = timing_point()
    print >>sys.stderr, "distributing for node", nodename
    sys.stderr.flush()
    curpos = get_curpos(nodename, nodeaddress)
    timing_point(timing, "get curpos")
    print >>sys.stderr, "current position", curpos
    sys.stderr.flush()
    entries = [base64.b64encode(entry) for entry in logorder[curpos:]]
    print >>sys.stderr, "sending log:",
    sys.stderr.flush()
    for chunk in chunks(entries, 1000):
        for trynumber in range(5, 0, -1):
            sendlogresult = sendlog(nodename, nodeaddress, {"start": curpos, "hashes": chunk})
            if sendlogresult == None:
                if trynumber == 1:
                    sys.exit(1)
                select.select([], [], [], 10.0)
                print >>sys.stderr, "tries left:", trynumber
                sys.stderr.flush()
                continue
            break
        if sendlogresult["result"] != "ok":
            print >>sys.stderr, "sendlog:", sendlogresult
            sys.exit(1)
        curpos += len(chunk)
        print >>sys.stderr, curpos,
        sys.stderr.flush()
    print >>sys.stderr
    timing_point(timing, "sendlog")
    print >>sys.stderr, "log sent"
    sys.stderr.flush()
    missingentries = get_missingentries(nodename, nodeaddress)
    timing_point(timing, "get missing")
    print >>sys.stderr, "missing entries:", len(missingentries)
    sys.stderr.flush()
    fetched_entries = 0
    print >>sys.stderr, "fetching missing entries",
    sys.stderr.flush()
    for missingentry in missingentries:
        hash = base64.b64decode(missingentry)
        sendentryresult = sendentry(nodename, nodeaddress, read_chain(chainsdir, hash), hash)
        if sendentryresult["result"] != "ok":
            print >>sys.stderr, "send sth:", sendentryresult
            sys.exit(1)
        fetched_entries += 1
        if added_entries % 1000 == 0:
            print >>sys.stderr, fetched_entries,
            sys.stderr.flush()
    print >>sys.stderr
    sys.stderr.flush()
    timing_point(timing, "send missing")
    sendsthresult = sendsth(nodename, nodeaddress, sth)
    if sendsthresult["result"] != "ok":
        print >>sys.stderr, "send sth:", sendsthresult
        sys.exit(1)
    timing_point(timing, "send sth")
    if args.timing:
        print >>sys.stderr, timing["deltatimes"]
        sys.stderr.flush()