Skip to content
This repository has been archived by the owner on Feb 16, 2023. It is now read-only.

Release v0.25.0 to develop #159

Merged
merged 3 commits into from
Dec 10, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions pkg/secrethub/credentials/bootstrap_code.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"regexp"
"strings"

"github.com/secrethub/secrethub-go/internals/api"
Expand All @@ -12,6 +14,10 @@ import (
"github.com/secrethub/secrethub-go/pkg/secrethub/internals/http"
)

var (
bootstrapCodeRegexp = regexp.MustCompile("[^a-zA-Z0-9]+")
)

// Enforce implementation of interfaces by structs.
var _ Creator = (*BackupCodeCreator)(nil)
var _ Provider = (*bootstrapCodeProvider)(nil)
Expand All @@ -27,6 +33,15 @@ func CreateBackupCode() *BackupCodeCreator {
return &BackupCodeCreator{}
}

// ValidateBootstrapCode validates a string and checks whether it is a valid bootstrap code.
func ValidateBootstrapCode(code string) error {
filtered := filterBootstrapCode(code)
if len(filtered) != crypto.SymmetricKeyLength*2 {
return errors.New("code does not consist of 64 hexadecimal characters")
}
return nil
}

// Create generates a new code and stores it in the BackupCodeCreator.
func (b *BackupCodeCreator) Create() error {
key, err := crypto.GenerateSymmetricKey()
Expand Down Expand Up @@ -79,9 +94,13 @@ func UseBackupCode(code string) Provider {

// Provide returns the auth.Authenticator and Decrypter corresponding to a bootstrap code.
func (b *bootstrapCodeProvider) Provide(_ *http.Client) (auth.Authenticator, Decrypter, error) {
bytes, err := hex.DecodeString(b.code)
if err != nil || len(bytes) != 32 {
return nil, nil, errors.New("malformed code")
err := ValidateBootstrapCode(b.code)
if err != nil {
return nil, nil, fmt.Errorf("malformed code: %v", err)
}
bytes, err := hex.DecodeString(filterBootstrapCode(b.code))
if err != nil {
return nil, nil, fmt.Errorf("malformed code: %v", err)
}
bootstrapCode := newBootstrapCode(bytes, b.t)
return auth.NewHTTPSigner(bootstrapCode), bootstrapCode, nil
Expand Down Expand Up @@ -158,6 +177,10 @@ func (b *bootstrapCode) Unwrap(ciphertext *api.EncryptedData) ([]byte, error) {
return decrypted, nil
}

func filterBootstrapCode(code string) string {
return bootstrapCodeRegexp.ReplaceAllString(code, "")
}

func splitStringByWidth(in string, width int) []string {
var out []string
tmp := ""
Expand Down