This repository has been archived by the owner on Jun 19, 2023. It is now read-only.
forked from geek-cookbook/traefik-forward-auth
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathforwardauth.go
344 lines (284 loc) · 8.49 KB
/
forwardauth.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package main
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
const (
defaultNonceSize = 16
)
// ForwardAuth represents forward autheentication object
type ForwardAuth struct {
Path string
Lifetime time.Duration
Secret []byte
AuthHost string
CookieName string
CookieDomains []CookieDomain
CSRFCookieName string
InfoCookieName string
Secure bool
Domain []string
Whitelist []string
UMAAuthorization bool
tokenMinValidity time.Duration
LogoutPath string
PostLogoutPath string
AccessTokenRolesField string
AccessTokenRolesDelimiter string
}
// Request Validation
// ValidateSessionAuthCookie validates cookies using the following formula: Cookie = hash(secret, cookie domain, content, expires)|expires|content
func (f *ForwardAuth) ValidateSessionAuthCookie(r *http.Request, c *http.Cookie) (bool, string, error) {
parts := strings.Split(c.Value, "|")
if len(parts) != 3 {
return false, "", errors.New("Invalid cookie format")
}
mac, err := base64.URLEncoding.DecodeString(parts[0])
if err != nil {
return false, "", fmt.Errorf("Unable to decode cookie mac: %s", err)
}
expectedSignature := f.cookieSignature(r, parts[2], parts[1])
expected, err := base64.URLEncoding.DecodeString(expectedSignature)
if err != nil {
return false, "", fmt.Errorf("Unable to generate mac: %s", err)
}
// Valid token?
if !hmac.Equal(mac, expected) {
return false, "", fmt.Errorf("Invalid cookie mac %s, expected %s", mac, expected)
}
expires, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil {
return false, "", fmt.Errorf("Unable to parse cookie expiry: %s", err)
}
// Has it expired?
if time.Unix(expires, 0).Before(time.Now()) {
return false, "", errors.New("Cookie has expired")
}
// Looks valid
return true, parts[2], nil
}
// ValidateEmail validates that the email address belongs to one of the white listed
// or configured domains.
func (f *ForwardAuth) ValidateEmail(email string) bool {
found := false
if len(f.Whitelist) > 0 {
for _, whitelist := range f.Whitelist {
if email == whitelist {
found = true
}
}
} else if len(f.Domain) > 0 {
parts := strings.Split(email, "@")
if len(parts) < 2 {
return false
}
for _, domain := range f.Domain {
if domain == parts[1] {
found = true
}
}
} else {
return true
}
return found
}
// Utility methods
// Get the redirect base
func (f *ForwardAuth) redirectBase(r *http.Request) string {
proto := r.Header.Get("X-Forwarded-Proto")
host := r.Header.Get("X-Forwarded-Host")
return fmt.Sprintf("%s://%s", proto, host)
}
// Return url
func (f *ForwardAuth) returnURL(r *http.Request) string {
path := r.Header.Get("X-Forwarded-Uri")
return fmt.Sprintf("%s%s", f.redirectBase(r), path)
}
// Get oauth redirect uri
func (f *ForwardAuth) redirectURI(r *http.Request) string {
if use, _ := f.useAuthDomain(r); use {
proto := r.Header.Get("X-Forwarded-Proto")
return fmt.Sprintf("%s://%s%s", proto, f.AuthHost, f.Path)
}
return fmt.Sprintf("%s%s", f.redirectBase(r), f.Path)
}
// Should we use auth host + what it is
func (f *ForwardAuth) useAuthDomain(r *http.Request) (bool, string) {
if f.AuthHost == "" {
return false, ""
}
// Does the request match a given cookie domain?
reqMatch, reqHost := f.matchCookieDomains(r.Header.Get("X-Forwarded-Host"))
// Do any of the auth hosts match a cookie domain?
authMatch, authHost := f.matchCookieDomains(f.AuthHost)
// We need both to match the same domain
return reqMatch && authMatch && reqHost == authHost, reqHost
}
// -- Cookie methods
// ClearCSRFCookie sets a cookie to clear previous CSRF cookie.
func (f *ForwardAuth) ClearCSRFCookie(r *http.Request) *http.Cookie {
return &http.Cookie{
Name: f.CSRFCookieName,
Value: "",
Path: "/",
Domain: f.csrfCookieDomain(r),
HttpOnly: true,
Secure: f.Secure,
Expires: time.Now().Local().Add(time.Hour * -1),
}
}
// ClearCookie removes a cookie with given name.
func (f *ForwardAuth) ClearCookie(r *http.Request, name string) *http.Cookie {
return &http.Cookie{
Name: name,
Value: "",
Path: "/",
Domain: f.cookieDomain(r),
HttpOnly: true,
Secure: f.Secure,
Expires: time.Now().Local().Add(time.Hour * -1),
}
}
// MakeCSRFCookie creates a CSRF cookie (used during login only)
func (f *ForwardAuth) MakeCSRFCookie(r *http.Request, nonce string) *http.Cookie {
return &http.Cookie{
Name: f.CSRFCookieName,
Value: nonce,
Path: "/",
Domain: f.csrfCookieDomain(r),
HttpOnly: true,
Secure: f.Secure,
Expires: f.cookieExpiry(),
}
}
func (f *ForwardAuth) MakeSessionAuthCookie(r *http.Request, content string) *http.Cookie {
expires := f.cookieExpiry()
mac := f.cookieSignature(r, content, fmt.Sprintf("%d", expires.Unix()))
value := fmt.Sprintf("%s|%d|%s", mac, expires.Unix(), content)
return f.MakeCookieWithExpiry(r, f.CookieName, value, expires, true)
}
func (f *ForwardAuth) MakeSessionInfoCookie(r *http.Request, content string) *http.Cookie {
expires := f.cookieExpiry()
value := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf("%d|%s", expires.Unix(), content)))
return f.MakeCookieWithExpiry(r, f.InfoCookieName, value, expires, false)
}
// MakeCookieWithExpiry creates a cookie of a given name with given content, with explicit expiry.
func (f *ForwardAuth) MakeCookieWithExpiry(r *http.Request, name, value string, expires time.Time, httpOnly bool) *http.Cookie {
return &http.Cookie{
Name: name,
Value: value,
Path: "/",
Domain: f.cookieDomain(r),
HttpOnly: httpOnly,
Secure: f.Secure,
Expires: expires,
}
}
// ValidateCSRFCookie validates the CSRF cookie against state.
func (f *ForwardAuth) ValidateCSRFCookie(c *http.Cookie, state string) (bool, string, error) {
if len(c.Value) != 32 {
return false, "", errors.New("Invalid CSRF cookie value")
}
if len(state) < 34 {
return false, "", errors.New("Invalid CSRF state value")
}
// Check nonce match
if c.Value != state[:32] {
return false, "", errors.New("CSRF cookie does not match state")
}
// Valid, return redirect
return true, state[33:], nil
}
// Nonce generates a new random nonce using the default nonce size.
func (f *ForwardAuth) Nonce() (string, error) {
return f.NonceWithSize(defaultNonceSize)
}
// NonceWithSize generates a new random nonce using the specified size.
func (f *ForwardAuth) NonceWithSize(size int) (string, error) {
// Make nonce
nonce := make([]byte, size)
_, err := rand.Read(nonce)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", nonce), nil
}
// Cookie domain
func (f *ForwardAuth) cookieDomain(r *http.Request) string {
host := r.Header.Get("X-Forwarded-Host")
// Check if any of the given cookie domains matches
_, domain := f.matchCookieDomains(host)
return domain
}
// Cookie domain
func (f *ForwardAuth) csrfCookieDomain(r *http.Request) string {
var host string
if use, domain := f.useAuthDomain(r); use {
host = domain
} else {
host = r.Header.Get("X-Forwarded-Host")
}
// Remove port
p := strings.Split(host, ":")
return p[0]
}
// Return matching cookie domain if exists
func (f *ForwardAuth) matchCookieDomains(domain string) (bool, string) {
// Remove port
p := strings.Split(domain, ":")
for _, d := range f.CookieDomains {
if d.Match(p[0]) {
return true, d.Domain
}
}
return false, p[0]
}
// Create cookie hmac
func (f *ForwardAuth) cookieSignature(r *http.Request, content, expires string) string {
hash := hmac.New(sha256.New, f.Secret)
hash.Write([]byte(f.cookieDomain(r)))
hash.Write([]byte(content))
hash.Write([]byte(expires))
return base64.URLEncoding.EncodeToString(hash.Sum(nil))
}
// Get cookie expirary
func (f *ForwardAuth) cookieExpiry() time.Time {
return time.Now().Local().Add(f.Lifetime)
}
// -- Cookie Domain
// CookieDomain represents a cookie domain.
type CookieDomain struct {
Domain string
DomainLen int
SubDomain string
SubDomainLen int
}
// NewCookieDomain returns a new CookieDomain for a given domain name.
func NewCookieDomain(domain string) *CookieDomain {
return &CookieDomain{
Domain: domain,
DomainLen: len(domain),
SubDomain: fmt.Sprintf(".%s", domain),
SubDomainLen: len(domain) + 1,
}
}
// Match returns true of the given host matches the cookie domain.
func (c *CookieDomain) Match(host string) bool {
// Exact domain match?
if host == c.Domain {
return true
}
// Subdomain match?
if len(host) >= c.SubDomainLen && host[len(host)-c.SubDomainLen:] == c.SubDomain {
return true
}
return false
}