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
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
Joe Nemer
Joe Nemer
— September 12, 2019

Real-Time Application Monitoring with Amazon Kinesis

Amazon Kinesis is a real-time data streaming service that makes it easy to collect, process, and analyze data so you can get quick insights and react as fast as possible to new information.  With Amazon Kinesis you can ingest real-time data such as application logs, website clickstre...

Read more
  • amazon kinesis
  • AWS
  • Stream Analytics
  • Streaming data
Joe Nemer
Joe Nemer
— September 6, 2019

Google Cloud Functions vs. AWS Lambda: The Fight for Serverless Cloud Domination

Serverless computing: What is it and why is it important? A quick background The general concept of serverless computing was introduced to the market by Amazon Web Services (AWS) around 2014 with the release of AWS Lambda. As we know, cloud computing has made it possible for users to ...

Read more
  • AWS
  • Azure
  • Google Cloud Platform
Joe Nemer
Joe Nemer
— September 3, 2019

Google Vision vs. Amazon Rekognition: A Vendor-Neutral Comparison

Google Cloud Vision and Amazon Rekognition offer a broad spectrum of solutions, some of which are comparable in terms of functional details, quality, performance, and costs. This post is a fact-based comparative analysis on Google Vision vs. Amazon Rekognition and will focus on the tech...

Read more
  • Amazon Rekognition
  • AWS
  • Google Cloud Platform
  • Google Vision
Alisha Reyes
Alisha Reyes
— August 30, 2019

New on Cloud Academy: CISSP, AWS, Azure, & DevOps Labs, Python for Beginners, and more…

As Hurricane Dorian intensifies, it looks like Floridians across the entire state might have to hunker down for another big one. If you've gone through a hurricane, you know that preparing for one is no joke. You'll need a survival kit with plenty of water, flashlights, batteries, and n...

Read more
  • AWS
  • Azure
  • Google Cloud Platform
  • New content
  • Product Feature
  • Python programming
Joe Nemer
Joe Nemer
— August 27, 2019

Amazon Route 53: Why You Should Consider DNS Migration

What Amazon Route 53 brings to the DNS table Amazon Route 53 is a highly available and scalable Domain Name System (DNS) service offered by AWS. It is named by the TCP or UDP port 53, which is where DNS server requests are addressed. Like any DNS service, Route 53 handles domain regist...

Read more
  • Amazon
  • AWS
  • Cloud Migration
  • DNS
  • Route 53
Alisha Reyes
Alisha Reyes
— August 22, 2019

How to Unlock Complimentary Access to Cloud Academy

Are you looking to get trained or certified on AWS, Azure, Google Cloud Platform, DevOps, Cloud Security, Python, Java, or another technical skill? Then you'll want to mark your calendars for August 23, 2019. Starting Friday at 12:00 a.m. PDT (3:00 a.m. EDT), Cloud Academy is offering c...

Read more
  • AWS
  • Azure
  • cloud academy content
  • complimentary access
  • GCP
  • on the house
Avatar
Michael Sheehy
— August 19, 2019

What Exactly Is a Cloud Architect and How Do You Become One?

One of the buzzwords surrounding the cloud that I'm sure you've heard is "Cloud Architect." In this article, I will outline my understanding of what a cloud architect does and I'll analyze the skills and certifications necessary to become one. I will also list some of the types of jobs ...

Read more
  • AWS
  • Cloud Computing
Avatar
Nitheesh Poojary
— August 19, 2019

Boto: Using Python to Automate AWS Services

Boto allows you to write scripts to automate things like starting AWS EC2 instances Boto is a Python package that provides programmatic connectivity to Amazon Web Services (AWS). AWS offers a range of services for dynamically scaling servers including the core compute service, Elastic...

Read more
  • Automated AWS Services
  • AWS
  • Boto
  • Python
Avatar
Andrew Larkin
— August 13, 2019

Content Roadmap: AZ-500, ITIL 4, MS-100, Google Cloud Associate Engineer, and More

Last month, Cloud Academy joined forces with QA, the UK’s largest B2B skills provider, and it put us in an excellent position to solve a massive skills gap problem. As a result of this collaboration, you will see our training library grow with additions from QA’s massive catalog of 500+...

Read more
  • AWS
  • Azure
  • content roadmap
  • Google Cloud Platform
Avatar
Adam Hawkins
— August 9, 2019

DevSecOps: How to Secure DevOps Environments

Security has been a friction point when discussing DevOps. This stems from the assumption that DevOps teams move too fast to handle security concerns. This makes sense if Information Security (InfoSec) is separate from the DevOps value stream, or if development velocity exceeds the band...

Read more
  • AWS
  • cloud security
  • DevOps
  • DevSecOps
  • Security
Avatar
Stefano Giacone
— August 8, 2019

Test Your Cloud Knowledge on AWS, Azure, or Google Cloud Platform

Cloud skills are in demand | In today's digital era, employers are constantly seeking skilled professionals with working knowledge of AWS, Azure, and Google Cloud Platform. According to the 2019 Trends in Cloud Transformation report by 451 Research: Business and IT transformations re...

Read more
  • AWS
  • Cloud skills
  • Google Cloud
  • Microsoft Azure