4
votes

I have a web tool which allows IAM users to do magic with their AWS account. Considering I have a free plan, any AWS user could create new IAM users once the trial has ended, so they would eventually never pay for my service. Is there any way to know the Aws Account Id of a particular IAM user? That way I can store that ID on db and block any other new IAM user coming from that particular AWS account.

5
Do you have credentials for these users? How are they identified to you at the moment?Frederick Cheung
Yes, I do have their Access Key ID and the Secret Access Keyalexandresaiz

5 Answers

2
votes

If you have access to the iam GetUser then that call returns (among other things) the ARN for the user, which includes the account id. You don't need to know the user name to call it - if none is specified it uses the calling user.

A call like aws iam get-user

Would return:

{
  "User": {
    "UserName": "test",
    "PasswordLastUsed": "2015-01-18T11:08:07Z",
    "CreateDate": "2014-10-21T20:30:04Z",
    "UserId": "AIDAXXXXXXXXXXXXX",
    "Path": "/",
    "Arn":  "arn:aws:iam::123456789012:user/test"
  }
}

The ARN (Amazon Resource Number (arn)) for iam entities is of the format arn:aws:iam::account-number:resource, so you just need to extract this portion ( 123456789012) from it. You can't guarantee that latter portions won't also contain digits, so you should split on : and take the 5th component.

4
votes

From CLI

aws sts get-caller-identity

If you use IAM based calls (same as what other people suggested) your IAM user needs to have proper permissions for those calls but sts one should go through for any IAM user.

2
votes

Ruby SDK

#!/usr/bin/ruby
require 'aws-sdk'
require 'pp'
require 'colorize'

current_region='us-west-2'
current_profile='default'

Aws.config.update({
                      region: current_region,
                      credentials: Aws::SharedCredentials.new(profile_name: current_profile),
                  })

iam = Aws::IAM::Client.new
client = iam.get_account_authorization_details({
                                                   max_items: 1,
                                               })
resp=client.user_detail_list[0].arn
acc="#{resp}".split(":")[4]
puts acc
0
votes

You can do Get-IAMUser and get the information, including the ARN; parsing the ARN would have the Account ID as well. Screenshot below.

PowerShell

Import-Module AWSPowerShell.psd1
Get-IAMUser

enter image description here

Boto

import boto
iam = boto.connect_iam()
iam.get_user()
0
votes

Another Python boto2 variant in case you don't have access/permissions for iam.get_user()

import boto.utils

print boto.utils.get_instance_metadata()['iam']['info']['InstanceProfileArn'].split(':')[4]