Skip to content

Java back-end post object on S3 Bucket giving wrong signature

0

I'm coding a back-end in Java to upload files to my private S3 bucket and I'm getting an error that says: The request signature we calculated does not match the signature you provided. Check your key and signing method. My S3 Service looks like this:

public void uploadFileToS3(MultipartFile file) throws IOException {
        // Create the S3 client
        S3Client s3Client = S3Client.builder()
                .region(Region.US_EAST_2)
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(config.getAwsAccessKey(), config.getAwsSecretKey())))
                .build();

        // Convert MultipartFile to Path
        Path tempFilePath = Files.createTempFile("upload-", file.getOriginalFilename());
        Files.copy(file.getInputStream(), tempFilePath, StandardCopyOption.REPLACE_EXISTING);

        // Create the PutObjectRequest
        PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                .bucket(config.getS3BucketName())
                .key(file.getOriginalFilename())
                .build();

        try {
            // Upload the file to S3
            s3Client.putObject(putObjectRequest, tempFilePath);
            System.out.println("File uploaded successfully to S3!");
        } catch (S3Exception e) {
            System.err.println("Error uploading file: " + e.awsErrorDetails().errorMessage());
            throw new IOException("Failed to upload file to S3", e);
        } finally {
            // Clean up temporary file
            Files.deleteIfExists(tempFilePath);
        }
    }

I'm sure my "config" instance is populated with the correct Key, Secret and bucket name! Things that I think matters to help with this issue:

  1. My bucket is private, I've created the Access Key on a system user with only two permissions (S3 FullAccess and S3 ReadAccess) but, the AWS CLI on my local computer is configured to my dev user, does this affect the outcome?
  2. The Access Key that I've created is an "application running outside AWS" key, I'm building it inside an EC2, should I create a new Access Key that's "for applications running inside AWS" for when I'm building it inside the EC2?]
  3. My bucket is compose by some folders, for example the one I'm trying to save is located at "my_bucket/folder", how should I build the "url"?
    1. I'm separating my variables by "bucket name" and "folder", should I then save my bucket name variable as "my_bucket" or "my_bucket/"?
    2. And on my folder variable, should I save as "folder" or "folder/"?
  4. I'm using AWS SDK V2 as a dependency (Maven) What I've tried until now:
  5. Creating multiple access keys
  6. Created and using an access key on my dev user
  7. Changed my code and even passing it through ChatGPT (trying multiple ways of coding)
  8. Testing on my local and inside my EC2 If anyone could give me some light of what to do or what to test, it'd be awesome!

asked 2 years ago1.1K views

3 Answers
2
Accepted Answer

When you need access to AWS resources from an EC2 instance, you absolutely shouldn't be using static access keys to authenticate. Instead, you should create an IAM role with the appropriate permissions for your server(s), associate the role with an EC2 instance profile, and attach the EC2 instance profile to your EC2 instance(s).

Once that is done, in your program code, you shouldn't specify any credentials. The AWS SDK will automatically discover that it's running on an EC2 instance and will obtain temporary credentials from the EC2 instance metadata service, which it will then use to sign requests the SDK makes to AWS resources.

The theory is explained and the practicalities explained in more detail here: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html

Regardless of whether you use static access keys or temporary credentials, as heavily recommended both by AWS and me, you also shouldn't grant your program full S3 permissions. If the credentials are exfiltrated, the AmazonS3FullAccess policy will allow the outsider to steal all your data and destroy or encrypt it permanently. They can also incur unlimited costs that you'd be accountable for, for example, by creating massive numbers of copies of a large file, and possibly even using S3 Object Lock to prevent you from deleting the masses of useless data.

If your code is only going to upload files to one bucket, the policy you should attach to the IAM role associated with the EC2 instance profile would look like this:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyS3AccessFromOutsideVpc",
      "Effect": "Deny",
      "Action": "s3:*",
      "Resource": "*",
      "Condition": {
        "StringNotEqualsIfExists": {
          "aws:SourceVpc": "${aws:Ec2InstanceSourceVpc}"
        },
        "BoolIfExists": {
          "aws:ViaAWSService": "false"
        }
      }
    }, {
      "Sid": "AllowBucketAccess",
      "Effect": "Allow",
      "Action": [
        "s3:GetBucketLocation",
        "s3:ListBucket"
      ],
      "Resource": "arn:aws:s3:::example-bucket"
    }, {
      "Sid": "AllowObjectAccess",
      "Effect": "Allow",
      "Action": [
        "s3:PutObject"
      ],
      "Resource": "arn:aws:s3:::example-bucket/*"
    }
  ]
}

If you want also to allow your code to read/download and delete objects from the bucket, then the policy should look like this. You can simply choose between the actions s3:GetObject (=download), s3:PutObject (=upload), and s3:DeleteObject to determine which operations are permitted:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyS3AccessFromOutsideVpc",
      "Effect": "Deny",
      "Action": "s3:*",
      "Resource": "*",
      "Condition": {
        "StringNotEqualsIfExists": {
          "aws:SourceVpc": "${aws:Ec2InstanceSourceVpc}"
        },
        "BoolIfExists": {
          "aws:ViaAWSService": "false"
        }
      }
    }, {
      "Sid": "AllowBucketAccess",
      "Effect": "Allow",
      "Action": [
        "s3:GetBucketLocation",
        "s3:ListBucket"
      ],
      "Resource": "arn:aws:s3:::example-bucket"
    }, {
      "Sid": "AllowObjectAccess",
      "Effect": "Allow",
      "Action": [
        "s3:DeleteObject",
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "arn:aws:s3:::example-bucket/*"
    }
  ]
}

Of course, you'll need to replace example-bucket with the name of your bucket.

For this configuration to work and to be very secure, the expectation is that the S3 bucket is in the same region (such as us-east-2) as your EC2 instance and that you have a VPC gateway endpoint for S3 created in your VPC and associated with all the VPC route tables. The gateway endpoint is easy to create in a couple of minutes via the VPC management console under "endpoints." A detailed explanation of the theory and step-by-step instructions are available here: https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-s3.html

The VPC gateway endpoint allows you to access S3 buckets in the same region where your EC2 instance resides without paying any network traffic fees. The "Deny" policy statement above also guarantees that even if the temporary credentials (or static access key, if you decide to continue to use one) are stolen, they won't allow accessing any S3 services from outside your VPC.

EXPERT

answered 2 years ago

EXPERT

reviewed 2 years ago

  • Thank you for taking your time to explain the logic and giving me some docs to learn from! I'll definitely use the recommended way of accessing S3 services from inside the EC2 but my problem at this moment is that I need to access it from outside of an EC2 instance, it's a dev environment, that's why I used "application.properties", the "-dev" version has the ID and Key, the "-prod" one doesn't so it'll use the temporary credentials as you said!

  • Holy Jesus it worked!! It's not what you said, but I'll accept your answer since it is REALLY complete and helped me to understand some stuff but, here's the problem I was having: My Bucket name is "my-bucket" and on my application.properties I set it as "my-bucket/", thinking it'd be good to specify folders like that and stuff, that's why my folder properties, "folder-1" and "folder-2" are set as "folder-1/" and "folder-2/" BUT, apparently AWS Java Lib doesn't communicate the Bucket name like that! I had to change my bucket name variable from "my-bucket/" to "my-bucket", then it worked fine! And I kept my folder variables as "folder-1/" and "folder-2/", not that intuitive if you ask me but no matter, it worked! This post helped me a lot so, give cred to them! Thank you so much AWS community! https://stackoverflow.com/questions/68757161/s3exception-the-request-signature-we-calculated-does-not-match-the-signature-yo

0

Based on the information provided, there are a few potential issues that could be causing the signature mismatch error:

  1. AWS CLI Configuration: The AWS CLI configuration on your local machine should not affect the outcome of your Java application. The application is using the credentials you provide explicitly in the code, not the ones from your AWS CLI config.

  2. Access Key Type: For an application running on EC2, it's generally recommended to use IAM roles instead of access keys. However, if you must use access keys, the "applications running outside AWS" type should work fine for both local and EC2 environments.

  3. Bucket and Folder Naming: Your bucket name should not include a trailing slash. For the key (which represents the object's path in the bucket), you should include the full path including any folders. For example:

    .key("folder/" + file.getOriginalFilename())
  4. SDK Version: Using AWS SDK V2 is correct and should work properly.

Here are some suggestions to troubleshoot and resolve the issue:

  1. Double-check your AWS access key and secret key. Ensure they are correct and have not expired.

  2. Verify that the system time on your local machine or EC2 instance is accurate. Time skew can cause signature mismatches.

  3. Ensure that your S3 bucket is in the same region (US_EAST_2) as specified in your code.

  4. Add the expected bucket owner to your PutObjectRequest:

    PutObjectRequest putObjectRequest = PutObjectRequest.builder()
        .bucket(config.getS3BucketName())
        .key("folder/" + file.getOriginalFilename())
        .expectedBucketOwner(YOUR_ACCOUNT_ID)
        .build();
  5. If you're still having issues, try enabling debug logging for the AWS SDK to get more detailed information about the request and signature calculation:

    System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "DEBUG");
  6. Consider using the S3TransferManager for more robust file uploads, especially for larger files:

    S3TransferManager transferManager = S3TransferManager.builder()
        .s3ClientConfiguration(b -> b.region(Region.US_EAST_2)
            .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(config.getAwsAccessKey(), config.getAwsSecretKey()))))
        .build();
    
    UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
        .putObjectRequest(r -> r.bucket(config.getS3BucketName()).key("folder/" + file.getOriginalFilename()))
        .source(tempFilePath)
        .build();
    
    FileUpload upload = transferManager.uploadFile(uploadFileRequest);
    
    CompletedFileUpload uploadResult = upload.completionFuture().join();

If these suggestions don't resolve the issue, you may need to review your IAM permissions to ensure the user associated with the access key has the necessary permissions to upload to the specific bucket and folder.

Sources
Missing S3 bucket owner condition | Amazon Q, Detector Library
Upload an object to an S3 on Outposts bucket - Amazon S3 on Outposts

answered 2 years ago

EXPERT

reviewed 2 years ago

  • Sorry for the time that I took me, I was trying some solutions and after looking into what you said, tried everything you asked me to, the IAM permission is set to "S3FullControl" (as a test, I'd remove it after), tried with multiple access keys, from inside and outside connection, removed and added the Keys to try the "default authentication" but still, nothing! Still giving me an signature error. I think it has something to do with my internet, my provider didn't map Window's clock server, so my clock is totally wrong (changed the CMOS battery, just no use), so the only thing I can imagine is happening is the time on my dev environment but still, didn't work inside the EC2 either so, I'm totally lost now.

  • You can set a regular Windows machine running outside AWS to synchronise its clock against AWS's public NTP service time.aws.com by running this command in an admin-elevated command window. This will work over any regular internet connection:

    w32tm /config /manualpeerlist:time.aws.com /syncfromflags:manual /update
    
0

Hi,

Given the error message that you get, the issue is very probably in AwsBasicCredentials.create(config.getAwsAccessKey(), config.getAwsSecretKey()), i.e., your access and secret keys don't match.

What I'd suggest to debug your problem is to let the default credentials do the job for you, at least initially. So, as explained in https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials-chain.html:

  1. set the 2 standard env vars AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY in your environment
  2. do NOT specify any credential provider in your request
  3. let the default credentials provider chain do the job for you and find those 2 variables for you
  4. it will then compute the SigV4 signature of your request that is currently incorrect
  5. ... and it should go through

By doing that, you will make sure that your 2 values are correct and then you can reuse them in your config object.

Note: if you hard-code those keys via the config object in the source code, it is not the best idea. The default credential provider is here to avoid that as you can always easily set env vars with those values in a Lambda, container, EC2 instance, etc. The additional benefit is that your code can work from multiple locations by using the local values of those env vars. It allows those values to have different values in those different locations.

Best,

Didier

EXPERT

answered 2 years ago

EXPERT

reviewed 2 years ago

  • Tried that, didn't work! I tried with multiple keys on multiple different accounts with AND without the correct permissions, same error every time!

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.