Enhancing Security for Toll SDK on AWS Infrastructure

Securing Your TollGuru SDK: A Comprehensive Guide to Implementing HTTPS and Managing Security Groups in Your AWS Deployment

MapUp Team
TollGuru
9 min readOct 10, 2023

--

Protecting your TollGuru SDK deployment on AWS is paramount for data integrity and consistent service access. This guide will walk you through essential steps to enhance the security of your TollGuru SDK setup, focusing primarily on two key areas.

  1. Setting up SSL Certificate for HTTPS Usage
  2. Attaching Security Groups for Inbound and Outbound Restrictions

Note: This article is a continuation of our previous guide on deploying the TollGuru SDK on AWS. If you haven’t set up the TollGuru SDK on your AWS cloud yet, please refer to the TollGuru SDK deployment guide before proceeding with the security setup.

Secure TollGuru SDK with HTTPS Configuration

Let’s start with fortifying your data security by walking through the crucial steps to enable HTTPS for the TollGuru SDK. This will ensure encrypted and secure data transmission through SSL certificate integration.

Prerequisites:

  • Buy a valid domain, if not already done so.
  • Make sure that your hosted zone is properly configured in AWS Route 53.

Steps:

1. Configure an AWS subdomain to point to the load balancer of your TollGuru SDK service:

  • Navigate to AWS Route 53 and select your hosted zone (e.g., “example.com”).
  • Create a new Record Set with the Name set to your desired subdomain (e.g., “sdk”). Set Type to “A — IPv4 address”, toggle Alias to “Yes”, and pick your ELB from the Alias Target dropdown.
  • Confirm with “Create records” to point the subdomain to the ELB.
Configure a subdomain on Route 53

2. Generate ACM Certificate

Navigate to the AWS Certificate Manager (ACM) and create an SSL certificate for your new subdomain created in the earlier step.

Request public certificate through AWS ACM

3. Apply Certificate to Kubernetes Configuration

We get an Amazon Resource Name (ARN) for the certificate generated by ACM.

Apply certificate to Kubernetes configuration

Add this ARN to the relevant section of your Kubernetes service YAML file. Here’s an example script of how to configure your Kubernetes service file (YAML) after inserting the ARN for the SSL certificate and adjusting the ports.

  • Replace <YOUR_ACM_ARN> with the ARN generated above
  • Replace subnets <PUBLIC_SUBNET_1>, <PUBLIC_SUBNET_2> IDs generated in Step 3 of the Toll SDK Installation Guide
  • Change port 80 to 443
    along with other highlighted information based on your requirements:
apiVersion: v1
kind: Service
metadata:
name: tollguru-sdk-loadbalancer
namespace: tollguru
annotations:
service.beta.kubernetes.io/aws-load-balancer-ssl-cert: <YOUR_ACM_ARN>
service.beta.kubernetes.io/aws-load-balancer-backend-protocol: http
service.beta.kubernetes.io/aws-load-balancer-ssl-ports: "443"
service.beta.kubernetes.io/aws-load-balancer-subnets: "<PUBLIC_SUBNET_1>,<PUBLIC_SUBNET_2>"
spec:
selector:
app: tollguru-sdk
ports:
- protocol: TCP
port: 443
targetPort: 3001
type: LoadBalancer

Setting Up Security Groups and DNS Firewall for Inbound and Outbound Traffic

Boost data security by fine-tuning both inbound and outbound traffic using strategic Security Group settings and DNS Firewall in the TollGuru SDK, ensuring comprehensive access control.

Modify Security Inbound Rules to Restrict Access to Elastic Load Balancer (ELB):

Follow the steps given below to modify the security inbound rules

Step 1: Access the EC2 Dashboard

  • Navigate to the AWS Management Console and access the EC2 dashboard.
  • Locate the required ELB and click on ‘Load Balancers’ in the left navigation pane to see a list of load balancers.
  • Choose the ELB to which you want to apply the access restrictions.
Display load balancers

Step 2: Modify Security Groups

  • Find the ‘Security groups’ section under the ‘Description’ tab.
  • To access the ELB’s configuration settings, click the security group associated with it.
Display security groups
  • Navigate to the ‘Inbound rules’ tab.
  • Click on ‘Edit inbound rules’ to change existing rules or add new rules based on the access restrictions required.
Modify security group
  • To control access to the ELB, define the protocol, port range, and source IP addresses or CIDR blocks.
  • To apply the changes, click ‘Save rules’.
Set security group inbound rules

Implement DNS Firewall for Outbound Traffic:

If you’ve followed the Toll SDK Deployment guide, the DNS Firewall for outbound traffic would have already been set up as an integral part of the deployment process.

Domains Allowed for Outbound Traffic:

  • *.mapup.ai
  • *.amazonaws.com
  • *.cloudfront.net
  • *.internal
  • *.svc.cluster.local
  • *.docker.io
  • k8s.gcr.io
  • *.k8s.gcr.io

Ensure that these domains are whitelisted in the DNS Firewall configuration to guarantee smooth communication and operations with essential services.

Modifying the Whitelist

If there are other trusted domains specific to your operations, you have the flexibility to add them to the whitelist in the Terraform script. However, exercise caution when adding new domains. Ensure that they are trusted and necessary for your operations. A careless addition can introduce vulnerabilities or unwanted traffic, compromising the security of your deployment.

How to Modify in Terraform (Setup.tf):

Look for a block in your ‘setup.tf’ YAML script similar to the one below:

resource "aws_route53_resolver_firewall_domain_list" "example_resource_name" {
name = "example_resource_name"
domains = [
"*.mapup.ai",
"*.amazonaws.com",
"*.cloudfront.net",
"*.internal",
"*.svc.cluster.local",
"*.docker.io",
"k8s.gcr.io",
"*.k8s.gcr.io"
]
}

Replace example_resource_name with the relevant resource name in your setup. To add new domains, simply add them to the domains list.

Authentication Setup and Testing For TollGuru SDK

This document outlines the process for setting up authentication for an existing API endpoint using Amazon Cognito. The setup process is divided into two main sections:

  • Setting up Authentication using AWS Cognito and API Key
  • Testing the Authentication setup

Pre-requisites

  • An AWS account with access to Amazon Cognito
  • An existing Cognito user pool

Section 1: Setting AWS Cognito Authentication

Step 1: Retrieve Cognito URL

You will need the Cognito URL to configure the authentication. The URL follows this pattern:

https://cognito-idp.<aws-region>.amazonaws.com/<cognito-pool-id>/.well-known/jwks.json

Replace <aws-region> with your AWS region and <cognito-pool-id> with your Cognito user pool ID.

Step 2: Adding and Configuring Environment Variables

Configuring the SDK Config Map

  1. Locate the 01-tollguru-sdk-config-map.yml file in your project repository.
  2. Add the following environment variables related to Cognito (replace the placeholders with actual values):
AUTHENTICATION_TYPE: “COGNITO”
COGNITO_PUBLIC_KEYS_URL: “https://cognito-idp.<aws-region>.amazonaws.com/<cognito-pool-id>/.well-known/jwks.json"

Save the file with the changes.

Configuring the SDK Deployment

  1. Open the 04-tollguru-sdk-deployment.yml file.
  2. Add the necessary environment variables as you did in the config map.
  3. Ensure that the deployment is configured to use the updated config map.
- name: AUTHENTICATION_TYPE
valueFrom:
configMapKeyRef:
name: tollguru-sdk
key: AUTHENTICATION_TYPE
— name: COGNITO_PUBLIC_KEYS_URL
valueFrom:
configMapKeyRef:
name: tollguru-sdk
key: COGNITO_PUBLIC_KEYS_URL

Save the file with the changes.

Step 3: Applying Configuration Changes

kubectl apply -f ./01-tollguru-sdk-config-map.yml
kubectl apply -f ./04-tollguru-sdk-deployment.yml

Section 2: Setting API Authentication

Step 1: Adding API keys in Secret Variables

Configuring the SDK Secret Variables

  1. Locate the 02-tollguru-sdk-secret-vars.yml file in your project repository.
AUTH_API_KEYS: “<API_KEY_1>,<API_KEY_2>”

Step 2: Adding and Configuring Environment Variables

Configuring the SDK Config Map:

  1. Locate the 01-tollguru-sdk-config-map.yml file in your project repository.
  2. Add the following environment variables related to Cognito (replace the placeholders with actual values):
AUTHENTICATION_TYPE: “APIKEY”

Save the file with the changes.

Note: If AWS Cognito has already been added as an authentication type, then use comma-separated values in order to use both authentication types, i.e

AUTHENTICATION_TYPE: “COGNITO,APIKEY”

Configuring the SDK Deployment:

  1. Open the 04-tollguru-sdk-deployment.yml file.
  2. Add the necessary environment variables as you did in the config map.
  3. Ensure that the deployment is configured to use the updated config map.
- name: AUTH_API_KEYS
valueFrom:
secretKeyRef:
name: my-secret
key: AUTH_API_KEYS

Save the file with the changes.

Step 3: Applying Configuration Changes

kubectl apply -f ./01-tollguru-sdk-config-map.yml
kubectl apply -f ./02-tollguru-sdk-secret-vars.yml
kubectl apply -f ./04-tollguru-sdk-deployment.yml

Testing AWS Cognito Authentication

This section provides a step-by-step process for testing your AWS Cognito Authentication setup using a Python script to generate tokens.

Pre-requisites

  • AWS Account: You must have an AWS account set up with access to the AWS Cognito service.
  • User Pool: A Cognito User Pool should be configured, and you should have the necessary Client ID.
  • Python Environment: Ensure Python is installed on your system and you are able to run Python scripts.
  • Boto3 Library: Install the Boto3 library for AWS in Python by running:
pip install boto3

Follow the steps below to prepare the script for execution:

  • Initialize Boto3 Cognito Client:
    Initialize the Cognito client by specifying the region your User Pool is located in by replacing the REGION_NAME placeholder.
  • Set Authentication Parameters:
    Replace the placeholders with the appropriate USERNAME and PASSWORD that you wish to authenticate.
  • Provide Your Client ID:
    Replace the placeholder CLIENT_ID with the Client ID of your User Pool App Client without a client secret.

Script to generate access tokens for authentication:

import boto3
# Initialize the Cognito client
cognito = boto3.client('cognito-idp', region_name='<REGION_NAME>')
# Authenticate the user and obtain tokens
response = cognito.initiate_auth(
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': '<USERNAME>',
'PASSWORD': '<PASSWORD>'
},
ClientId='<CLIENT_ID>'
)
# Access the tokens
id_token = response['AuthenticationResult']['IdToken']
access_token = response['AuthenticationResult']['AccessToken']
refresh_token = response['AuthenticationResult']['RefreshToken']
print("ID Token:", id_token)
print("Access Token:", access_token)
print("Refresh Token:", refresh_token)

Placeholders:

  • <REGION_NAME>: AWS region of your Cognito User Pool (e.g., us-east-1).
  • <USERNAME>: Username of the Cognito user.
  • <PASSWORD>: Password of the Cognito user.
  • <CLIENT_ID>: Client ID of the App Client in your Cognito User Pool.

Testing Steps:

  • Once you have filled in the information needed for generating the tokens for authentication, replace the file_name placeholder with the name of your script and execute the script:
python <file_name.py>

If you are using Python 3:

python3 <file_name.py>

Check the Output

  • If the authentication is successful, the ID, Access, and Refresh tokens will be printed to the console.
  • Note down the Access Token as this is what will be used to make authenticated requests to the TollGuru SDK endpoints.
  • Note: Access Tokens issued by AWS Cognito are valid for 1 hour (3600 seconds) by default. This duration can be configured in the AWS Cognito User Pool settings under the “App clients” section to suit your application’s security needs.

Error Handling

If you encounter errors, ensure your User Pool, App Client settings, and user credentials are correct.

Validate Tokens

Once you have the tokens, follow the next section to make Authenticated requests to the TollGuru SDK endpoints.

Making Authenticated Requests

With Amazon Cognito Access Token

Include the Access token generated in the previous section in the authorization header as a bearer token:

Authorization: Bearer <cognito_access_token>

Sample cURL (Replace base_url and cognito_access_token placeholders):

curl --location '<base_url>/polyline-map-matching' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <cognito_access_token>' \
--data-raw '{
"polyline": "_f`GwjixRSe@MIIEICGAIA_Al@MHIDe@VKFm@f@SLKLCFEHCF?HAF?NTH\\N`Ab@x@b@`@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s@}AMWk@uAK[GOIa@I_@EYCQGm@Co@A]?M?O@]@UD[Fa@D]FWLk@Pg@N]P_@N[dBaDpBkD@AdCsEbAkBd@_APa@HUHUVaAES?EAE?E?EJ_ADk@@W@UEaAAOIm@M_ABCKa@CMESA?EMK[KWCIACAAKWs@sAq@gAEIEGS[S]GMGKWa@g@mAe@eA]OSIEAG?WAG@OBIBGDGF[b@IJKFk@`Au@pA}@~AMXcC~E_BnCY`@MT",
"locTimes": [
[
0,
1660110342
],
[
30,
1660110642
],
[
60,
1660110942
],
[
232,
1660111182
]
],
"vehicle": {
"type": "2AxlesAuto"
},
"fuelOptions": {
"fuelCost": {
"value": 3.72,
"currency": "USD",
"units": "$/gallon"
},
"fuelEfficiency": {
"city": 23.4,
"hwy": 30,
"units": "mpg"
}
}
}'

With API Key (Optional):

Include the API key in the request header:

X-API-KEY: <your_api_key>

Conclusion:

By establishing robust security inbound rules, you effectively restrict access to your ELB. Simultaneously, the DNS Firewall ensures that outbound traffic communicates only with trusted domains. Together, these measures fortify your TollGuru SDK services by regulating both incoming and outgoing traffic. This approach significantly enhances the security posture of your AWS infrastructure, safeguarding data and ensuring reliable operations.

--

--