/
otpc.go
373 lines (336 loc) · 7.27 KB
/
otpc.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
// otpc is a command-line OTP client that handles standard HOTP and TOTP tokens.
package main
import (
"encoding/base32"
"encoding/json"
"encoding/pem"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gokyle/readpass"
"github.com/gokyle/twofactor"
)
func errorf(m string, args ...interface{}) {
m = "[!] " + m
if m[len(m)-1] != '\n' {
m += "\n"
}
fmt.Fprintf(os.Stderr, m, args...)
}
// account name -> url
var accounts = map[string]string{}
var passphrase []byte
func openFile(filename string) {
fileData, err := decryptFile(filename)
if err != nil {
errorf("Failed to open accounts file: %v", err)
os.Exit(1)
}
err = json.Unmarshal(fileData, &accounts)
if err != nil {
errorf("Failed to open accounts file: %v", err)
os.Exit(1)
}
}
func saveFile(filename string) {
encoded, err := json.Marshal(accounts)
if err != nil {
errorf("Failed to serialise accounts: %v", err)
os.Exit(1)
}
err = encryptFile(filename, encoded)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
}
func listLabels(filename string) {
openFile(filename)
fmt.Println("Accounts:")
for label := range accounts {
fmt.Printf("\t%s\n", label)
}
}
const (
HOTP = iota + 1
TOTP
GoogleTOTP
)
func addAccount(label string, otpType int) {
if accounts[label] != "" {
errorf("warning: label %s exists with url %s", label, accounts[label])
}
// Default prompt is echoing, which we want here.
secret, err := readpass.DefaultPasswordPrompt("Secret: ")
if err != nil {
errorf("Failed to read password.")
os.Exit(1)
}
secret = sanitiseSecret(secret)
switch otpType {
case HOTP:
in, err := readpass.DefaultPasswordPrompt("Initial counter (0): ")
if err != nil {
errorf("%v", err)
os.Exit(1)
}
if in == "" {
in = "0"
}
d, err := strconv.Atoi(in)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
in, err = readpass.DefaultPasswordPrompt("Digits (6 or 8): ")
if err != nil {
errorf("%v", err)
os.Exit(1)
} else if in == "" {
in = "6"
}
digits, err := strconv.Atoi(in)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
key, err := base32.StdEncoding.DecodeString(secret)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
var hotp *twofactor.HOTP
hotp = twofactor.NewHOTP(key, uint64(d), digits)
fmt.Printf("Confirmation: %s\n", hotp.OTP())
secret = hotp.URL(label)
case TOTP:
in, err := readpass.DefaultPasswordPrompt("Time step (30s): ")
if err != nil {
errorf("%v", err)
os.Exit(1)
}
if in == "" {
in = "30s"
}
d, err := time.ParseDuration(in)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
in, err = readpass.DefaultPasswordPrompt("Digits (6 or 8): ")
if err != nil {
errorf("%v", err)
os.Exit(1)
} else if in == "" {
in = "6"
}
digits, err := strconv.Atoi(in)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
key, err := base32.StdEncoding.DecodeString(secret)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
var totp *twofactor.TOTP
totp = twofactor.NewTOTPSHA1(key, 0, uint64(d.Seconds()), digits)
fmt.Printf("Confirmation: %s\n", totp.OTP())
secret = totp.URL(label)
case GoogleTOTP:
var totp *twofactor.TOTP
totp, err = twofactor.NewGoogleTOTP(secret)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
fmt.Printf("Confirmation: %s\n", totp.OTP())
secret = totp.URL(label)
default:
errorf("unrecognised OTP type")
os.Exit(1)
}
accounts[label] = secret
}
func addNewAccount(filename string, label string, t int) {
if _, err := os.Stat(filename); err != nil && !os.IsNotExist(err) {
errorf("Failed to open account store: %v", err)
os.Exit(1)
} else if err == nil {
openFile(filename)
}
addAccount(label, t)
saveFile(filename)
}
func printTOTP(label string, otp twofactor.OTP) {
fmt.Println(otp.OTP())
for {
for {
t := time.Now()
if t.Second() == 0 {
break
} else if t.Second() == 30 {
break
}
<-time.After(1 * time.Second)
}
fmt.Println(otp.OTP())
<-time.After(30 * time.Second)
}
}
func sanitiseSecret(in string) string {
in = strings.ToUpper(in)
in = strings.Replace(in, " ", "", -1)
if len(in)%8 != 0 {
padding := 8 - (len(in) % 8)
for i := 0; i < padding; i++ {
in += "="
}
}
return in
}
func exportDatabase(filename, outFile string) {
data, err := ioutil.ReadFile(filename)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
p := &pem.Block{
Type: "OTPC ACCOUNT STORE",
Bytes: data,
}
var out io.Writer
if outFile == "-" {
out = os.Stdout
} else {
out, err = os.Create(outFile)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
}
fmt.Fprintf(out, "%s\n", string(pem.EncodeToMemory(p)))
}
func importDatabase(filename, inFile string) {
var dataFile io.Reader
var err error
if inFile == "-" {
dataFile = os.Stdin
} else {
dataFile, err = os.Open(inFile)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
}
pemData, err := ioutil.ReadAll(dataFile)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
p, _ := pem.Decode(pemData)
if p == nil {
errorf("No PEM data found.")
os.Exit(1)
} else if p.Type != "OTPC ACCOUNT STORE" {
errorf("Invalid PEM type.")
os.Exit(1)
}
err = ioutil.WriteFile(filename, p.Bytes, 0600)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
}
func changePassword(fileName string) {
blob, err := decryptFile(fileName)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
defer zero(blob)
zero(passphrase)
passphrase = nil
err = encryptFile(fileName, blob)
if err != nil {
errorf("%v", err)
os.Exit(1)
}
}
func main() {
baseFile := filepath.Join(os.Getenv("HOME"), ".otpc.db")
fileName := flag.String("f", baseFile, "path to account store")
chPass := flag.Bool("chpass", false, "change password")
otpType := flag.String("type", "google", "type of OTP")
addNew := flag.Bool("new", false, "add a new account")
doExport := flag.Bool("export", false, "export database in PEM format to stdout")
doImport := flag.Bool("import", false, "import database from PEM format")
showList := flag.Bool("list", false, "list accounts in database")
removeLabel := flag.Bool("remove", false, "remove account")
flag.Parse()
if *doExport || *doImport {
if flag.NArg() != 1 {
errorf("Need the PEM file specified as an argument.")
os.Exit(1)
}
if *doExport {
exportDatabase(*fileName, flag.Arg(0))
} else {
importDatabase(*fileName, flag.Arg(0))
}
os.Exit(0)
} else if *showList {
listLabels(*fileName)
os.Exit(0)
} else if *chPass {
changePassword(*fileName)
os.Exit(0)
}
if flag.NArg() == 0 {
errorf("No label provided.")
os.Exit(1)
}
label := flag.Arg(0)
defer zero(passphrase)
if *addNew {
var t int
switch *otpType {
case "google":
t = GoogleTOTP
case "hotp":
t = HOTP
case "totp":
t = TOTP
default:
errorf("Unsupported OTP type: %s", *otpType)
os.Exit(1)
}
addNewAccount(*fileName, label, t)
} else if *removeLabel {
openFile(*fileName)
fmt.Printf("Removing %s with URL: %s\n", label, accounts[label])
delete(accounts, label)
saveFile(*fileName)
} else {
openFile(*fileName)
otp, label, err := twofactor.FromURL(accounts[label])
if err != nil {
errorf("Invalid OTP: %v", err)
os.Exit(1)
}
switch otp.Type() {
case twofactor.OATH_TOTP:
printTOTP(label, otp)
default:
errorf("unknown OTP type")
os.Exit(1)
}
}
}