summaryrefslogtreecommitdiff
path: root/support/ctlogconfig
blob: a3ac6ff5855d7e311080f5b1b8c9df4ecfc365cb (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
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import re
import sqlite3
import sys


def create_tables(db_name):
    cxn = sqlite3.connect(db_name)
    cur = cxn.cursor()

    cur.execute(
        'CREATE TABLE loginfo('
        + 'id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '
        + 'log_id TEXT, '
        + 'public_key TEXT, '  # path to PEM-encoded file
        + 'distrusted INTEGER, '  # non-zero if not trusted
        + 'min_valid_timestamp INTEGER, '
        + 'max_valid_timestamp INTEGER, '
        + 'url TEXT)'
    )
    cur.close()
    cxn.commit()
    cxn.close()


def record_id_arg(cur, args, required=False):
    if len(args) < 1 or args[0][0] != '#' or len(args[0]) < 2:
        if required:
            print >> sys.stderr, 'A record id was not provided'
            sys.exit(1)
        return None
    record_id = args.pop(0)[1:]
    stmt = 'SELECT * FROM loginfo WHERE id = ?'
    cur.execute(stmt, [record_id])
    recs = list(cur.fetchall())
    assert len(recs) < 2
    if len(recs) == 0:
        print >> sys.stderr, 'Record #%s was not found' % record_id
        sys.exit(1)
    return record_id


def log_id_arg(cur, args, required=True):
    if len(args) < 1 or len(args[0]) != 64:
        if not required:
            return None
        print >> sys.stderr, 'A log id was not provided'
        sys.exit(1)
    log_id = args.pop(0).upper()
    if len(re.compile(r'[A-Z0-9]').findall(log_id)) != len(log_id):
        print >> sys.stderr, 'The log id is not formatted properly'
        sys.exit(1)
    return log_id


def public_key_arg(args):
    if len(args) < 1:
        print >> sys.stderr, 'A public key file was not provided'
        sys.exit(1)
    pubkey = args.pop(0)
    if not os.path.exists(pubkey):
        print >> sys.stderr, 'Public key file %s could not be read' % pubkey
        sys.exit(1)
    return pubkey


def time_arg(args):
    if len(args) < 1:
        print >> sys.stderr, 'A timestamp was not provided'
        sys.exit(1)
    t = args.pop(0)
    if t == '-':
        return None
    bad_val = False
    val = None
    try:
        val = int(t)
    except ValueError:
        bad_val = True

    if bad_val or val < 1:
        print >> sys.stderr, 'The timestamp "%s" is invalid' % t
        sys.exit(1)

    return val


def configure_public_key(cur, args):
    record_id = record_id_arg(cur, args, False)
    public_key = public_key_arg(args)
    if len(args) != 0:
        usage()
    if not record_id:
        stmt = 'INSERT INTO loginfo (public_key) VALUES(?)'
        cur.execute(stmt, [public_key])
    else:
        stmt = 'UPDATE loginfo SET public_key = ? WHERE id = ?'
        cur.execute(stmt, [public_key, record_id])


def configure_url(cur, args):
    # can't specify more than one of record-id and log-id
    log_id = None
    record_id = record_id_arg(cur, args, False)
    if not record_id:
        log_id = log_id_arg(cur, args, False)
    if len(args) != 1:
        usage()
    url = args.pop(0)

    if record_id:
        stmt = 'UPDATE loginfo SET url = ? WHERE id = ?'
        args = [url, record_id]
    elif log_id:
        stmt = 'INSERT INTO loginfo (log_id, url) VALUES(?, ?)'
        args = [log_id, url]
    else:
        stmt = 'INSERT INTO loginfo (url) VALUES(?)'
        args = [url]

    cur.execute(stmt, args)


def forget_log(cur, args):
    record_id = record_id_arg(cur, args, False)
    log_id = None
    if not record_id:
        log_id = log_id_arg(cur, args, True)
    if len(args) != 0:
        usage()
    if record_id:
        stmt = 'DELETE FROM loginfo WHERE id = ?'
        args = [record_id]
    else:
        stmt = 'DELETE FROM loginfo WHERE log_id = ?'
        args = [log_id]
    cur.execute(stmt, args)


def trust_distrust_log(cur, args):
    # could take a record id or a log id
    record_id = record_id_arg(cur, args, False)
    if record_id:
        log_id = None
    else:
        log_id = log_id_arg(cur, args)

    if len(args) != 1:
        usage()
    flag = args.pop(0)

    if not record_id:
        stmt = 'INSERT INTO loginfo (log_id, distrusted) VALUES(?, ?)'
        cur.execute(stmt, [log_id, flag])
    else:
        stmt = 'UPDATE loginfo SET distrusted = ? WHERE id = ?'
        cur.execute(stmt, [flag, record_id])


def trust_log(cur, args):
    trust_distrust_log(cur, args + [0])


def distrust_log(cur, args):
    trust_distrust_log(cur, args + [1])


def time_range(cur, args):
    # could take a record id or a log id
    record_id = record_id_arg(cur, args, False)
    if record_id:
        log_id = None
    else:
        log_id = log_id_arg(cur, args)

    min_valid_time = time_arg(args)
    max_valid_time = time_arg(args)
    if len(args) != 0:
        usage()
    if not record_id:
        stmt = 'INSERT INTO loginfo ' + \
               '(log_id, min_valid_timestamp, max_valid_timestamp) ' + \
               'VALUES(?, ?, ?)'
        cur.execute(stmt, [log_id, min_valid_time, max_valid_time])
    else:
        stmt = 'UPDATE loginfo SET min_valid_timestamp = ?, ' + \
               'max_valid_timestamp = ? WHERE id = ?'
        cur.execute(stmt, [min_valid_time, max_valid_time, record_id])


class ConfigEntry:

    pass


def dump_ll(cur):
    stmt = 'SELECT * FROM loginfo'
    cur.execute(stmt)
    recs = []
    for row in cur.fetchall():
        obj = ConfigEntry()
        obj.id = row[0]
        obj.log_id = row[1]
        obj.public_key = row[2]
        obj.distrusted = row[3]
        obj.min_valid_timestamp = row[4]
        obj.max_valid_timestamp = row[5]
        obj.url = row[6]
        recs += [obj]
    return recs


def dump(cur, args):
    if len(args) != 0:
        usage()
    recs = dump_ll(cur)
    for rec in recs:
        not_conf = '(not configured)'

        mint = \
            str(rec.min_valid_timestamp) if rec.min_valid_timestamp else '-INF'
        maxt = \
            str(rec.max_valid_timestamp) if rec.max_valid_timestamp else '+INF'
        print 'Log entry:'
        print '  Record ' + str(rec.id) + \
            (' (DISTRUSTED)' if rec.distrusted else '')
        print '  Log id         : ' + (rec.log_id if rec.log_id else not_conf)
        print '  Public key file: ' + \
            (rec.public_key if rec.public_key else not_conf)
        print '  URL            : ' + (rec.url if rec.url else not_conf)
        print '  Time range     : ' + mint + ' to ' + maxt
        print ''


def usage():
    help = """Usage: %s /path/to/log-config-db command args

Commands:
  display config-db contents:
    dump
  configure public key:
    configure-public-key [log-id|record-id] /path/log-pub-key.pem
  configure URL:
    configure-url [log-id|record-id] http://www.example.com/path/
  configure min and/or max valid timestamps:
    valid-time-range log-id|record-id min-range max-range
  mark log as trusted (default):
    trust log-id|record-id
  mark log as untrusted:
    distrust log-id|record-id
  remove log config from config-db:
    forget log-id|record-id

log-id is a 64-character hex string representation of a log id

record-id references an existing entry and is in the form:
  #<record-number>
  (displayable with the dump command)
""" % sys.argv[0]
    print >> sys.stderr, help
    sys.exit(1)


def main(argv):
    if len(argv) < 3:
        usage()

    db_name = argv[1]
    cmd = argv[2]
    args = argv[3:]

    cmds = {'configure-public-key': configure_public_key,
            'configure-url': configure_url,
            'distrust': distrust_log,
            'trust': trust_log,
            'forget': forget_log,
            'valid-time-range': time_range,
            'dump': dump,
            }

    cmds_requiring_db = ['dump', 'forget']  # db must already exist

    if not cmd in cmds:
        usage()

    if not os.path.exists(db_name):
        if not cmd in cmds_requiring_db:
            create_tables(db_name)
        else:
            print >> sys.stderr, 'Database "%s" does not exist' % db_name
            sys.exit(1)

    cxn = sqlite3.connect(db_name)
    cur = cxn.cursor()

    cmds[cmd](cur, args)

    cur.close()
    cxn.commit()
    cxn.close()

if __name__ == "__main__":
    main(sys.argv)