BlueGit

timfa bluegit

Files

bluegit / internal / backupserver / protocol / protocol.go

protocol.go

protocol.go 4.5 KiB Download Raw
1// Package protocol is het draadformaat tussen BlueGit en bluegit-backup.
2// Het moet gelijk blijven aan internal/backup in BlueGit (docs/BACKUP.md).
3package protocol
4
5import (
6 "crypto/hmac"
7 "crypto/sha256"
8 "encoding/hex"
9 "errors"
10 "net/http"
11 "path"
12 "strconv"
13 "strings"
14 "time"
15)
16
17// KeyPrefix staat voor elke Backupserver-Key.
18const KeyPrefix = "bgbk_"
19
20// Koppen van een ondertekend verzoek van BlueGit.
21const (
22 HeaderInstance = "X-BlueGit-Instance"
23 HeaderTimestamp = "X-BlueGit-Timestamp"
24 HeaderSignature = "X-BlueGit-Signature"
25)
26
27// MaxSkew is hoe ver de klokken uit elkaar mogen lopen.
28const MaxSkew = 5 * time.Minute
29
30// DBPath is het logische pad van de databasekopie.
31const DBPath = "state/bluegit.db"
32
33// Entry is één bestand in het manifest van BlueGit.
34type Entry struct {
35 Path string `json:"path"`
36 Size int64 `json:"size"`
37 MTime int64 `json:"mtime"`
38 Mode uint32 `json:"mode"`
39 SHA256 string `json:"sha256,omitempty"`
40}
41
42// Manifest is de volledige lijst op één moment.
43type Manifest struct {
44 Instance string `json:"instance_id"`
45 CreatedAt time.Time `json:"created_at"`
46 Files []Entry `json:"files"`
47}
48
49// Info is GET /api/v1/backup/info.
50type Info struct {
51 InstanceID string `json:"instance_id"`
52 BaseURL string `json:"base_url"`
53 ServerURL string `json:"server_url"`
54 ServerID string `json:"server_id"`
55 HasStorage bool `json:"has_storage"`
56 // Protocol en MinProtocol zijn 0 bij een BlueGit van vóór de
57 // protocolversie (dat is protocol 1).
58 Protocol int `json:"protocol"`
59 MinProtocol int `json:"min_protocol"`
60 Version string `json:"version"`
61}
62
63// Peer geeft het protocol van BlueGit uit info.
64func (i Info) Peer() Peer {
65 p := Peer{Protocol: i.Protocol, MinProtocol: i.MinProtocol, Version: cleanVersion(i.Version)}
66 if p.Protocol < 1 {
67 p.Protocol = 1
68 }
69 if p.MinProtocol < 1 {
70 p.MinProtocol = 1
71 }
72 return p
73}
74
75// SigningSecret leidt het HMAC-geheim af uit de key.
76func SigningSecret(key string) string {
77 s := sha256.Sum256([]byte("bluegit-backup-sign:" + key))
78 return hex.EncodeToString(s[:])
79}
80
81// Signature is hex(HMAC-SHA256(secret, METHOD \n PATH \n TS \n sha256hex(body))).
82func Signature(secret, method, p, ts string, body []byte) string {
83 sum := sha256.Sum256(body)
84 mac := hmac.New(sha256.New, []byte(secret))
85 mac.Write([]byte(strings.ToUpper(method) + "\n" + p + "\n" + ts + "\n" + hex.EncodeToString(sum[:])))
86 return hex.EncodeToString(mac.Sum(nil))
87}
88
89// Sign zet de koppen op een uitgaand verzoek (gebruikt in tests en door
90// BlueGit zelf).
91func Sign(req *http.Request, secret, instance string, body []byte, now time.Time) {
92 ts := strconv.FormatInt(now.Unix(), 10)
93 req.Header.Set(HeaderInstance, instance)
94 req.Header.Set(HeaderTimestamp, ts)
95 req.Header.Set(HeaderSignature, Signature(secret, req.Method, req.URL.Path, ts, body))
96}
97
98// Verify controleert een binnenkomend ondertekend verzoek.
99func Verify(r *http.Request, secret string, body []byte, now time.Time) error {
100 ts := r.Header.Get(HeaderTimestamp)
101 n, err := strconv.ParseInt(ts, 10, 64)
102 if err != nil {
103 return errors.New("timestamp ontbreekt")
104 }
105 d := now.Sub(time.Unix(n, 0))
106 if d < 0 {
107 d = -d
108 }
109 if d > MaxSkew {
110 return errors.New("timestamp te oud of in de toekomst")
111 }
112 want := Signature(secret, r.Method, r.URL.Path, ts, body)
113 if !hmac.Equal([]byte(want), []byte(r.Header.Get(HeaderSignature))) {
114 return errors.New("handtekening klopt niet")
115 }
116 return nil
117}
118
119var (
120 stateFiles = []string{"bluegit.db", "secret.key"}
121 stateDirs = []string{"ssh", "logos", "avatars"}
122 dataDirs = []string{"repos", "releases", "artifacts"}
123)
124
125// CleanLogical controleert een logisch pad zoals BlueGit dat doet. Een pad
126// buiten de bekende mappen komt nooit in de kopie.
127func CleanLogical(p string) (string, bool) {
128 if p == "" || strings.Contains(p, "\\") || strings.ContainsRune(p, 0) || strings.HasPrefix(p, "/") {
129 return "", false
130 }
131 c := path.Clean(p)
132 if c != p || c == "." {
133 return "", false
134 }
135 parts := strings.Split(c, "/")
136 for _, part := range parts {
137 if part == ".." || part == "." || part == "" {
138 return "", false
139 }
140 }
141 if len(parts) < 2 {
142 return "", false
143 }
144 switch parts[0] {
145 case "state":
146 if len(parts) == 2 && has(stateFiles, parts[1]) {
147 return c, true
148 }
149 if len(parts) >= 3 && has(stateDirs, parts[1]) {
150 return c, true
151 }
152 case "data":
153 if len(parts) >= 3 && has(dataDirs, parts[1]) && parts[2] != ".incoming" {
154 return c, true
155 }
156 }
157 return "", false
158}
159
160func has(list []string, v string) bool {
161 for _, x := range list {
162 if x == v {
163 return true
164 }
165 }
166 return false
167}