-
Notifications
You must be signed in to change notification settings - Fork 0
/
digest.go
286 lines (244 loc) · 7.41 KB
/
digest.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
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
// Copyright 2012 Robert W. Johnstone. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package httpauth
import (
"container/heap"
"crypto/md5"
"fmt"
"hash"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
// The constant DefaultClientCacheResidence contains the default value used
// for the ClientCacheResidence field when creating new Digest instances or
// new Cookie instances.
const (
DefaultClientCacheResidence = 1 * time.Hour
)
type digestClientInfo struct {
numContacts uint64 // number of client connects
lastContact int64 // time of last communication with this client (unix nanoseconds)
nonce string // unique per client salt
}
type digestPriorityQueue []*digestClientInfo
func (pq digestPriorityQueue) Len() int {
return len(pq)
}
func (pq digestPriorityQueue) Less(i, j int) bool {
return pq[i].lastContact < pq[j].lastContact
}
func (pq digestPriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
func (pq *digestPriorityQueue) Push(x interface{}) {
*pq = append(*pq, x.(*digestClientInfo))
}
func (pq *digestPriorityQueue) Pop() interface{} {
n := len(*pq)
ret := (*pq)[n-1]
*pq = (*pq)[:n-1]
return ret
}
func (pq digestPriorityQueue) MinValue() int64 {
n := len(pq)
return pq[n-1].lastContact
}
// A Digest is a policy for authenticating users using the digest authentication scheme.
type Digest struct {
// Realm provides a 'namespace' where the authentication will be considered.
Realm string
// Auth provides a function or closure that retrieve the password for a given username.
Auth PasswordLookup
// WriteUnauthorized provides a function or closure that writes out the HTML portion of a unauthorized access response.
WriteUnauthorized HtmlWriter
// This is a nonce used by the HTTP server to prevent dictionary attacks
opaque string
// CientCacheResidence controls how long client information is retained
ClientCacheResidence time.Duration
mutex sync.Mutex
clients map[string]*digestClientInfo
lru digestPriorityQueue
md5 hash.Hash
}
func calcHash(h hash.Hash, data string) string {
h.Reset()
h.Write([]byte(data))
return fmt.Sprintf("%x", h.Sum(nil))
}
// NewDigest creates a new authentication policy that uses the digest authentication scheme.
func NewDigest(realm string, auth PasswordLookup, writer HtmlWriter) (*Digest, error) {
nonce, err := createNonce()
if err != nil {
return nil, err
}
if writer == nil {
writer = defaultHtmlWriter
}
return &Digest{
realm,
auth,
writer,
nonce,
DefaultClientCacheResidence,
sync.Mutex{},
make(map[string]*digestClientInfo),
nil,
md5.New()}, nil
}
func (a *Digest) evictLeastRecentlySeen() {
now := time.Now().UnixNano()
// Remove all entries from the client cache older than the
// residence time.
for len(a.lru) > 0 && a.lru.MinValue()+a.ClientCacheResidence.Nanoseconds() <= now {
client := heap.Pop(&a.lru).(*digestClientInfo)
delete(a.clients, client.nonce)
}
}
func parseDigestAuthHeader(r *http.Request) map[string]string {
// Extract the authentication token.
token := r.Header.Get("Authorization")
if token == "" {
return nil
}
// Check that the token supplied corresponds to the digest authorization
// protocol. If not, return nil to indicate failure. No error
// code is used as a malformed protocol is simply an authentication
// failure.
ndx := strings.IndexRune(token, ' ')
if ndx < 1 || token[0:ndx] != "Digest" {
return nil
}
token = token[ndx+1:]
// Token is a comma separated list of name/value pairs. Break-out pieces
// and fill in a map.
params := make(map[string]string)
for _, str := range strings.Split(token, ",") {
ndx := strings.IndexRune(str, '=')
if ndx < 1 {
// malformed name/value pair
// ignore
continue
}
name := strings.Trim(str[0:ndx], `" `)
value := strings.Trim(str[ndx+1:], `" `)
params[name] = value
}
return params
}
// Authorize retrieves the credientials from the HTTP request, and
// returns the username only if the credientials could be validated.
// If the return value is blank, then the credentials are missing,
// invalid, or a system error prevented verification.
func (a *Digest) Authorize(r *http.Request) (username string) {
// Extract and parse the token
params := parseDigestAuthHeader(r)
if params == nil {
return ""
}
// Verify the token's parameters
if params["opaque"] != a.opaque || params["algorithm"] != "MD5" || params["qop"] != "auth" {
return ""
}
// Verify if the requested URI matches auth header
switch u, err := url.Parse(params["uri"]); {
case err != nil || r.URL == nil:
return
case r.URL.Path != u.Path:
return
}
username = params["username"]
if username == "" {
return ""
}
password := a.Auth(username)
if password == "" {
return ""
}
ha1 := calcHash(a.md5, username+":"+a.Realm+":"+password)
ha2 := calcHash(a.md5, r.Method+":"+params["uri"])
ha3 := calcHash(a.md5, ha1+":"+params["nonce"]+":"+params["nc"]+
":"+params["cnonce"]+":"+params["qop"]+":"+ha2)
if ha3 != params["response"] {
return ""
}
// Determine the number of contacts that the client believes that
// it has had with this serveri.
numContacts, err := strconv.ParseUint(params["nc"], 16, 64)
if err != nil {
return ""
}
// Pull out the nonce, and verify
nonce, ok := params["nonce"]
if !ok || len(nonce) != nonceLen {
return ""
}
// The next block of actions require accessing field internal to the
// digest structure. Need to lock.
a.mutex.Lock()
defer a.mutex.Unlock()
// Check for old clientInfo, and evict those older than
// residence time.
a.evictLeastRecentlySeen()
// Find the client, and check against authorization parameters.
if client, ok := a.clients[nonce]; ok {
if client.numContacts != 0 && client.numContacts >= numContacts {
return ""
}
client.numContacts = numContacts
client.lastContact = time.Now().UnixNano()
} else {
return ""
}
return username
}
// NotifyAuthRequired adds the headers to the HTTP response to
// inform the client of the failed authorization, and which scheme
// must be used to gain authentication.
func (a *Digest) NotifyAuthRequired(w http.ResponseWriter, r *http.Request) {
// Create an entry for the client
nonce, err := createNonce()
if err != nil {
http.Error(w, "Internal server error.", http.StatusInternalServerError)
return
}
// Create the header
hdr := `Digest realm="` + a.Realm + `", nonce="` + nonce + `", opaque="` +
a.opaque + `", algorithm="MD5", qop="auth"`
w.Header().Set("WWW-Authenticate", hdr)
w.WriteHeader(http.StatusUnauthorized)
a.WriteUnauthorized(w, r)
// The next block of actions require accessing field internal to the
// digest structure. Need to lock.
a.mutex.Lock()
defer a.mutex.Unlock()
// Add the client info to the LRU.
ci := &digestClientInfo{0, time.Now().UnixNano(), nonce}
a.clients[nonce] = ci
heap.Push(&a.lru, ci)
}
// Logout removes the nonce associated with the HTTP request from the cache.
func (a *Digest) Logout(r *http.Request) {
// Extract the authentication parameters
params := parseDigestAuthHeader(r)
if params == nil {
return
}
nonce, ok := params["nonce"]
if !ok {
return
}
// The next block of actions require accessing field internal to the
// digest structure. Need to lock.
a.mutex.Lock()
defer a.mutex.Unlock()
// Use the nonce to find the entry
if client, ok := a.clients[nonce]; ok {
// Increase the time since last contact, and force an eviction.
client.lastContact = 0
}
}