Unable to access S3 file with IAM role from EC2

Prakash Kumar Chakka

I created an IAM role 'test' and assigned to an EC2 instance. And I created a S3 bucket with bucket policy

{
    "Version": "2012-10-17",
    "Id": "Policy1475837721706",
    "Statement": [
        {
            "Sid": "Stmt1475837720370",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::770370070203:role/test"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::test-role-123/*"
        }
    ]
}

From EC2, I got the AccessKey and SecretKey from this AWS article by sending a curl request to

curl http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name>

Using the response from the above, I wrote a node script to make a request to the resource in the bucket

var AWS = require('aws-sdk');

var d = {
    "Code" : "Success",
    "LastUpdated" : "2016-10-07T12:28:09Z",
    "Type" : "AWS-HMAC",
    "AccessKeyId" : "ASIAIMJBHYLH6GWOWNMQ",
    "SecretAccessKey" : "7V/k5nvFdhXOcT+nhYjGqHM4QmUWjNBUM1ERJQJs",
    "Token" : "FQoDYXdzEO7//////////wEaDGG+SgxD4Es4Z1RBZCKzAz855JuKfm8s7LDcP5T9TGvDdJELsYTzPi47HJ9Q5oaK8OTb0Us0RjvpGW278Mb1gg1dNip1VD2N/GW5/1TFC6xhNpnnZ9+LNkJAwVVZg5raGM91k56X/VOA++/5WivSpO4jWg8fZDibivVyHuoMJJTkurFtEXrweDOCqpiabypTCc5jFtX8NfQuHubwl4C1jp2pMasVS1jwhjU72TA8Pn9EsIIvh8JXDC1dVfppwnslolAeJyOOAHdL1AQSs3nI6IvPCtKhBjtDaVuoiH/lHrnKrw6AeMHoTYQay4wOYRnE4ffngtksekZEULXvERWE4NCs3leXGMqrdzOr8xdZ9m0j3IkshqSS56fkq6E9JtLhSVGyy44ELrL7kYW/dpHE03V+dwQPXMhRafjsVsPD7sUnBfH/+4yyL0VDX1vlFRKbRi50i/Eqvxsb9bcSTsE0W5yWmOWR8reTTYWcWyQXGvxKVYVxLWZKVRfmNfx6IX2sqan7e7pjCtUrqXB1TBMpXdy8KSH9qoJtNAQTYBXws7oFLYY+F2esnNCma0bdNcCeAQ6t/6aPfUdpdLgv8BcGciZxayiqqd6/BQ==",
    "Expiration" : "2016-10-07T18:51:57Z"
};
AWS.config.accessKeyId = d.AccessKeyId;
AWS.config.secretAccessKey = d.SecretAccessKey;
var s3params = {Key: "test.json", Bucket:"test-role-123"};
AWS.config.region = 'ap-south-1';

var s3 = new AWS.S3();

s3.getSignedUrl('getObject', s3params, function(err, url) {
    console.log(url);
});

On running this code I am getting the signed url. But this is giving an InvalidAccessKeyId error. I doubted if the s3 bucket policy is wrong so tried to get with similar policy with an IAM user credentials. It is completely working.

Any hints or suggestions are welcome.

John Rotenstein

There are three things to note:

  • How credentials are provided and accessed from an Amazon EC2 instance
  • How to assign permissions for access to Amazon S3
  • How Pre-Signed URLs function

1. How credentials are provided and accessed from an Amazon EC2 instance

When an Amazon EC2 instance is launched with an IAM Role, the Instance Metadata automatically provides temporary access credentials consisting of an Access Key, Secret Key and Token. These credentials are rotated approximately every six hours.

Any code that uses an AWS SDK (eg Python, Java, PHP) knows how to automatically retrieve these credentials. Therefore, code running on an Amazon EC2 instance that was launched with an IAM role does not require you to retrieve nor provide access credentials -- it just works automagically!

So, in your above code sample, you could remove any lines that specifically refer to credentials. Your job is simply to ensure that the IAM Role has sufficient permissions for the operations you wish to perform.

This also applies to the AWS Command-Line Interface (CLI), which is actually just a Python program that provides command-line access to AWS API calls. Since it uses the AWS SDK for Python, it automatically retrieves the credentials from Instance Metadata and does not require credentials when used from an Amazon EC2 instance that was launched with an IAM Role.

2. How to assign permissions for access to Amazon S3

Objects in Amazon S3 are private by default. There are three ways to assign permission to access objects:

  • Object ACLs (Access Control Lists): These are permissions on the objects themselves
  • Bucket Policies: This is a set of rules applied to the bucket as a whole, but it can also specify permissions related to a subset of a bucket (eg a particular path within the bucket)
  • IAM Policies that are applied to IAM Users, Groups or Roles: These permissions apply specifically to those entities

Since you are wanting to grant access to Amazon S3 objects to a specific IAM User, it is better to assign permissions via an IAM Policy attached to that user, rather than being part of the Bucket Policy.

Therefore, you should:

  • Remove the Bucket Policy
  • Create an Inline Policy in IAM and attach it to the desired IAM User. The policy then applies to that User and does not require a Principal

Here is a sample policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::MY-BUCKET/*"
            ]
        }
    ]
}

I have recommended an Inline Policy because this policy applies to just one user. If you are assigning permissions to many users, it is recommended to attach the policy to an IAM Group and then the Users assigned to that group will in inherit the permissions. Alternatively, create an IAM Policy and then attach that policy to all relevant Users.

3. How Pre-Signed URLs function

Amazon S3 Pre-Signed URLs are a means of granting temporary access to Amazon S3 objects. The generated URL includes:

  • The Access Key of an IAM User that has permission to access the object
  • An expiration time
  • A signature created via a has operation that authorises the URL

The key point to realise is related to the permissions used when generating the pre-signed URL. As mentioned in the Amazon S3 documentation Share an Object with Others:

Anyone with valid security credentials can create a pre-signed URL. However, in order to successfully access an object, the pre-signed URL must be created by someone who has permission to perform the operation that the pre-signed URL is based upon.

This means that the credentials used when generating the pre-signed URL are also the credentials used as part of the pre-signed URL. The entity associated with those credentials, of course, needs permission to access the object -- the pre-signed URL is merely a means of on-granting access to an object for a temporary period.

What this also means is that, in the case of your example, you do not need to create a specific role for granting access to the object(s) in Amazon S3. Instead, you can use a more permissive IAM Role with your Amazon EC2 instance (for example, one that can also upload objects to S3) but when it generates a pre-signed URL it is only granting temporary access to the object (and not other permissions, such as the upload permission).

If the software running on your Amazon EC2 instance only interacts with AWS to created signed URLs, then your Role that has only GetObject permissions is fine. However, if your instance wants to do more, then create a Role that grants the instance the appropriate permissions (including GetObject access to S3) and generate Signed URLs using that Role.

If you wish to practice generating signed URLs, recent versions of the AWS Command-Line Interface (CLI) includes a aws s3 presign s3://path command that can generate pre-signed URLs. Try with with various --profile settings to see how it works with different IAM Users.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

AWS IAM Role in EC2 and access to S3 from JupyterHub

From Dev

AWS EC2 access to S3 with IAM role

From Dev

Retrieve file from S3 with curl from EC2 using IAM role

From Dev

EC2 cannot access S3 object via IAM role

From Dev

aws access s3 from spark using IAM role

From Dev

access AWS S3 from java using IAM Role

From Dev

AWS - Unable to access S3 bucket from EC2 windows

From Dev

Unable to upload file to S3 with Python using IAM role credentials

From Dev

EC2 instance temporary creds from IAM role not working

From Java

How to access S3 using IAM role from my local machine

From Dev

Template to create IAM role for spectrum S3 access

From Java

How to use java to access dynamodb without access credential on an ec2 instance with IAM role

From Dev

AWS CLI in Windows EC2 cannot use role to access S3

From Dev

Accessing S3 bucket from a script using IAM Role

From Dev

Unable to retrieve secret from secretsmanager on aws-ec2 using an IAM role

From Java

Access SQS from EC2 - Instance Profile vs Role

From Dev

Unable to grant an EC2 instance access to an Amazon S3 bucket

From Dev

How to deny other users/roles from creating EC2 instances with an IAM role

From Dev

Using IAM role permissions to prevent user from launching EC2 instance in CLI without a key pair

From Dev

Unable to access S3 from EC2 Instance in Cloudformation -- A client error (301) occurred when calling the HeadObject operation: Moved Permanently

From Dev

AWS S3 Access point access denied from EC2 (VPC)

From Dev

Access denied for cross account S3 access from EC2 instance

From Dev

Get "fatal error: Unable to locate credentials" when I'm copying file from S3 to EC2 using aws cli

From Java

How do I use Boto3 to launch an EC2 instance with an IAM role?

From Dev

python boto3 attach/replace IAM role to ec2

From Dev

The file upload by CloudFront Origin Access Identity signed url can't be access by boto3 or IAM role?

From Dev

What permissions should i assign to an S3 bucket to only make it accessible from an EC2 instance using IAM roles?

From Dev

Unable to access the ec2 Geronimo port from outside

From Dev

Unable to restric IAM Role to a specific key and subkeys in S3 (getting AccessDenied)

Related Related

  1. 1

    AWS IAM Role in EC2 and access to S3 from JupyterHub

  2. 2

    AWS EC2 access to S3 with IAM role

  3. 3

    Retrieve file from S3 with curl from EC2 using IAM role

  4. 4

    EC2 cannot access S3 object via IAM role

  5. 5

    aws access s3 from spark using IAM role

  6. 6

    access AWS S3 from java using IAM Role

  7. 7

    AWS - Unable to access S3 bucket from EC2 windows

  8. 8

    Unable to upload file to S3 with Python using IAM role credentials

  9. 9

    EC2 instance temporary creds from IAM role not working

  10. 10

    How to access S3 using IAM role from my local machine

  11. 11

    Template to create IAM role for spectrum S3 access

  12. 12

    How to use java to access dynamodb without access credential on an ec2 instance with IAM role

  13. 13

    AWS CLI in Windows EC2 cannot use role to access S3

  14. 14

    Accessing S3 bucket from a script using IAM Role

  15. 15

    Unable to retrieve secret from secretsmanager on aws-ec2 using an IAM role

  16. 16

    Access SQS from EC2 - Instance Profile vs Role

  17. 17

    Unable to grant an EC2 instance access to an Amazon S3 bucket

  18. 18

    How to deny other users/roles from creating EC2 instances with an IAM role

  19. 19

    Using IAM role permissions to prevent user from launching EC2 instance in CLI without a key pair

  20. 20

    Unable to access S3 from EC2 Instance in Cloudformation -- A client error (301) occurred when calling the HeadObject operation: Moved Permanently

  21. 21

    AWS S3 Access point access denied from EC2 (VPC)

  22. 22

    Access denied for cross account S3 access from EC2 instance

  23. 23

    Get "fatal error: Unable to locate credentials" when I'm copying file from S3 to EC2 using aws cli

  24. 24

    How do I use Boto3 to launch an EC2 instance with an IAM role?

  25. 25

    python boto3 attach/replace IAM role to ec2

  26. 26

    The file upload by CloudFront Origin Access Identity signed url can't be access by boto3 or IAM role?

  27. 27

    What permissions should i assign to an S3 bucket to only make it accessible from an EC2 instance using IAM roles?

  28. 28

    Unable to access the ec2 Geronimo port from outside

  29. 29

    Unable to restric IAM Role to a specific key and subkeys in S3 (getting AccessDenied)

HotTag

Archive