AWS IAM Security Through the Command Line and SDKs (Java, Ruby, and PHP)‏

Amazon security requires the use of AWS IAM with temporary authentication credentials. We’ll explore implementation via the command line and SDKs.

Cloud security is shared between AWS and its customers. Amazon Web Services Security takes responsibility for the compute and networking layers (security of the cloud), while we’re on the hook for our instances, networks, web applications, and databases (security in the cloud). But, as I discussed in a previous post on AWS security, Amazon also provides you with powerful tools to help you maintain your side of the deal; especially their Identity and Access Management system (IAM).

IAM allows you to create and manage permissions for multiple users. It works on the philosophy of least privilege, by providing only the precise rights a user or role will need to do exactly their task and nothing more. AWS best practices are, as the name suggests, the very best way to tighten your AWS  IAM security. While most best practices can be implemented without modification, using IAM roles for apps or scripts running on EC2 instances might require a little work. In this post, we’ll see some examples of code-based IAM role implementation in your applications.

What is an AWS IAM role and how does it work

When AWS IAM users want to access the AWS Management Console, they log in using their usernames and passwords. Programmatic access to AWS services requires an Access Key and Secret Key. Your keys might look something like this (use this guide to create your own keys):

aws_access_key_id = ARTDOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnTRSMI/K756ENG/bPxRfiCYEXAMPLEKEY

You could hard code your access keys in your application to enable access to AWS services like S3 or DynamoDB, but anyone with access to the code will be able to see the keys in plain text. If your server gets hacked, imagine the consequences of having left code like this lying around:

AWS IAM codeInstead of the above code, you can completely avoid this vulnerability by using an IAM role, which lets you securely distribute keys to your users and applications. IAM role credentials can (and should) be rotated regularly and temporary credentials provided for service access. If your application needs to access objects in an s3 bucket, temporary security credentials are provided to the host ec2 instance. IAM roles for EC2 instances also work within Amazon Virtual Private Clouds:

Amazon Virtual Private Clouds

Benefits:

  • No need to share permanent security credentials.
  • Uses temporary security credentials when making requests from running EC2 instance. Effective Amazon security requires the use of AWS IAM with temporary authentication credentials: we’ll explore implementation via the command line and SDKs to AWS services.
  • Integrated with All AWS Software Development Kits (SDKs) and the command line interface tool (CLI).

Creating an AWS IAM role

  1. Log into the IAM console.
  2. Click on Roles on the left panel, and then click Create New Role.
  3. Specify a descriptive Role name.AWS IAM role
  4. Select Role Type as EC2.
    AWS IAM Role Type
  5. On the Attach Policy page, you can either select an existing policy or go back and create a new policy as per your needs.
  6. Review the role information, and then click Create Role.
  7. You can launch an instance using either a CLI or the Console: in Ec2 dashboard, click Launch Instance.
  8. Select your AMI, then select an instance type and click Next: Configure Instance Details.
  9. On the Configure Instance Details page, Specify the role when you launch your instances.AWS IAM instance configure instance details
  10. Once this is done, your application will retrieve a set of temporary credentials and use them in your application.

Using AWS IAM Roles with the command line interface

Here’s a simple script to launch an instance using the AWS CLI. As you can see for yourself, we have included no AWS Keys. The “/etc/profile.d/aws-apitools-common.sh” file provides all the authentication you’ll need at run time (note, that if you’re running an AMI besides Amazon Linux, you may need to install this file manually).

#!/bin/bash
. /etc/profile.d/aws-apitools-common.sh
aws ec2 run-instances --image-id ami-1ecae776 --region us-east-1 --placement AvailabilityZone=us-east-1b --instance-type t2.large --key-name demo-key --subnet-id subnet-45874145 --security-group-ids sg-1254854

Using AWS IAM Roles with the PHP SDK

When using an IAM role with a PHP application, you can create caching layers on top of your IAM role credentials to specify a credentials cache using the credentials.cache option in a client’s factory method, or in a service builder configuration file. The configuration setting (credentials.cache) should be configured to an object that implements Guzzle’s CacheAdapterInterface . A credential’s cache can also be used in a service builder configuration.

<?php
// File saved as /path/to/custom/config.php
use Doctrine\Common\Cache\FilesystemCache;
use Guzzle\Cache\DoctrineCacheAdapter;
$cacheAdapter = new DoctrineCacheAdapter(new FilesystemCache('/tmp/cache'));
return array(
    'includes' => array('_aws'),
    'services' => array(
        'default_settings' => array(
            'params' => array(
                'credentials.cache' => $cacheAdapter
            )
        )
    )
);

Using AWS IAM Roles with the Java SDK

In order to use the AWS java SDK to connect AWS IAM service, all dependent Packages related to AWS IAM and AWS credentials need to be specified in the build path. The Java SDK uses “Class InstanceProfileCredentialsProvider” that loads credentials from the Amazon EC2 Instance Metadata Service, which retrieves temporary AWS credentials that have the same permissions as the IAM role associated with our EC2 instance. At the start of your program, you need to import the “com.amazonaws.auth.*” class.

import com.amazonaws.auth.profile.ProfileCredentialsProvider;

Using AWS IAM Roles with the Ruby SDK

In the Ruby SDK, EC2Provider objects retrieve credentials with the same permissions as the IAM role. These credentials refresh regularly to get access to AWS services.

AWS.config(:credential_provider => AWS::Core::CredentialProviders::EC2Provider.new)

Here’s a sample program that will download an object from AWS S3. As you can see, we have used no credentials within the code.

require 'rubygems'
require 'aws-sdk'
s3 = AWS::S3.newaws-iam-instance
bucket_name = 'text-content'
obj_name = 'text-object.txt'
document = s3.buckets[bucket_name].objects[obj_name]
File.open(obj_name, "w") do |f|
  f.write(document.read)
end
puts "'#{obj_name}' copied from S3."

Avatar

Written by

Nitheesh Poojary

My professional IT career began nine years back when I was just out of my college. I worked with a great team as an infrastructure management engineer, managing hundreds of enterprise application servers. I found my passion when I got the opportunity to work with Cloud technologies: I'm addicted to AWS Cloud Services, DevOps engineering, and all the cloud tools and technologies that make engineers' lives easier. Currently, I am working as a Solution Architect in SixNines IT. We are an experienced team of engineers that have helped hundreds of customers move to the cloud responsibly. I have achieved 5 AWS certifications, happily helping fellow engineers across the globe through my blogs and answering questions in various forums.


Related Posts

Avatar
Dzenan Dzevlan
— November 20, 2019

Application Load Balancer vs. Classic Load Balancer

What is an Elastic Load Balancer? This post covers basics of what an Elastic Load Balancer is, and two of its examples: Application Load Balancers and Classic Load Balancers. For additional information — including a comparison that explains Network Load Balancers — check out our post o...

Read more
  • ALB
  • Application Load Balancer
  • AWS
  • Elastic Load Balancer
  • ELB
Albert Qian
Albert Qian
— November 13, 2019

Advantages and Disadvantages of Microservices Architecture

What are microservices? Let's start our discussion by setting a foundation of what microservices are. Microservices are a way of breaking large software projects into loosely coupled modules, which communicate with each other through simple Application Programming Interfaces (APIs). ...

Read more
  • AWS
  • Docker
  • Kubernetes
  • Microservices
Nisar Ahmad
Nisar Ahmad
— November 12, 2019

Kubernetes Services: AWS vs. Azure vs. Google Cloud

Kubernetes is a popular open-source container orchestration platform that allows us to deploy and manage multi-container applications at scale. Businesses are rapidly adopting this revolutionary technology to modernize their applications. Cloud service providers — such as Amazon Web Ser...

Read more
  • AWS
  • Azure
  • Google Cloud
  • Kubernetes
Avatar
Stuart Scott
— October 31, 2019

AWS Internet of Things (IoT): The 3 Services You Need to Know

The Internet of Things (IoT) embeds technology into any physical thing to enable never-before-seen levels of connectivity. IoT is revolutionizing industries and creating many new market opportunities. Cloud services play an important role in enabling deployment of IoT solutions that min...

Read more
  • AWS
  • AWS IoT Events
  • AWS IoT SiteWise
  • AWS IoT Things Graph
  • IoT
Avatar
Cloud Academy Team
— October 23, 2019

Which Certifications Should I Get?

As we mentioned in an earlier post, the old AWS slogan, “Cloud is the new normal” is indeed a reality today. Really, cloud has been the new normal for a while now and getting credentials has become an increasingly effective way to quickly showcase your abilities to recruiters and compan...

Read more
  • AWS
  • Azure
  • Certifications
  • Cloud Computing
  • Google Cloud Platform
Valery Calderón Briz
Valery Calderón Briz
— October 22, 2019

How to Go Serverless Like a Pro

So, no servers? Yeah, I checked and there are definitely no servers. Well...the cloud service providers do need servers to host and run the code, but we don’t have to worry about it. Which operating system to use, how and when to run the instances, the scalability, and all the arch...

Read more
  • AWS
  • Lambda
  • Serverless
Avatar
Stuart Scott
— October 16, 2019

AWS Security: Bastion Hosts, NAT instances and VPC Peering

Effective security requires close control over your data and resources. Bastion hosts, NAT instances, and VPC peering can help you secure your AWS infrastructure. Welcome to part four of my AWS Security overview. In part three, we looked at network security at the subnet level. This ti...

Read more
  • AWS
Avatar
Sudhi Seshachala
— October 9, 2019

Top 13 Amazon Virtual Private Cloud (VPC) Best Practices

Amazon Virtual Private Cloud (VPC) brings a host of advantages to the table, including static private IP addresses, Elastic Network Interfaces, secure bastion host setup, DHCP options, Advanced Network Access Control, predictable internal IP ranges, VPN connectivity, movement of interna...

Read more
  • AWS
  • best practices
  • VPC
Avatar
Stuart Scott
— October 2, 2019

Big Changes to the AWS Certification Exams

With AWS re:Invent 2019 just around the corner, we can expect some early announcements to trickle through with upcoming features and services. However, AWS has just announced some big changes to their certification exams. So what’s changing and what’s new? There is a brand NEW ...

Read more
  • AWS
  • Certifications
Alisha Reyes
Alisha Reyes
— October 1, 2019

New on Cloud Academy: ITIL® 4, Microsoft 365 Tenant, Jenkins, TOGAF® 9.1, and more

At Cloud Academy, we're always striving to make improvements to our training platform. Based on your feedback, we released some new features to help make it easier for you to continue studying. These new features allow you to: Remove content from “Continue Studying” section Disc...

Read more
  • AWS
  • Azure
  • Google Cloud Platform
  • ITIL® 4
  • Jenkins
  • Microsoft 365 Tenant
  • New content
  • Product Feature
  • Python programming
  • TOGAF® 9.1
Avatar
Stuart Scott
— September 27, 2019

AWS Security Groups: Instance Level Security

Instance security requires that you fully understand AWS security groups, along with patching responsibility, key pairs, and various tenancy options. As a precursor to this post, you should have a thorough understanding of the AWS Shared Responsibility Model before moving onto discussi...

Read more
  • AWS
  • instance security
  • Security
  • security groups
Avatar
Jeremy Cook
— September 17, 2019

Cloud Migration Risks & Benefits

If you’re like most businesses, you already have at least one workload running in the cloud. However, that doesn’t mean that cloud migration is right for everyone. While cloud environments are generally scalable, reliable, and highly available, those won’t be the only considerations dri...

Read more
  • AWS
  • Azure
  • Cloud Migration