-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmac.go
231 lines (197 loc) · 6.17 KB
/
mac.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
package security
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"math/big"
"net/http"
"strings"
"time"
"github.com/go-openapi/runtime"
)
// Our constant header names
const (
AuthzHeaderKey = "Authorization"
TsHeaderKey = "X-Date"
SaltHeaderKey = "X-Data-Salt"
)
// WrongHMAC is an error which contains the two hmacs which differ. A
// caller can use this values to log the computed value.
type WrongHMAC struct {
Got string
Want string
}
func (w *WrongHMAC) Error() string {
return "Wrong HMAC found"
}
func newWrongHMAC(got, want string) *WrongHMAC {
return &WrongHMAC{Got: got, Want: want}
}
var (
errIllegalAuthFound = errors.New("illegal auth found")
errUnknownAuthFound = errors.New("unknown authtype found")
)
// A HMACAuth is an authenticator which uses a hmac calculation.
type HMACAuth struct {
key []byte
Lifetime time.Duration
Type string
AuthUser User
}
// HMACAuthOption is a option type for HMACAuth
type HMACAuthOption func(*HMACAuth)
// NewHMACAuth returns a new HMACAuth initialized with the given key. A service
// implementation and a client must share the same key and authtype. The authtype
// will be transported as a scheme in the "Authentication" header. The key
// has to be private and will never be transmitted over the wire.
func NewHMACAuth(authtype string, key []byte, opts ...HMACAuthOption) HMACAuth {
res := HMACAuth{
key: key,
Lifetime: 15 * time.Second,
Type: authtype,
AuthUser: guest,
}
for _, o := range opts {
o(&res)
}
return res
}
// WithUser sets the user which is connected to this HMAC auth.
func WithUser(u User) HMACAuthOption {
return func(h *HMACAuth) {
h.AuthUser = u
}
}
// WithLifetime sets the lifetime which is connected to this HMAC auth. If the
// lifetime is zero, there will be no datetime checking. Do not do this in
// productive code (only useful in tests).
func WithLifetime(max time.Duration) HMACAuthOption {
return func(h *HMACAuth) {
h.Lifetime = max
}
}
func (hma *HMACAuth) createMac(vals ...[]byte) string {
h := hmac.New(sha256.New, hma.key)
for _, v := range vals {
// FIXME add errcheck
//nolint:errcheck
h.Write(v)
}
sha := hex.EncodeToString(h.Sum(nil))
return sha
}
// create returns a a formatted timestamp and the generated HMAC.
func (hma *HMACAuth) create(t time.Time, vals ...[]byte) (string, string) {
ts := t.UTC().Format(time.RFC3339)
vals = append([][]byte{[]byte(ts)}, vals...)
return hma.createMac(vals...), ts
}
// AddAuth adds the needed headers to the given request so the given values in the vals-array
// are correctly signed. This function can be used by a client to enhance the request before
// submitting it.
func (hma *HMACAuth) AddAuth(rq *http.Request, t time.Time, body []byte) {
headers := hma.AuthHeaders(rq.Method, t)
for k, v := range headers {
rq.Header.Add(k, v)
}
}
// AddAuthToClientRequest to support openapi too
func (hma *HMACAuth) AddAuthToClientRequest(rq runtime.ClientRequest, t time.Time) {
headers := hma.AuthHeaders(rq.GetMethod(), t)
for k, v := range headers {
// FIXME add errcheck
//nolint:errcheck
rq.SetHeaderParam(k, v)
}
}
// AuthHeaders creates the necessary headers
func (hma *HMACAuth) AuthHeaders(method string, t time.Time) map[string]string {
salt := randByteString(24)
mac, ts := hma.create(t, []byte(method), salt)
headers := make(map[string]string)
headers[TsHeaderKey] = ts
headers[SaltHeaderKey] = string(salt)
headers[AuthzHeaderKey] = hma.Type + " " + mac
return headers
}
// RequestData wraps the http request data
type RequestData struct {
Method string
AuthzHeader string
TimestampHeader string
SaltHeader string
}
// RequestDataGetter is a supplied func which returns the RequestData
type RequestDataGetter func() RequestData
// User calculates the hmac from header values. The input-values for the calculation
// are: Date-Header, Request-Method, Request-Content.
// If the result does not match the HMAC in the header, this function returns an error. Otherwise
// it returns the user which is connected to this hmac-auth.
func (hma *HMACAuth) User(rq *http.Request) (*User, error) {
rqd := RequestData{
Method: rq.Method,
AuthzHeader: rq.Header.Get(AuthzHeaderKey),
TimestampHeader: rq.Header.Get(TsHeaderKey),
SaltHeader: rq.Header.Get(SaltHeaderKey),
}
return hma.UserFromRequestData(rqd)
}
// UserFromRequestData calculates the hmac from header values. The input-values for the calculation
// are: Date-Header, Request-Method, Request-Content.
// If the result does not match the HMAC in the header, this function returns an error. Otherwise
// it returns the user which is connected to this hmac-auth.
func (hma *HMACAuth) UserFromRequestData(requestData RequestData) (*User, error) {
t := requestData.TimestampHeader
auth := requestData.AuthzHeader
if auth == "" {
return nil, errNoAuthFound
}
splitToken := strings.Split(auth, " ")
if len(splitToken) != 2 {
return nil, errIllegalAuthFound
}
if strings.TrimSpace(splitToken[0]) != hma.Type {
return nil, errUnknownAuthFound
}
hm := strings.TrimSpace(splitToken[1])
ts, err := time.Parse(time.RFC3339, t)
if err != nil {
return nil, fmt.Errorf("unknown timestamp %q in %q header, use RFC3339: %w", t, TsHeaderKey, err)
}
if hma.Lifetime > 0 {
if time.Since(ts) > hma.Lifetime {
return nil, fmt.Errorf("the timestamp in your header is too old: %q", t)
}
}
vals := hma.getData(requestData.Method, requestData.SaltHeader)
calc, _ := hma.create(ts, vals...)
if calc != hm {
return nil, newWrongHMAC(hm, calc)
}
// lets return a copy of our user so the caller cannot change it
newuser := hma.AuthUser
return &newuser, nil
}
func (hma *HMACAuth) getData(method, saltHeader string) [][]byte {
return [][]byte{
[]byte(method),
[]byte(saltHeader),
}
}
// replaceable function to create a random byte string
var randByteString = randomByteString
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func randomByteString(n int) []byte {
ret := make([]byte, n)
for i := range n {
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letterBytes))))
if err != nil {
continue
}
ret[i] = letterBytes[num.Int64()]
}
return ret
}