2

I'm retrieving a secret from AWS Secrets Manager that's used to decode a JWT on a webserver. The program retrieves the secret correctly and I confirm its identical to the one used to encode the jwts. However, the jwt-go library is unable to decode the incoming token citing "signature invalid" despite the secrets being identical. Notably, If I hard paste the secret instead of using the secrets manager the server decodes the jwt fine. This leads me to believe there is some weird encoding issue going on between how golang handles strings and how the aws secrets manager does.

Secret in question: KZQVGKt0WglphtNyME8912pa9RlnSZ1s8Xcdqe5OnQ

Secret Retrieval Script:

func GetTokenSecret(secretName string) (string, error) {
    region := "us-east-1"

    //Create a Secrets Manager client
    svc := secretsmanager.New(session.New(),
        aws.NewConfig().WithRegion(region))
    input := &secretsmanager.GetSecretValueInput{
        SecretId:     aws.String(secretName),
        VersionStage: aws.String("AWSCURRENT"), // VersionStage defaults to AWSCURRENT if unspecified
    }

    // In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
    // See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html

    result, err := svc.GetSecretValue(input)
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok {
            switch aerr.Code() {
            case secretsmanager.ErrCodeDecryptionFailure:
                // Secrets Manager can't decrypt the protected secret text using the provided KMS key.
                log.Println(secretsmanager.ErrCodeDecryptionFailure, aerr.Error())

            case secretsmanager.ErrCodeInternalServiceError:
                // An error occurred on the server side.
                log.Println(secretsmanager.ErrCodeInternalServiceError, aerr.Error())

            case secretsmanager.ErrCodeInvalidParameterException:
                // You provided an invalid value for a parameter.
                log.Println(secretsmanager.ErrCodeInvalidParameterException, aerr.Error())

            case secretsmanager.ErrCodeInvalidRequestException:
                // You provided a parameter value that is not valid for the current state of the resource.
                log.Println(secretsmanager.ErrCodeInvalidRequestException, aerr.Error())

            case secretsmanager.ErrCodeResourceNotFoundException:
                // We can't find the resource that you asked for.
                log.Println(secretsmanager.ErrCodeResourceNotFoundException, aerr.Error())
            }
        } else {
            // Print the error, cast err to awserr.Error to get the Code and
            // Message from an error.
            log.Println(err.Error())
        }
        return "", err
    }

    // Decrypts secret using the associated KMS CMK.
    // Depending on whether the secret is a string or binary, one of these fields will be populated.
    var secretString, decodedBinarySecret string
    if result.SecretString != nil {
        secretString = *result.SecretString
    } else {
        decodedBinarySecretBytes := make([]byte, base64.StdEncoding.DecodedLen(len(result.SecretBinary)))
        len, err := base64.StdEncoding.Decode(decodedBinarySecretBytes, result.SecretBinary)
        if err != nil {
            log.Println("Base64 Decode Error:", err)
            return "", err
        }
        decodedBinarySecret = string(decodedBinarySecretBytes[:len])
        return decodedBinarySecret, nil
    }
    return secretString, nil
    // Your code goes here.
}

JWT Decode:

func (s *Server) parseJWT(encodedToken string) (Student, error) {
    token, err := jwt.ParseWithClaims(encodedToken, &userClaims{}, func(token *jwt.Token) (interface{}, error) {
        if _, isvalid := token.Method.(*jwt.SigningMethodHMAC); !isvalid {
            return nil, fmt.Errorf("Invalid token %s", token.Header["alg"])
        }
        return []byte(s.tokenSecret), nil
    })

    if err != nil {
        //ERROR THROWN HERE
        log.Println("Error Parsing JWT: ", err)
        return Student{}, err
    }
Prad
  • 53
  • 3
  • 1
    You should never include the secret key. Better remove it before someone misuse it. – Shubham Chadokar Mar 16 '21 at 06:34
  • "there is some weird encoding issue" you can check for this by printing out the string as hex (`fmt.Printf("%x\n", s.tokenSecret)`) and checking for special characters (or comparing with the hex of the version you copied/pasted). – Brits Mar 16 '21 at 08:55

0 Answers0