forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_login.go
104 lines (89 loc) · 2.57 KB
/
path_login.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
package userpass
import (
"crypto/subtle"
"fmt"
"strings"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
"golang.org/x/crypto/bcrypt"
)
func pathLogin(b *backend) *framework.Path {
return &framework.Path{
Pattern: "login/" + framework.GenericNameRegex("username"),
Fields: map[string]*framework.FieldSchema{
"username": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Username of the user.",
},
"password": &framework.FieldSchema{
Type: framework.TypeString,
Description: "Password for this user.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathLogin,
},
HelpSynopsis: pathLoginSyn,
HelpDescription: pathLoginDesc,
}
}
func (b *backend) pathLogin(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
username := strings.ToLower(d.Get("username").(string))
password := d.Get("password").(string)
if password == "" {
return nil, fmt.Errorf("missing password")
}
// Get the user and validate auth
user, err := b.user(req.Storage, username)
if err != nil {
return nil, err
}
if user == nil {
return logical.ErrorResponse("invalid username or password"), nil
}
// Check for a password match. Check for a hash collision for Vault 0.2+,
// but handle the older legacy passwords with a constant time comparison.
passwordBytes := []byte(password)
if user.PasswordHash != nil {
if err := bcrypt.CompareHashAndPassword(user.PasswordHash, passwordBytes); err != nil {
return logical.ErrorResponse("invalid username or password"), nil
}
} else {
if subtle.ConstantTimeCompare([]byte(user.Password), passwordBytes) != 1 {
return logical.ErrorResponse("invalid username or password"), nil
}
}
return &logical.Response{
Auth: &logical.Auth{
Policies: user.Policies,
Metadata: map[string]string{
"username": username,
},
DisplayName: username,
LeaseOptions: logical.LeaseOptions{
TTL: user.TTL,
Renewable: true,
},
},
}, nil
}
func (b *backend) pathLoginRenew(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
// Get the user
user, err := b.user(req.Storage, req.Auth.Metadata["username"])
if err != nil {
return nil, err
}
if user == nil {
// User no longer exists, do not renew
return nil, nil
}
return framework.LeaseExtend(user.TTL, user.MaxTTL, b.System())(req, d)
}
const pathLoginSyn = `
Log in with a username and password.
`
const pathLoginDesc = `
This endpoint authenticates using a username and password.
`