-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
462 lines (404 loc) · 12 KB
/
main.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
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// (c) 2017 - Bas Westerbaan <[email protected]>
// You may redistribute this file under the conditions of the GPLv3.
// irma-watchdogd is a simple webserver that checks various properties of
// the public irma infrastructure.
package main
import (
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
"path"
"strings"
"sync"
"time"
irma "github.com/privacybydesign/irmago"
"github.com/ashwanthkumar/slack-go-webhook"
"github.com/dustin/go-humanize"
"gopkg.in/yaml.v2"
"github.com/bwesterb/go-atum"
)
var exampleConfig string = `
checkschememanagers:
https://privacybydesign.foundation/schememanager/pbdf:
|
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELzHV5ipBimWpuZIDaQQd+KmNpNop
dpBeCqpDwf+Grrw9ReODb6nwlsPJ/c/gqLnc+Y3sKOAJ2bFGI+jHBSsglg==
-----END PUBLIC KEY-----
bindaddr: ':8079'
interval: 5m `
var rawTemplate string = `
<html>
<head>
<title>irma watchdog</title>
<style>
body {
color: white;
background-color: black;
font-family: Open Sans,Helvetica,Arial,sans-serif;
font-size: smaller;
}
</style>
</head>
<body>
<ul>
{{ range $i, $issue := .Issues }}
<li>{{ $issue }}</li>
{{ else }}
<li>Everything is ok!</li>
{{ end }}
</ul>
<p>Last update {{ .LastCheck }}</p>
<script type="text/javascript">
setTimeout(function() {
window.location.reload(1);
}, {{ .Interval }});
</script>
</body>
</html>`
type templateContext struct {
Issues []string
Interval int
LastCheck string
}
// Globals
var (
conf Conf
ticker *time.Ticker
lastCheck time.Time
initialCheck bool
issues issueEntries
parsedTemplate *template.Template
)
// Configuration
type Conf struct {
CheckSchemeManagers map[string]string // {url: pk}
BindAddr string // port to bind to
CheckCertificateExpiry []string
CheckAtumServers []string
HealthChecks []HealthCheck
Interval time.Duration
SlackWebhooks []string
WebHooks []string
}
func main() {
var confPath string
// set configuration defaults
conf.BindAddr = ":8079"
conf.Interval = 5 * time.Minute
// parse commandline
flag.StringVar(&confPath, "config", "config.yaml",
"Path to configuration file")
flag.Parse()
// parse configuration file
if _, err := os.Stat(confPath); os.IsNotExist(err) {
fmt.Printf("Could not find config file: %s\n", confPath)
fmt.Println("It should look something like")
fmt.Println(exampleConfig)
os.Exit(1)
return
} else if err != nil {
log.Fatalf("Could not stat configuration file: %v", err)
}
buf, err := os.ReadFile(confPath)
if err != nil {
log.Fatalf("Could not read config file %s: %s", confPath, err)
}
if err := yaml.Unmarshal(buf, &conf); err != nil {
log.Fatalf("Could not parse config file: %s", err)
}
// Load IRMA configuration
tempDir, err := os.MkdirTemp("", "")
if err != nil {
log.Printf("checkSchemeManager: TempDir: %s", err)
return
}
defer os.RemoveAll(tempDir)
icDir := path.Join(tempDir, "irma_configuration")
err = os.Mkdir(icDir, 0700)
if err != nil {
log.Printf("MkDir in temp dir for IRMA configuration (%s): %s", icDir, err)
return
}
irmaConfig, err := irma.NewConfiguration(icDir, irma.ConfigurationOptions{})
if err != nil {
log.Printf("IRMA configuration could not be loaded in temp dir %s: %s", icDir, err)
return
}
for url, pk := range conf.CheckSchemeManagers {
if err = irmaConfig.InstallScheme(url, []byte(pk)); err != nil {
log.Printf("could not install scheme %s: %s", icDir, err)
return
}
}
// set up HTTP server
http.HandleFunc("/", handler)
// parse template
parsedTemplate, err = template.New("template").Parse(rawTemplate)
if err != nil {
panic(err)
}
log.Printf("Will check status every %s", conf.Interval)
ticker = time.NewTicker(conf.Interval)
go func() {
initialCheck = true
for {
runChecks(irmaConfig)
<-ticker.C
}
}()
log.Printf("Listening on %s", conf.BindAddr)
log.Fatal(http.ListenAndServe(conf.BindAddr, nil))
}
// Handle / HTTP request
func handler(w http.ResponseWriter, r *http.Request) {
err := parsedTemplate.Execute(w, templateContext{
LastCheck: humanize.Time(lastCheck),
Issues: issues.messages(),
Interval: int(conf.Interval.Seconds() * 1000),
})
if err != nil {
log.Printf("Error executing template: %s", err)
}
}
// Computes difference between old and new issues
func difference(old, cur issueEntries) (came, gone issueEntries) {
lut := make(map[string]bool)
for _, x := range old {
lut[x.message] = true
}
for _, x := range cur {
if _, ok := lut[x.message]; !ok {
came = append(came, x)
} else {
lut[x.message] = false
}
}
for _, x := range old {
isGone := lut[x.message]
if isGone {
gone = append(gone, x)
}
}
return
}
func runChecks(irmaConfig *irma.Configuration) {
var curIssues issueEntries
log.Println("Running checks ...")
curIssues = append(curIssues, checkSchemeManagers(irmaConfig)...)
curIssues = append(curIssues, checkCertificateExpiry()...)
curIssues = append(curIssues, checkAtumServers()...)
curIssues = append(curIssues, runHealthChecks(conf.HealthChecks)...)
logCurrentIssues(curIssues.messages())
newIssues, fixedIssues := difference(issues, curIssues)
if len(conf.SlackWebhooks) > 0 {
go pushToSlack(newIssues, fixedIssues, initialCheck)
}
// If this is an initial check, don't send the issues to webhooks
if len(conf.WebHooks) > 0 && !initialCheck {
go pushToWebHooks(newIssues)
}
issues = curIssues
initialCheck = false
lastCheck = time.Now()
}
func pushToWebHooks(newIssues issueEntries) {
dangers := newIssues.filter(danger)
for _, msg := range dangers {
for _, bareURL := range conf.WebHooks {
u := fmt.Sprintf(bareURL, url.QueryEscape("Watchdog: "+msg))
res, err := http.Get(u)
if err != nil {
log.Printf("Webhook %s: %s", u, err)
return
}
body, err := io.ReadAll(res.Body)
if err != nil {
log.Printf("Webhook response body error: %s", err)
return
}
if len(body) != 0 {
log.Printf("Webhook response body: %s", string(body))
}
}
}
}
func pushToSlack(newIssues, fixedIssues issueEntries, initial bool) {
strGood := "good"
strWarning := "warning"
strBad := "bad"
if len(newIssues) > 0 {
if initial {
pushMessageToSlack("I just (re)started, so I might repeat some known issues.", []slack.Attachment{})
}
dangers := newIssues.filter(danger)
warnings := newIssues.filter(warning)
if len(dangers) > 0 {
// Add mention such that notifications for warnings can be suppressed.
message := "<!channel> New issues discovered."
var attachments []slack.Attachment
for _, msg := range dangers {
msg := msg
attachments = append(attachments, slack.Attachment{
Fallback: &msg,
Text: &msg,
Color: &strBad,
})
}
pushMessageToSlack(message, attachments)
}
if len(warnings) > 0 {
message := "New warnings discovered."
var attachments []slack.Attachment
for _, msg := range warnings {
msg := msg
attachments = append(attachments, slack.Attachment{
Fallback: &msg,
Text: &msg,
Color: &strWarning,
})
}
pushMessageToSlack(message, attachments)
}
}
if len(fixedIssues) > 0 {
message := "The following issues and warnings were fixed."
var attachments []slack.Attachment
for _, msg := range fixedIssues.messages() {
msg := msg
attachments = append(attachments, slack.Attachment{
Fallback: &msg,
Text: &msg,
Color: &strGood,
})
}
pushMessageToSlack(message, attachments)
}
}
func pushMessageToSlack(message string, attachments []slack.Attachment) {
for _, url := range conf.SlackWebhooks {
payload := slack.Payload{
Text: message,
Username: "irma-watchdogd",
IconEmoji: ":dog:",
Attachments: attachments,
}
if err := slack.Send(url, "", payload); err != nil {
log.Printf("SlackWebhook %s: %s", url, err)
continue
}
}
}
func logCurrentIssues(curIssues []string) {
if len(curIssues) > 0 {
log.Printf("Issues found:\n%s", strings.Join(curIssues, "\n"))
}
}
func checkCertificateExpiry() (ret issueEntries) {
var waitGroup sync.WaitGroup
waitGroup.Add(len(conf.CheckCertificateExpiry))
issueEntriesChan := make(chan issueEntries, len(conf.CheckCertificateExpiry))
for _, check := range conf.CheckCertificateExpiry {
check := check
go func() {
issueEntriesChan <- checkCertificateExpiryOf(check)
waitGroup.Done()
}()
// Introduce a small delay to prevent all checks to be started at the same time.
time.Sleep(10 * time.Millisecond)
}
waitGroup.Wait()
close(issueEntriesChan)
for entries := range issueEntriesChan {
ret = append(ret, entries...)
}
return
}
func checkCertificateExpiryOf(url string) (ret issueEntries) {
log.Printf(" checking certificate expiry on %s", url)
client := newHTTPClient()
resp, err := client.Head(url)
if err != nil {
ret = append(ret, issueEntry{warning, fmt.Sprintf("%s: error %s", url, err)})
return
}
defer resp.Body.Close()
if resp.TLS == nil {
ret = append(ret, issueEntry{warning, fmt.Sprintf("%s: no TLS enabled", url)})
return
}
for _, cert := range resp.TLS.PeerCertificates {
issuer := strings.Join(cert.Issuer.Organization, ", ")
daysExpired := int(time.Since(cert.NotAfter).Hours() / 24)
if daysExpired > 0 {
ret = append(ret, issueEntry{danger, fmt.Sprintf("%s: certificate from %s has expired %d days", url, issuer, daysExpired)})
} else if daysExpired > -30 {
ret = append(ret, issueEntry{warning, fmt.Sprintf("%s: certificate from %s will expire in %d days", url, issuer, -daysExpired)})
}
}
return ret
}
func checkAtumServers() (ret issueEntries) {
for _, url := range conf.CheckAtumServers {
ret = append(ret, checkAtumServer(url)...)
}
return
}
func checkAtumServer(url string) (ret issueEntries) {
log.Printf(" checking atum server %s", url)
ts, err := atum.JsonStamp(url, []byte{1, 2, 3, 4, 5})
if err != nil {
ret = append(ret, issueEntry{danger, fmt.Sprintf("%s: requesting Atum stamp failed: %s", url, err)})
return
}
valid, _, url2, err := atum.Verify(ts, []byte{1, 2, 3, 4, 5})
if err != nil {
ret = append(ret, issueEntry{danger, fmt.Sprintf("%s: failed to verify signature: %s", url, err)})
return
}
if !valid {
ret = append(ret, issueEntry{danger, fmt.Sprintf("%s: timestamp invalid", url)})
return
}
if url != url2 {
ret = append(ret, issueEntry{warning, fmt.Sprintf("%s: timestamp set for wrong url: %s", url, url2)})
return
}
return
}
// The IRMA app keeps functioning when the scheme is down, so all issues that we find are warnings.
func checkSchemeManagers(irmaConfig *irma.Configuration) (ret issueEntries) {
log.Printf(" checking schememanagers")
// Clear warnings of previous invocations
irmaConfig.Warnings = []string{}
// Schemes are already downloaded in main(), only an update is required now
// Updating the schemes also automatically reparses them when necessary, populating irmaConfig.Warnings
err := irmaConfig.UpdateSchemes()
if err != nil {
ret = append(ret, issueEntry{warning, fmt.Sprintf("irma scheme verify: update schemes: %s", err)})
return
}
// ParseFolder of UpdateSchemes is skipped when non of the schemes had to be updated. To enforce
// the warnings from ParseFolder to be generated always, ParseFolder has to be invoked here too.
// To avoid duplicate warnings, also clear warnings again.
irmaConfig.Warnings = []string{}
err = irmaConfig.ParseFolder()
if err != nil {
ret = append(ret, issueEntry{warning, fmt.Sprintf("irma scheme verify: parse folder: %s", err)})
return
}
// Check expiry dates on public keys
if err = irmaConfig.ValidateKeys(); err != nil {
ret = append(ret, issueEntry{warning, fmt.Sprintf("irma scheme verify: keys: %s", err)})
return
}
for _, warn := range irmaConfig.Warnings {
ret = append(ret, issueEntry{warning, warn})
}
return
}