summaryrefslogtreecommitdiff
path: root/monitor/josef_experimental.py
blob: 5df124bcb0cdc77689cc467661d260159b750448 (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
#!/usr/bin/python
# -*- coding: utf-8 -*-     

import sys
import os
from josef_lib import *
from josef_lib2 import *
# import leveldb
import argparse
import json
import time
# from josef_leveldb import *
from datetime import datetime as dt
# from josef_monitor import verify_inclusion_by_hash
from monitor_conf import *

def is_new_timestamp(ts):
    MAX_TIMEDIFF = 300 # 5 min, allows for some clock skew
    ts_time = datetime.datetime.fromtimestamp(ts / 1000, UTC()).strftime('%Y-%m-%d %H:%M:%S')
    start_time = datetime.datetime.utcnow().strftime('2015-10-19 00:00:00')
    # delta_time = datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') - datetime.datetime.strptime(ts_time, '%Y-%m-%d %H:%M:%S')
    # print delta_time.seconds
    if ts_time < start_time:
        return False
    else:
        return True

def check_inclusion_by_submission(first, last, source, dests):
    # print entries
    for s_log in source:
        try:
            entries = []
            while len(entries) <= last - first:

                print "Getting " + str(first + len(entries)) + " to " + str(last)
                entries += get_entries(s_log["url"], first + len(entries), last)["entries"]
                # print "Fetched entries up to " + str(len(first + len(entries)))
        except:
            print "Failed to get entries from " + s_log["name"]

        for i in range(len(entries)):
            item = entries[i]
            inclusions = []
            for d_log in dests:
                try:
                    entry = extract_original_entry(item)
                    if entry[2]:
                        precert = True
                    else:
                        precert = False
                    submission = []

                    for e in entry[0]:
                        submission.append(base64.b64encode(e))

                    if entry[2]:
                        res = add_prechain(d_log["url"], {"chain" : submission})
                    else:
                        res = add_chain(d_log["url"], {"chain" : submission})
                    # print_reply(res, entry)
                    print res

                    if not is_new_timestamp(res["timestamp"]):
                        inclusions.append(d_log["name"])

                except KeyboardInterrupt:
                    sys.exit()
                except Exception ,e:
                    print Exception, e
                    pass
            s = s_log["name"] + "[" + str(first + i) + "] found in " + str(len(inclusions)) + " logs: " + str(inclusions)
            print s
            # log(logfile, s)
            time.sleep(1)


def update_roots(log):
    roots_hash = None

    roots = get_all_roots(log["url"])
    new_roots_hash = str(hash(str(roots)))

    if new_roots_hash != roots_hash:
        cert_dir = OUTPUT_DIR + log["name"] + "-roots"
        if not os.path.exists(cert_dir):
            os.makedirs(cert_dir)

        hash_list = []
        for cert in roots:
            h = str(hash(str(cert)))
            hash_list.append(h)

        loaded_list = os.listdir(cert_dir)

        added, removed = compare_lists(hash_list[:-1], loaded_list)

        # TODO log changes
        if len(added) != 0:
            print str(len(added)) + " new roots found!"
        if len(removed) != 0:
            print str(len(removed)) + " roots removed!"

        for item in removed:
            data = open(cert_dir + "/" + item).read()

            root_cert = base64.decodestring(data)
            subject = get_cert_info(root_cert)["subject"]
            issuer = get_cert_info(root_cert)["issuer"]
            if subject == issuer:
                print "Removed Root: " + item + ", " + subject
            else: 
                print "WTF? Not a root..."


        for item in added:
            root_cert = base64.decodestring(roots[hash_list.index(item)])
            subject = get_cert_info(root_cert)["subject"]
            issuer = get_cert_info(root_cert)["issuer"]
            if subject == issuer:
                print "New Root: " + item + ", " + subject
            else: 
                print "WTF? Not a root..."

            fn = cert_dir + "/" + item
            tempname = fn + ".new"
            data = roots[hash_list.index(item)]
            open(tempname, 'w').write(data)
            mv_file(tempname, fn)

def parse_entry(e, idx, log):
    # print the following fields, separated by sep
    sep = ";"

    s = log["name"]
    s += sep + str(idx) # index
    s += sep + e["subject"] # Subject
    s += sep + e["SAN"] # SAN
    s += sep + e["issuer"] # issuer
    s += sep + e["chain_length"] # path length
    s += sep + e["sig_algorithm"] # Signature algothithm
    s += sep + e["pubkey_algorithm"] # pubkey algorithm
    s += sep + e["not_before"] # valid from
    s += sep + e["not_after"] # valid to
    s += sep + e["validation"] # EV?
    s += sep + e["in_mozilla"] # chains to mozilla root?

    return s

def check_api2(url):
    print "\nTesting " + url
    try:
        print get_sth_v2(url)
    except:
        print "GET STH Failed..."

if __name__ == '__main__':

    




    # Data gathering for Niklas
    if False:
        log = CTLOGS[0]
        sth = get_sth(log["url"])
        # size = sth["tree_size"]
        # for i in range(15,200):
        start = 5757748
        end = 5757847
        print "Getting " + str(start) + " to " + str(end)
        entries = get_entries(log["url"],start ,end)["entries"]

        # TODO set filename
        filename = "ct_log_content.txt"
        # TODO remove file if exists
        if os.path.exists(filename):
            os.remove(filename)
        # TODO open file
        with open(filename, 'a') as f:
        # TODO write lines
            for i in range(len(entries)):
                entry = entries[i]
                res = check_domain_extended(entry)
                string = parse_entry(res, i + start, log)
                f.write(string + "\n")