I am trying to use AWS CLI to describe my AWS policy. However, AWS does not seem to be recognizing the policy-id.
I have executed this:
aws iam get-policy --policy-arn arn:aws:iam::160936793253:policy/MyAWSPolicy
and got the following returned:
{
"Policy": {
"PolicyName": "MyAWSPolicy",
"PolicyId": "ANPAIIJNOIYOWCAK6KH7I",
"Arn": "arn:aws:iam::160936796653:policy/MyAWSPolicy",
"Path": "/",
"DefaultVersionId": "v8",
"AttachmentCount": 2,
"IsAttachable": true,
"CreateDate": "2019-03-20T20:20:26Z",
"UpdateDate": "2019-04-01T18:19:08Z"
}
}
However when I enter in this command:
aws organizations describe-policy --policy-id ANPAIIJNOIYOWCAK6KH7I
I get an InvalidInputException because according to AWS documentation (https://docs.aws.amazon.com/cli/latest/reference/organizations/describe-policy.html#examples):
The unique identifier (ID) of the policy that you want details about. You can get the ID from the ListPolicies or ListPoliciesForTarget operations.
The regex pattern for a policy ID string requires "p-" followed by from 8 to 128 lower-case letters or digits.
However when I add p- to ANPAIIJNOIYOWCAK6KH7I AWS does not recognize this policy.
Any idea what is going on?
The documentation you reference suggests that you get the policy id from ListPolicies or ListPoliciesForTarget operations, which is likely referencing the operations on the organizations service. The ID you took is from an IAM policy.
I am not completely familiar with the interactions between IAM and orgnaizations, but I imagine they are using different policy objects with different identifiers.
Related
I'm studying AWS EKS and I'm following the ufficial AWS Documentation. As explained here I created the "AWSLoadBalancerControllerIAMPolicy" but I would like to check if it has been correctly created. How can I see the list of the created policies?
I'm asking because I already tried to create many of them with different names (like: AWSLoadBalancerControllerIAMPolicyTest, AWSLoadBalancerControllerIAMPolicyExperiment... etc) but, once created, I can't find them anywhere.
I tried to give a look here (the IAM policy manager) but as you can see from the following screenshot they are not listed. Is there a way? Also through a CLI command?
To be honest it will be really usefull when I need to clean up the environment.
Thanks really appreciate your help!
Ennio
After run the command
aws iam create-policy --policy-name AWSLoadBalancerControllerIAMPolicyTest --policy-document file://iam_policy.json
you get a response like this:
{
"Policy": {
"PolicyName": "AWSLoadBalancerControllerIAMPolicyTest",
"PolicyId": "ANPA2BMVX57HOOWXXXXXX",
"Arn": "arn:aws:iam::<ACCOUNT_ID>:policy/AWSLoadBalancerControllerIAMPolicyTest",
"Path": "/",
"DefaultVersionId": "v1",
"AttachmentCount": 0,
"PermissionsBoundaryUsageCount": 0,
"IsAttachable": true,
"CreateDate": "2022-01-XXTXX:XX:XX+00:00",
"UpdateDate": "2022-01-XXTXX:XX:XX+00:00"
}
}
Make sure the account you are using when running the command is the same you are checking on the web console.
I'm working on a system that receives new findings from Amazon GuardDuty. Most access in our organization is delegated to IAM roles instead of directly to users, so the findings usually result from the actions of assumed roles, and the actor identity of the GuardDuty finding looks something like this:
"resource": {
"accessKeyDetails": {
"accessKeyId": "ASIALXUWSRBXSAQZECAY",
"principalId": "AROACDRML13PHK3X7J1UL:129545928468",
"userName": "my-permitted-role",
"userType": "AssumedRole"
},
"resourceType": "AccessKey"
},
I know that the accessKeyId is created when a security principal performs the iam:AssumeRole action. But I can't tell who assumed the role in the first place! If it was an IAM user, I want to know the username. Is there a way to programmatically map temporary AWS STS keys (starts with ASIA...) back to an original user?
Ideally I'm looking for a method that runs in less than 30 seconds so I can use it as part of my security event pipeline to enrich GuardDuty findings with the missing information.
I've already looked at aws-cli and found aws cloudtrail lookup-events but it lacks the ability to narrow the query to a specific accessKeyId so it takes a loooong time to run. I've explored the CloudTrail console but it's only about as capable as aws-cli here. I tried saving my CloudTrail logs to S3 and running an Athena query, but that was pretty slow too.
This seems like it would be a common requirement. Is there something obvious that I'm missing?
Actually, aws-cli can perform a lookup on the session! Just make sure to specify ResourceName as the attribute key in the lookup attributes.
$ aws cloudtrail lookup-events \
--lookup-attributes 'AttributeKey=ResourceName,AttributeValue=ASIALXUWSRBXSAQZECAY' \
--query 'Events[*].Username'
[
"the.user#example.com"
]
I have created a service account using the command
gcloud iam service-accounts create test-sa --display-name "TEST SA"
And then I go ahead and give this service account admin privileges on a GCS bucket.
gsutil iam ch serviceAccount:test-sa#<PROJECT>.iam.gserviceaccount.com:admin gs://<BUCKET>
Now I want a method to check what roles/permissions are granted to a service account.
One way is to do something like:
gcloud projects get-iam-policy <PROJECT> \
--flatten="bindings[].members" \
--format='table(bindings.role)' \
--filter="bindings.members: serviceAccount:test-sa#<PROJECT>.iam.gserviceaccount.com"
But the above command returns empty.
But if I get the ACL for the bucket, I can clearly see that the members and the roles for the bucket.
gsutil iam get gs://<BUCKET>
{
"bindings": [
{
"members": [
"serviceAccount:test-sa#<PROJECT>.iam.gserviceaccount.com"
],
"role": "roles/storage.admin"
},
{
"members": [
"projectEditor:<PROJECT>",
"projectOwner:<PROJECT>"
],
"role": "roles/storage.legacyBucketOwner"
},
{
"members": [
"projectViewer:<PROJECT>"
],
"role": "roles/storage.legacyBucketReader"
}
],
"etag": "CAI="
}
Can someone guide me as to how can I view the buckets/permissions associated with a service account and not the other way around ?
The issue here is that you are mixing project-level roles with bucket-level roles by assigning the permissions to the bucket directly(bucket-level role), and then checking at project-level. You can find more information about this over here.
This is why you get different results when checking either the project(cloud projects get-iam-policy ) or the bucket(gsutil iam get gs://).
You should stick to using either bucket-level roles or project-level roles and avoid mixing the 2 as if you start mixing them, it is gonna get tricky to know what roles each user has and were.
Depending on the number of buckets you plan to manage, it may be easier for you to stick to bucket-level roles and just iterate over a list of buckets when checking the permissions of a user as you can do this very easily with the Cloud SDK in a little for cycle such as:
for i in $(cat bucket-list.txt)
do
gsutil iam get gs://$i
done
Hope you find this useful.
As you are giving permission at Bucket ACL level and not using service account iam-binding,
gcloud projects get-iam-policy command wont return this permission.
You can only get this from querying bucket ACL.
You can assign permission at a resource such as a Project/Folder/Organization and at individual resources such as buckets, objects, compute engine instances, KMS keys, etc. There is no single command that checks everything.
At the Project level permissions are project-wide. At the resource level such as an object, only affect that object. You will need to check everything to know exactly what/where an IAM member has permissions.
I've been working with the AWS PHP SDK and I seem to get everything except the IAM Roles and permissions.
Can someone please explain to me in the simplest term how the IAM roles work and explain the following terms: StatementId, Action, ARN and most importantly Principal in simple English?
To give you the source of my confusion, here is a problem I recently faced. I'm trying to create an API Gateway in which a Resource's method triggers a Lambda function. It wasn't working until I copy pasted this bit:
$lambdaClient->addPermission([
'FunctionName' => 'fn name',
'StatementId' => 'ManagerInvokeAccess',
'Action' => 'lambda:InvokeFunction',
'Principal' => 'apigateway.amazonaws.com',
]);
But in some other thread someone suggested to use the following for the same:
const permissions = {
FunctionName: target,
StatementId: 'api-gateway-execute',
Action: 'lambda:InvokeFunction',
Principal: 'apigateway.amazonaws.com',
SourceArn: 'arn:aws:execute-api:' + nconf.get('awsRegion') + ':' + nconf.get('awsAccountId') + ':' + nconf.get('apiGatewayId') + '/*'};
How come the the first one doesn't contain any account info but The second one does? Also then there is another person who has pasted something totally different to get the same working for him. There are so many keys in the last example (like "Fn::Join"), I don't even know where to begin and what it does.
How does one figure out where to find these policies? Do we just copy-paste them from somewhere is there is a way to ascertain them. If so what keys must always be specified.
Any help will be appreciated because I'm totally confused right now.
First of all, Welcome to the world of AWS !!! :-D
Let me try to explain your doubts about how to understand IAM(in general) with an analogy.
Think that there is an organization called ORG1.
Deparments of ORG1: HR-dept, Test-dept, DEV-dept
Employees of ORG1: EMP1, EMP2, EMP3 ... EMP10
Members of HR dept: HR1, HR2, HR3
Now I want to create a role for HR dept to give them permission to hire/suspend an employee. The policy will look like below:
{
"Version": "2012-10-17", // This is version of the template. Don't change this. This is NOT a date field for your use.
"Statement": [
{
"Sid": "SOME-RANDOM-ID-WITH-NUMBER-1P1PP43EZUVRM", // This is used as ID in some cases to identify different statments
"Principal": HR-dept, // the dept who is allowed to assume this role or the one who is allowed to invoke this role
"Effect": "Allow", // has only 2 values: ALLOW/DENY. Either You want to provided the below privileges or you want to striped off these privileges.
"Action": [
"hire",
"suspend",
], // these are privileges which are granted
"Resource": "EMP1", // the entity on whom do you want to apply those actions on. In this case employee EMP1.
"Condition": {
"ArnLike": {
"AWS:SourceArn": "HR*" // You want anyone from HR-dept whose id starts with HR to be able to execute the action.ie HR1,HR2 or HR3 .
}
}
}
]
}
Now try to understand the below code from the same perspective(Internally this code creates a template similar to above):
const permissions = {
FunctionName: target,
StatementId: 'api-gateway-execute', // This is just an ID. Dont sweat about it.
Principal: 'apigateway.amazonaws.com', //which entity group the invoker belongs to
Action: 'lambda:InvokeFunction', // The privilege you are giving to API gateway api's
SourceArn: 'arn:aws:execute-api:.. blah blah blah' // ie. the exact Id of api-gateway which all has rights to invoke lambda function
};
In AWS ARN is a unique ID of a resource. Kind of like EmployeeId in a company.This is unique globally.
Believe me, At first it may seem that what you are trying to do in AWS is difficult to comprehend, But at some point you will start getting comfortable as you go on crossing each hurdle you face. And then you will admire at how customizable AWS features are.
How does one figure out where to find these policies?
You need to refer the AWS Documentation for specific service to find out what are the principals, actions and statements they support. For example if you need to find out policies for DynamoDB, check DynamoDB API Permissions. It can be confusing at first, since AWS Need to cater using IAM to authorize all of their services, but it becomes straight forward over time.
Let me explain each part of the policy
StatementId(Sid) - Its just and optional statement identifier (e.g 1, 2, abcd & etc.) and for some services(e.g SQS, SNS) it requires uniqueness.
Action - What your policy allows to do on a AWS Service. e.g For DynamoDB you can allow creating Tables, Putting new items & etc. For EC2 instance, it can allow starting and stopping.
ARN(Amazon Resource Name) - This is a unique name to uniquely identify AWS resources like a EC2 server, S3 bucket, DynamoDB table and even IAM policy, Role & etc.
Principal - Principal is to restrict who is allowed to use this policy. It can be a user (IAM user, federated user, or assumed-role user), AWS account, AWS service, or other principal entity that is allowed or denied access to a resource.
In addition you need to include Resource parameter, where you can either use a wildcard '*' or a ARN with Account ID within it.
I think most of the answers are correct but here it is from the horse's mouth/the great AWS document (full credit)
Role: An IAM role is an IAM identity that you can create in your account that has specific permissions.
Policies: IAM policies define permissions for an action regardless of the method that you use to perform the operation
Typically you have a role and you assign polices to your role.
To answer last part of your question "How does one figure out where to find these policies". This is all depends on what you are trying to do but always start with the least amount of permission (same concept as linux file permission don't give 777 ). How do you define your policies there are standard one already defined in your AWS account but you can use a tool to customize yours policies using the below tool
https://awspolicygen.s3.amazonaws.com/policygen.html
I would like to be able to query the AWS SDK to check what the IAM role of the current credentials is. I want to check if I am running using a particular role, and if not, then try to assume that role.
Is it possible to do this? I am using the AWS SDK for JavaScript for node.js. In the AWS.config.credentials, I have access to my keys, but not to which role they belong.
I think the method you want is GetCallerIdentity on the STS (Security Token Service) API:
API reference
JS example
This returns either nice user info (if no role in effect):
{
Account: "123456789012",
Arn: "arn:aws:iam::123456789012:user/Alice",
UserId: "AKIAI44QH8DHBEXAMPLE"
}
or info on the temporary session/user and role (if a role is in effect):
{
Account: "123456789012",
Arn: "arn:aws:sts::123456789012:assumed-role/my-role-name/my-role-session-name",
UserId: "AKIAI44QH8DHBEXAMPLE:my-role-session-name"
}
As noted, IAM().GetUser() (to return info on the current user) only works in the first instance, if no role is assumed. It fails if there is a role, so code defensively, but it's worth considering as when no role is in effect it returns a nicely formatted objects (though you could just regex-parse the arn:aws:iam::(.*):user/(.*) ARN from the GetCallerIdentity):
{
User: {
Arn: "arn:aws:iam::123456789012:user/Bob",
CreateDate: <Date Representation>,
Path: "/",
UserId: "AKIAIOSFODNN7EXAMPLE",
UserName: "Bob"
}
}
I suspect GetUser fails when a role is used because from what I can tell you are allocated a temporary user, I could see it being problematic to revert that role-assumption on the server, which would be necessary in order to make GetUser work in that case. And in some cases (instance profiles?) I think there isn't any real user account to revert back to.
To get the username of a user based on a set of keys you can use:
var iam = new AWS.IAM();
iam.getUser().User.UserName;
The API docs give the full details.
To get the role arn of an instance you'd probably have to use the instance metadata API endpoint as there is no method available in the SDK.
This answer and this one give details on different ways to query instance metadata.
Using just the AWS CLI:
aws sts get-caller-identity
The AWS Security Token Service (STS) returns something like:
{
"UserId": "ABBBCCC123123DDDDEEEE",
"Account": "123456789012",
"Arn": "arn:aws:iam::123456789012:user/bob"
}
(the username is within the Arn value, after the last :)
I will provide example how to do it in AWS CLI and you can convert it into NodeJS code:
aws sts get-caller-identity
get ARN from the response and get the user name from there (everything that comes after user/)
aws iam list-groups-for-user --user-name UserNameFromPreviousResponse
Then for each group you can dive in to the policies that are builtin or attached to that group:
aws iam list-group-policies --group-name GroupName
aws iam list-attached-group-policies --group-name GroupName
from here you can dive in into the policies to get their ARN if needed but I believe at this level it already should satisfy your needs.