This repository was archived by the owner on Sep 10, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcmd_serve.go
More file actions
695 lines (599 loc) · 14.3 KB
/
Copy pathcmd_serve.go
File metadata and controls
695 lines (599 loc) · 14.3 KB
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//
// This is a golang port of the purple-alert server.
//
// Incoming submissions are received over HTTP POSTS to /events, and
// alerts are processed as expected.
//
// There is also a web-view, for processing events.
//
// Steve
// --
//
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/google/subcommands"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
_ "github.com/skx/golang-metrics"
"github.com/skx/purppura/alert"
"github.com/skx/purppura/alerts"
)
// key is the type for a context-key
//
// We use context to store the remote host (URI), username, & password
// in our session-cookie.
type key int
const (
// keyUser stores the username.
keyUser key = iota
)
//
// The secure-cookie object we use.
//
var cookieHandler *securecookie.SecureCookie
//
// The persistence object for getting/setting alerts.
//
var storage *alerts.Alerts
// LoadCookie loads the persistent cookies from disc, if they exist.
func LoadCookie() {
//
// Read the hash
//
hash, err := ioutil.ReadFile(".cookie.hsh")
if err == nil {
//
// If there was no error read the block
//
var block []byte
block, err = ioutil.ReadFile(".cookie.blk")
if err == nil {
//
// And create the cookie-helper.
//
cookieHandler = securecookie.New(hash, block)
return
}
}
//
// So we either failed to find, or failed to read, the existing
// values. (Perhaps this is the first run.)
//
// Generate random values.
//
h := securecookie.GenerateRandomKey(64)
b := securecookie.GenerateRandomKey(32)
//
// Now write them out.
//
// If writing fails then we'll use the values, and this means
// when the server restarts authentication will need to to be
// repeated by the users.
//
// (i.e. They'll be logged out.)
//
err = ioutil.WriteFile(".cookie.hsh", h, 0644)
if err != nil {
fmt.Printf("WARNING: failed to write .cookie.hsh for our secure cookie")
cookieHandler = securecookie.New(h, b)
return
}
err = ioutil.WriteFile(".cookie.blk", b, 0644)
if err != nil {
fmt.Printf("WARNING: failed to write .cookie.blk for our secure cookie")
cookieHandler = securecookie.New(h, b)
return
}
//
// Create the cookie, if we got here we've saved the data
// for the next restart.
//
cookieHandler = securecookie.New(h, b)
}
// LoadEvents sets up a new (MySQL) database-connection.
func LoadEvents() error {
var err error
storage, err = alerts.New()
if err != nil {
return err
}
return nil
}
// AddContext updates our HTTP-handlers to be username-aware.
func AddContext(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//
// If we have a session-cookie
//
if cookie, err := r.Cookie("cookie"); err == nil {
// Make a map
cookieValue := make(map[string]string)
// Decode it.
if err = cookieHandler.Decode("cookie", cookie.Value, &cookieValue); err == nil {
//
// Add the context to the handler, with the
// username.
//
userName := cookieValue["name"]
ctx := context.WithValue(r.Context(), keyUser, userName)
//
// And fire it up.
//
next.ServeHTTP(w, r.WithContext(ctx))
return
}
}
//
// We either failed to decode the cookie, or the cookie
// was missing.
//
// So we fall-back to assuming we're there is no user logged
// in, and supply no context.
//
next.ServeHTTP(w, r)
})
}
// RemoteIP handles retrieving the remote IP which made a particular
// HTTP-request, handling reverse-proxies as well as direct connections.
func RemoteIP(request *http.Request) string {
//
// Get the X-Forwarded-For header, if present.
//
xForwardedFor := request.Header.Get("X-Forwarded-For")
//
// No forwarded IP? Then use the remote address directly.
//
if xForwardedFor == "" {
ip, _, _ := net.SplitHostPort(request.RemoteAddr)
return ip
}
entries := strings.Split(xForwardedFor, ",")
address := strings.TrimSpace(entries[0])
return (address)
}
// alertSubmissionHandler receives alerts from remote sources and
// stores them in our database.
func alertSubmissionHandler(res http.ResponseWriter, request *http.Request) {
//
// We'll read JSON from STDIN.
//
// We do this manually because we want to see if we're
// getting a single event:
//
// {id:"blah",...}
//
// Or an array of events:
//
// [{id:"blah", ..},{id:"more-blah"..}
//
content, err := ioutil.ReadAll(request.Body)
if err != nil {
http.Error(res, err.Error(), 400)
return
}
//
// The incoming JSON might contain a single entry, or
// an array of entries.
//
var single alert.Alert
var multi []alert.Alert
//
// Decode - into the array, or single entry, as appropriate.
//
if strings.HasPrefix(string(content), "[") {
err = json.Unmarshal(content, &multi)
} else {
err = json.Unmarshal(content, &single)
}
if err != nil {
http.Error(res, err.Error(), 400)
return
}
//
// Get the source of the submission.
//
ip := RemoteIP(request)
//
// Did we get multiple entries?
//
if len(multi) > 0 {
//
// For each one - add it
//
for _, ent := range multi {
//
// Ensure the alert has an IP.
//
if ent.Source == "" {
ent.Source = ip
}
//
// Ensure we have all the fields we expect
//
if ent.Subject == "" {
http.Error(res, "Missing 'subject' field", 500)
return
}
if ent.ID == "" {
http.Error(res, "Missing 'ID' field", 500)
return
}
if ent.Raise == "" {
http.Error(res, "Missing 'raise' field", 500)
return
}
if ent.Detail == "" {
http.Error(res, "Missing 'detail' field", 500)
return
}
//
// Remove any IPv6-prefix, if present, on the source IP.
//
ent.Source = strings.TrimPrefix(ent.Source, "::ffff:")
//
// Add the event.
//
err = storage.AddEvent(ent)
if err != nil {
fmt.Printf("ERROR - addMulti%s\n", err.Error())
http.Error(res, err.Error(), 400)
return
}
}
} else {
//
// Ensure the alert has a source specified.
//
if single.Source == "" {
single.Source = ip
}
//
// Ensure we have all the fields we expect
//
if single.Subject == "" {
http.Error(res, "Missing 'subject' field", 500)
return
}
if single.ID == "" {
http.Error(res, "Missing 'ID' field", 500)
return
}
if single.Raise == "" {
http.Error(res, "Missing 'raise' field", 500)
return
}
if single.Detail == "" {
http.Error(res, "Missing 'detail' field", 500)
return
}
//
// Remove any IPv6-prefix, if present, on the source IP.
//
single.Source = strings.TrimPrefix(single.Source, "::ffff:")
//
// Add it.
//
err = storage.AddEvent(single)
if err != nil {
fmt.Printf("ERROR - AddSingle:%s\n", err.Error())
http.Error(res, err.Error(), 400)
return
}
}
//
// Send a simple reply to the caller.
//
fmt.Fprintf(res, "OK")
}
//
// Acknowledge an event.
//
func ackEvent(res http.ResponseWriter, req *http.Request) {
//
// Ensure the user is logged-in.
//
username := req.Context().Value(keyUser)
if username == nil {
http.Redirect(res, req, "/login", http.StatusFound)
return
}
//
// Get the ID we're going to acknowledge
//
vars := mux.Vars(req)
id := vars["id"]
storage.AckEvent(id)
http.Redirect(res, req, "/", http.StatusFound)
}
//
// Clear an event.
//
func clearEvent(res http.ResponseWriter, req *http.Request) {
//
// Ensure the user is logged-in.
//
username := req.Context().Value(keyUser)
if username == nil {
http.Redirect(res, req, "/login", http.StatusFound)
return
}
//
// Get the ID we're going to clear.
//
vars := mux.Vars(req)
id := vars["id"]
storage.ClearEvent(id)
http.Redirect(res, req, "/", http.StatusFound)
}
//
// Raise an event.
//
func raiseEvent(res http.ResponseWriter, req *http.Request) {
//
// Ensure the user is logged-in.
//
username := req.Context().Value(keyUser)
if username == nil {
http.Redirect(res, req, "/login", http.StatusFound)
return
}
//
// Get the ID we're going to raise.
//
vars := mux.Vars(req)
id := vars["id"]
storage.RaiseEvent(id)
http.Redirect(res, req, "/", http.StatusFound)
}
//
// Serve a static-resource
//
func serveResource(response http.ResponseWriter, request *http.Request, resource string, mime string) {
tmpl, err := getResource(resource)
if err != nil {
fmt.Fprint(response, err.Error())
return
}
response.Header().Set("Content-Type", mime)
fmt.Fprint(response, string(tmpl))
}
//
// Serve the login-form
//
func loginForm(response http.ResponseWriter, request *http.Request) {
serveResource(response, request, "data/login.html", "text/html; charset=utf-8")
}
//
// Process a login-event.
//
func loginHandler(response http.ResponseWriter, request *http.Request) {
//
// Get the username/password from the incoming form
// submission.
//
name := request.FormValue("name")
pass := request.FormValue("password")
//
// Open our list of users/passwords
//
valid, err := storage.ValidateLogin(name, pass)
if err != nil {
http.Error(response, err.Error(), 400)
return
}
//
// If this succeeded then let the login succeed.
//
if valid {
value := map[string]string{
"name": name,
}
if encoded, err := cookieHandler.Encode("cookie", value); err == nil {
cookie := &http.Cookie{
Name: "cookie",
Value: encoded,
Path: "/",
}
http.SetCookie(response, cookie)
}
http.Redirect(response, request, "/", http.StatusFound)
return
}
//
// Failure to login, redirect to try again.
//
http.Redirect(response, request, "/login#failed", http.StatusFound)
}
//
// logout handler
//
func logoutHandler(response http.ResponseWriter, request *http.Request) {
cookie := &http.Cookie{
Name: "cookie",
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(response, cookie)
http.Redirect(response, request, "/", http.StatusFound)
}
//
// Get all events as a JSON array.
//
// This is used by /purppura.js to dynamically update the display.
//
func eventsHandler(response http.ResponseWriter, request *http.Request) {
//
// Ensure the user is logged-in.
//
username := request.Context().Value(keyUser)
if username == nil {
http.Redirect(response, request, "/login", http.StatusFound)
return
}
//
// Get all the alerts, and their states.
//
results, err := storage.Alerts()
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
//
// Ensure that we send a suitable content-type.
//
response.Header().Set("Content-Type", "application/json")
//
// Output the alerts.
//
if len(results) > 0 {
out, _ := json.Marshal(results)
fmt.Fprintf(response, "%s", out)
} else {
fmt.Fprintf(response, "[]")
}
}
//
// index page
//
func indexPageHandler(response http.ResponseWriter, request *http.Request) {
//
// Ensure the user is logged-in.
//
username := request.Context().Value(keyUser)
if username == nil {
http.Redirect(response, request, "/login", http.StatusFound)
return
}
serveResource(response, request, "data/index.html", "text/html; charset=utf-8")
}
//
// serve our JS
//
func jsPage(response http.ResponseWriter, request *http.Request) {
serveResource(response, request, "data/purppura.js", "application/javascript")
}
//
// The options set by our command-line flags.
//
type serveCmd struct {
bindHost string
bindPort int
notifyBinary string
}
//
// Glue
//
func (*serveCmd) Name() string { return "serve" }
func (*serveCmd) Synopsis() string { return "Launch the HTTP server." }
func (*serveCmd) Usage() string {
return `serve [options]:
Launch the HTTP server for receiving and viewing alerts
`
}
//
// Flag setup
//
func (p *serveCmd) SetFlags(f *flag.FlagSet) {
f.IntVar(&p.bindPort, "port", 8080, "The port to bind upon.")
f.StringVar(&p.bindHost, "host", "127.0.0.1", "The IP to listen upon.")
f.StringVar(&p.notifyBinary, "notify-binary", "purppura-notify", "The binary to execute to issue notifications")
}
//
// Entry-point.
//
func (p *serveCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
//
// Start the server
//
serve(*p)
//
// All done.
//
return subcommands.ExitSuccess
}
//
// Entry-point.
//
func serve(settings serveCmd) {
//
// Configure our secure cookies
//
LoadCookie()
//
// Ensure we have a database for our HTTP-handler
//
err := LoadEvents()
if err != nil {
fmt.Printf("Error with DB setup: %s\n", err.Error())
os.Exit(1)
}
//
// Create a scheduler to process our events frequently enough
// to be responsive.
//
go ProcessAlertsScheduler(settings.notifyBinary)
//
// Configure our routes.
//
var router = mux.NewRouter()
router.HandleFunc("/", indexPageHandler)
router.HandleFunc("/purppura.js", jsPage).Methods("GET")
router.HandleFunc("/login", loginForm).Methods("GET")
router.HandleFunc("/login/", loginForm).Methods("GET")
router.HandleFunc("/login", loginHandler).Methods("POST")
router.HandleFunc("/login/", loginHandler).Methods("POST")
router.HandleFunc("/logout", logoutHandler).Methods("GET")
router.HandleFunc("/logout/", logoutHandler).Methods("GET")
router.HandleFunc("/logout", logoutHandler).Methods("POST")
router.HandleFunc("/logout/", logoutHandler).Methods("POST")
router.HandleFunc("/events", eventsHandler).Methods("GET")
router.HandleFunc("/events/", eventsHandler).Methods("GET")
router.HandleFunc("/events", alertSubmissionHandler).Methods("POST")
router.HandleFunc("/events/", alertSubmissionHandler).Methods("POST")
router.HandleFunc("/acknowledge/{id}", ackEvent).Methods("GET")
router.HandleFunc("/clear/{id}", clearEvent).Methods("GET")
router.HandleFunc("/raise/{id}", raiseEvent).Methods("GET")
http.Handle("/", router)
//
// Show what we're going to bind upon.
//
bind := fmt.Sprintf("%s:%d", settings.bindHost, settings.bindPort)
fmt.Printf("Listening on http://%s/\n", bind)
//
// Wire up logging.
//
loggedRouter := handlers.LoggingHandler(os.Stdout, router)
//
// Wire up context (i.e. cookie-based session stuff.)
//
contextRouter := AddContext(loggedRouter)
//
// We want to make sure we handle timeouts effectively
//
srv := &http.Server{
Addr: bind,
Handler: contextRouter,
ReadTimeout: 25 * time.Second,
IdleTimeout: 25 * time.Second,
WriteTimeout: 25 * time.Second,
}
//
// Launch the server.
//
err = srv.ListenAndServe()
if err != nil {
fmt.Printf("\nError starting HTTP server: %s\n", err.Error())
}
}