main.go 11.5 KB
Newer Older
Bas Westerbaan's avatar
Bas Westerbaan committed
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
// (c) 2017 - Bas Westerbaan <bas@westerbaan.name>
// 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 (
	"encoding/xml"
	"flag"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	netUrl "net/url"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"

	"gopkg.in/yaml.v2"

27
	"github.com/ashwanthkumar/slack-go-webhook"
28
29
	"github.com/privacybydesign/irmago"
	schememgr "github.com/privacybydesign/irmago/schememgr/cmd"
Bas Westerbaan's avatar
Bas Westerbaan committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
)

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>
Bas Westerbaan's avatar
Bas Westerbaan committed
45
46
47
48
49
50
51
52
53
54
55
    <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>
Bas Westerbaan's avatar
Bas Westerbaan committed
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
    <body>
        <ul>
        {{ range $i, $issue := .Issues }}
            <li>{{ $issue }}</li>
        {{ else }}
            <li>Everything is ok!</li>
        {{ end }}
        </ul>
        <p>Last update at {{ .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
Bas Westerbaan's avatar
Bas Westerbaan committed
84
	initialCheck   bool
Bas Westerbaan's avatar
Bas Westerbaan committed
85
86
87
88
89
90
	issues         []string
	parsedTemplate *template.Template
)

// Configuration
type Conf struct {
Bas Westerbaan's avatar
Bas Westerbaan committed
91
92
93
94
	CheckSchemeManagers    map[string]string // {url: pk}
	BindAddr               string            // port to bind to
	CheckCertificateExpiry []string
	Interval               time.Duration
95
	SlackWebhooks          []string
Bas Westerbaan's avatar
Bas Westerbaan committed
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
}

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
	}

	buf, err := ioutil.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)
	}

	// 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() {
Bas Westerbaan's avatar
Bas Westerbaan committed
141
		initialCheck = true
Bas Westerbaan's avatar
Bas Westerbaan committed
142
143
144
145
146
147
148
149
150
151
152
		for {
			check()
			<-ticker.C
		}
	}()

	log.Printf("Listening on %s", conf.BindAddr)

	log.Fatal(http.ListenAndServe(conf.BindAddr, nil))
}

153
// Handle / HTTP request
Bas Westerbaan's avatar
Bas Westerbaan committed
154
155
156
157
158
159
160
161
162
163
164
func handler(w http.ResponseWriter, r *http.Request) {
	err := parsedTemplate.Execute(w, templateContext{
		LastCheck: lastCheck.Format("2006-01-02 15:04:05"),
		Issues:    issues,
		Interval:  int(conf.Interval.Seconds() * 1000),
	})
	if err != nil {
		log.Printf("Error executing template: %s", err)
	}
}

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Computes difference between old and new issues
func difference(old, cur []string) (came, gone []string) {
	came = []string{}
	gone = []string{}
	lut := make(map[string]bool)
	for _, x := range old {
		lut[x] = false
	}
	for _, x := range cur {
		if _, ok := lut[x]; !ok {
			came = append(came, x)
		} else {
			lut[x] = true
		}
	}
	for x, isGone := range lut {
		if isGone {
			gone = append(gone, x)
		}
	}
	return
}

Bas Westerbaan's avatar
Bas Westerbaan committed
188
func check() {
189
	curIssues := []string{}
Bas Westerbaan's avatar
Bas Westerbaan committed
190
191

	log.Println("Running checks ...")
192
193
	curIssues = append(curIssues, checkSchemeManagers()...)
	curIssues = append(curIssues, checkCertificateExpiry()...)
Bas Westerbaan's avatar
Bas Westerbaan committed
194

195
196
	if len(conf.SlackWebhooks) > 0 {
		newIssues, fixedIssues := difference(issues, curIssues)
Bas Westerbaan's avatar
Bas Westerbaan committed
197
		go pushToSlack(newIssues, fixedIssues, initialCheck)
198
199
200
	}

	issues = curIssues
Bas Westerbaan's avatar
Bas Westerbaan committed
201
	initialCheck = false
Bas Westerbaan's avatar
Bas Westerbaan committed
202
203
204
	lastCheck = time.Now()
}

Bas Westerbaan's avatar
Bas Westerbaan committed
205
func pushToSlack(newIssues, fixedIssues []string, initial bool) {
206
207
208
209
	strGood := "good"
	strBad := "bad"
	for _, url := range conf.SlackWebhooks {
		if len(newIssues) > 0 {
Bas Westerbaan's avatar
Bas Westerbaan committed
210
211
212
213
			text := "New issues discovered."
			if initial {
				text = "I just (re)started and found the following issues."
			}
214
			payload := slack.Payload{
Bas Westerbaan's avatar
Bas Westerbaan committed
215
				Text:        text,
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
				Username:    "irma-historyd",
				IconEmoji:   ":dog:",
				Attachments: []slack.Attachment{},
			}
			for _, newIssue := range newIssues {
				payload.Attachments = append(payload.Attachments, slack.Attachment{
					Fallback: &newIssue,
					Text:     &newIssue,
					Color:    &strBad,
				})
			}
			if err := slack.Send(url, "", payload); err != nil {
				log.Printf("SlackWebhook %s: %s", url, err)
				continue
			}
		}
		if len(fixedIssues) > 0 {
			payload := slack.Payload{
				Text:        "The following issues were fixed.",
				Username:    "irma-historyd",
				IconEmoji:   ":dog:",
				Attachments: []slack.Attachment{},
			}
			for _, fixedIssue := range fixedIssues {
				payload.Attachments = append(payload.Attachments, slack.Attachment{
					Fallback: &fixedIssue,
					Text:     &fixedIssue,
					Color:    &strGood,
				})
			}
			if err := slack.Send(url, "", payload); err != nil {
				log.Printf("SlackWebhook %s: %s", url, err)
				continue
			}
		}
	}
}

Bas Westerbaan's avatar
Bas Westerbaan committed
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
func checkCertificateExpiry() []string {
	ret := []string{}
	for _, url := range conf.CheckCertificateExpiry {
		ret = append(ret, checkCertificateExpiryOf(url)...)
	}
	return ret
}

func checkCertificateExpiryOf(url string) (ret []string) {
	ret = []string{}
	resp, err := http.Head(url)
	if err != nil {
		ret = append(ret, fmt.Sprintf("%s: error %s", url, err))
		return
	}
	defer resp.Body.Close()
	if resp.TLS == nil {
		ret = append(ret, 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, fmt.Sprintf("%s: certificate from %s has expired %d days", url, issuer, daysExpired))
		} else if daysExpired > -30 {
			ret = append(ret, fmt.Sprintf("%s: certificate from %s will expire in %d days", url, issuer, -daysExpired))
		}
	}
	return ret
}

Bas Westerbaan's avatar
Bas Westerbaan committed
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
func checkSchemeManagers() []string {
	ret := []string{}
	for url, pk := range conf.CheckSchemeManagers {
		ret = append(ret, checkSchemeManager(url, pk)...)
	}
	return ret
}

func checkSchemeManager(url, pk string) (ret []string) {
	ret = []string{}
	log.Printf(" checking schememanager %s", url)

	// First, we download all the files of the schememanager.
	// We need a temporary directory to store the files.
	// As `schememgr verify' is a bit picky, we put everything in
	//    <temp dir>/irma_configuration/<name of schememgr>
	tempDir, err := ioutil.TempDir("", "")
	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("checkSchemeManager: MkDir(%s): %s", icDir, err)
		return
	}

	parsedUrl, err := netUrl.Parse(url)
	if err != nil {
		ret = append(ret, fmt.Sprintf("Failed to parse url %s: %s", url, err))
		return
	}
	_, name := path.Split(parsedUrl.Path)

	baseDir := path.Join(icDir, name)
	err = os.Mkdir(baseDir, 0700)
	if err != nil {
		log.Printf("checkSchemeManager: MkDir(%s): %s", icDir, err)
		return
	}

	// Helper.
	download := func(fn string) error {
		resp, err := http.Get(url + "/" + fn)
		if err != nil {
			return err
		}
		if resp.StatusCode != 200 {
			return fmt.Errorf("HTTP Code %d", resp.StatusCode)
		}
		defer resp.Body.Close()

		localFn := path.Join(baseDir, fn)
		localDir := filepath.Dir(localFn)
		if _, err := os.Stat(localDir); os.IsNotExist(err) {
			if err = os.MkdirAll(localDir, 0700); err != nil {
				return fmt.Errorf("local: os.MkdirAll(%s): %s", localDir, err)
			}
		}

		fh, err := os.Create(localFn)
		if err != nil {
			return fmt.Errorf("local: os.Create(%s): %s", localFn, err)
		}
		defer fh.Close()

		_, err = io.Copy(fh, resp.Body)
		if err != nil {
			return fmt.Errorf("while downloading %s/%s: %s", url, fn, err)
		}
		return nil
	}

	// Download index.sig and index separately
	if err = download("index.sig"); err != nil {
		ret = append(ret, fmt.Sprintf("%s: failed to download index signature: %s", url, err))
	}
	if err = download("pk.pem"); err != nil {
		ret = append(ret, fmt.Sprintf("%s: failed to download pk.pem: %s", url, err))
	}
	if err = download("index"); err != nil {
		ret = append(ret, fmt.Sprintf("%s: failed to download index: %s", url, err))
		return
	}

	// Overwrite public key
	if err = ioutil.WriteFile(path.Join(baseDir, "pk.pem"), []byte(pk), 0600); err != nil {
		log.Printf("checkSchemeManager: failed to write pk.pem: %s", err)
		return
	}

	// Parse index
	var idx irma.SchemeManagerIndex = make(map[string]irma.ConfigurationFileHash)
	idxBytes, err := ioutil.ReadFile(path.Join(baseDir, "index"))
	if err != nil {
		log.Printf("checkSchemeManager: failed to open downloaded index file: %s", err)
		return
	}
	err = idx.FromString(string(idxBytes))
	if err != nil {
		ret = append(ret, fmt.Sprintf("%s: failed to parse index: %s", url, err))
		return
	}

	// Download files
	ok := true
	for fn, _ := range idx {
		bits := strings.SplitN(fn, "/", 2)
		if len(bits) != 2 {
			ret = append(ret, fmt.Sprintf("%s: unexpected index entry: %v", url, fn))
			continue
		}
		err = download(bits[1])
		if err != nil {
			ok = false
			ret = append(ret, fmt.Sprintf("%s: failed to download %s: %s", url, bits[1], err))
		}
	}
	if !ok {
		return
	}

	// Verify signatures
	err = schememgr.RunVerify(icDir)
	if err != nil {
		ret = append(ret, fmt.Sprintf("%s: schememgr verify: %s", url, err))
	}

	// Check expiry dates on public keys
	pkDirs, err := filepath.Glob(path.Join(icDir, "*/*/PublicKeys"))
	if err != nil {
		log.Printf("checkSchemeManager: Glob(*/*/PublicKeys): %s", err)
		return
	}

	for _, pkDir := range pkDirs {
		pks, err := filepath.Glob(path.Join(pkDir, "*.xml"))
		if err != nil {
			log.Printf("checkSchemeManager: Glob: %s", err)
			return
		}
		var maxExpiry int64 = 0
		for _, pk := range pks {
			var pkData struct{ ExpiryDate int64 }
			pkBytes, err := ioutil.ReadFile(pk)
			if err != nil {
				log.Printf("checkSchemeManager: ReadFile(%s): %s", pk, err)
				return
			}
			if err = xml.Unmarshal(pkBytes, &pkData); err != nil {
				ret = append(ret, fmt.Sprintf("%s: failed to parse %s: %s", url, pk, err))
				return
			}
			if maxExpiry < pkData.ExpiryDate {
				maxExpiry = pkData.ExpiryDate
			}
		}
		daysExpired := time.Since(time.Unix(maxExpiry, 0)).Hours() / 24
		pkDirRel, _ := filepath.Rel(icDir, pkDir)
		pkDirBits := strings.Split(pkDirRel, "/")
		if daysExpired > 0 {
			ret = append(ret, fmt.Sprintf("%s: publickey for %s.%s has expired %d days",
				url, pkDirBits[0], pkDirBits[1], int(daysExpired)))
		} else if daysExpired > -30 {
			ret = append(ret, fmt.Sprintf("%s: publickey for %s.%s will expire in %d days",
				url, pkDirBits[0], pkDirBits[1], int(-daysExpired)))
		}
	}

	return
}