-
Notifications
You must be signed in to change notification settings - Fork 15
/
totp_key.go
71 lines (63 loc) · 1.53 KB
/
totp_key.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
package localauth
import (
"bytes"
"encoding/base64"
"errors"
"image/png"
"time"
"github.com/ashirt-ops/ashirt-server/backend"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
)
// TOTPKey represents the secret and QR code for a given URL to authenticate with
type TOTPKey struct {
URL string `json:"url"`
Secret string `json:"secret"`
QRCode string `json:"qr"`
}
const totpDigits = otp.DigitsSix
const totpAlgorithm = otp.AlgorithmSHA1
func generateTOTP(accountName string) (*TOTPKey, error) {
key, err := totp.Generate(totp.GenerateOpts{
Issuer: "ashirt",
AccountName: accountName,
SecretSize: 64,
Digits: totpDigits,
Algorithm: totpAlgorithm,
})
if err != nil {
return nil, err
}
img, err := key.Image(200, 200)
if err != nil {
return nil, err
}
var buf bytes.Buffer
png.Encode(&buf, img)
return &TOTPKey{
URL: key.URL(),
Secret: key.Secret(),
QRCode: "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()),
}, nil
}
func validateTOTP(passcode string, totpSecret string) error {
if passcode == "" {
return backend.MissingValueErr("TOTP Passcode")
}
if totpSecret == "" {
return backend.MissingValueErr("TOTP Secret")
}
isValid, err := totp.ValidateCustom(passcode, totpSecret, time.Now().UTC(), totp.ValidateOpts{
Period: 30,
Skew: 1,
Digits: totpDigits,
Algorithm: totpAlgorithm,
})
if err != nil {
return backend.InvalidTOTPErr(err)
}
if !isValid {
return backend.InvalidTOTPErr(errors.New("totp.Validate failure"))
}
return nil
}