forked from VictorNine/bitwarden-go
/
auth.go
350 lines (296 loc) · 8.53 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
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
package auth
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strings"
"time"
"golang.org/x/crypto/pbkdf2"
jwt "github.com/dgrijalva/jwt-go"
bw "github.com/VictorNine/bitwarden-go/internal/common"
)
type Auth struct {
db database
signingKey []byte
jwtExpire int
}
func New(db database, signingKey string, jwtExpire int) Auth {
auth := Auth{
db: db,
signingKey: []byte(signingKey),
jwtExpire: jwtExpire,
}
return auth
}
// Interface to make testing easier
type database interface {
AddAccount(acc bw.Account) error
GetAccount(username string, refreshtoken string) (bw.Account, error)
UpdateAccountInfo(acc bw.Account) error
Update2FAsecret(secret string, email string) error
}
func reHashPassword(key, salt string, itr int) (string, error) {
b, err := base64.StdEncoding.DecodeString(key)
if err != nil {
return "", err
}
hash := pbkdf2.Key(b, []byte(salt), itr, 256/8, sha256.New)
return base64.StdEncoding.EncodeToString(hash), nil
}
func (auth *Auth) HandlePrelogin(w http.ResponseWriter, req *http.Request) {
// Get email
decoder := json.NewDecoder(req.Body)
var acc bw.Account
err := decoder.Decode(&acc)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(http.StatusText(http.StatusBadRequest)))
log.Println(err)
return
}
defer req.Body.Close()
// Get account data from DB
acc, err = auth.db.GetAccount(acc.Email, "")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(http.StatusText(500)))
log.Println(err)
return
}
// Return Kdf data
itrData := struct {
Kdf int
KdfIterations int
}{
Kdf: acc.Kdf,
KdfIterations: acc.KdfIterations,
}
data, err := json.Marshal(&itrData)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
func (auth *Auth) HandleRegister(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var acc bw.Account
err := decoder.Decode(&acc)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(http.StatusText(http.StatusBadRequest)))
log.Println(err)
return
}
defer req.Body.Close()
log.Println(acc.Email + " is trying to register")
// Check iterations
if acc.KdfIterations < 5000 || acc.KdfIterations > 100000 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(http.StatusText(http.StatusBadRequest)))
return
}
acc.MasterPasswordHash, err = reHashPassword(acc.MasterPasswordHash, acc.Email, acc.KdfIterations)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(http.StatusText(500)))
log.Println(err)
return
}
err = auth.db.AddAccount(acc)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(http.StatusText(500)))
log.Println(err)
return
}
w.Write([]byte{0x00})
}
func createRefreshToken() string {
token := make([]byte, 32)
_, err := rand.Read(token)
if err != nil {
log.Fatal(err)
}
tokenStr := base64.StdEncoding.EncodeToString(token)
return tokenStr
}
type resToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
Key string `json:"Key"`
}
// PrivateKey is needed by the web vault. But android will crash if it's included
type resTokenWPK struct {
resToken
PrivateKey string `json:"PrivateKey"`
}
func (auth *Auth) HandleLogin(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
grantType, ok := req.PostForm["grant_type"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(http.StatusText(http.StatusBadRequest)))
log.Println("Login without grant_type")
return
}
clientID := req.PostForm["client_id"][0]
var acc bw.Account
var err error
if grantType[0] == "refresh_token" {
rrefreshToken := req.PostForm["refresh_token"][0]
if len(rrefreshToken) < 4 {
// Fatal to always catch this
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(http.StatusText(401)))
log.Println("fake refreshToken " + rrefreshToken)
return
}
acc, err = auth.db.GetAccount("", rrefreshToken)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(http.StatusText(401)))
log.Println("Account not found")
return
}
log.Println(acc.Email + " is trying to refresh a token ")
if acc.RefreshToken != rrefreshToken {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(http.StatusText(401)))
log.Println("Login attempt failed")
return
}
} else {
// Login with username
username := req.PostForm["username"][0]
passwordHash := req.PostForm["password"][0]
log.Println(username + " is trying to login")
acc, err = checkPassword(auth.db, username, passwordHash)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(http.StatusText(401)))
log.Println(err)
return
}
// Check 2FA
if len(acc.TwoFactorSecret) > 0 {
err := check2FA(w, req, acc.TwoFactorSecret)
if err != nil {
return
}
}
}
// Don't change refresh token every time or the other clients will be logged out
if acc.RefreshToken == "" {
// Create refreshtoken and store in db
acc.RefreshToken = createRefreshToken()
err = auth.db.UpdateAccountInfo(acc)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(http.StatusText(401)))
log.Println(err)
return
}
}
// Create the token
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["nbf"] = time.Now().Unix()
claims["exp"] = time.Now().Add(time.Second * time.Duration(auth.jwtExpire)).Unix()
claims["iss"] = "NA"
claims["sub"] = "NA"
claims["email"] = acc.Email
claims["name"] = acc.Name
claims["premium"] = false
claims["email_verified"] = false
tokenString, _ := token.SignedString(auth.signingKey)
rtoken := resToken{AccessToken: tokenString,
ExpiresIn: auth.jwtExpire,
TokenType: "Bearer",
RefreshToken: acc.RefreshToken,
Key: acc.Key,
}
var data []byte
// Login from web vault add priv key
if clientID == "web" {
rtokenWPK := resTokenWPK{resToken: rtoken, PrivateKey: acc.KeyPair.EncryptedPrivateKey}
data, err = json.Marshal(&rtokenWPK)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
log.Println("Account not found")
return
}
} else {
data, err = json.Marshal(&rtoken)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
log.Println("Account not found")
return
}
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
type ctxKey string
func GetEmail(req *http.Request) string {
return req.Context().Value(ctxKey("email")).(string)
}
func (auth *Auth) JwtMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
tokens, ok := req.Header["Authorization"]
if !ok && len(tokens) < 1 {
log.Println("Missing auth header")
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(http.StatusText(401)))
return
}
tokenString := tokens[0]
tokenString = strings.TrimPrefix(tokenString, "Bearer ")
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return auth.signingKey, nil
})
if err != nil {
log.Println("JWT: " + err.Error()) // Fatal for now to catch all errors here
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(http.StatusText(401)))
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
email, ok := claims["email"].(string)
if ok {
ctx := context.WithValue(req.Context(), ctxKey("email"), email)
next.ServeHTTP(w, req.WithContext(ctx))
return
}
}
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(http.StatusText(401)))
})
}
func checkPassword(db database, username, passwordHash string) (bw.Account, error) {
acc, err := db.GetAccount(username, "")
if err != nil {
return bw.Account{}, err
}
reHash, _ := reHashPassword(passwordHash, acc.Email, acc.KdfIterations)
if acc.MasterPasswordHash != reHash {
return bw.Account{}, errors.New("Login attempt failed")
}
return acc, nil
}