Friday, November 29, 2019

Changes to the AWS EC2 Instance Metadata Service (IMDS) around the recent Capital One hack

Captial One Bank (1) and 30 different organizations were hacked around end of July, I have written a blog (1) around the same time on how to recreate the hack in your own AWS account and also a few mitigations around the same. Now, AWS has made a few changes to the AWS EC2 Instance Metadata Service (IMDS) around the same (1, 2). Here (Security best practices for the Amazon EC2 instance metadata service) is the AWS re:Invent 2019 session around the same.

The old/existing approach is called IMDSv1 and the new one IMDSv2. Although IMDSv1 solves a few problems like not storing the access keys on the EC2, it bought its own headaches which lead to the hacks. Earlier the access keys for a IAM Role can be got using the below command. But, with the new IMDSv2 the same command would lead to `401 - Unauthorized` error after enabling IMDSv2. This would block SSRF and other such attacks.


Lets try to see it in action with the sequence of steps.

Step 1: Create an Ubuntu EC2 (t2.micro) and login to it via Putty.

Step 2: Create a role (Role4EC2-MetaDataMod) with the below JSON Policy (MetaDataModPolicy). Attach the role to the EC2.

    "Version": "2012-10-17",
    "Statement": [
            "Effect": "Allow",
            "Action": "ec2:ModifyInstanceMetadataOptions",
            "Resource": "*"

Step 3: Execute the below commands on the EC2 instance to configure the AWS CLI.

sudo apt-get update; sudo apt-get install -y python3-pip
pip3 install awscli --upgrade
export PATH="$PATH:/home/ubuntu/.local/bin/"

Configure the AWS CLI, make sure to provide only the region (us-east-1 or some other) and rest of them as blank.

aws configure

Step 4: Execute the below command on the EC2 instance to get the access keys associated with the IAM Role. The access keys would be displayed in the console.


Step 5: Turn off IMDSv1 executing the below command on the EC2 instance, by default both (IMDSv1 and IMDSv2) of them are turned on. Make sure to replace the EC2 instance-id in the below command. With this IMDSv1 is disabled and IMDSv2 is enabled. If IMDSv1 and IMDSv2 both should be enabled for the sake of compatibility with the existing applications the http-token can be set to optional. More on the command syntax and the documentation here.

aws ec2 modify-instance-metadata-options --instance-id i-053cb17f19ca95067 --profile default --http-endpoint enabled --http-token required

Step 6: Now the same command from Step 4 leads to `401 - Unauthorized` error message. as shown in the below screen.

Step 7: With the IMDSv2 a session token has to be got via the HTTP PUT method and then the token used to retrieve the access keys or in-fact with any of the EC2 Instance Metadata Service.

TOKEN=`curl -X PUT "" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
echo $TOKEN
curl -H "X-aws-ec2-metadata-token: $TOKEN"

Now the access keys can be got as shown in the below screen.

How IMDSv2 would prevent the hack from happening?

IMDSv2 would not prevent hacks like the Capital One hack from happening, but it addresses many misconfigurations and application bugs to some extent. There might be still a probability that a WAF is not configured properly to block the HTTP PUT requests with a bug in the application code to get the IMDS token and access the EC2 Metadata Service form outside the EC2.

For those who are hosting applications on AWS, would recommend enabling IMDSv2 and disabling IMDSv1 as mentioned here (1, 2, 3). But, before making the changes make sure the applications on AWS EC2 are compatible with IMDSv2. There won't be any changes required for any applications using the AWS SDK as this internally gets the token and then accesses the EC2 Instance Metadata Service using the token. But, if your application accesses the EC2 Instance Metadata Service using the HTTP endpoint as in the case of Step 4, it would require changes to the code to get the token.

This is a nice step from AWS, but it took more than 100 days for them to come up with a solution to block more such attacks. GCP has also the instance metadata service (1), not really sure if the same vulnerability is in GCP also and how GCP handles it. If you are familiar with how GCP tackles it, please let me know in the comments section and I will update this blog.

Along, the same lines AWS also introduced managed WAF rules (1) to avoid similar attacks.

Thursday, November 28, 2019

Creating a K8S Cluster on AWS using eksctl

As mentioned in the official K8S documentation (1), there are different ways of setting up K8S, some used for learning purpose and some for production setup. Same is the case, there are different ways of setting up K8S on AWS (1). Today we will explore setting up using the eksctl way (1) which is kinda easy. There are lot of tools which make the K8S installation easier, but if you are looking on how to build from scratch then K8S the hard way (1) is the way to go. This will also help with the CKA certification (1).

As of this writing AWS EKS charges $0.20 per hour for each Cluster created, this is independent of the worker nodes in the Cluster. And there is a separate charge for EC2 and EBS for the worker nodes. As the Cluster charges are flat, there is no way to optimize it. So, I used a t2.micro for the worker nodes to optimize the cost. But, it didn't work out as t2.micro supports a maximum of 2 network interfaces and 2 IPv4 addresses per network interface (1). This boils to the fact that t2.micro can have maximum of 4 IP addresses.

Whenever a new Pod is created on the worker node, AWS allocates a new IP address from the VPC subnet. As mentioned above, t2.micro can have a maximum of 4 IP address, one of which is attached  to the EC2 itself. There are 3 more IP address left, which can be allocated to the Pods on the worker nodes. This makes is difficult to use the t2.micro EC2 Instance which falls under the AWS free tier, as some of the pods are used by K8S installation itself. The below steps would be using a single EC2 Spot Instance (t3.small or t2.medium) for the worker nodes.

Also, AWS has recently introduced managed Node Groups (1). With this most of the grunt work like upgrading K8S on the worker nodes is managed by AWS with no additional cost. So, we have node-groups which have to be managed by the customer and the new managed-node-groups which are managed by AWS.

Node-groups had been there for some time and support EC2 Spot Instances, but managed-node-groups is relatively new and looks like it doesn't support the EC2 Spot Instances as of now.

Here are the steps for creating an AWS EKS Cluster using the eksctl. References (1, 2, 3)

Step 1: Create an Ubuntu EC2 Instance (t2.micro) and connect to it. On this Instance we would be running the eksctl and other commands for creating the AWS EKS Cluster.

Step 2: Execute the below commands on Ubuntu to create key pairs and install AWS CLI, aws-iam-authenticator, kubectl and eksctl softwares.

#generation of ssh keypairs to be used by the worker K8S Instances
ssh-keygen -f .ssh/id_rsa

#installation of the required software
curl -s | sudo apt-key add -
echo "deb kubernetes-xenial main" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list

sudo apt-get update
sudo apt-get install -y python3-pip kubectl

curl -o aws-iam-authenticator
chmod +x ./aws-iam-authenticator
sudo mv ./aws-iam-authenticator /usr/local/bin

pip3 install awscli --upgrade
export PATH="$PATH:/home/ubuntu/.local/bin/"

curl --silent --location "$(uname -s)_amd64.tar.gz" | tar xz -C /tmp
sudo mv /tmp/eksctl /usr/local/bin

Step 3: Get the access keys for the root and provide them using the `aws configure` command.

Step 4: Create a cluster.yaml file for a nodegroup or managed nodegroup and start creating the Cluster. The yaml configuration file for both of them has been mentioned below. It would take 10-15 minutes time. This configuration will use existing VPC, note to change the availability zone and subnet-id in the yaml to where the worker nodes have to be deployed.

eksctl create cluster -f cluster.yaml

Check the number of nodes in the cluster.

kubectl get nodes

Once the cluster has been created the below command can be used to login to each of the worker nodes. Make sure to replace the EC2 IP of the worker nodes.

ssh -i ./.ssh/id_rsa ec2-user@

Step 5: Create a deployment with 2 ngnix pods and get the pod details.

kubectl run nginx --image=nginx -r=2
kubectl getpods -o wide

Step 6: Delete the Cluster. Again, the deletion of the Cluster would take 10-15 minutes of time. The progress would be displayed in the console.

eksctl delete cluster --wait --region=us-east-1 --name=praveen-k8s-cluster

Step 7: Make sure to terminate the EC2 Instance created in Step 1.

# An example of ClusterConfig showing nodegroups with spot instances
kind: ClusterConfig

    name: praveen-k8s-cluster
    region: us-east-1

      us-east-1a: { id: subnet-32740f6e }
      us-east-1b: { id: subnet-78146a1f }
      us-east-1c: { id: subnet-16561338 }

    - name: ng-1
        allow: true
      minSize: 1
      maxSize: 2
        instanceTypes: ["t3.small", "t3.medium"]
        onDemandBaseCapacity: 0
        onDemandPercentageAboveBaseCapacity: 0
        spotInstancePools: 2

# An example of ClusterConfig showing managed nodegroups with spot instances
kind: ClusterConfig

      us-east-1a: { id: subnet-32740f6e }
      us-east-1b: { id: subnet-78146a1f }
      us-east-1c: { id: subnet-16561338 }

    name: praveen-k8s-cluster
    region: us-east-1

  - name: managed-ng-1
    instanceType: t3.small
    minSize: 1
    maxSize: 1
    desiredCapacity: 1
    volumeSize: 20
      allow: true

Screen shots from the above sequence of steps

1. eksctl uses CloudFormation templates to create the EKS Cluster and the NodeGroup. The status of the Stack creation can be monitored from the CloudFomation Management Console.

2. The above mentioned CloudFormation templates create a  EKS Cluster and the NodeGroup as shown in the below EKS Management Console.

3. One of the EC2 Instance was created in Step 1. Other one was created by eksctl for the NodeGroup worker nodes.

4. Interaction with the Cluster using kubctl to
     - get the nodes
     - create a deployment and get the list of pods

 5. Finally, deletion of the EKS Cluster and the NodeGroup.


As shown above eksctl provides an easy way to create a K8S Cluster in the AWS easily. The same thing can be done with the AWS Management Console also (1). Doing with the AWS Management Console is more of a manual way, which gives us clarity on the different resources getting created and how they interact with each other.

Monday, November 25, 2019

Interacting with AWS S3 using Java on EC2

Many web applications are being built on top of the Cloud Infrastructure. Let's take the case of a photo sharing website like Instagram. The website can be deployed on EC2 and let it interact with S3 to store the pictures. Building a full fledged photo sharing website is beyond the scope of this blog, but we will explore how to execute a Java program on top of EC2 to interact with S3.

Here are the sequence of steps with the assumption that the reader is familiar with the basics of AWS. Also, all the steps in this blog will fall under the free tier.

Step 1: Create an Ubuntu EC2 instance (t2.micro) and connect to it via Putty or any other means. For the EC2 SecurityGroup the port 22/SSH has to be opened in the inbound.

Step 2: Get the list of softwares and install maven, java-common by executing the below commands on Ubuntu EC2 instance.
sudo apt-get update
sudo apt install maven java-common

Step 3: By default EC2 has no permission to interact with S3 or in fact with any other service. Create a role with AmazonS3FullAccess policy attached. This policy gives full permissions to all the folders and files in S3, which is not recommended. It's always best to give limited privileges by creating a custom policy and attaching it to the EC2.

Step 4: Attach the policy to the EC2. Now the EC2 has permissions to interact with S3.

Step 5: Get the link to the latest Amazon Corretto Java from this link and replace the link in the below wget command. Execute the wget commands in the Ubuntu EC2 to download Amazon Corretto Java. OpenJDK or Oracle JDK can also be used.


Install Amazon Corretto Java on Ubuntu using the dpkg command as an administrator.

sudo dpkg --install java-11-amazon-corretto-jdk_11.0.5.10-1_amd64.deb

Step 6: Create basic maven package using the below command. This will create a myapp folder with pom.xml, and other artifacts.

mvn -B archetype:generate \
  -DarchetypeGroupId=org.apache.maven.archetypes \
  -DgroupId=org.example.basicapp \
Step 6: In the myapp folder, remove the pom.xml and replace with pom.xml mentioned here. Replace the exec-maven-plugin (1) and aws-java-sdk (1) versions with the latest versions got from the maven repository in the pom.xml file.

Step 7: Remove the file created by maven.

cd /home/ubuntu/myapp/src/main/java/org/example/basicapp

Create a file by the with the java program mentioned here in the above folder.

Step 8: Execute the below commands to compile the program and execute it.

cd ~/myapp
mvn clean compile exec:java

Step 9: Note that interaction with the S3 happening in the output of the above command towards the end as shown below. A bucket is created in S3, a file uploaded/downloaded. The S3 cleanup is also done in the Java program, so when seen in the S3 Management Console there won't be any changes.

Modify the Java program not to do the S3 cleanup and the changes done by the Java program can be seen in the S3 Management Console.

Friday, November 22, 2019

How to integrate different AWS services to create interesting applications?

Cloud (AWS or any other) provides a cost efficient and quicker approach of deploying applications. For this AWS provides a myriad of services including EC2, S3, RDS, Rekognition and many more. Each of these individual services are powerful enough. For ex., EC2 provides virtual servers from 1/2 GB (t2.nano) to 3,904 GB (x1e.32xlarge) of RAM. The high end memory instances are used for in-memory databases and analytics. What makes AWS more powerful is integrating these services to meet the business requirements and save cost.

The below web architecture uses WAF, CloudFront, ELB, EC2, EBS, RDS and Auto Scaling services. The architecture can also use Serverless technologies like Lambda, DynamoDB and others to make the application easy to develop/maintain, highly available and scalable.

This blog is all about references with detailed instructions on how to integrate different AWS services to build very interesting applications. It would be a good learning experience for those who are getting started with AWS to try the below and figure out what AWS has to offer.

Architect an Airline Booking Application, End-to-End (incomplete article, but interesting one)

Controlling your AWS costs by deleting unused Amazon EBS volumes

Creating image thumbnails using Lambda and S3 (Serverless)

Converting Airline dataset from the row format to columnar format using AWS EMR

Processing the Airline dataset with AWS Athena

Exploring images on social media using Amazon Rekognition and Amazon Athena

Creating an Amazon Rekognition Lambda Function for video label detection

How to Optimize and Visualize Your Security Groups

Build a Serverless Web Application

How to add file upload features to your website with AWS Lambda and S3

Build a Modern Web Application

Error Processor Sample Application for AWS Lambda

Enable RESTful API to manage the Wild Rydes Unicorn Stable

Serverless Image Handler

How AWS built a production service using serverless technologies

Building a serverless weather bot with two-way SMS, AWS SAM, and AWS Lambda

Please add any additional references in the comments and I would be adding them here.