> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# SQS Queues Should Not Be Publicly Exposed

### More Info:

There should not be any publicly accessible SQS queues available in your AWS account in order to protect against unauthorized users. Unauthorized access can lead to unauthorized actions such as intercepting, deleting and sending queue messages.

### Risk Level

High

### Address

Reliability, Security

### Compliance Standards

* APRA CPS 234 (Australia)
* BSI C5 (Germany)
* Brazil LGPD
* CCPA / CPRA (California)
* CIS Critical Security Controls v8
* CMMC 2.0
* CSA Cloud Controls Matrix v4
* DPDPA
* Digital Operational Resilience Act (EU)
* Essential 8
* ISO/IEC 27017
* ISO/IEC 27018
* ISO/IEC 27701
* KSA PDPL
* MAS Technology Risk Management (Singapore)
* MITRE ATT\&CK (Cloud)
* NIS2 Directive
* NIST SP 800-171
* NYDFS 23 NYCRR 500
* PCI
* SWIFT Customer Security Controls Framework
* Sarbanes-Oxley IT General Controls
* UK NCSC Cyber Assessment Framework

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Sure, here are the step-by-step instructions to remediate this misconfiguration:

        1. Log in to the AWS Management Console and open the Amazon SQS console at [https://console.aws.amazon.com/sqs/](https://console.aws.amazon.com/sqs/).

        2. In the navigation pane, choose 'Queues'.

        3. In the 'Queue URLs' list, choose the name of the queue that you want to change the permissions for.

        4. Choose the 'Permissions' tab.

        5. Here you can see all the permissions currently granted. If 'Everyone' (which means public access) is listed, you need to remove this permission.

        6. Select the 'Everyone' permission and then click on 'Remove permissions'.

        7. In the 'Remove permissions' dialog box, confirm the removal by clicking 'Remove'.

        8. The changes take effect immediately.

        9. Repeat these steps for all queues that are publicly accessible.

        Remember, it's a best practice to restrict access to your Amazon SQS queues. You should grant only the necessary permissions that allow authenticated AWS users to perform specific actions.
      </Accordion>

      <Accordion title="Using CLI">
        Sure, here are the step-by-step instructions to remediate this issue using AWS CLI:

        1. **Identify the publicly exposed SQS queue**: First, you need to identify the SQS queues that are publicly exposed. You can do this by using the following command:

        ```bash theme={null}
        aws sqs list-queues
        ```

        This command will list all the SQS queues in your AWS account.

        2. **Get the SQS queue's policy**: Once you have identified the SQS queue, you need to check its policy. You can do this by using the following command:

        ```bash theme={null}
        aws sqs get-queue-attributes --queue-url <Your-Queue-URL> --attribute-names Policy
        ```

        Replace `<Your-Queue-URL>` with your actual SQS queue URL. This command will display the policy of the SQS queue.

        3. **Identify the issue in the policy**: Check if the policy has "Principal": "\*" with "Effect": "Allow". This means the SQS queue is publicly accessible.

        4. **Modify the policy**: You need to remove the public access from the policy. You can do this by removing the statement with "Principal": "\*" and "Effect": "Allow". Make sure you do not remove other statements that are needed for your application to function properly.

        5. **Set the new policy**: Once you have modified the policy, you need to set it back to the SQS queue. You can do this by using the following command:

        ```bash theme={null}
        aws sqs set-queue-attributes --queue-url <Your-Queue-URL> --attributes Policy=<Your-New-Policy>
        ```

        Replace `<Your-Queue-URL>` with your actual SQS queue URL, and `<Your-New-Policy>` with your new policy.

        6. **Verify the changes**: Finally, verify if the changes have been applied properly. You can do this by getting the SQS queue's policy again and checking if the public access has been removed.

        Please remember to replace the placeholders with your actual values. Also, make sure you have the necessary permissions to perform these actions.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of SQS Queues being publicly exposed, you can use Boto3, the Amazon Web Services (AWS) SDK for Python. Here are the step-by-step instructions:

        1. First, make sure you have installed the AWS SDK for Python (Boto3). If not, install it using pip:
           ```
           pip install boto3
           ```

        2. Import the necessary libraries:
           ```python theme={null}
           import boto3
           from botocore.exceptions import NoCredentialsError
           ```

        3. Create a session using your AWS credentials. Replace 'your\_access\_key', 'your\_secret\_key', and 'your\_region' with your AWS access key, secret key, and the region your SQS queue is in, respectively:
           ```python theme={null}
           session = boto3.Session(
               aws_access_key_id='your_access_key',
               aws_secret_access_key='your_secret_key',
               region_name='your_region'
           )
           ```

        4. Create a client for SQS:
           ```python theme={null}
           sqs = session.client('sqs')
           ```

        5. Get the URL of the SQS queue. Replace 'your\_queue\_name' with the name of your queue:
           ```python theme={null}
           response = sqs.get_queue_url(QueueName='your_queue_name')
           queue_url = response['QueueUrl']
           ```

        6. Get the current policy of the SQS queue:
           ```python theme={null}
           current_policy = sqs.get_queue_attributes(
               QueueUrl=queue_url,
               AttributeNames=['Policy']
           )
           ```

        7. Check if the policy allows everyone to send messages to the queue. If it does, modify the policy to only allow specific AWS accounts or IAM users to send messages to the queue. Here's an example of a policy that only allows a specific AWS account to send messages:

           ```python theme={null}
           new_policy = {
               "Version": "2012-10-17",
               "Id": "MyQueuePolicy",
               "Statement": [
                   {
                       "Sid": "AllowSpecificAWSAccount",
                       "Effect": "Allow",
                       "Principal": {
                           "AWS": "arn:aws:iam::YourAWSAccountID:root"
                       },
                       "Action": "sqs:SendMessage",
                       "Resource": "arn:aws:sqs:region:YourAWSAccountID:YourQueueName"
                   }
               ]
           }
           ```

        8. Set the new policy:
           ```python theme={null}
           sqs.set_queue_attributes(
               QueueUrl=queue_url,
               Attributes={
                   'Policy': json.dumps(new_policy)
               }
           )
           ```

        9. Finally, handle any exceptions that may occur during the process:
           ```python theme={null}
           try:
               # Your code here
           except NoCredentialsError:
               print("No AWS credentials found.")
           except Exception as e:
               print(f"An error occurred: {e}")
           ```

        Please replace 'YourAWSAccountID', 'region', and 'YourQueueName' with your AWS account ID, the region your SQS queue is in, and the name of your queue, respectively.

        This will change your SQS queue's policy to only allow a specific AWS account to send messages to it, thus remediating the misconfiguration.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "aws_sqs_queue" "this" {
          name = "NON_PUBLIC_QUEUE_NAME" # replace with your queue name
        }

        data "aws_iam_policy_document" "sqs_non_public" {
          statement {
            sid = "AllowSpecificProducerOnly" # replace with the label/Sid you want to keep/use

            effect = "Allow"

            principals {
              type        = "AWS"
              identifiers = ["ALLOWED_AWS_PRINCIPAL_ARN"] # replace with the IAM user/role/account ARN that should access the queue
            }

            actions = [
              "sqs:SendMessage",
              "sqs:ReceiveMessage",
              "sqs:DeleteMessage",
              "sqs:GetQueueAttributes",
              "sqs:GetQueueUrl",
            ]

            resources = [aws_sqs_queue.this.arn]
          }

          # IMPORTANT:
          # Do NOT add any statement with:
          #   principals.identifiers = ["*"]
          # or
          #   principals { type = "*", identifiers = ["*"] }
          # i.e., no public ("*") principal in any statement.
        }

        resource "aws_sqs_queue_policy" "this" {
          queue_url = aws_sqs_queue.this.id
          policy    = data.aws_iam_policy_document.sqs_non_public.json
        }
        ```

        This Terraform configuration replaces the SQS queue policy with one that has no statement granting access to the `*` principal, which is equivalent to using `aws sqs remove-permission` (or `set-queue-attributes` for a full replacement) to remove the public access statement; it may remove other existing statements, so construct `data.aws_iam_policy_document.sqs_non_public` carefully to retain all legitimate access.

        Changing only `aws_sqs_queue_policy.this` updates the policy in place and does not replace the queue itself.

        To verify, `terraform plan` should show:

        * `~ aws_sqs_queue_policy.this` with the old policy JSON being replaced by a new one that has no `Principal: "*"` or `{"AWS": "*"}` in any statement.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-security-best-practices.html](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-security-best-practices.html)
