Add helper for encoding/decoding root tokens and OTP generation in SDK module (#10504) (#10505)

This commit is contained in:
Pavlos Tzianos
2021-12-01 13:05:49 +00:00
committed by GitHub
parent 662541804a
commit 14aded6956
18 changed files with 239 additions and 90 deletions

View File

@@ -2,19 +2,15 @@ package command
import (
"bytes"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"os"
"strings"
"github.com/hashicorp/go-secure-stdlib/base62"
"github.com/hashicorp/go-secure-stdlib/password"
uuid "github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/helper/pgpkeys"
"github.com/hashicorp/vault/helper/xor"
"github.com/hashicorp/vault/sdk/helper/roottoken"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -290,32 +286,15 @@ func (c *OperatorGenerateRootCommand) generateOTP(client *api.Client, kind gener
return "", 2
}
switch status.OTPLength {
case 0:
// This is the fallback case
buf := make([]byte, 16)
readLen, err := rand.Read(buf)
if err != nil {
c.UI.Error(fmt.Sprintf("Error reading random bytes: %s", err))
return "", 2
}
if readLen != 16 {
c.UI.Error(fmt.Sprintf("Read %d bytes when we should have read 16", readLen))
return "", 2
}
return base64.StdEncoding.EncodeToString(buf), 0
default:
otp, err := base62.Random(status.OTPLength)
if err != nil {
c.UI.Error(fmt.Errorf("Error reading random bytes: %w", err).Error())
return "", 2
}
return otp, 0
otp, err := roottoken.GenerateOTP(status.OTPLength)
var retCode int
if err != nil {
retCode = 2
c.UI.Error(err.Error())
} else {
retCode = 0
}
return otp, retCode
}
// decode decodes the given value using the otp.
@@ -364,36 +343,10 @@ func (c *OperatorGenerateRootCommand) decode(client *api.Client, encoded, otp st
return 2
}
var token string
switch status.OTPLength {
case 0:
// Backwards compat
tokenBytes, err := xor.XORBase64(encoded, otp)
if err != nil {
c.UI.Error(fmt.Sprintf("Error xoring token: %s", err))
return 1
}
uuidToken, err := uuid.FormatUUID(tokenBytes)
if err != nil {
c.UI.Error(fmt.Sprintf("Error formatting base64 token value: %s", err))
return 1
}
token = strings.TrimSpace(uuidToken)
default:
tokenBytes, err := base64.RawStdEncoding.DecodeString(encoded)
if err != nil {
c.UI.Error(fmt.Errorf("Error decoding base64'd token: %w", err).Error())
return 1
}
tokenBytes, err = xor.XORBytes(tokenBytes, []byte(otp))
if err != nil {
c.UI.Error(fmt.Errorf("Error xoring token: %w", err).Error())
return 1
}
token = string(tokenBytes)
token, err := roottoken.DecodeToken(encoded, otp, status.OTPLength)
if err != nil {
c.UI.Error(fmt.Sprintf("Error decoding root token: %s", err))
return 1
}
switch Format(c.UI) {