Skip to content
Open
Show file tree
Hide file tree
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
4 changes: 2 additions & 2 deletions aws_signing_helper/cert_store_signer_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ func GetCertStoreSigner(certIdentifier CertIdentifier, useLatestExpiringCert boo
}
selectedCertContainer = certContainers[len(certContainers)-1]
if Debug {
log.Print(fmt.Sprintf("selected certificate: %s", DefaultCertContainerToString(selectedCertContainer)))
log.Printf("selected certificate: %s", DefaultCertContainerToString(selectedCertContainer))
}
cert = selectedCertContainer.Cert
certRef = certRefs[selectedCertContainer.Index]
Expand Down Expand Up @@ -260,7 +260,7 @@ func (signer *DarwinCertStoreSigner) CertificateChain() ([]*x509.Certificate, er

certChainArr := C.SecTrustCopyCertificateChain(trustRef)
defer C.CFRelease(C.CFTypeRef(certChainArr))
for i := C.CFIndex(0); i < nChain; i++ {
for i := range nChain {
chainCertRef := C.SecCertificateRef(C.CFArrayGetValueAtIndex(certChainArr, i))
if chainCertRef == 0 {
return nil, errors.New("nil certificate in chain")
Expand Down
2 changes: 1 addition & 1 deletion aws_signing_helper/file_system_signer.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func (fileSystemSigner *FileSystemSigner) readCertFiles() (crypto.PrivateKey, *x
passwordPromptInput := PasswordPromptProps{
InitialPassword: fileSystemSigner.pkcs8Password,
NoPassword: false,
CheckPassword: func(password string) (interface{}, error) {
CheckPassword: func(password string) (any, error) {
return ReadPrivateKeyData(fileSystemSigner.privateKeyPath, password)
},
IncorrectPasswordMsg: "incorrect PKCS#8 private key password",
Expand Down
6 changes: 3 additions & 3 deletions aws_signing_helper/pkcs11_signer.go
Original file line number Diff line number Diff line change
Expand Up @@ -912,10 +912,10 @@ retry_search:

// So that hunting for the key can be more efficient in the future,
// return a key URI that has CKA_ID and CKA_LABEL appropriately set.
if privateKeyObj.id != nil && len(privateKeyObj.id) != 0 {
if len(privateKeyObj.id) != 0 {
keyUri.SetPathAttribute("id", escapeAll(privateKeyObj.id))
}
if privateKeyObj.label != nil && len(privateKeyObj.label) != 0 {
if len(privateKeyObj.label) != 0 {
keyUri.SetPathAttribute("object", escapeAll(privateKeyObj.label))
}

Expand Down Expand Up @@ -1181,7 +1181,7 @@ const hexchar = "0123456789ABCDEF"
func escapeAll(s []byte) string {
res := make([]byte, len(s)*3)
j := 0
for i := 0; i < len(s); i++ {
for i := range s {
c := s[i]
res[j] = '%'
res[j+1] = hexchar[c>>4]
Expand Down
14 changes: 3 additions & 11 deletions aws_signing_helper/pkcs8_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,20 +288,12 @@ func readPKCS8EncryptedPrivateKey(privateKeyId string, pkcs8Password []byte) (cr
return nil, errors.New("incorrect password or invalid key format")
}

switch privateKey.(type) {
switch privateKey := privateKey.(type) {
case *rsa.PrivateKey:
rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey)
if ok {
return rsaPrivateKey, nil
}
return privateKey, nil
case *ecdsa.PrivateKey:
ecPrivateKey, ok := privateKey.(*ecdsa.PrivateKey)
if ok {
return ecPrivateKey, nil
}
return privateKey, nil
default:
return nil, errors.New("could not parse PKCS#8 private key")
}

return nil, errors.New("could not parse PKCS#8 private key")
}
2 changes: 1 addition & 1 deletion aws_signing_helper/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ func FindTokenTTLSeconds(r *http.Request) (string, error) {
expiration, ok := tokenMap[token]
mutex.Unlock()
if ok {
tokenTTLFloat := expiration.Sub(time.Now()).Seconds()
tokenTTLFloat := time.Until(expiration).Seconds()
tokenTTLInt64 := int64(tokenTTLFloat)
return strconv.FormatInt(tokenTTLInt64, 10), nil
} else {
Expand Down
16 changes: 8 additions & 8 deletions aws_signing_helper/signer.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,22 +146,22 @@ func GetPassword(ttyReadFile *os.File, ttyWriteFile *os.File, prompt string, par
}

password := string(passwordBytes[:])
strings.Replace(password, "\r", "", -1) // Remove CR
strings.ReplaceAll(password, "\r", "") // Remove CR
return password, nil
}

type PasswordPromptProps struct {
InitialPassword string
NoPassword bool
CheckPassword func(string) (interface{}, error)
CheckPassword func(string) (any, error)
IncorrectPasswordMsg string
Prompt string
Reprompt string
ParseErrMsg string
CheckPasswordAuthorizationErrorMsg string
}

func PasswordPrompt(passwordPromptInput PasswordPromptProps) (string, interface{}, error) {
func PasswordPrompt(passwordPromptInput PasswordPromptProps) (string, any, error) {
var (
err error
ttyReadPath string
Expand All @@ -174,8 +174,8 @@ func PasswordPrompt(passwordPromptInput PasswordPromptProps) (string, interface{
password string
incorrectPasswordMsg string
checkPasswordAuthorizationErrorMsg string
checkPassword func(string) (interface{}, error)
checkPasswordResult interface{}
checkPassword func(string) (any, error)
checkPasswordResult any
noPassword bool
)

Expand Down Expand Up @@ -478,7 +478,7 @@ func CreateRequestSignFinalizeFunction(signer crypto.Signer, signingRegion strin
return func(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (out middleware.FinalizeOutput, metadata middleware.Metadata, err error) {
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, errors.New(fmt.Sprintf("unexpected request middleware type %T", in.Request))
return out, metadata, fmt.Errorf("unexpected request middleware type %T", in.Request)
}

payloadHash := v4.GetPayloadHash(ctx)
Expand Down Expand Up @@ -514,7 +514,7 @@ func signRequest(signer crypto.Signer, signingRegion string, signingAlgorithm st

// Create the canonical query string.
func createCanonicalQueryString(r *http.Request) string {
rawQuery := strings.Replace(r.URL.Query().Encode(), "+", "%20", -1)
rawQuery := strings.ReplaceAll(r.URL.Query().Encode(), "+", "%20")
return rawQuery
}

Expand Down Expand Up @@ -732,7 +732,6 @@ func readRSAPrivateKey(privateKeyId string) (*rsa.PrivateKey, error) {
// the container and treats that as the end-entity certificate. Also, the
// order of the other certificates in the chain aren't guaranteed. It's
// also not guaranteed that those certificates form a chain with the
// end-entity certificate either.
func ReadPKCS12Data(certificateId string) (certChain []*x509.Certificate, privateKey crypto.PrivateKey, err error) {
var (
bytes []byte
Expand Down Expand Up @@ -799,6 +798,7 @@ func ReadPKCS12Data(certificateId string) (certChain []*x509.Certificate, privat

return certChain, privateKey, nil
}
// end-entity certificate either.

// Load the private key referenced by `privateKeyId`. If `pkcs8Password` is provided, attempt to load an encrypted PKCS#8 key.
func ReadPrivateKeyData(privateKeyId string, pkcs8Password ...string) (crypto.PrivateKey, error) {
Expand Down
20 changes: 10 additions & 10 deletions aws_signing_helper/test_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ func RunSignTestWithTestTable(t *testing.T, testTable []CredentialsOpts) {

pubKey := signer.Public()
if credOpts.CertificateId != "" && pubKey == nil {
t.Log(fmt.Sprintf("Signer didn't provide public key for '%s'/'%s'",
credOpts.CertificateId, credOpts.PrivateKeyId))
t.Logf("Signer didn't provide public key for '%s'/'%s'",
credOpts.CertificateId, credOpts.PrivateKeyId)
t.Fail()
return
}
Expand All @@ -48,8 +48,8 @@ func RunSignTestWithTestTable(t *testing.T, testTable []CredentialsOpts) {
// makes sure that the context-specific PIN was saved.
signer.Sign(rand.Reader, []byte(msg), digest)
if err != nil {
t.Log(fmt.Sprintf("Failed to %s sign the input message for '%s'/'%s': %s",
digest, credOpts.CertificateId, credOpts.PrivateKeyId, err))
t.Logf("Failed to %s sign the input message for '%s'/'%s': %s",
digest, credOpts.CertificateId, credOpts.PrivateKeyId, err)
t.Fail()
return
}
Expand All @@ -63,8 +63,8 @@ func RunSignTestWithTestTable(t *testing.T, testTable []CredentialsOpts) {
if pubKey != nil {
valid, _ := Verify([]byte(msg), pubKey, digest, signatureBytes)
if !valid {
t.Log(fmt.Sprintf("Failed to verify %s signature for '%s'/'%s'",
digest, credOpts.CertificateId, credOpts.PrivateKeyId))
t.Logf("Failed to verify %s signature for '%s'/'%s'",
digest, credOpts.CertificateId, credOpts.PrivateKeyId)
t.Fail()
return
}
Expand Down Expand Up @@ -97,8 +97,8 @@ func RunNegativeSignTestWithTestTable(t *testing.T, testTable []CredentialsOpts)

pubKey := signer.Public()
if credOpts.CertificateId != "" && pubKey == nil {
t.Log(fmt.Sprintf("Signer didn't provide public key for '%s'/'%s'",
credOpts.CertificateId, credOpts.PrivateKeyId))
t.Logf("Signer didn't provide public key for '%s'/'%s'",
credOpts.CertificateId, credOpts.PrivateKeyId)
t.Fail()
return
}
Expand All @@ -107,8 +107,8 @@ func RunNegativeSignTestWithTestTable(t *testing.T, testTable []CredentialsOpts)
_, err := signer.Sign(rand.Reader, []byte(msg), digest)
signer.Sign(rand.Reader, []byte(msg), digest)
if err == nil {
t.Log(fmt.Sprintf("Expected %s sign on the input message to fail for '%s'/'%s': %s, but it succeeded",
digest, credOpts.CertificateId, credOpts.PrivateKeyId, err))
t.Logf("Expected %s sign on the input message to fail for '%s'/'%s': %s, but it succeeded",
digest, credOpts.CertificateId, credOpts.PrivateKeyId, err)
t.Fail()
return
}
Expand Down
11 changes: 3 additions & 8 deletions aws_signing_helper/tpm_signer.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,7 @@ func (tpmv2Signer *TPMv2Signer) Sign(rand io.Reader, digest []byte, opts crypto.
return nil, errors.New("failed to obtain ecdsa.PublicKey")
}
bitSize := ecPubKey.Curve.Params().BitSize
byteSize := (bitSize + 7) / 8
if byteSize > sha512.Size {
byteSize = sha512.Size
}
byteSize := min((bitSize + 7) / 8, sha512.Size)
switch byteSize {
case sha512.Size:
algo = tpm2.AlgSHA512
Expand Down Expand Up @@ -248,7 +245,7 @@ func (tpmv2Signer *TPMv2Signer) signHelper(rw io.ReadWriter, keyHandle tpmutil.H
passwordPromptInput := PasswordPromptProps{
InitialPassword: tpmv2Signer.password,
NoPassword: tpmv2Signer.emptyAuth,
CheckPassword: func(password string) (interface{}, error) {
CheckPassword: func(password string) (any, error) {
return tpm2.Sign(rw, keyHandle, password, digest, nil, sigScheme)
},
IncorrectPasswordMsg: "incorrect TPM key password",
Expand Down Expand Up @@ -354,9 +351,7 @@ func GetTPMv2Signer(opts GetTPMv2SignerOpts) (signer Signer, signingAlgorithm st
return nil, "", errors.New("invalid TPM handle format")
}
hexHandleStr := handleParts[1]
if strings.HasPrefix(hexHandleStr, "0x") {
hexHandleStr = hexHandleStr[2:]
}
hexHandleStr = strings.TrimPrefix(hexHandleStr, "0x")
handleValue, err := strconv.ParseUint(hexHandleStr, 16, 32)
if err != nil {
return nil, "", errors.New("invalid hex TPM handle value")
Expand Down
8 changes: 4 additions & 4 deletions cmd/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/big"
"regexp"
"slices"
"strings"

helper "github.com/aws/rolesanywhere-credential-helper/aws_signing_helper"
"github.com/spf13/cobra"
"os"
)

var (
Expand Down Expand Up @@ -54,7 +54,7 @@ var (
X509_SERIAL_KEY,
}

DUPLICATE_KEYS_ERR_STR = "duplicate %s keys can't be present in cert selector"
DUPLICATE_KEYS_ERR_STR = "duplicate %s keys can't be present in cert selector"
CERT_SELECTOR_KEY_VALUE_REGEX = regexp.MustCompile(`^\s*Key=(.+?),Value=(.+?)\s*(?:Key=|$)`)
)

Expand Down Expand Up @@ -117,7 +117,7 @@ func getStringMap(s string) (map[string]string, error) {
m := make(map[string]string)
for {
match := CERT_SELECTOR_KEY_VALUE_REGEX.FindStringSubmatch(s)
if match == nil || len(match) == 0 {
if len(match) == 0 {
break
} else {
if len(match) < 3 {
Expand Down Expand Up @@ -238,7 +238,7 @@ func PopulateCertIdentifier(certSelector string, systemStoreName string) (helper

if certSelector != "" {
if strings.HasPrefix(certSelector, "file://") {
certSelectorFile, err := ioutil.ReadFile(strings.TrimPrefix(certSelector, "file://"))
certSelectorFile, err := os.ReadFile(strings.TrimPrefix(certSelector, "file://"))
if err != nil {
return helper.CertIdentifier{}, errors.New("unable to read cert selector file")
}
Expand Down
15 changes: 4 additions & 11 deletions cmd/sign_string.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"slices"
"strconv"
"strings"

helper "github.com/aws/rolesanywhere-credential-helper/aws_signing_helper"
"github.com/spf13/cobra"
"io"
)

var (
Expand Down Expand Up @@ -50,15 +51,7 @@ func (e enum) String() string {
}

func (a *enum) Set(p string) error {
isIncluded := func(opts []string, val string) bool {
for _, opt := range opts {
if val == opt {
return true
}
}
return false
}
if !isIncluded(a.Allowed, p) {
if !slices.Contains(a.Allowed, p) {
return fmt.Errorf("%s is not included in %s", p, strings.Join(a.Allowed, ","))
}
a.Value = p
Expand Down Expand Up @@ -173,7 +166,7 @@ var signStringCmd = &cobra.Command{
"Credential Helper Signing Test\" || SIGN_STRING_TEST_VERSION || SHA256(\"IAM RA\" || PUBLIC_KEY_BYTE_ARRAY)\"")
}
} else {
stringToSignBytes, _ = ioutil.ReadAll(bufio.NewReader(os.Stdin))
stringToSignBytes, _ = io.ReadAll(bufio.NewReader(os.Stdin))
}

sigBytes, err := signer.Sign(rand.Reader, stringToSignBytes, digest)
Expand Down
6 changes: 3 additions & 3 deletions internal/configsources/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ type EnableEndpointDiscoveryProvider interface {
// ResolveEnableEndpointDiscovery extracts the first instance of a EnableEndpointDiscoveryProvider from the config slice.
// Additionally returns a aws.EndpointDiscoveryEnableState to indicate if the value was found in provided configs,
// and error if one is encountered.
func ResolveEnableEndpointDiscovery(ctx context.Context, configs []interface{}) (value aws.EndpointDiscoveryEnableState, found bool, err error) {
func ResolveEnableEndpointDiscovery(ctx context.Context, configs []any) (value aws.EndpointDiscoveryEnableState, found bool, err error) {
for _, cfg := range configs {
if p, ok := cfg.(EnableEndpointDiscoveryProvider); ok {
value, found, err = p.GetEnableEndpointDiscovery(ctx)
Expand All @@ -33,7 +33,7 @@ type UseDualStackEndpointProvider interface {

// ResolveUseDualStackEndpoint extracts the first instance of a UseDualStackEndpoint from the config slice.
// Additionally returns a boolean to indicate if the value was found in provided configs, and error if one is encountered.
func ResolveUseDualStackEndpoint(ctx context.Context, configs []interface{}) (value aws.DualStackEndpointState, found bool, err error) {
func ResolveUseDualStackEndpoint(ctx context.Context, configs []any) (value aws.DualStackEndpointState, found bool, err error) {
for _, cfg := range configs {
if p, ok := cfg.(UseDualStackEndpointProvider); ok {
value, found, err = p.GetUseDualStackEndpoint(ctx)
Expand All @@ -52,7 +52,7 @@ type UseFIPSEndpointProvider interface {

// ResolveUseFIPSEndpoint extracts the first instance of a UseFIPSEndpointProvider from the config slice.
// Additionally, returns a boolean to indicate if the value was found in provided configs, and error if one is encountered.
func ResolveUseFIPSEndpoint(ctx context.Context, configs []interface{}) (value aws.FIPSEndpointState, found bool, err error) {
func ResolveUseFIPSEndpoint(ctx context.Context, configs []any) (value aws.FIPSEndpointState, found bool, err error) {
for _, cfg := range configs {
if p, ok := cfg.(UseFIPSEndpointProvider); ok {
value, found, err = p.GetUseFIPSEndpoint(ctx)
Expand Down
Loading