BlueGit

timfa bluegit

Files

bluegit / internal / backup / sign.go

sign.go

sign.go 1.7 KiB Download Raw
1package backup
2
3import (
4 "crypto/hmac"
5 "crypto/sha256"
6 "encoding/hex"
7 "errors"
8 "net/http"
9 "strconv"
10 "strings"
11 "time"
12)
13
14// Koppen van een ondertekend verzoek tussen BlueGit en de backup server.
15const (
16 HeaderInstance = "X-BlueGit-Instance"
17 HeaderTimestamp = "X-BlueGit-Timestamp"
18 HeaderSignature = "X-BlueGit-Signature"
19)
20
21// MaxSkew is hoe ver de klokken uit elkaar mogen lopen.
22const MaxSkew = 5 * time.Minute
23
24// Signature is hex(HMAC-SHA256(secret, METHOD \n PATH \n TS \n sha256hex(body))).
25func Signature(secret, method, path, ts string, body []byte) string {
26 sum := sha256.Sum256(body)
27 mac := hmac.New(sha256.New, []byte(secret))
28 mac.Write([]byte(strings.ToUpper(method) + "\n" + path + "\n" + ts + "\n" + hex.EncodeToString(sum[:])))
29 return hex.EncodeToString(mac.Sum(nil))
30}
31
32// Sign zet de koppen op een uitgaand verzoek. body is wat er verstuurd wordt.
33func Sign(req *http.Request, secret, instance string, body []byte, now time.Time) {
34 ts := strconv.FormatInt(now.Unix(), 10)
35 req.Header.Set(HeaderInstance, instance)
36 req.Header.Set(HeaderTimestamp, ts)
37 req.Header.Set(HeaderSignature, Signature(secret, req.Method, req.URL.Path, ts, body))
38}
39
40// Verify controleert een binnenkomend ondertekend verzoek.
41func Verify(r *http.Request, secret string, body []byte, now time.Time) error {
42 ts := r.Header.Get(HeaderTimestamp)
43 n, err := strconv.ParseInt(ts, 10, 64)
44 if err != nil {
45 return errors.New("timestamp ontbreekt")
46 }
47 d := now.Sub(time.Unix(n, 0))
48 if d < 0 {
49 d = -d
50 }
51 if d > MaxSkew {
52 return errors.New("timestamp te oud of in de toekomst")
53 }
54 want := Signature(secret, r.Method, r.URL.Path, ts, body)
55 if !hmac.Equal([]byte(want), []byte(r.Header.Get(HeaderSignature))) {
56 return errors.New("handtekening klopt niet")
57 }
58 return nil
59}