-
Notifications
You must be signed in to change notification settings - Fork 3
/
user_2fa.go
572 lines (459 loc) · 11.8 KB
/
user_2fa.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
package pitchfork
import (
"encoding/base32"
"encoding/hex"
"errors"
purl "net/url"
"strconv"
"strings"
"time"
"trident.li/keyval"
)
/* Whether we verify 2FA tokens or not (--disabletwofactor) */
var CheckTwoFactor = true
type PfUser2FA struct {
Id int `label:"ID" pfset:"none" pfcol:"id"`
UserName string `label:"UserName" pfset:"self" pfcol:"member" pftype:"ident" hint:"Owner of the Token"`
Name string `label:"Description" pfset:"self" pfcol:"descr" hint:"Helpful name of the token"`
Type string `label:"Type" pfset:"self" pfcol:"type"`
Entered time.Time `label:"Entered" pfset:"nobody" pfget:"user"`
Active bool `label:"Active" pfset:"self" pfcol:"active" hint:"Is the token active"`
Key string `label:"Key" pfset:"self" pfcol:"key"`
Counter int `trilanel:"Count" pfset:"self" pfcol:"counter" hint:"HOTP counter"`
}
func NewPfUser2FA() *PfUser2FA {
return &PfUser2FA{}
}
func TwoFactorTypes() (types keyval.KeyVals) {
q := "SELECT type, descr " +
"FROM second_factor_types " +
"ORDER BY type"
rows, err := DB.Query(q)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var t_type string
var t_descr string
err = rows.Scan(&t_type, &t_descr)
if err != nil {
types = nil
return
}
types.Add(t_type, t_descr)
}
return
}
func (tfa *PfUser2FA) fetch(id int) (err error) {
p := []string{"id"}
v := []string{strconv.Itoa(id)}
err = StructFetch(tfa, "second_factors", p, v)
if err != nil {
tfa.Id = 0
Log(err.Error() + " '" + strconv.Itoa(id) + "'")
}
return
}
func (tfa *PfUser2FA) Refresh() (err error) {
return tfa.fetch(tfa.Id)
}
/* Extends PfUserS object */
func (user *PfUserS) Fetch2FA() (tokens []PfUser2FA, err error) {
q := "SELECT id, member, descr, type, entered, active, key, counter " +
"FROM second_factors " +
"WHERE member = $1 "
rows, err := DB.Query(q, user.GetUserName())
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var tfa PfUser2FA
err = rows.Scan(&tfa.Id, &tfa.UserName, &tfa.Name, &tfa.Type, &tfa.Entered,
&tfa.Active, &tfa.Key, &tfa.Counter)
if err != nil {
tokens = nil
return
}
tokens = append(tokens, tfa)
}
return
}
func (tfa *PfUser2FA) Select(ctx PfCtx, id int, perms Perm) (err error) {
/* Fetch it if it exists */
err = tfa.fetch(id)
if err != nil {
/* Failed */
return err
}
/* SysAdmins can select any */
if ctx.IsSysAdmin() {
return nil
}
/* Can select self */
if ctx.IsPermSet(perms, PERM_USER_SELF) &&
ctx.IsLoggedIn() &&
tfa.UserName == ctx.TheUser().GetUserName() {
return nil
}
return errors.New("Could not select 2FA Token")
}
/*
* If id is set to a value other than zero this function will
* compare with that one and only one token, even if it disabled.
*/
func (user *PfUserS) Verify_TwoFactor(ctx PfCtx, twofactor string, id int) (err error) {
var pw PfPass
var rows *Rows
var args []interface{}
/* Don't check TwoFactor Authentication */
if CheckTwoFactor == false {
return nil
}
q := "SELECT id, type, counter, key " +
"FROM second_factors"
DB.Q_AddWhereAnd(&q, &args, "member", user.GetUserName())
if id > 0 {
DB.Q_AddWhereAnd(&q, &args, "id", id)
} else {
DB.Q_AddWhereAnd(&q, &args, "active", true)
}
rows, err = DB.Query(q, args...)
defer rows.Close()
if err != nil {
err = errors.New("Verifying Two Factor Authentication failed: " + err.Error())
return
}
has2fa := false
for rows.Next() {
has2fa = true
/* When 2FA is configured, we require it */
if twofactor == "" {
return errors.New("2FA required, not provided")
}
var t_id int
var t_type string
var t_counter int64
var t_key string
err = rows.Scan(&t_id, &t_type, &t_counter, &t_key)
if err != nil {
return
}
switch t_type {
case "HOTP":
if pw.VerifyHOTP(t_key, t_counter, twofactor) {
/* Correct, increase counter */
q := "UPDATE second_factors " +
"SET counter = counter + 1 " +
"WHERE id = $1"
DB.Exec(ctx,
"Increased HOTP counter for 2FA $1",
1, q,
t_id)
return nil
}
break
case "TOTP":
if pw.VerifyTOTP(t_key, twofactor) {
/* Correct */
return nil
}
break
case "SOTP":
if pw.VerifySOTP(t_key, twofactor) {
/* Correct, remove Single-use OTP code */
q := "DELETE FROM second_factors " +
"WHERE id = $1"
DB.Exec(ctx,
"Used SOTP code $1 (SOTP code removed)",
1, q, t_id)
return nil
}
break
default:
return errors.New("Unknown Hash Type")
}
}
/* If the user has no 2FA tokens, then allow them in */
if has2fa {
return errors.New("Invalid 2FA")
}
/* If 2FA set but not required, fail */
if !has2fa && twofactor != "" {
return errors.New("Invalid 2FA")
}
/* If we require 2FA */
if System_Get().Require2FA {
return errors.New("2FA required but not configured for this user")
}
return nil
}
func (tfa *PfUser2FA) String() (out string) {
out = tfa.UserName + " " + strconv.Itoa(tfa.Id)
out += " " + tfa.Name + " " + tfa.Type + "\n"
out += " " + tfa.Entered.String() + " " + strconv.FormatBool(tfa.Active) + "\n"
return
}
func CreateKey(length int) (out string, err error) {
/* Generate Key */
var pw PfPass
pwd, err := pw.GenRandHex(10)
if err != nil {
return
}
hex, err := hex.DecodeString(pwd)
if err != nil {
return
}
out = string(hex)
return
}
func EncodeKey(secret string) (out string) {
out = base32.StdEncoding.EncodeToString([]byte(secret))
return
}
func user_2fa_list(ctx PfCtx, args []string) (err error) {
var tfa PfUser2FA
var tokens []PfUser2FA
user := ctx.SelectedUser()
tokens, err = user.Fetch2FA()
for _, tfa = range tokens {
ctx.OutLn(tfa.String())
}
return
}
func user_2fa_add(ctx PfCtx, args []string) (err error) {
var id int
var secret string
/* username := args[0] */
pw := args[1]
token_type := strings.ToUpper(args[2])
descr := args[3]
user := ctx.SelectedUser()
/* SysAdmins can bypass the password check */
if !ctx.TheUser().IsSysAdmin() {
err = user.Verify_Password(ctx, pw)
if err != nil {
return
}
}
ctx.Dbg("Adding 2FA for " + user.GetUserName() + ", Type: " + token_type)
switch token_type {
case "TOTP", "HOTP":
counter := 0
secret, err = CreateKey(10)
if err != nil {
return
}
key := EncodeKey(secret)
/*
* Create otpauth:// URL
*
* Format: https://github.com/google/google-authenticator/wiki/Key-Uri-Format
*/
var u purl.URL
u.Path = "otpauth://" + strings.ToLower(token_type) + "/"
u.Path += AppName
u.Path += ":"
u.Path += user.GetUserName()
u.Path += " ("
u.Path += descr
u.Path += ")"
p := purl.Values{}
p.Add("secret", key)
p.Add("issuer", AppName)
/* Add counter which is required by Google Authenticator */
if token_type == "HOTP" {
p.Add("counter", strconv.Itoa(counter))
}
u.RawQuery = p.Encode()
url := u.String()
/* Add DB Record */
q := "INSERT INTO second_factors " +
"(member, type, descr, entered, active, key, counter)" +
"VALUES($1, $2, $3, now(), 'f', $4, $5) " +
"RETURNING id"
err = DB.QueryRowA(ctx,
"Add 2FA Token $2: $3",
q,
user.GetUserName(), token_type, descr, secret, counter).Scan(&id)
if err != nil {
err = errors.New("Could not add 2FA Token")
return
}
ctx.OutLn("Name: %s", descr)
ctx.OutLn("Token Type: %s", token_type)
ctx.OutLn("URL: %s", url)
if token_type == "HOTP" {
ctx.OutLn("Counter: %s", counter)
}
break
case "SOTP":
var pw PfPass
count := 5
for count > 0 {
secret, err = CreateKey(6)
if err != nil {
return
}
count_str := strconv.Itoa(count)
key := pw.SOTPHash(secret)
q := "INSERT INTO second_factors " +
"(member, type, descr, entered, active, key)" +
"VALUES($1, $2, $3, now(), 't', $4) " +
"RETURNING id"
name := descr + "-" + count_str
err = DB.QueryRowA(ctx,
"Add 2FA Token $2: $3",
q,
user.GetUserName(), token_type, name, key).Scan(&id)
if err != nil {
err = errors.New("Could not add email address")
return
}
count--
ctx.OutLn("Name: %s", name)
ctx.OutLn("Token Type: %s", token_type)
ctx.OutLn("Code: %s", secret)
}
break
default:
err = errors.New("Unknown 2FA Token Type: " + token_type)
break
}
return
}
func user_2fa_active_mod(ctx PfCtx, id string, curpassword string, active bool, code string) (err error) {
var member string
var curact bool
user := ctx.SelectedUser()
/* SysAdmins can bypass the password check */
if !ctx.TheUser().IsSysAdmin() {
err = user.Verify_Password(ctx, curpassword)
if err != nil {
return
}
}
q := "SELECT member, active " +
"FROM second_factors " +
"WHERE id = $1"
err = DB.QueryRow(q, id).Scan(&member, &curact)
if err != nil {
err = errors.New("No such token")
return
}
if !ctx.TheUser().IsSysAdmin() && user.GetUserName() != member {
ctx.Log("User " + user.GetUserName() + " attempted to access token " + id + " of user " + member)
err = errors.New("No such token")
return
}
newstate := "active"
if !active {
newstate = "inactive"
}
if curact == active {
err = errors.New("Token " + id + " already in " + newstate + " state")
return
}
if newstate == "active" {
id_int, err := strconv.Atoi(id)
if err != nil {
return errors.New("ID not numeric")
}
if user.Verify_TwoFactor(ctx, code, id_int) != nil {
return errors.New("Token value not correct")
}
}
q = "UPDATE second_factors " +
"SET active = $1 " +
"WHERE member = $2 " +
"AND id = $3"
act := "t"
if !active {
act = "f"
}
err = DB.Exec(ctx,
"Change 2FA Token $3 to "+newstate,
1, q,
act, member, id)
if err != nil {
err = errors.New("Could not modify 2FA token state")
return
}
ctx.OutLn("State of 2FA token %s changed to %s", id, newstate)
return
}
func user_2fa_enable(ctx PfCtx, args []string) (err error) {
/* username := args[0] */
id := args[1]
pw := args[2]
tf := args[3]
err = user_2fa_active_mod(ctx, id, pw, true, tf)
return
}
func user_2fa_disable(ctx PfCtx, args []string) (err error) {
/* username := args[0] */
id := args[1]
pw := args[2]
err = user_2fa_active_mod(ctx, id, pw, false, "")
return
}
func user_2fa_remove(ctx PfCtx, args []string) (err error) {
user := ctx.SelectedUser()
username := user.GetUserName()
id := args[1]
pw := args[2]
/* SysAdmins can bypass the password check */
if !ctx.TheUser().IsSysAdmin() {
err = user.Verify_Password(ctx, pw)
if err != nil {
return
}
}
q := "DELETE from second_factors " +
"WHERE member = $1 " +
"AND id = $2 AND (active = 'f' OR type = 'SOTP')"
err = DB.Exec(ctx,
"Removed 2FA Token $2",
1, q,
username, id)
if err != nil {
err = errors.New("Could not remove 2FA token")
return
}
ctx.OutLn("2FA Token %s removed", id)
return
}
func user_2fa_types(ctx PfCtx, args []string) (err error) {
types := TwoFactorTypes()
for _, kv := range types {
key := kv.Key.(string)
val := kv.Value.(string)
ctx.OutLn("%s %s\n", key, val)
}
return
}
func user_2fa_menu(ctx PfCtx, args []string) (err error) {
perms := PERM_USER_SELF
menu := NewPfMenu([]PfMEntry{
{"list", user_2fa_list, 1, 1, []string{"username"}, perms, "List tokens"},
{"add", user_2fa_add, 4, 4, []string{"username", "curpassword#password", "type#2fatoken", "descr"}, perms, "Add tokens"},
{"enable", user_2fa_enable, 4, 4, []string{"username", "id", "curpassword#password", "twofactorcode#int"}, perms, "Enable token"},
{"disable", user_2fa_disable, 3, 3, []string{"username", "id", "curpassword#password"}, perms, "Disable token"},
{"remove", user_2fa_remove, 3, 3, []string{"username", "id", "curpassword#password"}, perms, "Remove token"},
{"types", user_2fa_types, 0, 0, nil, PERM_NONE, "List available 2FA Types"},
})
if len(args) >= 2 {
/* Check if we have perms for this user */
err = ctx.SelectUser(args[1], perms)
if err != nil {
return
}
} else {
/* Nothing selected */
ctx.SelectUser("", PERM_NONE)
}
err = ctx.Menu(args, menu)
return
}