File: ct-dns-server-test.py

package info (click to toggle)
golang-github-google-certificate-transparency 0.0~git20160709.0.0f6e3d1~ds1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 5,676 kB
  • sloc: cpp: 35,278; python: 11,838; java: 1,911; sh: 1,885; makefile: 950; xml: 520; ansic: 225
file content (368 lines) | stat: -rw-r--r-- 10,792 bytes parent folder | download
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
import base64
import dns.resolver
import dns.rdatatype
import logging
import math
import os
import random
import shlex
import signal
import subprocess
import sys
import time

NUMBER_OF_CERTS = 100

basepath = os.path.dirname(sys.argv[0])

sys.path.append(os.path.join(basepath, '../../python'))
from ct.crypto import merkle
from ct.proto import ct_pb2

tmpdir = sys.argv[1]

class CTDNSLookup:
    def __init__(self, nameservers, port):
        self.resolver = dns.resolver.Resolver(configure=False)
        self.resolver.nameservers = nameservers
        self.resolver.port = port

    def Get(self, name):
        answers = self.resolver.query(name, 'TXT')
        assert answers.rdtype == dns.rdatatype.TXT
        return answers

    def GetOne(self, name):
        answers = self.Get(name)
        assert len(answers) == 1
        txt = answers[0]
        assert len(txt.strings) == 1
        return txt.strings[0]

    def GetSTH(self):
        sth_str = self.GetOne('sth.example.com')
        sth = ct_pb2.SignedTreeHead()
        parts = str(sth_str).split('.')
        sth.tree_size = int(parts[0])
        sth.timestamp = int(parts[1])
        sth.sha256_root_hash = base64.b64decode(parts[2])
        #FIXME(benl): decompose signature into its parts
        #sth.signature = base64.b64decode(parts[3])
        return sth

    def GetEntry(self, level, index, size):
        return self.GetOne(str(level) + '.' + str(index) + '.' + str(size)
                           + '.tree.example.com')

    def GetLeafHash(self, index):
        return self.GetOne(str(index) + '.leafhash.example.com')

class DNSServerRunner:
    def Run(self, cmd):
        args = shlex.split(cmd)
        self.proc = subprocess.Popen(args)

def OpenSSL(*params):
    logging.info("RUN: openssl " + str(params))
    null = open("/dev/null")
    subprocess.check_call(("openssl",) + params, stdout=null, stderr=null)

class timeout:
    def __init__(self, seconds, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message

    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)

    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)

    def __exit__(self, type, value, traceback):
        signal.alarm(0)

class CTServer:
    def __init__(self, cmd, base, ca):
        self.cmd_ = cmd
        self.base_ = base
        self.ca_ = ca
        self.GenerateKey()

    def __del__(self):
        self.proc.terminate()
        self.proc.wait()

    def PrivateKey(self):
        return self.base_ + "-ct-server-private-key.pem"
        
    def PublicKey(self):
        return self.base_ + "-ct-server-public-key.pem"

    def Database(self):
        return self.base_ + "-database.sqlite"

    def GenerateKey(self):
        OpenSSL("ecparam",
                "-out", self.PrivateKey(),
                "-name", "secp256r1",
                "-genkey")
        OpenSSL("ec",
                "-in", self.PrivateKey(),
                "-pubout",
                "-out", self.PublicKey())

    def URL(self):
        return "http://localhost:9999/"

    def Run(self):
        cmd = (self.cmd_ + " -key " + self.PrivateKey() +
               " -trusted_cert_file " + self.ca_.RootCertificate() +
               " -sqlite_db " + self.Database() +
               " -tree_signing_frequency_seconds 1" +
               " -logtostderr")
        logging.info("RUN: " + cmd)
        args = shlex.split(cmd)
        self.proc = subprocess.Popen(args, stdout=subprocess.PIPE)
        with timeout(10):
            while self.proc.stdout.readline() != "READY\n":
                continue

RootConfig = """[ req ]
distinguished_name=req_distinguished_name
prompt=no
x509_extensions=v3_ca

[ req_distinguished_name ]
countryName=GB
stateOrProvinceName=Wales
localityName=Erw Wen
0.organizationName=Certificate Transparency Test CA

[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints=CA:TRUE
"""

CAConfig = """[ ca ]
default_ca = CA_default

[ CA_default ]
default_startdate = 120601000000Z
default_enddate   = 220601000000Z
default_md	  = sha1
unique_subject	  = no
email_in_dn	  = no
policy	          = policy_default
serial            = {serial}
database          = {database}

[ policy_default ]
countryName	    = supplied
organizationName    = supplied
stateOrProvinceName = optional
localityName	    = optional
commonName          = optional
"""

RequestConfig = """[ req ]
distinguished_name=req_distinguished_name
prompt=no

[ req_distinguished_name ]
countryName=GB
stateOrProvinceName=Wales
localityName=Erw Wen
0.organizationName={subject}

# For the precert
[ pre ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints=CA:FALSE
1.3.6.1.4.1.11129.2.4.3=critical,ASN1:NULL

# For the simple cert, without embedded proof extensions
[ simple ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints=CA:FALSE

# For the cert with an embedded proof
[ embedded ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints=CA:FALSE
"""

def WriteFile(name, content):
    with open(name, "w") as f:
        f.write(content)

class CA:
    def __init__(self, base):
        self.base_ = base

        os.mkdir(self.Directory())
        
        open(self.Database(), "w")
        WriteFile(self.Serial(), "0000000000000001")

        WriteFile(self.RootConfig(), RootConfig)
        ca_config = CAConfig.format(database = self.Database(),
                                    serial = self.Serial())
        WriteFile(self.CAConfig(), ca_config)

        self.GenerateRootCertificate()

        os.mkdir(self.IssuedCertificates())

    def Directory(self):
        """Where the CA does house-keeping"""
        return self.base_ + "-housekeeping"

    def Database(self):
        return self.Directory() + "/database"

    def Serial(self):
        return self.Directory() + "/serial"

    def RootConfig(self):
        return self.base_ + "-root-config"

    def CAConfig(self):
        return self.base_ + "-ca-config"

    def PrivateKey(self):
        return self.base_ + "-private-key.pem"

    def RootCertificate(self):
        return self.base_ + "-cert.pem"

    def TempFile(self, name):
        return self.base_ + "-temp-" + name

    def RequestConfig(self):
        return self.TempFile("req-config")

    def IssuedCertificates(self):
        return self.base_ + "-issued"

    def IssuedFile(self, name, subject):
        return self.IssuedCertificates() + "/" + name + "-" + subject + ".pem"

    def IssuedPrivateKey(self, subject):
        return self.IssuedFile("private-key", subject)

    def IssuedCertificate(self, subject):
        return self.IssuedFile("certificate", subject)

    def GenerateRootCertificate(self):
        csr = self.TempFile("csr")
        OpenSSL("req",
                "-new",
                "-newkey", "rsa:2048",
                "-keyout", self.PrivateKey(),
                "-out", csr,
                "-config", self.RootConfig(),
                "-nodes")
        OpenSSL("ca",
                "-in", csr,
                "-selfsign",
                "-keyfile", self.PrivateKey(),
                "-config", self.CAConfig(),
                "-extfile", self.RootConfig(),
                "-extensions", "v3_ca",
                "-outdir", self.Directory(),
                "-out", self.RootCertificate(),
                "-batch")

    def CreateAndLogCert(self, ct_server, subject):
        WriteFile(self.RequestConfig(), RequestConfig.format(subject=subject))
        csr = self.TempFile("csr")
        OpenSSL("req",
                "-new",
                "-newkey", "rsa:1024",
                "-keyout", self.IssuedPrivateKey(subject),
                "-out", csr,
                "-config", self.RequestConfig(),
                "-nodes")
        OpenSSL("ca",
                "-in", csr,
                "-cert", self.RootCertificate(),
                "-keyfile", self.PrivateKey(),
                "-config", self.CAConfig(),
                "-extfile", self.RequestConfig(),
                "-extensions", "simple",
                "-outdir", self.Directory(),
                "-out", self.IssuedCertificate(subject),
                "-batch")

        # Reverse the order of these to show a bug in ct-server where
        # it accepts the CA cert even though there's a redundant extra
        # cert in the chain. At least, I think its a bug.
        certs = (open(self.IssuedCertificate(subject)).read()
                 + open(self.RootCertificate()).read())
        chain_file = self.TempFile("chain")
        WriteFile(chain_file, certs)
        subprocess.check_call(("client/ct", "upload",
                               "-ct_server_submission", chain_file,
                               "-ct_server", ct_server.URL(),
                               "-ct_server_public_key", ct_server.PublicKey(),
                               "-ct_server_response_out", self.TempFile("sct")))

logging.basicConfig(level="WARNING")

# Set up our test CA
ca = CA(tmpdir + "/ct-test-ca")

# Run a CT server
ct_cmd = basepath + "/ct-server"
ct_server = CTServer(ct_cmd, tmpdir + "/ct-test", ca)
ct_server.Run()

# Add nn certs to the CT server
for x in range(NUMBER_OF_CERTS):
    ca.CreateAndLogCert(ct_server, "TestCertificate" + str(x))

# Make sure server has had enough time to assimilate all certs
time.sleep(2)

# We'll need the DB for the DNS server
db = ct_server.Database()
# Kill the CT server (shared database access not currently supported)
del ct_server

# Now run the DNS server from the same database
server_cmd = basepath + "/ct-dns-server --port=1111 --domain=example.com. --db=" + db
runner = DNSServerRunner()
runner.Run(server_cmd)

# Get the STH
lookup = CTDNSLookup(['127.0.0.1'], 1111)

sth = lookup.GetSTH()
logging.info("sth = " + str(sth))
logging.info("size = " + str(sth.tree_size))

assert sth.tree_size == NUMBER_OF_CERTS

# test all the entries
for index in range(NUMBER_OF_CERTS):
    leaf_hash = lookup.GetLeafHash(index)
    logging.info("index = " + str(index) + " hash = " + leaf_hash)

    verifier = merkle.MerkleVerifier()
    audit_path = []
    for level in range(0, verifier.audit_path_length(index, sth.tree_size)):
        hash = lookup.GetEntry(level, index, sth.tree_size)
        logging.info("hash = " + hash)
        audit_path.append(base64.b64decode(hash))

    logging.info("path = " + str(map(base64.b64encode, audit_path)))

    assert verifier.verify_leaf_hash_inclusion(base64.b64decode(leaf_hash),
                                               index, audit_path, sth)

print "DNS Server test passed"