-
Notifications
You must be signed in to change notification settings - Fork 35
/
auth.go
287 lines (251 loc) · 7.27 KB
/
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
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
package gold
import (
"crypto/sha256"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// DigestAuthentication structure
type DigestAuthentication struct {
Type, Source, Username, Realm, Nonce, URI, QOP, NC, CNonce, Response, Opaque, Algorithm string
}
// DigestAuthorization structure
type DigestAuthorization struct {
Type, Source, Username, Nonce, Signature string
}
func (req *httpRequest) authn(w http.ResponseWriter) string {
user, err := req.userCookie()
if err != nil {
req.Server.debug.Println("userCookie error:", err)
}
if len(user) > 0 {
req.Server.debug.Println("Cookie auth OK for User: " + user)
return user
}
// try WebID-RSA
if len(req.Header.Get("Authorization")) > 0 {
user, err = WebIDDigestAuth(req)
if err != nil {
req.Server.debug.Println("WebID-RSA auth error:", err)
}
if len(user) > 0 {
req.Server.debug.Println("WebID-RSA auth OK for User: " + user)
}
}
// fall back to WebID-TLS
if len(user) == 0 {
user, err = WebIDTLSAuth(req)
if err != nil {
req.Server.debug.Println("WebID-TLS error:", err)
}
if len(user) > 0 {
req.Server.debug.Println("WebID-TLS auth OK for User: " + user)
}
}
if len(user) > 0 {
if len(req.Header.Get("On-Behalf-Of")) > 0 {
delegator := debrack(req.Header.Get("On-Behalf-Of"))
if verifyDelegator(delegator, user) {
req.Server.debug.Println("Setting delegation user to:", delegator)
user = delegator
}
}
req.Server.userCookieSet(w, user)
return user
}
user = ""
req.Server.debug.Println("Unauthenticated User")
return user
}
func (req *httpRequest) userCookie() (string, error) {
value := make(map[string]string)
cookie, err := req.Cookie("Session")
if err != nil {
return "", errors.New(err.Error() + " Got: " + fmt.Sprintf("%s", req.Cookies()))
}
err = req.Server.cookie.Decode("Session", cookie.Value, &value)
if err != nil {
return "", err
}
return value["user"], nil
}
func (srv *Server) userCookieSet(w http.ResponseWriter, user string) error {
value := map[string]string{
"user": user,
}
encoded, err := srv.cookie.Encode("Session", value)
if err != nil {
return err
}
t := time.Duration(srv.Config.CookieAge) * time.Hour
cookieCfg := &http.Cookie{
Expires: time.Now().Add(t),
Name: "Session",
Path: "/",
Value: encoded,
Secure: true,
}
http.SetCookie(w, cookieCfg)
return nil
}
func (srv *Server) userCookieDelete(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: "Session",
Value: "deleted",
Path: "/",
MaxAge: -1,
})
}
// ParseDigestAuthenticateHeader parses an Authenticate header and returns a DigestAuthentication object
func ParseDigestAuthenticateHeader(header string) (*DigestAuthentication, error) {
auth := DigestAuthentication{}
if len(header) == 0 {
return &auth, errors.New("Cannot parse WWW-Authenticate header: no header present")
}
opts := make(map[string]string)
parts := strings.SplitN(header, " ", 2)
opts["type"] = parts[0]
parts = strings.Split(parts[1], ",")
for _, part := range parts {
vals := strings.SplitN(strings.TrimSpace(part), "=", 2)
key := vals[0]
val := strings.Replace(vals[1], "\"", "", -1)
opts[key] = val
}
auth = DigestAuthentication{
opts["type"],
opts["source"],
opts["username"],
opts["realm"],
opts["nonce"],
opts["uri"],
opts["qop"],
opts["nc"],
opts["qnonce"],
opts["response"],
opts["opaque"],
opts["algorithm"],
}
return &auth, nil
}
// ParseDigestAuthorizationHeader parses an Authorization header and returns a DigestAuthorization object
func ParseDigestAuthorizationHeader(header string) (*DigestAuthorization, error) {
auth := DigestAuthorization{}
if len(header) == 0 {
return &auth, errors.New("Cannot parse Authorization header: no header present")
}
opts := make(map[string]string)
parts := strings.SplitN(header, " ", 2)
opts["type"] = parts[0]
if opts["type"] == "Bearer" {
return &auth, errors.New("Not a Digest authorization header. Got " + opts["type"])
}
parts = strings.Split(parts[1], ",")
for _, part := range parts {
vals := strings.SplitN(strings.TrimSpace(part), "=", 2)
key := vals[0]
val := strings.Replace(vals[1], "\"", "", -1)
opts[key] = val
}
auth = DigestAuthorization{
opts["type"],
opts["source"],
opts["username"],
opts["nonce"],
opts["sig"],
}
return &auth, nil
}
func ParseBearerAuthorizationHeader(header string) (string, error) {
if len(header) == 0 {
return "", errors.New("Cannot parse Authorization header: no header present")
}
parts := strings.SplitN(header, " ", 2)
if parts[0] != "Bearer" {
return "", errors.New("Not a Bearer header. Got: " + parts[0])
}
return decodeQuery(parts[1])
}
func NewTokenValues() map[string]string {
return make(map[string]string)
}
// NewSecureToken generates a signed token to be used during account recovery
func NewSecureToken(tokenType string, values map[string]string, duration time.Duration, s *Server) (string, error) {
valid := time.Now().Add(duration).Unix()
values["valid"] = fmt.Sprintf("%d", valid)
token, err := s.cookie.Encode(tokenType, values)
if err != nil {
s.debug.Println("Error encoding new token: " + err.Error())
return "", err
}
return token, nil
}
// ValidateSecureToken returns the values of a secure cookie
func ValidateSecureToken(tokenType string, token string, s *Server) (map[string]string, error) {
values := make(map[string]string)
err := s.cookie.Decode(tokenType, token, &values)
if err != nil {
s.debug.Println("Secure token decoding error: " + err.Error())
return values, err
}
return values, nil
}
func GetValuesFromToken(tokenType string, token string, req *httpRequest, s *Server) (map[string]string, error) {
values := NewTokenValues()
token, err := decodeQuery(token)
if err != nil {
s.debug.Println("Token URL decoding error for type: " + tokenType + " : " + err.Error())
return values, err
}
err = s.cookie.Decode(tokenType, token, &values)
if err != nil {
s.debug.Println("Token decoding error for type: " + tokenType + " \nToken: " + token + "\n" + err.Error())
return values, err
}
return values, nil
}
func IsTokenDateValid(valid string) error {
v, err := strconv.ParseInt(valid, 10, 64)
if err != nil {
return err
}
if time.Now().Local().Unix() > v {
return errors.New("Token has expired!")
}
return nil
}
func GetAuthzFromToken(token string, req *httpRequest) (string, error) {
// values, err := GetValuesFromToken("Authorization", token, req, s)
values, err := req.Server.getPersistedToken("Authorization", req.Host, token)
if err != nil {
return "", err
}
if len(values["webid"]) == 0 && len(values["valid"]) == 0 &&
len(values["origin"]) == 0 {
return "", errors.New("Malformed token is missing required values")
}
err = IsTokenDateValid(values["valid"])
if err != nil {
return "", err
}
origin := req.Header.Get("Origin")
if len(origin) > 0 && origin != values["origin"] {
return "", errors.New("Cannot authorize user: " + req.User + ". Origin: " + origin + " does not match the origin in the token: " + values["origin"])
}
return values["webid"], nil
}
func saltedPassword(salt, pass string) string {
s := sha256.Sum256([]byte(salt + pass))
toString := fmt.Sprintf("%x", s)
return toString
}
func encodeQuery(s string) string {
return url.QueryEscape(s)
}
func decodeQuery(s string) (string, error) {
return url.QueryUnescape(s)
}