-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathpullCTLogsIntoDB.go
167 lines (157 loc) · 4.88 KB
/
pullCTLogsIntoDB.go
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
/* Script that pulls certificates from the CT log
and inserts them into the observatory database
usage: TLSOBS_DBUSER=tlsobsapi TLSOBS_DBPASS=mysecretpassphrase TLSOBS_DBHOST=127.0.0.1:5432 go run pullCTLogsIntoDB.go
*/
package main
import (
"bytes"
"encoding/base64"
"encoding/pem"
"fmt"
"log"
"net/http"
"os"
"strconv"
"time"
"crypto/x509"
"github.com/google/certificate-transparency/go"
"github.com/google/certificate-transparency/go/client"
"github.com/google/certificate-transparency/go/jsonclient"
ctx509 "github.com/google/certificate-transparency/go/x509"
"github.com/mozilla/tls-observatory/certificate"
pg "github.com/mozilla/tls-observatory/database"
)
const CTBATCHSIZE = 100
func main() {
var (
err error
offset int
)
db, err := pg.RegisterConnection(
"observatory",
os.Getenv("TLSOBS_DBUSER"),
os.Getenv("TLSOBS_DBPASS"),
os.Getenv("TLSOBS_DBHOST"),
"require")
defer db.Close()
if err != nil {
log.Fatalf("Failed to connect to database: %v", err)
}
var one uint
err = db.QueryRow("SELECT 1").Scan(&one)
if err != nil {
log.Fatal("Database connection failed:", err)
}
if one != 1 {
log.Fatal("Apparently the database doesn't know the meaning of one anymore. Crashing.")
}
httpCli := &http.Client{
Transport: &http.Transport{
DisableCompression: true,
DisableKeepAlives: false,
},
Timeout: 10 * time.Second,
}
// create a certificate transparency client
ctLog, err := client.New(os.Getenv("CTLOG"), httpCli, jsonclient.Options{})
if err != nil {
log.Fatalf("Failed to connect to CT log: %v", err)
}
if len(os.Args) > 1 {
offset, err = strconv.Atoi(os.Args[1])
if err != nil {
log.Fatal(err)
}
}
for {
log.Printf("retrieving CT logs %d to %d", offset, offset+CTBATCHSIZE)
rawEnts, err := ctLog.GetEntries(nil, int64(offset), int64(offset+CTBATCHSIZE))
if err != nil {
log.Println("Failed to retrieve entries from CT log: ", err)
time.Sleep(10 * time.Second)
continue
}
// loop over CT records
for i, ent := range rawEnts {
log.Printf("CT index=%d", offset+i)
var ctcertX509 *ctx509.Certificate
switch ent.Leaf.TimestampedEntry.EntryType {
case ct.X509LogEntryType:
ctcertX509, err = ctx509.ParseCertificate(ent.Leaf.TimestampedEntry.X509Entry.Data)
case ct.PrecertLogEntryType:
ctcertX509, err = ctx509.ParseTBSCertificate(ent.Leaf.TimestampedEntry.PrecertEntry.TBSCertificate)
}
if err != nil {
log.Printf("Failed to parse CT certificate: %v", err)
continue
}
log.Printf("CN=%s; Issuer=%s", ctcertX509.Subject.CommonName, ctcertX509.Issuer.CommonName)
log.Printf("Not Before=%s; Not After=%s", ctcertX509.NotBefore, ctcertX509.NotAfter)
certHash := certificate.SHA256Hash(ctcertX509.Raw)
id, err := db.GetCertIDBySHA256Fingerprint(certHash)
if err != nil {
log.Printf("Failed to lookup certificate hash %s in database: %v", certHash, err)
continue
}
if id > 0 {
// if the cert already exists in DB, return early
log.Printf("Certificate is already in database: id=%d", id)
continue
}
// Format the PEM certificate, this is silly but we need to because the CT x509 is
// different from the crypto/x509 type
payload := base64.StdEncoding.EncodeToString(ctcertX509.Raw)
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "-----BEGIN CERTIFICATE-----\n")
for len(payload) > 0 {
chunkLen := len(payload)
if chunkLen > 64 {
chunkLen = 64
}
fmt.Fprintf(buf, "%s\n", payload[0:chunkLen])
payload = payload[chunkLen:]
}
fmt.Fprintf(buf, "-----END CERTIFICATE-----")
block, _ := pem.Decode(buf.Bytes())
if block == nil {
log.Printf("Failed to parse certificate PEM")
continue
}
certX509, err := x509.ParseCertificate(block.Bytes)
if err != nil {
log.Printf("Could not parse X.509 certificate: %v", err)
continue
}
var valInfo certificate.ValidationInfo
cert := certificate.CertToStored(certX509, certHash, "", "", "", &valInfo)
id, err = db.InsertCertificate(&cert)
if err != nil {
log.Print("Failed to store certificate in database: %v", err)
continue
}
cert.ID = id
// If the cert is self-signed (aka. Root CA), we're done here
if cert.IsSelfSigned() {
log.Print("Certificate is self-signed")
continue
}
// to insert the trust, first build the certificate paths, then insert one trust
// entry for each known parent of the cert
paths, err := db.GetCertPaths(&cert)
if err != nil {
log.Printf("Failed to retrieve chains from database: %v", err)
continue
}
for _, parent := range paths.Parents {
cert.ValidationInfo = parent.GetValidityMap()
_, err := db.InsertTrustToDB(cert, cert.ID, parent.Cert.ID)
if err != nil {
log.Printf("Failed to store trust in database: %v", err)
continue
}
}
log.Printf("URL = https://tls-observatory.services.mozilla.com/static/certsplainer.html?id=%d", id)
}
offset += CTBATCHSIZE
}
}