-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
577 lines (478 loc) · 13.3 KB
/
main.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
573
574
575
576
577
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/base32"
"encoding/binary"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"os/exec"
"os/user"
"regexp"
"strconv"
"strings"
"time"
badger "github.com/dgraph-io/badger/v2"
"github.com/manifoldco/promptui"
)
var db *badger.DB
type Items struct {
Items []Item `json:"items"`
}
type Item struct {
Type string `json:"type"`
Title string `json:"title"`
Arg string `json:"arg"`
Autocomplete string `json:"autocomplete"`
}
// Colour takes in a colour and text returns the text in that colour.
func Colour(colour, text string) string {
colours := map[string]string{
"Red": "\033[1;31m%s\033[0m",
"Green": "\033[01;32m%s\033[0m",
"Blue": "\033[1;34m%s\033[0m",
"Magenta": "\033[1;35m%s\033[0m",
}
return fmt.Sprintf(colours[colour], text)
}
// addTo adds an Alfred style JSON item to the Items struct.
func (i *Items) addTo(title, key string) []Item {
i.Items = append(i.Items, Item{
Type: "default",
Title: title,
Arg: key,
Autocomplete: key,
})
return i.Items
}
func main() {
const version = "0.7.1"
var err error
flag.Parse()
args := flag.Args()
db, err = initDb()
if err != nil {
fmt.Println(Colour("Red", err.Error()))
return
}
defer db.Close()
if len(args) == 0 {
prompt()
return
}
if args[0] == "v" || args[0] == "version" {
fmt.Printf("%s %s\n", Colour("Green", "Version"), Colour("Blue", version))
return
}
if args[0] == "help" {
fmt.Printf("%s\n", Colour("Green", "WELCOME TO GOTP"))
fmt.Printf("%s\n\n", "The purpose of this package is to help with getting a 2FA otp without having to go through the shlep of taking your phone out and typing in the otp (though it's probably meant to be tedious... security via tediousnessness).")
fmt.Printf("%s\n%s\n%s\n%s\n%s\n\n", Colour("Green", "ADD A NEW TOKEN"), Colour("Magenta", "gotp add key token."), "eg:", Colour("Blue", "gotp add key 564HJKHJKHKKKHGJKHJKYUFHFGHJ65E"), Colour("Blue", "gotp add key - local 564HJKHJKHKKKHGJKHJKYUFHFGHJ65E"))
fmt.Printf("%s\n%s\n%s\n%s\n%s\n\n", Colour("Green", "LIST KEYS"), Colour("Blue", "gotp ls"), "And example of the output would be:", Colour("Magenta", "1: key"), Colour("Magenta", "2: key - local"))
fmt.Printf("%s\n%s\n%s\n%s\n%s\n%s\n\n", Colour("Green", "GET OTP"), Colour("Magenta", "gotp key"), Colour("Magenta", "gotp get key"), "or you could use the index from gotp ls", Colour("Blue", "gotp 2"), "The main difference between the above commands is that get is a simple returning/printing of the key where without get the key is added to your clipboard and prints out a statement of the key being added to your clipboard. The simplified version (with the get key word) is for piping to other utilities.")
fmt.Printf("%s\n%s\n%s %s %s\n\n", Colour("Green", "GET OTP VIA PROMPT"), Colour("Magenta", "gotp"), "If you only type", Colour("Blue", "gotp"), "a prompt will be brought up of the keys that have been stored. You can use this prompt to select the key you want to use.")
fmt.Printf("%s\n%s\n%s\n%s\n%s\n", Colour("Green", "REMOVE KEYS"), Colour("Magenta", "gotp rm key"), Colour("Magenta", "gotp rm key - local"), "or you could use the index from gotp ls", Colour("Blue", "gotp rm 2"))
return
}
if index, err := strconv.Atoi(args[0]); err == nil {
getOtpByIndex(index)
return
}
if args[0] == "add" {
l := len(args)
addToken(strings.Join(args[1:(l-1)], " "), args[l-1])
return
}
if args[0] == "ls" {
listKeys()
return
}
if args[0] == "rm" {
if index, err := strconv.Atoi(args[1]); err == nil {
removeKeyByIndex(index)
return
}
l := len(args)
queryOtp(args[1:l], "rm")
return
}
if args[0] == "get" {
l := len(args)
queryOtp(args[1:l], "simple")
return
}
if args[0] == "lsJson" {
listJson()
return
}
if args[0] == "queryJson" {
l := len(args)
queryJson(args[1:l])
return
}
queryOtp(args, "terminal")
}
// prompt shows a prompt of all the keys available with the ability to choose a key using the keyboard
func prompt() {
keys := getKeyList()
if len(keys) == 0 {
fmt.Printf("%s\n%s\n%s", Colour("Magenta", "You don't have any otp's saved yet."), "Try adding one by typing:", Colour("Blue", "gotp add key token"))
return
}
prompt := promptui.Select{
Label: "Select a key",
Items: keys,
}
_, key, err := prompt.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", Colour("Red", err.Error()))
return
}
getOtp(key, "terminal")
}
// getKeyList retrieves a list of keys to pass to other functions.
func getKeyList() []string {
var keys []string
err := db.View(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
keys = append(keys, string(item.Key()))
}
return nil
})
if err != nil {
fmt.Println(Colour("Red", err.Error()))
return []string{}
}
return keys
}
// listKeys outputs a list of keys and their index.
func listKeys() {
err := db.View(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
i := 1
opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
k := item.Key()
fmt.Printf("%s: %s\n", Colour("Green", strconv.Itoa(i)), k)
i++
}
return nil
})
if err != nil {
fmt.Println(Colour("Red", err.Error()))
}
}
// addToken takes in a key and secret and adds a token to the db.
func addToken(key, secret string) {
txn := db.NewTransaction(true)
defer txn.Discard()
// Use the transaction...
err := txn.Set([]byte(key), []byte(secret))
if err != nil {
fmt.Println(Colour("Red", err.Error()))
}
// Commit the transaction and check for error.
if err := txn.Commit(); err != nil {
fmt.Println(Colour("Red", err.Error()))
return
}
fmt.Println(Colour("Green", "Your key and secret have been saved"))
}
// removeKey removes a key.
func removeKey(key string) {
err := db.Update(func(txn *badger.Txn) error {
err := txn.Delete([]byte(key))
if err != nil {
return err
}
fmt.Printf("%s has been removed", Colour("Green", key))
return nil
})
if err != nil {
fmt.Println(Colour("Red", err.Error()))
}
}
// removeKeyByIndex removes a key by index.
func removeKeyByIndex(index int) {
err := db.Update(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
i := 1
opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
if index != i {
i++
continue
}
item := it.Item()
err := txn.Delete(item.Key())
if err != nil {
return err
}
fmt.Printf("%s has been removed", Colour("Green", string(item.Key())))
break
}
return nil
})
if err != nil {
fmt.Println(Colour("Red", err.Error()))
}
}
// queryOtp takes in query and finds the first key associated to it.
// Depending on the output the a key will be output or removed depending on if the output is simple, terminal or rm
func queryOtp(query []string, output string) {
var key string
err := db.View(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
key = string(item.Key())
if testQuery(query, key) {
break
}
}
return nil
})
if err != nil {
fmt.Println(Colour("Red", err.Error()))
}
if output == "rm" {
removeKey(key)
} else {
getOtp(key, output)
}
}
// getOtp takes in a key and output type and returns the otp.
// The otp's format is based on the type of output passed in, simple or terminal.
func getOtp(key string, output string) {
err := db.View(func(txn *badger.Txn) error {
var token string
item, err := txn.Get([]byte(key))
if err != nil {
return err
}
err = item.Value(func(val []byte) error {
token = string(val)
return nil
})
if err != nil {
return err
}
otp := getToken(token)
if output == "simple" {
fmt.Println(otp)
} else {
fmt.Printf("Your otp for %s is: %s\n", Colour("Blue", key), Colour("Green", otp))
//Checking if the pbcopy command is on the system.
_, err := exec.LookPath("pbcopy")
if err != nil {
return nil
}
//Copies the otp generated to your clipboard
err = exec.Command("bash", "-c", fmt.Sprintf("echo %s | tr -d \"\n, \" | pbcopy", otp)).Run()
if err != nil {
return err
}
fmt.Printf("%s has been copied to your clipboard\n", Colour("Green", otp))
}
return nil
})
if err != nil {
fmt.Println(Colour("Red", err.Error()))
}
}
// getOtpByIndex gets the otp by index.
func getOtpByIndex(index int) {
var key string
err := db.View(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
i := 1
opts.PrefetchValues = false
it := txn.NewIterator(opts)
for it.Rewind(); it.Valid(); it.Next() {
if index != i {
i++
continue
}
item := it.Item()
key = string(item.Key())
it.Close()
break
}
return nil
})
if key == "" {
fmt.Println(Colour("Magenta", "Could not find your key"))
return
}
if err != nil {
fmt.Println(Colour("Red", err.Error()))
return
}
getOtp(key, "terminal")
}
// listJson outputs Alfred style JSON of the keys available.
func listJson() {
items := new(Items)
err := db.View(func(txn *badger.Txn) error {
var k string
opts := badger.DefaultIteratorOptions
opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
k = string(item.Key())
items.addTo(k, k)
}
return nil
})
if err != nil {
fmt.Println(Colour("Red", err.Error()))
return
}
b, err := json.Marshal(items)
if err != nil {
fmt.Println(Colour("Red", err.Error()))
return
}
fmt.Println(string(b))
}
// queryJson outputs Alfred style JSON of the keys available filtered by a query.
func queryJson(query []string) {
var key string
var action string
matchAdd := false
items := new(Items)
keys := getKeyList()
l := len(query)
if l > 0 {
action = query[0]
}
matchRm, _ := regexp.MatchString("^rm", action)
if matchRm {
for _, k := range keys {
key = string(k)
if l == 1 || testQuery(query[1:], key) {
items.addTo("Remove "+key, "rm "+key)
}
}
}
if l == 0 || (!matchRm) {
for _, k := range keys {
key = string(k)
if l == 0 || testQuery(query, key) {
items.addTo(key, key)
}
}
}
if l > 0 {
matchAdd, _ = regexp.MatchString("^ad?d?", query[0])
}
if l == 0 {
query = append(query, "add")
} else if l == 1 && matchAdd {
query[0] = "add "
} else if l > 1 && matchAdd {
query[0] = "add"
} else {
query = append(query, query[0])
query[0] = "add"
}
items.addTo("Add", strings.Join(query, " "))
b, err := json.Marshal(items)
if err != nil {
fmt.Println(Colour("Red", err.Error()))
return
}
fmt.Println(string(b))
}
// testQuery tests to see if a query matches a key.
func testQuery(query []string, key string) bool {
for _, q := range query {
if !strings.Contains(key, q) {
return false
}
}
return true
}
// initDb initializes the database.
// The database is stored in ~/.config/gotp.
// If ~/.config/gotp is not there it will be created.
func initDb() (*badger.DB, error) {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
dbPath := usr.HomeDir + "/.config/gotp"
os.MkdirAll(dbPath, os.ModePerm)
options := badger.DefaultOptions(dbPath)
options.Logger = nil
db, err := badger.Open(options)
return db, err
}
// The code below has been taken from https://blog.gojekengineering.com/a-diy-two-factor-authenticator-in-golang-32e5641f6ec5
// Thank you Tilak Lodha for writing the article.
// getToken takes in a secret and converts it to a HOTP Token that is seeded every 30 seconds.
func getToken(secret string) string {
interval := time.Now().Unix() / 30
//Converts secret to base32 Encoding. Base32 encoding desires a 32-character
//subset of the twenty-six letters A–Z and ten digits 0–9
key, err := base32.StdEncoding.DecodeString(strings.ToUpper(secret))
if err != nil {
key, err = base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret)
if err != nil {
fmt.Println(Colour("Red", err.Error()))
}
}
bs := make([]byte, 8)
binary.BigEndian.PutUint64(bs, uint64(interval))
//Signing the value using HMAC-SHA1 Algorithm
hash := hmac.New(sha1.New, key)
hash.Write(bs)
h := hash.Sum(nil)
// We're going to use a subset of the generated hash.
// Using the last nibble (half-byte) to choose the index to start from.
// This number is always appropriate as it's maximum decimal 15, the hash will
// have the maximum index 19 (20 bytes of SHA1) and we need 4 bytes.
o := (h[19] & 15)
var header uint32
//Get 32 bit chunk from hash starting at the o
r := bytes.NewReader(h[o : o+4])
err = binary.Read(r, binary.BigEndian, &header)
if err != nil {
fmt.Println(Colour("Red", err.Error()))
}
//Ignore most significant bits as per RFC 4226.
//Takes division from one million to generate a remainder less than < 7 digits
h12 := (int(header) & 0x7fffffff) % 1000000
//Converts number as a string
otp := strconv.Itoa(int(h12))
return prefix0(otp)
}
//prefix0 appends extra 0s if the length of otp is less than 6
func prefix0(otp string) string {
if len(otp) == 6 {
return otp
}
for i := (6 - len(otp)); i > 0; i-- {
otp = "0" + otp
}
return otp
}