Home/Server & Website Managed Operations/Phone Call Alerts for AWS Account Security Events Using Amazon Polly
Server & Website Managed Operations

Phone Call Alerts for AWS Account Security Events Using Amazon Polly

Security of your AWS account is paramount. It is critical to stay informed about all the latest security-related events in your AWS account. You can receive alerts through various channels, such as email or SMS; however, in this blog post, I will demonstrate how to receive voice alerts on your mobile phone using Amazon AI services (such as Amazon Polly) along with any cloud-based communication platform (such as Twilio).

Amazon Polly is a service that converts text into lifelike speech, enabling you to build chat-enabled applications and create an entirely new category of voice-enabled products. It uses deep learning technology to synthesize speech that sounds like a human voice. The service offers a variety of voices in different languages.

For IT security professionals who are away from their desks, phone call alerts regarding security events in their AWS accounts can be extremely helpful. These security events can be customized based on severity and priority. High-severity and high-priority security events can be routed to a system that triggers phone call alerts.

For phone call alerts, I use Twilio, which provides API capabilities for voice, video, and messaging. When a security event occurs in a given AWS account, the Twilio platform enables programmatic API calls to initiate phone calls. Amazon Polly converts these text alerts into voice messages played over the phone.

Solution Overview

The solution consists of two systems, as shown in the following architecture diagram:

  • Event Detection and Notification System
  • Text-to-Speech Conversion System

The Event Detection and Notification System is decoupled from the Text-to-Speech Conversion System because the latter is generic and can be applied to any user-defined event detection. In this blog post, as a solution example, I focus on the Text-to-Speech Conversion System and utilize the Event Detection and Notification System introduced in my previous blog post.

polly-voice-alerts-1

As illustrated in the architecture diagram, the alert message from Step 3 is published to an Amazon SNS topic, which triggers a Lambda function in our Text-to-Speech Conversion System.

  1. This Lambda function parses the subject of the SNS alert message and uses Amazon Polly to convert the text into a speech file.
  2. This speech file is stored in an Amazon S3 bucket.
  3. Twilio uses the location of the speech file to place an outbound call to the relevant party and play the audio file. Note that you can apply an Amazon S3 object lifecycle policy to these files based on your needs after they have been used for outbound calls.

Demo

Prerequisites

  • An event detection and notification system. For example, you can set up monitoring and notifications for AWS account root user activity.
  • You will need a Twilio account authentication token to make API calls. You can register for a free (trial) Twilio account here.polly-voice-alerts-2
  • A phone number is assigned to your Twilio account. This is the caller ID number that appears when you receive call alerts.
    polly-voice-alerts-3
  • If you are using a trial account, you must verify the “To” phone number.
    polly-voice-alerts-4

Deployment Steps

The following deployment steps will deploy the text-to-speech system as shown in the diagram below.

polly-voice-alerts-5

  1. In the AWS CloudFormation console, select Create Stack. Use the CloudFormation JSON template launchstack. Select Next. (Note: Amazon Polly is not supported in China or AWS GovCloud (US) regions.)
  2. Create the stack in the region where you want to deploy the event detection and notification system.
  3. Enter the following parameter details, select Next, and then select Next:
    1. ToPhoneNo: The phone number that Twilio will call. Prefix the phone number with “+CountryCode”, e.g., +14561237890.
    2. FromPhoneNo: The virtual phone number used by Twilio to make the call. You can find this information in your Twilio account. See the “Prerequisites” section.
    3. TwilioAccntSid: Enter the Twilio Account SID. This is provided when you register at https://www.twilio.com/.
    4. TwilioAuthToken: Enter the Twilio Authentication Token.
    5. BucketName: Enter the name of the bucket you want to create. This bucket will store the voice files for event alerts.
    6. PollyVoiceId: Enter the Amazon Polly voice ID you wish to use for incoming alert calls. The default voice is “Amy”.
    7. LambdaS3Bucket: The name of the Amazon S3 bucket storing the Lambda function zip file.
    8. LambdaS3Key: The name of the Lambda function zip file. This is the full path of the S3 object, including the prefix. For example, “dir1/dir2/lambdafunction.zip”. The Lambda function zip file can be downloaded from the link in the Lambda function section of this blog post.
  4. Select Capabilities Acknowledgement and then Create. This field grants the stack permissions to create IAM roles and policies. These roles and policies are used by the Lambda function to perform specific actions, such as publishing messages to an SNS topic or listing account aliases.
  5. Once the CloudFormation stack is complete, check the Lambda function name provided in the Outputs tab.
  6. Next, we will add a trigger to this Lambda function. Go to the Lambda console, select the newly created Lambda function, then choose Triggers and Add trigger.
  7. In the trigger configuration box, select SNS, and choose the SNS topic from your “Event Detection and Notification” system that you want to use for phone calls. Select Submit.
    polly-voice-alerts-6
  8. The Lambda function is now ready to be triggered by the SNS topic from your “Event Detection and Notification” system. You can add as many triggers as needed for various event detection and notification systems. More information on triggering AWS Lambda can be found here.

SNS Triggering the Lambda Function

When triggered, the Text-to-Speech Lambda function parses the subject of the SNS message. It then passes the text from this subject field to the Amazon Polly service to convert it into a voice file. Once the text is converted into a voice file, the file is stored in the S3 bucket created earlier by the CloudFormation stack.

It then invokes the Twilio API to place a phone call and play the event notification audio file from the S3 bucket.

import boto3
import os
from contextlib import closing
import botocore.session
from botocore.exceptions import ClientError
session = botocore.session.get_session()
import logging
import uuid
import twilio
from twilio.rest import Client

import urllib
from urllib import request, parse
from urllib.parse import quote

logging.basicConfig(level=logging.DEBUG)
logger=logging.getLogger(__name__)

def lambda_handler(event, context):
    logger.setLevel(logging.DEBUG)
    logger.debug("Event is --- %s" %event)
    speak = event["Records"][0]["Sns"]["Subject"]
	
	# Convert the SNS message subject text to an mp3 voice file.
	
    polly = boto3.client('polly')
    response = polly.synthesize_speech( OutputFormat='mp3',
                                        Text = 'ALERT !' + speak,
                                        SampleRate='22050',
                                        VoiceId = os.environ['VoiceId']  
                                        )
    logger.debug("Polly Response is-- %s" %response)
    id = str(uuid.uuid4())
    logger.debug("ID= %s" %id)
    
    
    # Save the voice stream returned by Amazon Polly to Lambda's temporary
    # directory. If there are multiple text blocks, the voice streams
    # will be merged into a single file.
    if "AudioStream" in response:
        with closing(response["AudioStream"]) as stream:
            filename=id + ".mp3"
            output = os.path.join("/tmp/",filename)
            with open(output, "wb") as file:
                file.write(stream.read())
	
	# Upload the voice MP3 file to the S3 location
	
    s3 = boto3.client('s3')
    s3upload_response = s3.upload_file('/tmp/' + filename, os.environ['BUCKET_NAME'],filename,ExtraArgs={"ContentType": "audio/mp3"})
    logger.debug("S3 UPLOAD RESPONSE IS--- %s" %s3upload_response)
    s3.put_object_acl(ACL='public-read', Bucket=os.environ['BUCKET_NAME'], Key= filename)
    
    location = s3.get_bucket_location(Bucket=os.environ['BUCKET_NAME'])
    logger.debug("Location response is -- %s" %location)
    region = location['LocationConstraint']
    
    if region is None:
    	url_begining = "https://s3.amazonaws.com/"
    else:
    	url = url_begining + str(os.environ['BUCKET_NAME']) + "/" + filename
    
    url = '{}/{}/{}'.format(s3.meta.endpoint_url, os.environ['BUCKET_NAME'], filename)
    
    # Encode URL
    encode_url = quote(url, safe='')
    logger.debug("ENCODED URL-- %s" %encode_url)
    
    # Get these credentials from http://twilio.com/user/account
    account_sid = os.environ['account_sid']
    auth_token = os.environ['auth_token']
    client = Client(account_sid, auth_token)
    
    # Make a phone call using Twilio
    call_response = client.api.account.calls.create(to=os.environ['ToPhoneNo'],  # Any phone number
    												from_=os.environ['FromPhoneNo'], # Must be a valid Twilio number
    												url="http://twimlets.com/message?Message%5B0%5D=" + encode_url + <span

This AWS Lambda code zip file can be downloaded here and used for CloudFormation stack deployment.

Solution Verification

In the following example voice clips, I will demonstrate that after deploying an event detection system (to notify about root API activity) and integrating it with a text-to-speech system, I receive phone call alerts whenever root API activity is detected in the AWS account.

Example of a phone call alert triggered by console login via root credentials:

Example phone-call alert for an AWS account security event via Amazon Polly Listen now

Voice provided by Amazon Polly

Then, I create an Amazon EBS volume using root credentials and receive another phone call alert.

Example phone-call alert for an AWS account security event via Amazon Polly Listen now

Voice provided by Amazon Polly

Conclusion

In this post, I demonstrated how to create a phone call audio alerting system that can be integrated into existing alerting and monitoring systems. This framework is useful for obtaining near-real-time phone call alerts for critical events within an AWS account.

For further reading, we recommend the following articles:

FREE CHECKUP

Free server checkup

We will send a problem checklist and remediation advice within one business day — no obligation to engage.

135 410 16684
Weekdays Mon – Fri 10:00 – 22:00 (UTC+8) · 7×24 emergency response
Call now
CONTACT

Contact Us

How can we help?

* Required