To Understand IF

To Understand IF
http://aws.typepad.com/aws/2011/08/aws-identity-and-access-management-now-with-identity-federation.html

AWS Security Token Service API Actions

AssumeRole (temp creds for upto 1hr)

Returns a set of temporary security credentials. You call this API using the credentials of an existing IAM user. This API is useful to grant AWS access to users who do not have an IAM identity (that is, to federated users). It is also useful to allow existing IAM users to access AWS resources that they don’t already have access to, such as resources in another account. For more information, see Creating Temporary Security Credentials for Delegating API Access.

AssumeRoleWithWebIdentity

Returns a set of temporary security credentials for federated users who are authenticated using a public identity provider like Login with Amazon, Facebook, or Google. This API is useful for creating mobile applications or client-based web applications that require access to AWS but where users do not have their own AWS or IAM identity. For more information, see Creating a Role to Allow AWS Access for the Mobile App.

GetFederationToken (Temp creds for upto 36hr)

Returns a set of temporary security credentials for federated users. This API differs from AssumeRole in that the default expiration period is substantially longer (up to 36 hours instead of up to 1 hour); this can help reduce the number of calls to AWS because you do not need to get new credentials as often. For more information, see Creating Temporary Security Credentials to Enable Access for Federated Users.

GetSessionToken

Returns a set of temporary security credentials to an existing IAM user. This API is useful to provide enhanced security, such as to make AWS requests when MFA is enabled for the IAM user. For more information, see Creating Temporary Security Credentials to Enable Access for IAM Users.
Information Available in Requests for Federated Users

Federated users are users who are authenticated using a system other than IAM. For example, a company might have an application for use in-house that makes calls to AWS. It might be impractical to give an IAM identity to every corporate user who uses the application. Instead, the company might use a proxy (middle-tier) application that has a single IAM identity. This proxy application first authenticates individual users using the corporate network; the proxy application then uses its IAM identity to get temporary security credentials for individual users and gives them to the user’s local copy of the corporate application. The user’s local copy of the corporate application can use these temporary credentials to call AWS.

Similarly, you might create an app for a mobile device in which the app needs to access AWS resources. In that case, you might use web identity federation, where the app authenticates the user using a well-known identity provider like Login with Amazon, Facebook, or Google. The app can then use the user’s authentication information from these providers to get temporary security credentials for accessing AWS resources.
Using Your Company’s Own Authentication System to Grant Access to AWS Resources
1. http://docs.aws.amazon.com/STS/latest/UsingSTS/STSUseCases.html#IdentityBrokerApplication

2.Ways to Get Temporary Security Credentials
http://docs.aws.amazon.com/STS/latest/UsingSTS/Welcome.html#AccessingSTS

3.Permissions in Temporary Security Credentials for Federated Users
http://docs.aws.amazon.com/STS/latest/UsingSTS/sts-controlling-feduser-permissions.html
Calls to the AssumeRole action are made using the long-term security credentials of an IAM user. The call must specify the ARN of the role to assume. The IAM user whose credentials are used to make the call must as a minimum have sts:AssumeRole permissions, and must be listed as the principal in the role that is being assumed. By default, the role being assumed determines the permissions that are granted to the temporary security credentials. The permissions of the IAM user that’s used to make the AssumeRole API have no effect on the permissions granted to the temporary security credentials that are returned by the API. Optionally, the call can include a policy that further restricts the permissions of the temporary security credentials. The resulting credentials are based on the intersection of the role’s permissions and the passed permissions. (This means that the passed permissions can never escalate the permissions defined in the role.)

 

How do I choose which API?

When deciding which API to use, you should consider what services are required for your use case and where you want to maintain the policies associated with your federated users.

How do you want to maintain the policies associated with your delegated users?

If you prefer to maintain permissions solely within your organization, GetFederationToken is the better choice. Since the base permissions will be derived from the IAM user making the request and you need to cover your entire delegated user base, this IAM user will require the combination of all permissions of all federated users.

If you prefer to maintain permissions within AWS, choose AssumeRole, since the base permissions for the temporary credentials will be derived from the policy on a role. Like a GetFederationToken request, you can optionally scope down permissions by attaching a policy to the request. Using this method, the IAM user credentials used by your proxy server only requires the ability to call sts:AssumeRole.

 

Full Access to a specific S3 Bucket except DeleteObject

{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::testbucket-unni"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
              "s3:PutObject",
              "s3:GetObject"
              ],
            "Resource": [
                "arn:aws:s3:::testbucket-unni/*"
            ]
        }
    ]
}

Details:

  1. Get and List actions given to “arn:aws:s3:::*” to enable console view
  2. List action given by specifying exact ARN (without start) “arn:aws:s3:::testbucket-unni” to enable protection to other buckets if its name start “testbucket-unni”
  3. Put and Get actions given as “arn:aws:s3:::testbucket-unni/*” which means only to objects inside the bucket .

Identity Fed Setup for AWS

sudo apt-get install ruby
sudo apt-get install rubygems
sudo gem install json
sudo gem install cgi-spa
sudo gem install rest-open-uri
sudo apt-get install libxslt-dev libxml2-dev
sudo apt-get install build-essential
Create New IAM User to make API calls to STS. (User = identityfed)
Attach a Policy using Policy Generator with Amazon STS (the above ARN have to used.)

Access Key ID:
AKIADFAGFASDADSASD
Secret Access Key:
irJa8tNbsdfasddaLK:J;kj;jmL:HLIUh

Create an IAM Role (UnniRole)

Attached Policy Looks as Follows:

{
 "Version": "2012-10-17",
 "Statement": [
  {
    "Sid": "Stmt1384322508000",
    "Effect": "Allow",
    "Action": [
    "sts:*"
  ],
    "Resource": [
    "arn:aws:iam::122223333444455551:role/UnniRole"
  ]
}
]
}

AWS Ruby Script

Ruby Script by AWS for Identity Federation

#!/usr/bin/ruby

require 'rubygems'
require 'json'
require 'open-uri'
require 'cgi'
require 'aws-sdk'

# The temporary credentials will normally come from your identity
# broker, but for simplicity we create them in place
sts = AWS::STS.new(:access_key_id => "AKFFAASVASDE",
:secret_access_key => "irJa8tNsdfavaercravavraWA")

# A sample policy for accessing SNS in the console.
policy = AWS::STS::Policy.new
policy.allow(:actions => "*",:resources => :any)

session = sts.new_federated_session(
"FederatedUser(Unni)",
:policy => policy,
:duration => 3600)
# The issuer parameter specifies your internal sign-in
# page, for example https://mysignin.internal.mycompany.com/.
# The console parameter specifies the URL to the destination tab of the
# AWS Management Console. This example goes to the sns console.
# The signin parameter is the URL to send the request to.
issuer_url = "http://localhost/\"
console_url = "https://console.aws.amazon.com/\"
signin_url = "https://signin.aws.amazon.com/federation\"

# Create the signin token using temporary credentials,
# including the Access Key ID, Secret Access Key, and security token.

session_json = {
:sessionId => session.credentials[:access_key_id],
:sessionKey => session.credentials[:secret_access_key],
:sessionToken => session.credentials[:session_token]
}.to_json

get_signin_token_url = signin_url + "?Action=getSigninToken&SessionType=json&Session=" + CGI.escape(session_json)
returned_content = URI.parse(get_signin_token_url).read
signin_token = JSON.parse(returned_content)['SigninToken']
signin_token_param = "&SigninToken=" + CGI.escape(signin_token)

# The issuer parameter is optional, but recommended. Use it to direct users
# to your sign-in page when their session expires.
issuer_param = "&Issuer=" + CGI.escape(issuer_url)
destination_param = "&Destination=" + CGI.escape(console_url)

login_url = signin_url + "?Action=login" + signin_token_param + issuer_param + destination_param
puts "Login in URL - %s" % login_url;

IAM Users Only for Bucket Access

Ideally we have to IAM Roles if the access credentials is used by an App hosted in EC2, else the following can be setup :

  • Create an IAM Bucket say unni-test
  • Create an IAM User with the same name as bucket say – unni-test
  • Now we can use IAM Variables (here aws:username) to create just a Single Policy to Grant Acccess specifically to each bucket and apply it to the IAM Group. Hence all similar requirements can be added to this IAM Group.

Example :
{
“Version”: “2012-10-17”,
“Statement”: [
{
“Action”: [“s3:*”],
“Effect”: “Allow”,
“Resource”: [“arn:aws:s3:::mybucket”],
“Condition”:{“StringLike”:{“s3:prefix”:[“home/${aws:username}/*”]}}
},
{
“Action”:[“s3:*”],
“Effect”:”Allow”,
“Resource”: [“arn:aws:s3:::mybucket/home/${aws:username}/*”]
}
]
}

The policy uses a policy variable (${aws:username}) that is evaluated at run time and contains the friendly name of the IAM user who made the request.

Example IAM Policies : http://docs.aws.amazon.com/IAM/latest/UserGuide/ExampleIAMPolicies.html

ARN – AWS Documentation Excerpts

Here are some example ARNs:

<!– AWS Elastic Beanstalk application version –>

arn:aws:elasticbeanstalk:us-east-1:123456789012:environment/My App/MyEnvironment

<!– IAM user name –>

arn:aws:iam::123456789012:David

<!– Amazon RDS tag –>

arn:aws:rds:eu-west-1:001234567890:db:mysql-db

<!– Amazon S3 bucket (and all objects in it)–>

arn:aws:s3:::my_corporate_bucket/*

The following are the general formats for ARNs; the specific components and values used depend on the AWS service.

arn:aws:service:region:account:resource
arn:aws:service:region:account:resourcetype/resource
arn:aws:service:region:account:resourcetype:resource

ARN Examples for EC2
Amazon Elastic Compute Cloud (Amazon EC2)
Syntax:

 arn:aws:ec2:region:account:instance/instance-id
arn:aws:iam::account:instance-profile/instance-profile-name
arn:aws:ec2:region:account:placement-group/placement-group-name
arn:aws:ec2:region::snapshot/snapshot-id
arn:aws:ec2:region:account:volume/volume-id

Examples:

 arn:aws:ec2:us-east-1:123456789012:instance/*
arn:aws:ec2:us-east-1:123456789012:volume/*
arn:aws:ec2:us-east-1:123456789012:volume/vol-1a2b3c4d

ARN Examples of RDS
ARNs are used in Amazon RDS only with tags for DB instances. For more information, see Tagging a DB Instance in the Amazon Relational Database Service User Guide.
Syntax:

 arn:aws:service:region:account:database:databasename
arn:aws:service:region:account:snapshot:snapshotname

Examples:

 arn:aws:rds:eu-west-1:123456789012:db:mysql-db
arn:aws:rds:us-east-1:123456789012:snapshot:my-snapshot2

ARN Examples of Route53

Amazon Route 53
Syntax:

 arn:aws:route53:::hostedzone/zoneid
arn:aws:route53:::change/changeid

Note that Amazon Route 53 does not require an account number or region in ARNs.
Examples:

 arn:aws:route53:::hostedzone/Z148QEXAMPLE8V
arn:aws:route53:::change/C2RDJ5EXAMPLE2
arn:aws:route53:::change/*

ARN Examples of Amazon S3
Syntax:

 arn:aws:s3:::bucketname
arn:aws:s3:::bucketname/objectpath

Note that Amazon S3 does not require an account number or region in ARNs.
Examples:

 arn:aws:s3:::my_corporate_bucket
arn:aws:s3:::my_corporate_bucket/*
arn:aws:s3:::my_corporate_bucket/Development/*

AWS Service Namespaces

When you create AWS IAM policies or work with Amazon Resource Names (ARNs), you identify an AWS service using a namespace. For example, the namespace for Amazon S3 is s3, and the namespace for Amazon EC2 is ec2. You use namespaces when identifying actions and resources.

The following example shows an IAM policy where the value of the Action elements and the values in the Resource and Condition elements use namespaces to identify the services for the actions and resources.

{
"Statement":[{
"Effect":"Allow",
"Action":"iam:*",
"Resource":["arn:aws:iam::123456789012:group/marketing/*",
"arn:aws:iam::123456789012:user/marketing/*"]
},
{
"Effect":"Allow",
"Action":"s3:*",
"Resource":"arn:aws:s3:::example_bucket/marketing/*"
},
{
"Effect":"Allow",
"Action":"s3:ListBucket*",
"Resource":"arn:aws:s3:::example_bucket",
"Condition":{
"StringLike":{
"s3:prefix":"marketing/*"
}
}
}
]
}

The following lists the AWS service namespaces.

 

 

Service Namespace
Auto Scaling autoscaling
AWS Account Billing aws-portal
AWS CloudFormation cloudformation
Amazon CloudFront cloudfront
CloudWatch cloudwatch
Amazon DynamoDB dynamodb
Amazon EC2 ec2
AWS Elastic Beanstalk elasticbeanstalk
Elastic Load Balancing elasticloadbalancing
Amazon Elastic MapReduce elasticmapreduce
Amazon ElastiCache elasticache
Amazon Glacier glacier
IAM iam
AWS Marketplace aws-marketplace
AWS OpsWorks opsworks
Amazon RDS rds
Amazon Route 53 route53
Amazon S3 s3
Amazon SES ses
Amazon SimpleDB sdb
Amazon SNS sns
Amazon SQS sqs
Amazon SWF swf
AWS Storage Gateway storagegateway
AWS STS sts
AWS Support support
Amazon VPC ec2

IAM Users Best Practices – Excerpts from AWS Documentation!

Defining the right set of permissions requires some research to determine what is required for the specific task, what actions a particular service supports, and what permissions are required in order to perform those actions.
Permissions can be assigned in two ways: as user-based permissions or as resource-based permissions. User-based permissions are attached to an IAM user, group, or role and let you specify what that user, group, or role can do. For example, you can assign permissions to the IAM user named Bob, stating that he has permission to use the Amazon Elastic Compute Cloud (Amazon EC2) RunInstances action and that he has permission to get items from an Amazon DynamoDB table named MyCompany. The user Bob might also be granted access to manage his own IAM security credentials.
Resource-based permissions are attached to a resource like an Amazon S3 bucket or an Amazon SNS topic. They let you specify who has access to the resource and what actions they can perform on it.
When you add a new user we need to check if the policies that we intend to give the user are already existing as part of the Group or not. If so then take the Group that mostly match with the User and remaining policies of the group will be made as Deny for that particular user.

IAM Policies:

To assign permissions to a user, group, role, or resource, you create a policy, which is a document that explicitly lists permissions. In its most basic sense, a policy lets you specify the following:

Actions: what actions you will allow. Each AWS service has its own set of actions. For example, you might allow a user to use the Amazon S3 ListBucket action, which returns information about the items in a bucket. Any actions that you don’t explicitly allow are denied.

Resources: which resources you allow the action on. For example, what specific Amazon S3 buckets will you allow the user to perform the ListBucket action on? Users cannot access any resources that you have not explicitly granted permissions to.

Effect: what the effect will be when the user requests access—either allow or deny. Because the default is that resources are denied to users, you typically specify that you will allow users access to resource.

Policies are documents that are created using JSON. A policy consists of one or more statements, each of which describes one set of permissions. Here’s an example of a simple policy.

{
“Version”:”2012-10-17″,
“Statement”:[{
“Effect”:”Allow”,
“Action”:”s3:ListBucket”,
“Resource”:”arn:aws:s3:::example_bucket”
}]
}
To specify resource-based permissions, you can attach a policy to the resource, such as an Amazon SNS topic or Amazon S3 bucket. In that case, the policy has to include information about who is allowed to access the resource, known as the principal. (For user-based policies, the principal is the IAM user that the policy is attached to, or the user who gets the policy from a group.)

The following example shows a policy that might be attached to an Amazon S3 bucket and that lets IAM user Bob in account 123456789012 perform any actions in mybucket.

{
“Version”:”2012-10-17″,
“Id”: “S3-Account-Permissions”,
“Statement”: [
{
“Sid”: “1”,
“Effect”: “Allow”,
“Principal”: {
“AWS”: [
“arn:aws:iam::123456789012:user/Bob”
]
},
“Action”: “s3:*”,
“Resource”: “arn:aws:s3:::mybucket/*”
}
]
}

IAM Policy Evaluation Logic
IAMEvaluationLogic

1. The decision starts by assuming that the request will be denied.

2. The enforcement code evaluates all user-based and resource-based policies that are applicable to the request (based on the resource, principal, action, and conditions).

The order in which the enforcement code evaluates the policies is not important.

3. In all those policies, the enforcement code looks for an explicit deny instruction that would apply to the request.

If the code finds even one explicit deny that applies, the code returns a decision of “deny” and the process is finished.

4. If no explicit deny is found, the code looks for any “allow” instructions that would apply to the request.

If it finds even one explicit allow, the code returns a decision of “allow” and the service continues to process the request.

5. If no allow is found, the final decision is “deny.”
The distinction between a request being denied by default and an explicit deny in a policy is important. By default, a request is denied, but this can be overridden by an allow. In contrast, if a policy explicitly denies a request, that deny can’t be overridden.

Use roles for applications that run on Amazon EC2 instances

Applications that run on an Amazon EC2 instance need credentials in order to access other AWS services. To provide credentials to the application in a secure way, use IAM roles. A role is an entity that has its own set of permissions, but that isn’t a user or group. Roles also don’t have their own permanent set of credentials the way IAM users do. Instead, a role is assumed by other entities. Credentials are then either associated with the assuming identity, or IAM dynamically provides temporary credentials (in the case of Amazon EC2).

When you launch an Amazon EC2 instance, you can specify a role for the instance as a launch parameter. Applications that run on the EC2 instance can use the role’s credentials when they access AWS resources. The role’s permissions determine what the application is allowed to do.
Delegate by using roles instead of by sharing credentials
You might need to allow users from another AWS account to access resources in your AWS account. If so, don’t share security credentials, such as access keys, between accounts. Instead, use IAM roles. You can define a role that specifies what permissions the IAM users in the other account are allowed, and from which AWS accounts IAM users are allowed to assume the role.
Rotate credentials regularly
Change your own passwords and access keys regularly, and make sure that all IAM users in your account do as well. That way, if a password is compromised without your knowledge, you limit how long the password can be used to access your resources.
To make it easier to rotate credentials, let your users manage their own passwords.
Use policy conditions for extra security
To the extent that it’s practical, define the conditions under which the policy allows access to a resource. For example, you can write conditions to specify a range of allowable IP addresses for a request, or you can specify that a request is allowed only within a specified date range or time range. You can also set conditions that require the use of SSL or MFA. For example, you can require that a user has authenticated with an MFA device in order to be allowed to terminate an Amazon EC2 instance. The more explicitly you can define when resources are available (and otherwise unavailable), the safer your resources will be.
As an example, let’s say you want to let user John access your Amazon SQS queue under the following conditions:

The time is after 12:00 noon on 8/16/2013

The time is before 3:00 p.m. on 8/16/2013

The request (IAM or SQS) or message (SNS) comes from an IP address within the range 192.0.2.0 to 192.0.2.255 or 203.0.113.0 to 203.0.113.255.

Your condition block has three separate conditions, and all three of them must be met for John to have access to your queue, topic, or resource.

The following shows what the condition block looks like in your policy. The two values for aws:SourceIp are evaluated using OR. The three separate conditions are evaluated using AND.

“Condition” : {
“DateGreaterThan” : {
“aws:CurrentTime” : “2013-08-16T12:00:00Z”
},
“DateLessThan”: {
“aws:CurrentTime” : “2013-08-16T15:00:00Z”
},
“IpAddress” : {
“aws:SourceIp” : [“192.0.2.0/24”, “203.0.113.0/24”]
}
}
Available Keys for Conditions

Keys in a condition represent values that are part of the request sent by a user. AWS provides the following predefined keys for all AWS services that support the IAM for access control:

aws:CurrentTime—To check for date/time conditions.

aws:EpochTime—To check for date/time conditions using a date in epoch or UNIX time.

aws:MultiFactorAuthAge—To check how long ago (in seconds) the MFA-validated security credentials making the request were issued using Multi-Factor Authentication (MFA). Unlike other keys, if MFA is not used, this key is not present (see Existence of Condition Keys, Numeric Conditions and Using Multi-Factor Authentication (MFA) Devices with AWS.

aws:principaltype—To check the type of principal (user, account, federated user, etc.) for the current request.

aws:SecureTransport—To check whether the request was sent using SSL.

aws:SourceArn—To check the source of the request, using the Amazon Resource Name (ARN) of the source. (This value is available for only some services. For more information, see Amazon Resource Name (ARN) under “Element Descriptions” in the Amazon Simple Queue Service Developer Guide.)

aws:SourceIp—To check the requester’s IP address.

aws:UserAgent—To check the requester’s client application.

aws:userid—To check the requester’s user ID.

aws:username—To check the requester’s user name.

Note
Key names are case sensitive.
Some AWS services also provide service-specific keys. For example, for information about keys that you can use in policies for Amazon S3 resources, see Amazon S3 Policy Keys in the Amazon Simple Storage Service Developer Guide. For keys that are available in other services, see the documentation for the individual services.

Permissions Required for Using Roles with Amazon EC2

To launch an instance with a role, the developer must have permission to launch Amazon EC2 instances and permission to pass IAM roles.

The following sample policy allows users to use the AWS Management Console to launch an instance with a role. The policy allows a user to pass any role and to perform all Amazon EC2 actions by specifying an asterisk (*). The ListInstanceProfiles action allows users to view all the roles that are available on the AWS account.

Example Policy that grants a user permission to launch an instance with any role by using the Amazon EC2 console

{
“Version”: “2012-10-17”,
“Statement”: [{
“Effect”:”Allow”,
“Action”:”iam:PassRole”,
“Resource”:”*”
},
{
“Effect”:”Allow”,
“Action”:”iam:ListInstanceProfiles”,
“Resource”:”*”
},
{
“Effect”:”Allow”,
“Action”:”ec2:*”,
“Resource”:”*”
}]
}
Restricting Which Roles Can Be Passed to Amazon EC2 Instances (Using PassRole)

You can use the PassRole permission to prevent users from passing a role to Amazon EC2 that has more permissions than the user has already been granted, and then running applications under the elevated privileges for that role. In the role policy, allow the PassRole action and specify a resource (such as arn:aws:iam::111122223333:role/ec2Roles/*) to indicate that only a specific role or set of roles can be passed to an Amazon EC2 instance.

The following sample policy allows developers to use the Amazon EC2 API to launch an instance with a role. The Resource element specifies an Amazon Resource Name (ARN). By specifying the ARN, the policy grants the user to pass only the Get-pics role.

Example Policy that grants a user permission to launch an instance with a role by using the Amazon EC2 API

{
“Version”: “2012-10-17”,
“Statement”: [{
“Effect”:”Allow”,
“Action”:”ec2:RunInstances”,
“Resource”:”*”
},
{
“Effect”:”Allow”,
“Action”:”iam:PassRole”,
“Resource”:”arn:aws:iam::123456789012:role/Get-pics”
}]
}

References:
http://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPractices.html
http://docs.aws.amazon.com/IAM/latest/UserGuide/role-usecase-ec2app.html