-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgenerate.go
72 lines (54 loc) · 1.73 KB
/
generate.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
// Copyright 2017 Josh Komoroske. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE.txt file.
package ykman
import (
"os/exec"
"regexp"
)
// Generate returns an OATH code from the specified slot name
func Generate(name string) (string, error) {
cmd := exec.Command("ykman", "oath", "code", name)
output, err := cmd.CombinedOutput()
return parseGenerate(string(output), err, name)
}
func parseGenerate(body string, err error, name string) (string, error) {
lines := process(body)
if err != nil {
// Check if this is an exec.Error stating that the ykman executable was not found
if execErr, ok := err.(*exec.Error); ok {
if execErr.Err == exec.ErrNotFound {
return "", ErrorYkmanNotFound
}
}
// Case where a YubiKey isn't plugged in
if linesContain(lines, "Failed connecting to the YubiKey") {
return "", ErrorYubikeyNotDetected
}
// Case where ykman was killed/interruped with a signal
if linesContain(lines, "Aborted!") {
return "", ErrorYkmanInterrupted
}
// Case where ykman dumps a Python exception
if linesContain(lines, "Traceback (most recent call last)") {
// Case where yubikey is removed mid-operation
if linesContain(lines, "Failed to transmit with protocol") {
return "", ErrorYubikeyRemoved
}
// Case where YubiKey was not touched in time
if linesContain(lines, "APDU error") {
return "", ErrorYubikeyTimeout
}
}
// Generic catch-all
return "", err
}
oathCodeRegex := regexp.MustCompile("^" + name + "\\s+(\\d{6,})$")
for _, line := range lines {
matches := oathCodeRegex.FindStringSubmatch(line)
if len(matches) == 2 {
return matches[1], nil
}
}
return "", ErrorSlotNameUnknown
}