-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
authentication.go
465 lines (408 loc) · 14 KB
/
authentication.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// Copyright 2017 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package server
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"strconv"
"time"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/types"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
)
const (
// authPrefix is the prefix for RESTful endpoints used to provide
// authentication methods.
loginPath = "/login"
logoutPath = "/logout"
// secretLength is the number of random bytes generated for session secrets.
secretLength = 16
sessionCookieName = "session"
)
var webSessionTimeout = settings.RegisterNonNegativeDurationSetting(
"server.web_session_timeout",
"the duration that a newly created web session will be valid",
7*24*time.Hour,
)
type authenticationServer struct {
server *Server
memMetrics *sql.MemoryMetrics
}
// newAuthenticationServer allocates and returns a new REST server for
// authentication APIs.
func newAuthenticationServer(s *Server) *authenticationServer {
return &authenticationServer{
server: s,
memMetrics: &s.adminMemMetrics,
}
}
// RegisterService registers the GRPC service.
func (s *authenticationServer) RegisterService(g *grpc.Server) {
serverpb.RegisterLogInServer(g, s)
serverpb.RegisterLogOutServer(g, s)
}
// RegisterGateway starts the gateway (i.e. reverse proxy) that proxies HTTP requests
// to the appropriate gRPC endpoints.
func (s *authenticationServer) RegisterGateway(
ctx context.Context, mux *gwruntime.ServeMux, conn *grpc.ClientConn,
) error {
if err := serverpb.RegisterLogInHandler(ctx, mux, conn); err != nil {
return err
}
return serverpb.RegisterLogOutHandler(ctx, mux, conn)
}
// UserLogin verifies an incoming request by a user to create an web
// authentication session. It checks the provided credentials against the
// system.users table, and if successful creates a new authentication session.
// The session's ID and secret are returned to the caller as an HTTP cookie,
// added via a "Set-Cookie" header.
func (s *authenticationServer) UserLogin(
ctx context.Context, req *serverpb.UserLoginRequest,
) (*serverpb.UserLoginResponse, error) {
username := req.Username
if username == "" {
return nil, status.Errorf(
codes.Unauthenticated,
"no username was provided",
)
}
// Root user does not have a password, simply disallow this.
if username == security.RootUser {
return nil, status.Errorf(
codes.Unauthenticated,
"user %s must use certificate authentication instead of password authentication",
security.RootUser,
)
}
// Verify the provided username/password pair.
verified, err := s.verifyPassword(ctx, username, req.Password)
if err != nil {
return nil, apiInternalError(ctx, err)
}
if !verified {
return nil, status.Errorf(
codes.Unauthenticated,
"the provided username and password did not match any credentials on the server",
)
}
// Create a new database session, generating an ID and secret key.
id, secret, err := s.newAuthSession(ctx, username)
if err != nil {
return nil, apiInternalError(ctx, err)
}
// Generate and set a session cookie for the response. Because HTTP cookies
// must be strings, the cookie value (a marshaled protobuf) is encoded in
// base64.
cookieValue := &serverpb.SessionCookie{
ID: id,
Secret: secret,
}
cookie, err := encodeSessionCookie(cookieValue)
if err != nil {
return nil, apiInternalError(ctx, err)
}
// Set the cookie header on the outgoing response.
if err := grpc.SetHeader(ctx, metadata.Pairs("set-cookie", cookie.String())); err != nil {
return nil, apiInternalError(ctx, err)
}
return &serverpb.UserLoginResponse{}, nil
}
// UserLogout allows a user to terminate their currently active session.
func (s *authenticationServer) UserLogout(
ctx context.Context, req *serverpb.UserLogoutRequest,
) (*serverpb.UserLogoutResponse, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, apiInternalError(ctx, fmt.Errorf("couldn't get incoming context"))
}
sessionIDs := md.Get(webSessionIDKeyStr)
if len(sessionIDs) != 1 {
return nil, apiInternalError(ctx, fmt.Errorf("couldn't get incoming context"))
}
sessionID, err := strconv.Atoi(sessionIDs[0])
if err != nil {
return nil, fmt.Errorf("invalid session id: %d", sessionID)
}
// Revoke the session.
if n, err := s.server.internalExecutor.Exec(
ctx,
"revoke-auth-session",
nil, /* txn */
`UPDATE system.web_sessions SET "revokedAt" = now() WHERE id = $1`,
sessionID,
); err != nil {
return nil, apiInternalError(ctx, err)
} else if n == 0 {
msg := fmt.Sprintf("session with id %d nonexistent", sessionID)
log.Info(ctx, msg)
return nil, fmt.Errorf(msg)
}
// Send back a header which will cause the browser to destroy the cookie.
// See https://tools.ietf.org/search/rfc6265, page 7.
cookie := makeCookieWithValue("")
cookie.MaxAge = -1
// Set the cookie header on the outgoing response.
if err := grpc.SetHeader(ctx, metadata.Pairs("set-cookie", cookie.String())); err != nil {
return nil, apiInternalError(ctx, err)
}
return &serverpb.UserLogoutResponse{}, nil
}
// verifySession verifies the existence and validity of the session claimed by
// the supplied SessionCookie. Returns three parameters: a boolean indicating if
// the session was valid, the username associated with the session (if
// validated), and an error for any internal errors which prevented validation.
func (s *authenticationServer) verifySession(
ctx context.Context, cookie *serverpb.SessionCookie,
) (bool, string, error) {
// Look up session in database and verify hashed secret value.
const sessionQuery = `
SELECT "hashedSecret", "username", "expiresAt", "revokedAt"
FROM system.web_sessions
WHERE id = $1`
var (
hashedSecret []byte
username string
expiresAt time.Time
isRevoked bool
)
row, err := s.server.internalExecutor.QueryRow(
ctx,
"lookup-auth-session",
nil /* txn */, sessionQuery, cookie.ID)
if row == nil || err != nil {
return false, "", err
}
if row.Len() != 4 ||
row[0].ResolvedType() != types.Bytes ||
row[1].ResolvedType() != types.String ||
row[2].ResolvedType() != types.Timestamp {
return false, "", errors.Errorf("values returned from auth session lookup do not match expectation")
}
// Extract datum values.
hashedSecret = []byte(*row[0].(*tree.DBytes))
username = string(*row[1].(*tree.DString))
expiresAt = row[2].(*tree.DTimestamp).Time
isRevoked = row[3].ResolvedType() != types.Unknown
if isRevoked {
return false, "", nil
}
if now := s.server.clock.PhysicalTime(); !now.Before(expiresAt) {
return false, "", nil
}
hasher := sha256.New()
hashedCookieSecret := hasher.Sum(cookie.Secret)
if !bytes.Equal(hashedSecret, hashedCookieSecret) {
return false, "", nil
}
return true, username, nil
}
// verifyPassword verifies the passed username/password pair against the
// system.users table. The returned boolean indicates whether or not the
// verification succeeded; an error is returned if the validation process could
// not be completed.
func (s *authenticationServer) verifyPassword(
ctx context.Context, username string, password string,
) (bool, error) {
exists, hashedPassword, err := sql.GetUserHashedPassword(
ctx, s.server.execCfg, s.memMetrics, username,
)
if err != nil {
return false, err
}
if !exists {
return false, nil
}
return (security.CompareHashAndPassword(hashedPassword, password) == nil), nil
}
// newAuthSession attempts to create a new authentication session for the given
// user. If successful, returns the ID and secret value for the new session.
func (s *authenticationServer) newAuthSession(
ctx context.Context, username string,
) (int64, []byte, error) {
secret := make([]byte, secretLength)
if _, err := rand.Read(secret); err != nil {
return 0, nil, err
}
hasher := sha256.New()
hashedSecret := hasher.Sum(secret)
expiration := s.server.clock.PhysicalTime().Add(webSessionTimeout.Get(&s.server.st.SV))
insertSessionStmt := `
INSERT INTO system.web_sessions ("hashedSecret", username, "expiresAt")
VALUES($1, $2, $3)
RETURNING id
`
var id int64
row, err := s.server.internalExecutor.QueryRow(
ctx,
"create-auth-session",
nil, /* txn */
insertSessionStmt,
hashedSecret,
username,
expiration,
)
if err != nil {
return 0, nil, err
}
if row.Len() != 1 || row[0].ResolvedType() != types.Int {
return 0, nil, errors.Errorf(
"expected create auth session statement to return exactly one integer, returned %v",
row,
)
}
// Extract integer value from single datum.
id = int64(*row[0].(*tree.DInt))
return id, secret, nil
}
// authenticationMux implements http.Handler, and is used to provide session
// authentication for an arbitrary "inner" handler.
type authenticationMux struct {
server *authenticationServer
inner http.Handler
allowAnonymous bool
}
func newAuthenticationMuxAllowAnonymous(
s *authenticationServer, inner http.Handler,
) *authenticationMux {
return &authenticationMux{
server: s,
inner: inner,
allowAnonymous: true,
}
}
func newAuthenticationMux(s *authenticationServer, inner http.Handler) *authenticationMux {
return &authenticationMux{
server: s,
inner: inner,
allowAnonymous: false,
}
}
type webSessionUserKey struct{}
type webSessionIDKey struct{}
const webSessionUserKeyStr = "webSessionUser"
const webSessionIDKeyStr = "webSessionID"
func (am *authenticationMux) ServeHTTP(w http.ResponseWriter, req *http.Request) {
username, cookie, err := am.getSession(w, req)
if err != nil && !am.allowAnonymous {
log.Infof(req.Context(), "Web session error: %s", err)
http.Error(w, "a valid authentication cookie is required", http.StatusUnauthorized)
return
}
newCtx := context.WithValue(req.Context(), webSessionUserKey{}, username)
if cookie != nil {
newCtx = context.WithValue(newCtx, webSessionIDKey{}, cookie.ID)
}
newReq := req.WithContext(newCtx)
am.inner.ServeHTTP(w, newReq)
}
func encodeSessionCookie(sessionCookie *serverpb.SessionCookie) (*http.Cookie, error) {
cookieValueBytes, err := protoutil.Marshal(sessionCookie)
if err != nil {
return nil, errors.Wrap(err, "session cookie could not be encoded")
}
value := base64.StdEncoding.EncodeToString(cookieValueBytes)
return makeCookieWithValue(value), nil
}
func makeCookieWithValue(value string) *http.Cookie {
return &http.Cookie{
Name: sessionCookieName,
Value: value,
Path: "/",
HttpOnly: true,
Secure: true,
}
}
// getSession decodes the cookie from the request, looks up the corresponding session, and
// returns the logged in user name. If there's an error, it returns an error value and the
// HTTP error code.
func (am *authenticationMux) getSession(
w http.ResponseWriter, req *http.Request,
) (string, *serverpb.SessionCookie, error) {
// Validate the returned cookie.
rawCookie, err := req.Cookie(sessionCookieName)
if err != nil {
return "", nil, err
}
cookie, err := decodeSessionCookie(rawCookie)
if err != nil {
err = errors.Wrap(err, "a valid authentication cookie is required")
return "", nil, err
}
valid, username, err := am.server.verifySession(req.Context(), cookie)
if err != nil {
err := apiInternalError(req.Context(), err)
return "", nil, err
}
if !valid {
err := errors.New("the provided authentication session could not be validated")
return "", nil, err
}
return username, cookie, nil
}
func decodeSessionCookie(encodedCookie *http.Cookie) (*serverpb.SessionCookie, error) {
// Cookie value should be a base64 encoded protobuf.
cookieBytes, err := base64.StdEncoding.DecodeString(encodedCookie.Value)
if err != nil {
return nil, errors.Wrap(err, "session cookie could not be decoded")
}
var sessionCookieValue serverpb.SessionCookie
if err := protoutil.Unmarshal(cookieBytes, &sessionCookieValue); err != nil {
return nil, errors.Wrap(err, "session cookie could not be unmarshaled")
}
return &sessionCookieValue, nil
}
// authenticationHeaderMatcher is a GRPC header matcher function, which provides
// a conversion from GRPC headers to HTTP headers. This function is needed to
// attach the "set-cookie" header to the response; by default, Grpc-Gateway
// adds a prefix to all GRPC headers before adding them to the response.
func authenticationHeaderMatcher(key string) (string, bool) {
// GRPC converts all headers to lower case.
if key == "set-cookie" {
return key, true
}
// This is the default behavior of GRPC Gateway when matching headers -
// it adds a constant prefix to the HTTP header so that by default they
// do not conflict with any HTTP headers that might be used by the
// browser.
// TODO(mrtracy): A function "DefaultOutgoingHeaderMatcher" should
// likely be added to GRPC Gateway so that the logic does not have to be
// duplicated here.
return fmt.Sprintf("%s%s", gwruntime.MetadataHeaderPrefix, key), true
}
func forwardAuthenticationMetadata(ctx context.Context, _ *http.Request) metadata.MD {
md := metadata.MD{}
if user := ctx.Value(webSessionUserKey{}); user != nil {
md.Set(webSessionUserKeyStr, user.(string))
}
if sessionID := ctx.Value(webSessionIDKey{}); sessionID != nil {
md.Set(webSessionIDKeyStr, fmt.Sprintf("%v", sessionID))
}
return md
}