Skip to main content

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, 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 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 credentialsInstead 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:

AWS IAM access

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 select
  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
  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 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 the 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."

 

Written by

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

— November 28, 2018

Two New EC2 Instance Types Announced at AWS re:Invent 2018 – Monday Night Live

Let’s look at what benefits these two new EC2 instance types offer and how these two new instances could be of benefit to you. Both of the new instance types are built on the AWS Nitro System. The AWS Nitro System improves the performance of processing in virtualized environments by...

Read more
  • AWS
  • EC2
  • re:Invent 2018
— November 21, 2018

Google Cloud Certification: Preparation and Prerequisites

Google Cloud Platform (GCP) has evolved from being a niche player to a serious competitor to Amazon Web Services and Microsoft Azure. In 2018, research firm Gartner placed Google in the Leaders quadrant in its Magic Quadrant for Cloud Infrastructure as a Service for the first time. In t...

Read more
  • AWS
  • Azure
  • Google Cloud
Khash Nakhostin
— November 13, 2018

Understanding AWS VPC Egress Filtering Methods

Security in AWS is governed by a shared responsibility model where both vendor and subscriber have various operational responsibilities. AWS assumes responsibility for the underlying infrastructure, hardware, virtualization layer, facilities, and staff while the subscriber organization ...

Read more
  • Aviatrix
  • AWS
  • VPC
— November 10, 2018

S3 FTP: Build a Reliable and Inexpensive FTP Server Using Amazon’s S3

Is it possible to create an S3 FTP file backup/transfer solution, minimizing associated file storage and capacity planning administration headache?FTP (File Transfer Protocol) is a fast and convenient way to transfer large files over the Internet. You might, at some point, have conf...

Read more
  • Amazon S3
  • AWS
— October 18, 2018

Microservices Architecture: Advantages and Drawbacks

Microservices are a way of breaking large software projects into loosely coupled modules, which communicate with each other through simple Application Programming Interfaces (APIs).Microservices have become increasingly popular over the past few years. The modular architectural style,...

Read more
  • AWS
  • Microservices
— October 2, 2018

What Are Best Practices for Tagging AWS Resources?

There are many use cases for tags, but what are the best practices for tagging AWS resources? In order for your organization to effectively manage resources (and your monthly AWS bill), you need to implement and adopt a thoughtful tagging strategy that makes sense for your business. The...

Read more
  • AWS
  • cost optimization
— September 26, 2018

How to Optimize Amazon S3 Performance

Amazon S3 is the most common storage options for many organizations, being object storage it is used for a wide variety of data types, from the smallest objects to huge datasets. All in all, Amazon S3 is a great service to store a wide scope of data types in a highly available and resil...

Read more
  • Amazon S3
  • AWS
— September 18, 2018

How to Optimize Cloud Costs with Spot Instances: New on Cloud Academy

One of the main promises of cloud computing is access to nearly endless capacity. However, it doesn’t come cheap. With the introduction of Spot Instances for Amazon Web Services’ Elastic Compute Cloud (AWS EC2) in 2009, spot instances have been a way for major cloud providers to sell sp...

Read more
  • AWS
  • Azure
  • Google Cloud
— August 23, 2018

What are the Benefits of Machine Learning in the Cloud?

A Comparison of Machine Learning Services on AWS, Azure, and Google CloudArtificial intelligence and machine learning are steadily making their way into enterprise applications in areas such as customer support, fraud detection, and business intelligence. There is every reason to beli...

Read more
  • AWS
  • Azure
  • Google Cloud
  • Machine Learning
— August 17, 2018

How to Use AWS CLI

The AWS Command Line Interface (CLI) is for managing your AWS services from a terminal session on your own client, allowing you to control and configure multiple AWS services.So you’ve been using AWS for awhile and finally feel comfortable clicking your way through all the services....

Read more
  • AWS
Albert Qian
— August 9, 2018

AWS Summit Chicago: New AWS Features Announced

Thousands of cloud practitioners descended on Chicago’s McCormick Place West last week to hear the latest updates around Amazon Web Services (AWS). While a typical hot and humid summer made its presence known outside, attendees inside basked in the comfort of air conditioning to hone th...

Read more
  • AWS
  • AWS Summits
— August 8, 2018

From Monolith to Serverless – The Evolving Cloudscape of Compute

Containers can help fragment monoliths into logical, easier to use workloads. The AWS Summit New York was held on July 17 and Cloud Academy sponsored my trip to the event. As someone who covers enterprise cloud technologies and services, the recent Amazon Web Services event was an insig...

Read more
  • AWS
  • AWS Summits
  • Containers
  • DevOps
  • serverless