-
Notifications
You must be signed in to change notification settings - Fork 0
/
resetpasswordtoken.go
305 lines (257 loc) · 8.42 KB
/
resetpasswordtoken.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
/*
Copyright 2017-2020 Gravitational, Inc.
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 auth
import (
"bytes"
"context"
"fmt"
"image/png"
"net/url"
"time"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
"github.com/pquerna/otp/totp"
)
const (
// ResetPasswordTokenTypeInvite indicates invite UI flow
ResetPasswordTokenTypeInvite = "invite"
// ResetPasswordTokenTypePassword indicates set new password UI flow
ResetPasswordTokenTypePassword = "password"
)
// CreateResetPasswordTokenRequest is a request to create a new reset password token
type CreateResetPasswordTokenRequest struct {
// Name is the user name to reset.
Name string `json:"name"`
// TTL specifies how long the generated reset token is valid for.
TTL time.Duration `json:"ttl"`
// Type is a token type.
Type string `json:"type"`
}
// CheckAndSetDefaults checks and sets the defaults
func (r *CreateResetPasswordTokenRequest) CheckAndSetDefaults() error {
if r.Name == "" {
return trace.BadParameter("user name can't be empty")
}
if r.TTL < 0 {
return trace.BadParameter("TTL can't be negative")
}
if r.Type == "" {
r.Type = ResetPasswordTokenTypePassword
}
// We use the same mechanism to handle invites and password resets
// as both allow setting up a new password based on auth preferences.
// The only difference is default TTL values and URLs to web UI.
switch r.Type {
case ResetPasswordTokenTypeInvite:
if r.TTL == 0 {
r.TTL = defaults.SignupTokenTTL
}
if r.TTL > defaults.MaxSignupTokenTTL {
return trace.BadParameter(
"failed to create user invite token: maximum token TTL is %v hours",
defaults.MaxSignupTokenTTL)
}
case ResetPasswordTokenTypePassword:
if r.TTL == 0 {
r.TTL = defaults.ChangePasswordTokenTTL
}
if r.TTL > defaults.MaxChangePasswordTokenTTL {
return trace.BadParameter(
"failed to create reset password token: maximum token TTL is %v hours",
defaults.MaxChangePasswordTokenTTL)
}
default:
return trace.BadParameter("unknown reset password token request type(%v)", r.Type)
}
return nil
}
// CreateResetPasswordToken creates a reset password token
func (s *AuthServer) CreateResetPasswordToken(ctx context.Context, req CreateResetPasswordTokenRequest) (services.ResetPasswordToken, error) {
err := req.CheckAndSetDefaults()
if err != nil {
return nil, trace.Wrap(err)
}
_, err = s.GetUser(req.Name, false)
if err != nil {
return nil, trace.Wrap(err)
}
_, err = s.ResetPassword(req.Name)
if err != nil {
return nil, trace.Wrap(err)
}
token, err := s.newResetPasswordToken(req)
if err != nil {
return nil, trace.Wrap(err)
}
// remove any other existing tokens for this user
err = s.deleteResetPasswordTokens(ctx, req.Name)
if err != nil {
return nil, trace.Wrap(err)
}
_, err = s.Identity.CreateResetPasswordToken(ctx, token)
if err != nil {
return nil, trace.Wrap(err)
}
return s.GetResetPasswordToken(ctx, token.GetName())
}
// proxyDomainGetter is a reduced subset of the Auth API for formatAccountName.
type proxyDomainGetter interface {
GetProxies() ([]services.Server, error)
GetDomainName() (string, error)
}
// formatAccountName builds the account name to display in OTP applications.
// Format for accountName is user@address. User is passed in, this function
// tries to find the best available address.
func formatAccountName(s proxyDomainGetter, username string, authHostname string) (string, error) {
var err error
var proxyHost string
// Get a list of proxies.
proxies, err := s.GetProxies()
if err != nil {
return "", trace.Wrap(err)
}
// If no proxies were found, try and set address to the name of the cluster.
// If even the cluster name is not found (an unlikely) event, fallback to
// hostname of the auth server.
//
// If a proxy was found, and any of the proxies has a public address set,
// use that. If none of the proxies have a public address set, use the
// hostname of the first proxy found.
if len(proxies) == 0 {
proxyHost, err = s.GetDomainName()
if err != nil {
log.Errorf("Failed to retrieve cluster name, falling back to hostname: %v.", err)
proxyHost = authHostname
}
} else {
proxyHost, _, err = services.GuessProxyHostAndVersion(proxies)
if err != nil {
return "", trace.Wrap(err)
}
}
return fmt.Sprintf("%v@%v", username, proxyHost), nil
}
// RotateResetPasswordTokenSecrets rotates secrets for a given tokenID.
// It gets called every time a user fetches 2nd-factor secrets during registration attempt.
// This ensures that an attacker that gains the ResetPasswordToken link can not view it,
// extract the OTP key from the QR code, then allow the user to signup with
// the same OTP token.
func (s *AuthServer) RotateResetPasswordTokenSecrets(ctx context.Context, tokenID string) (services.ResetPasswordTokenSecrets, error) {
token, err := s.GetResetPasswordToken(ctx, tokenID)
if err != nil {
return nil, trace.Wrap(err)
}
// Fetch account name to display in OTP apps.
accountName, err := formatAccountName(s, token.GetUser(), s.AuthServiceName)
if err != nil {
return nil, trace.Wrap(err)
}
key, qr, err := newTOTPKeys("Teleport", accountName)
if err != nil {
return nil, trace.Wrap(err)
}
secrets, err := services.NewResetPasswordTokenSecrets(tokenID)
if err != nil {
return nil, trace.Wrap(err)
}
secrets.Spec.OTPKey = key
secrets.Spec.QRCode = string(qr)
err = s.UpsertResetPasswordTokenSecrets(ctx, &secrets)
if err != nil {
return nil, trace.Wrap(err)
}
return &secrets, nil
}
func (s *AuthServer) newResetPasswordToken(req CreateResetPasswordTokenRequest) (services.ResetPasswordToken, error) {
var err error
var proxyHost string
tokenID, err := utils.CryptoRandomHex(TokenLenBytes)
if err != nil {
return nil, trace.Wrap(err)
}
// Get the list of proxies and try and guess the address of the proxy. If
// failed to guess public address, use "<proxyhost>:3080" as a fallback.
proxies, err := s.GetProxies()
if err != nil {
return nil, trace.Wrap(err)
}
if len(proxies) == 0 {
proxyHost = fmt.Sprintf("<proxyhost>:%v", defaults.HTTPListenPort)
} else {
proxyHost, _, err = services.GuessProxyHostAndVersion(proxies)
if err != nil {
return nil, trace.Wrap(err)
}
}
url, err := formatResetPasswordTokenURL(proxyHost, tokenID, req.Type)
if err != nil {
return nil, trace.Wrap(err)
}
token := services.NewResetPasswordToken(tokenID)
token.Metadata.SetExpiry(s.clock.Now().UTC().Add(req.TTL))
token.Spec.User = req.Name
token.Spec.Created = s.clock.Now().UTC()
token.Spec.URL = url
return &token, nil
}
func formatResetPasswordTokenURL(proxyHost string, tokenID string, reqType string) (string, error) {
u := &url.URL{
Scheme: "https",
Host: proxyHost,
}
// We have 2 different UI flows to process password reset tokens
if reqType == ResetPasswordTokenTypeInvite {
u.Path = fmt.Sprintf("/web/invite/%v", tokenID)
} else if reqType == ResetPasswordTokenTypePassword {
u.Path = fmt.Sprintf("/web/reset/%v", tokenID)
}
return u.String(), nil
}
func (s *AuthServer) deleteResetPasswordTokens(ctx context.Context, username string) error {
tokens, err := s.GetResetPasswordTokens(ctx)
if err != nil {
return trace.Wrap(err)
}
for _, token := range tokens {
if token.GetUser() != username {
continue
}
err = s.DeleteResetPasswordToken(ctx, token.GetName())
if err != nil {
return trace.Wrap(err)
}
}
return nil
}
func newTOTPKeys(issuer string, accountName string) (key string, qr []byte, err error) {
// create totp key
otpKey, err := totp.Generate(totp.GenerateOpts{
Issuer: issuer,
AccountName: accountName,
})
if err != nil {
return "", nil, trace.Wrap(err)
}
// create QR code
var otpQRBuf bytes.Buffer
otpImage, err := otpKey.Image(456, 456)
if err != nil {
return "", nil, trace.Wrap(err)
}
if err := png.Encode(&otpQRBuf, otpImage); err != nil {
return "", nil, trace.Wrap(err)
}
return otpKey.Secret(), otpQRBuf.Bytes(), nil
}