summaryrefslogtreecommitdiff
path: root/bin-src/crtsh-pem2html.go
blob: 432020e5cd4c56ff39c7a6bac47e55d16c8df248 (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
package main

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"html/template"
	"io/ioutil"
	"os"
	"sort"
	"time"

	"./util"
)

func handleErr(err error, str string, a ...interface{}) {
	a = append([]interface{}{err}, a...)
	if err != nil {
		fmt.Fprintf(os.Stderr, str, a...)
		os.Exit(1)
	}
}

func handleBool(ok bool, str string, a ...interface{}) {
	if !ok {
		fmt.Fprintf(os.Stderr, str, a...)
		os.Exit(1)
	}
}

func rfc6962type(certX509 *x509.Certificate) string {
	if util.IsPrecertificate(certX509) {
		return "Precertificate"
	}
	return "Certificate"
}

var tmpl = template.Must(template.New("pem2html").
	Funcs(template.FuncMap{
		"red":           red,
		"green":         green,
		"rfc6962type":   rfc6962type,
		"date":          util.Date2HTML,
		"datetime":      util.DateTime2HTML,
		"colorDatetime": util.DateTime2ColorHTML,
	}).Parse(`<table class=sortable>
  <caption>
    <p>CT log (Updated {{.now | colorDatetime}})</p>
  </caption>
  <tr>
    <th>Logged</th>
    <th>NotBefore</th>
    <th>NotAfter</th>
    <th>Subject.CN</th>
    <th>Issuer.O</th>
    <th>SCTs</th>
  </tr>
{{range $cert := .certs}}
  <tr>
    <td style="background-color: {{$cert.Updated             | green}}"><a target="_blank" href="{{$cert.Main.Url}}">{{$cert.Updated             | date}}</a></td>
    <td style="background-color: {{$cert.Main.X509.NotBefore | green}}"><a target="_blank" href="{{$cert.Main.Url}}">{{$cert.Main.X509.NotBefore | date}}</a></td>
    <td style="background-color: {{$cert.Main.X509.NotAfter  | red  }}"><a target="_blank" href="{{$cert.Main.Url}}">{{$cert.Main.X509.NotAfter  | date}}</a></td>
    <td><a target="_blank" href="{{$cert.Main.Url}}">{{$cert.Main.X509.Subject.CommonName}}</a></td>
    <td><a target="_blank" href="{{$cert.Main.Url}}">{{$cert.Main.X509.Issuer.Organization}}</a></td>
    <td>{{range $i, $sct := $cert.Precerts}}
      <a target="_blank" href="{{$sct.Url}}">[{{$i}}]</a>
    {{end}}</td>
  </tr>
{{end}}
</table>
`))

func getNow() time.Time {
	stat, err := os.Stdin.Stat()
	if err == nil {
		return stat.ModTime()
	} else {
		return time.Now()
	}
}

var now = getNow()

func green(t time.Time) string {
	max := byte(0xF3)
	// When did we get the cert?
	//  - 30 days ago => 0 green
	//  - just now => max green
	greenness := util.MapRange(
		util.TimeRange{now.AddDate(0, 0, -30), now},
		util.ByteRange{0, max},
		t)
	return fmt.Sprintf("#%02X%02X%02X", max-greenness, max, max-greenness)
}

func red(t time.Time) string {
	max := byte(0xF3)
	// When with the cert expire?
	//  - now => max red
	//  - 30 days from now => 0 red
	redness := util.MapRange(
		util.TimeRange{now, now.AddDate(0, 0, 30)},
		util.ByteRange{max, 0},
		t)
	return fmt.Sprintf("#%02X%02X%02X", max, max-redness, max-redness)
}

type Cert struct {
	Url     string
	Updated time.Time
	X509    *x509.Certificate
}

// A CertSet is a set of certificates all sharing the same
// SerialNumber.  Normally, this will be 1 regular certificate, and
// any number of pre-certificates.
type CertSet []Cert

// Given a list of certificates all sharing the same serial number,
// return a list of CertSets.  If there are multiple regular
// certificates, it returns a seprate CertSet for each.
func NewCertSet(certs []Cert) []CertSet {
	if len(certs) == 0 {
		return nil
	}
	var retCerts []Cert
	var retPrecerts []Cert
	for _, cert := range certs {
		if util.IsPrecertificate(cert.X509) {
			retPrecerts = append(retPrecerts, cert)
		} else {
			retCerts = append(retCerts, cert)
		}
	}
	if len(retCerts) == 0 {
		return []CertSet{CertSet(retPrecerts)}
	}
	ret := make([]CertSet, len(retCerts))
	for i := range ret {
		ret[i] = append(CertSet{retCerts[i]}, retPrecerts...)
	}
	return ret
}

func (certs CertSet) Main() Cert {
	//if util.IsPrecertificate(certs[0].X509) {
	//	return Cert{X509: new(x509.Certificate)}
	//}
	return certs[0]
}

func (certs CertSet) Precerts() []Cert {
	return certs[1:]
}

// Updated returns the most recent "Updated" timestamp of any of the
// certificates in the CertSet.
func (certs CertSet) Updated() time.Time {
	ret := certs[0].Updated
	for _, cert := range certs {
		if cert.Updated.After(ret) {
			ret = cert.Updated
		}
	}
	return ret
}

type CertList []CertSet

// Len is the number of elements in the collection.
func (l CertList) Len() int {
	return len(l)
}

// Less reports whether the element with
// index i should sort before the element with index j.
func (l CertList) Less(i, j int) bool {
	return l[i].Updated().After(l[j].Updated())
}

// Swap swaps the elements with indexes i and j.
func (l CertList) Swap(i, j int) {
	tmp := l[i]
	l[i] = l[j]
	l[j] = tmp
}

func main() {
	data, err := ioutil.ReadAll(os.Stdin)
	handleErr(err, "Error reading stdin: %v\n")

	bySerial := make(map[string][]Cert)
	for len(data) > 0 {
		var certPem *pem.Block
		certPem, data = pem.Decode(data)

		var ok bool
		var cert Cert

		cert.Url, ok = certPem.Headers["X-Crt-Sh-Url"]
		handleBool(ok, "Did not get X-Crt-Sh-Url\n")

		str, ok := certPem.Headers["X-Crt-Sh-Updated"]
		handleBool(ok, "Did not get X-Crt-Sh-Updated\n")
		cert.Updated, err = time.Parse("2006-01-02T15:04:05Z", str)
		handleErr(err, "Could not parse updated time")

		cert.X509, err = x509.ParseCertificate(certPem.Bytes)
		handleErr(err, "Error parsing cert: %v\n")

		serial := fmt.Sprintf("%036x", cert.X509.SerialNumber)
		bySerial[serial] = append(bySerial[serial], cert)
	}

	var certs CertList
	for _, set := range bySerial {
		certs = append(certs, NewCertSet(set)...)
	}

	sort.Sort(certs)
	handleErr(tmpl.Execute(os.Stdout, map[string]interface{}{"certs": certs, "now": now}), "Could not execute template: %v\n")
}