AWS - SNS

Amazon Web Services Simple Notification Service (SNS).

IT Services · AWS - SNS

Details

IDAWS - SNS
ProviderAmazon
CategoryIT Services
From Version6.5.0
Docker Imagedemisto/boto3py3:1.0.0.10221838
Supported ModulesAgentix XSIAM

README

Amazon Web Services Simple Notification Service (SNS)

For more information regarding the AWS SNS service, please visit the official documentation found here.

For detailed instructions about setting up authentication, see: AWS Integrations - Authentication.

Configure AWS - SNS in Cortex

Parameter Description Required
AWS Default Region   True
Role Arn When using Access Key and Secret Key, there is no need to use Role Arn False
Role Session Name   False
Access Key   True
Secret Key   True
Role Session Duration   False
Timeout The time in seconds till a timeout exception is reached. You can specify just the read timeout (for example 60) or also the connect timeout followed after a comma (for example 60,10). If a connect timeout is not specified, a default of 10 second will be used. False
Retries The maximum number of retry attempts when connection or throttling errors are encountered. Set to 0 to disable retries. The default value is 5 and the limit is 10. Note: Increasing the number of retries will increase the execution time. False
AWS STS Regional Endpoints Sets the AWS_STS_REGIONAL_ENDPOINTS environment variable to specify the AWS STS endpoint resolution logic. By default, this option is set to “legacy” in AWS. Leave empty if the environment variable is already set using server configuration. False
Use system proxy settings   False
Trust any certificate (not secure)   False

Commands

You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.

aws-sns-create-subscription


Subscribes an endpoint to an Amazon SNS topic. If the endpoint type is HTTP/S or email, or if the endpoint and the topic are not in the same Amazon Web Services account, the endpoint owner must run the ConfirmSubscription action to confirm the subscription.

Base Command

aws-sns-create-subscription

Input

Argument Name Description Required
topicArn The ARN of the topic you want to subscribe to. Required
protocol The protocol that you want to use. Possible values are: http, https, email, email-json, sms, sqs, application, lambda, firehose. Required
endpoint The endpoint that you want to receive notifications. Optional
returnSubscriptionArn Sets whether the response from the Subscribe request includes the subscription ARN, even if the subscription is not yet confirmed. Possible values are: True, False. Optional
deliveryPolicy The policy that defines how Amazon SNS retries failed deliveries to HTTP/S endpoints. Optional
filterPolicy The simple JSON object that lets your subscriber receive only a subset of messages, rather than receiving every message published to the topic. Optional
rawMessageDelivery When set to true , enables raw message delivery to Amazon SQS or HTTP/S endpoints. Possible values are: True, False. Optional
redrivePolicy When specified, sends undeliverable messages to the specified Amazon SQS dead-letter queue. Optional
subscriptionRoleArn The ARN of the IAM role that has the following: 1. Permission to write to the Kinesis Data Firehose delivery stream 2. Amazon SNS listed as a trusted entity. Optional
region The AWS Region, if not specified the default region will be used. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.SNS.Subscriptions.SubscriptionArn string The Subscription Arn

Command Example


#### Human Readable Output

### aws-sns-list-topics

***
Returns a list of the requester's topics.

#### Base Command

`aws-sns-list-topics`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| nextToken | Token returned by the previous ListTopics request. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| AWS.SNS.Topics.TopicArn | string | The Topic ARN |

#### Command Example

Human Readable Output

aws-sns-send-message


Sends a message to an Amazon SNS topic, a text message (SMS message) directly to a phone number, or a message to a mobile platform endpoint (when you specify the TargetArn ).

Base Command

aws-sns-send-message

Input

Argument Name Description Required
topicArn The topic you want to publish to. If you don’t specify a value for the TopicArn parameter, you must specify a value for the PhoneNumber or TargetArn parameters. Optional
targetArn If you don’t specify a value for the TargetArn parameter, you must specify a value for the PhoneNumber or TopicArn parameters. Optional
phoneNumber The phone number to which you want to deliver an SMS message. Use E.164 format. Optional
message The message you want to send. Required
subject Optional parameter to be used as the “Subject” line when the message is delivered to email endpoints. Optional
messageStructure Set MessageStructure to json if you want to send a different message for each protocol. Optional
messageDeduplicationId This parameter applies only to FIFO (first-in-first-out) topics. Optional
messageGroupId This parameter applies only to FIFO (first-in-first-out) topics. Optional
region The AWS Region, if not specified the default region will be used. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

Path Type Description
AWS.SNS.SentMessages string Unique identifier assigned to the published message.

Command Example


#### Human Readable Output

### aws-sns-create-topic

***
Creates a new a topic to which notifications can be published. You can specify the attribute to create FIFO topic.

#### Base Command

`aws-sns-create-topic`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| topicName | The name of the new topic. | Required |
| deliveryPolicy | The policy that defines how Amazon SNS retries failed deliveries to HTTP/S endpoints. | Optional |
| displayName | The display name to use for a topic with SMS subscriptions. | Optional |
| fifoTopic | Set to true to create a FIFO topic. Possible values are: true, false. | Optional |
| policy | The policy that defines who can access your topic. By default, only the topic owner can publish or subscribe to the topic. | Optional |
| kmsMasterKeyId | The ID of an Amazon Web Services managed customer master key (CMK) for Amazon SNS or a custom CMK. | Optional |
| contentBasedDeduplication | Enables content-based deduplication. Possible values are: True, False. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| AWS.SNS.Topic.TopicArn | unknown | The ARN of the created Amazon SNS topic. |

#### Command Example

Human Readable Output

aws-sns-delete-topic


Deletes a topic and all its subscriptions.

Base Command

aws-sns-delete-topic

Input

Argument Name Description Required
topicArn The ARN of the topic you want to delete. Required
region The AWS Region, if not specified the default region will be used. Optional
roleArn The Amazon Resource Name (ARN) of the role to assume. Optional
roleSessionName An identifier for the assumed role session. Optional
roleSessionDuration The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. Optional

Context Output

There is no context output for this command.

Command Example


#### Human Readable Output

### aws-sns-list-subscriptions-by-topic

***
Returns a list of the subscriptions to a specific topic. Each call returns a limited list of subscriptions, up to 100.

#### Base Command

`aws-sns-list-subscriptions-by-topic`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| topicArn | The ARN of the topic for which you wish to find subscriptions. | Required |
| nextToken | Token returned by the previous ListTopics request. | Optional |
| region | The AWS Region, if not specified the default region will be used. | Optional |
| roleArn | The Amazon Resource Name (ARN) of the role to assume. | Optional |
| roleSessionName | An identifier for the assumed role session. | Optional |
| roleSessionDuration | The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) up to the maximum session duration setting for the role. | Optional |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| AWS.SNS.Subscriptions.SubscriptionArn | unknown | The Subscription Arn |

#### Command Example

Human Readable Output

Configuration parameters

  • defaultRegion — AWS Default Region (required)
  • roleArn — Role Arn
  • roleSessionName — Role Session Name
  • credentials — Access Key (required)
  • sessionDuration — Role Session Duration
  • timeout — Timeout
  • retries — Retries
  • sts_regional_endpoint — AWS STS Regional Endpoints
  • proxy — Use system proxy settings
  • insecure — Trust any certificate (not secure)

Commands (6)

  • aws-sns-create-subscription

    Subscribes an endpoint to an Amazon SNS topic. If the endpoint type is HTTP/S or email, or if the endpoint and the topic are not in the same Amazon Web Services account, the endpoint owner must run the ConfirmSubscription action to confirm the subscription.

  • aws-sns-create-topic

    Creates a new a topic to which notifications can be published. You can specify the attribute to create FIFO topic.

  • aws-sns-delete-topic

    Deletes a topic and all its subscriptions.

  • aws-sns-list-subscriptions-by-topic

    Returns a list of the subscriptions to a specific topic. Each call returns a limited list of subscriptions, up to 100.

  • aws-sns-list-topics

    Returns a list of the requester's topics.

  • aws-sns-send-message

    Sends a message to an Amazon SNS topic, a text message (SMS message) directly to a phone number, or a message to a mobile platform endpoint (when you specify the TargetArn ).

import demistomock as demisto  # noqa: F401
from AWSApiModule import *  # noqa: E402
from CommonServerPython import *  # noqa: F401


def create_entry(title, data, ec):  # pragme no cover
    return {
        "ContentsFormat": formats["json"],
        "Type": entryTypes["note"],
        "Contents": data,
        "ReadableContentsFormat": formats["markdown"],
        "HumanReadable": tableToMarkdown(title, data) if data else "No result were found",
        "EntryContext": ec,
    }


def raise_error(error):  # pragma no cover
    return {"Type": entryTypes["error"], "ContentsFormat": formats["text"], "Contents": str(error)}


def create_subscription(args, client):
    try:
        attributes = {}
        kwargs = {"TopicArn": args.get("topicArn"), "Protocol": args.get("protocol")}
        if args.get("endpoint") is not None:
            kwargs.update({"Endpoint": args.get("endpoint")})
        if args.get("returnSubscriptionArn") is not None:
            kwargs.update({"ReturnSubscriptionArn": bool(args.get("returnSubscriptionArn"))})

        if args.get("deliveryPolicy") is not None:
            attributes.update({"DeliveryPolicy": args.get("deliveryPolicy")})
        if args.get("filterPolicy") is not None:
            attributes.update({"FilterPolicy": args.get("filterPolicy")})
        if args.get("rawMessageDelivery") is not None:
            attributes.update({"RawMessageDelivery": args.get("rawMessageDelivery")})
        if args.get("redrivePolicy") is not None:
            attributes.update({"RedrivePolicy": args.get("RedrivePolicy")})
        if args.get("subscriptionRoleArn") is not None:
            attributes.update({"SubscriptionRoleArn": args.get("subscriptionRoleArn")})
        if attributes:
            kwargs.update({"Attributes": attributes})

        response = client.subscribe(**kwargs)
        data = {"SubscriptionArn": response["SubscriptionArn"]}

        ec = {"AWS.SNS.Subscriptions": data}
        return create_entry("AWS SNS Subscriptions", data, ec)

    except Exception as e:
        return raise_error(e)


def list_topics(args, client):
    try:
        data = []
        kwargs = {}
        if args.get("nextToken") is not None:
            kwargs.update({"NextToken": args.get("nextToken")})
        response = client.list_topics(**kwargs)
        for topic in response["Topics"]:
            data.append({"TopicArn": topic})

        ec = {"AWS.SNS.Topics": data}
        return create_entry("AWS SNS Topics", data, ec)

    except Exception as e:
        return raise_error(e)


def list_subscriptions_by_topic(args, client):
    try:
        data = []
        kwargs = {}
        if args.get("topicArn") is not None:
            kwargs.update({"TopicArn": args.get("topicArn")})
        if args.get("nextToken") is not None:
            kwargs.update({"NextToken": args.get("nextToken")})
        response = client.list_subscriptions_by_topic(**kwargs)
        for subscription in response["Subscriptions"]:
            data.append({"SubscriptionArn": subscription["SubscriptionArn"]})

        ec = {"AWS.SNS.Subscriptions": data}
        return create_entry("AWS SNS Subscriptions", data, ec)

    except Exception as e:
        return raise_error(e)


def send_message(args, client):
    try:
        data = []
        kwargs = {"Message": args.get("message")}

        if args.get("topicArn") is not None:
            kwargs.update({"TopicArn": args.get("topicArn")})
        if args.get("targetArn") is not None:
            kwargs.update({"TargetArn": args.get("targetArn")})
        if args.get("phoneNumber") is not None:
            kwargs.update({"PhoneNumber": args.get("phoneNumber")})
        if args.get("subject") is not None:
            kwargs.update({"Subject": args.get("subject")})
        if args.get("messageStructure") is not None:
            kwargs.update({"MessageStructure": args.get("messageStructure")})
        if args.get("messageDeduplicationId") is not None:
            kwargs.update({"MessageDeduplicationId": args.get("messageDeduplicationId")})
        if args.get("messageGroupId") is not None:
            kwargs.update({"MessageGroupId": args.get("messageGroupId")})

        response = client.publish(**kwargs)
        data.append({"MessageId": response["MessageId"]})
        ec = {"AWS.SNS.SentMessages": data}
        return create_entry("AWS SNS sent messages", data, ec)

    except Exception as e:
        return raise_error(e)


def create_topic(args, client):
    try:
        attributes = {}
        kwargs = {"Name": args.get("topicName")}
        if args.get("deliveryPolicy") is not None:
            attributes.update({"DeliveryPolicy": args.get("deliveryPolicy")})
        if args.get("displayName") is not None:
            attributes.update({"DisplayName": args.get("displayName")})
        if args.get("fifoTopic") is not None:
            attributes.update({"FifoTopic": bool(args.get("fifoTopic"))})
        if args.get("policy") is not None:
            attributes.update({"policy": args.get("Policy")})
        if args.get("kmsMasterKeyId") is not None:
            attributes.update({"KmsMasterKeyId": args.get("kmsMasterKeyId")})
        if args.get("contentBasedDeduplication") is not None:
            attributes.update({"ContentBasedDeduplication": args.get("contentBasedDeduplication")})
        if attributes:
            kwargs.update({"Attributes": attributes})

        response = client.create_topic(**kwargs)
        data = {"ARN": response["TopicArn"]}
        ec = {"AWS.SNS.Topic": data}
        return create_entry("AWS SNS Topic", data, ec)

    except Exception as e:
        return raise_error(e)


def delete_topic(args, client):
    try:
        response = client.delete_topic(TopicArn=args.get("topicArn"))
        if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
            return "The Topic has been deleted"

    except Exception as e:
        return raise_error(e)


def test_function(aws_client):  # pragma no cover
    try:
        client = aws_client.aws_session(service="sns")
        response = client.list_topics()
        if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
            return "ok"
    except Exception as e:
        return raise_error(e)


def main():  # pragma no cover
    params = demisto.params()
    aws_default_region = params.get("defaultRegion")
    aws_role_arn = params.get("roleArn")
    aws_role_session_name = params.get("roleSessionName")
    aws_role_session_duration = params.get("sessionDuration")
    aws_role_policy = None
    aws_access_key_id = params.get("credentials", {}).get("identifier", "")
    aws_secret_access_key = params.get("credentials", {}).get("password", "")
    verify_certificate = not params.get("insecure", False)
    timeout = params.get("timeout")
    retries = params.get("retries") or 5

    commands = {
        "aws-sns-create-subscription": create_subscription,
        "aws-sns-list-topics": list_topics,
        "aws-sns-list-subscriptions-by-topic": list_subscriptions_by_topic,
        "aws-sns-send-message": send_message,
        "aws-sns-create-topic": create_topic,
        "aws-sns-delete-topic": delete_topic,
    }

    try:
        validate_params(aws_default_region, aws_role_arn, aws_role_session_name, aws_access_key_id, aws_secret_access_key)
        aws_client = AWSClient(
            aws_default_region,
            aws_role_arn,
            aws_role_session_name,
            aws_role_session_duration,
            aws_role_policy,
            aws_access_key_id,
            aws_secret_access_key,
            verify_certificate,
            timeout,
            retries,
        )
        command = demisto.command()
        args = demisto.args()
        demisto.debug(f"Command being called is {command}")
        if command == "test-module":
            return_results(test_function(aws_client))
        elif command in commands:
            client = aws_client.aws_session(
                service="sns",
                region=args.get("region"),
                role_arn=args.get("roleArn"),
                role_session_name=args.get("roleSessionName"),
                role_session_duration=args.get("roleSessionDuration"),
            )
            return_results(commands[command](args, client))
        else:
            raise NotImplementedError(f"{command} is not an existing AWS-SNS command")

    except Exception as e:
        return_error(f"Failed to execute {demisto.command()} command.\nError:\n{e!s}")


if __name__ in ("__main__", "__builtin__", "builtins"):
    main()