/
hmac_auth.go
251 lines (227 loc) · 5.61 KB
/
hmac_auth.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package atm
import (
"bytes"
"crypto/hmac"
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/labstack/echo"
)
const AUTH_SEP = ":"
const XTIME = "X-Timestamp"
const CONTENT_TYPE = "Content-Type"
const CONTENT_MD5 = "Content-MD5"
const XNONCE = "X-Nonce"
const API_KEY = "api-key"
type KeyFinder func(string) (string, error)
type NonceChecker interface {
Add(string)
Valid(string) bool
}
type HmacOpts struct {
AuthPrefix string
Expiration time.Duration
SecretKeyFor KeyFinder
NonceChecker NonceChecker
}
func NewHmacOpts(f KeyFinder, nc NonceChecker) *HmacOpts {
o := &HmacOpts{
AuthPrefix: "ATM_Auth",
Expiration: 5 * time.Minute,
SecretKeyFor: f,
NonceChecker: nc,
}
return o
}
func HMACAuth(o *HmacOpts) echo.HandlerFunc {
return func(c *echo.Context) error {
auth, err := newAuth(c.Request(), o)
if nil != err {
return echo.NewHTTPError(http.StatusUnauthorized, err.Error())
}
if err := auth.Authentic(c.Request()); nil != err {
return echo.NewHTTPError(http.StatusUnauthorized, err.Error())
}
c.Set(API_KEY, auth.ApiKey)
return nil
}
}
type Authorizor struct {
ApiKey string
Signature string
Md5 string
Type string
Nonce string
Xtime string
Method string
Uri string
Timestamp time.Time
Opts *HmacOpts
}
type hmacError struct {
msg string
}
func (e hmacError) Error() string {
return e.msg
}
func AuthorizorForRequest(o *HmacOpts, method string, uri string) *Authorizor {
return &Authorizor{
Opts: o,
Method: strings.ToUpper(method),
Uri: uri,
}
}
func newAuth(r *http.Request, o *HmacOpts) (*Authorizor, error) {
h := r.Header
if len(h.Get(echo.Authorization)) <= 0 {
return nil, hmacError{"Missing required Authorization header"}
}
a := &Authorizor{
Opts: o,
Method: strings.ToUpper(r.Method),
Uri: r.URL.RequestURI(),
}
err := a.authorizorFromAuthHeader(h.Get(echo.Authorization))
if nil != err {
return nil, err
}
err = a.extractRequiredHeaders(&h)
if nil != err {
return nil, err
}
return a, nil
}
func (a *Authorizor) invalidNonce() error {
if a.Opts.NonceChecker.Valid(a.ApiKey + a.Nonce) {
return nil
}
return hmacError{"Reused Nonce"}
}
func (a *Authorizor) Authentic(r *http.Request) error {
if err := a.invalidTime(); nil != err {
return err
}
if err := a.invalidNonce(); nil != err {
a.Opts.NonceChecker.Add(a.ApiKey + a.Nonce)
return err
}
a.Opts.NonceChecker.Add(a.ApiKey + a.Nonce)
body := readerToByte(r.Body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
contentHash := md5Of(body)
if strings.ToLower(a.Md5) != strings.ToLower(contentHash) {
return hmacError{fmt.Sprintf("Content MD5s do not match:%s", contentHash)}
}
secret, err := a.Opts.SecretKeyFor(a.ApiKey)
if nil != err {
return err
}
if "" == secret {
return hmacError{fmt.Sprintf("No secret key for %s", a.ApiKey)}
}
generatedSig := a.SignatureWith(secret)
if "" == generatedSig {
return hmacError{"Unable to generate hmac signature"}
}
if hmac.Equal([]byte(generatedSig), []byte(a.Signature)) {
return nil
}
return hmacError{"HMAC Signature mismatch"}
}
func md5Of(b []byte) string {
h := md5.New()
h.Write(b)
return hex.EncodeToString(h.Sum(nil))
}
func readerToByte(s io.Reader) []byte {
b, _ := ioutil.ReadAll(s)
return b
}
func (a *Authorizor) invalidTime() error {
age := time.Since(a.Timestamp)
if age < 0 {
age *= -1
}
if age > a.Opts.Expiration {
return hmacError{"Timestamp out of range"}
}
return nil
}
func (a *Authorizor) SignatureWith(key string) string {
c := a.SigningString()
h := hmac.New(sha256.New, []byte(key))
h.Write([]byte(c))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
//Build the content for signging & sign it with the key
//method\nURI\nMD5\ntype\ntimestamp\nnonce
func (a *Authorizor) SigningString() string {
var b bytes.Buffer
b.WriteString(a.Method)
b.WriteString("\n")
b.WriteString(a.Uri)
b.WriteString("\n")
b.WriteString(a.Md5)
b.WriteString("\n")
if "" != a.Type {
b.WriteString(a.Type)
b.WriteString("\n")
}
b.WriteString(a.Xtime)
b.WriteString("\n")
b.WriteString(a.Nonce)
b.WriteString("\n")
b.WriteString(a.ApiKey)
return b.String()
}
// We need x-timestamp, content-md5, content-type, x-nonce
func (a *Authorizor) extractRequiredHeaders(h *http.Header) error {
a.Md5 = h.Get(CONTENT_MD5)
if "" == a.Md5 {
return hmacError{fmt.Sprintf("Missing required %s header", CONTENT_MD5)}
}
a.Type = h.Get(CONTENT_TYPE)
a.Nonce = h.Get(XNONCE)
if "" == a.Nonce {
return hmacError{fmt.Sprintf("Missing required %s header", XNONCE)}
}
return a.parseTimestamp(h.Get(XTIME))
}
func (a *Authorizor) parseTimestamp(t string) error {
if "" == t {
return hmacError{fmt.Sprintf("Missing required %s header", XTIME)}
}
a.Xtime = t
ts, err := time.Parse(time.RFC3339, t)
if nil != err {
return hmacError{fmt.Sprintf("Invalid timestamp: %s", err.Error())}
}
a.Timestamp = ts
return nil
}
func (a *Authorizor) authorizorFromAuthHeader(h string) error {
l := len(a.Opts.AuthPrefix)
if len(h)-l-1 <= 0 || h[:l] != a.Opts.AuthPrefix {
return hmacError{fmt.Sprintf("Authorization header invalid format: Missing %s prefix", a.Opts.AuthPrefix)}
}
parts := strings.SplitN(strings.Trim(h[l+1:], " "), AUTH_SEP, 2)
if len(parts) != 2 {
return hmacError{"Authorization header invalid format: Missing ApiKey:Signature"}
}
a.ApiKey = parts[0]
if "" == a.ApiKey {
return hmacError{"Authorization header invalid format: Missing ApiKey"}
}
a.Signature = parts[1]
if "" == a.Signature {
return hmacError{"Authorization header invalid format: Missing Signature"}
}
return nil
}