> ## 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.

# Ec2 public instances exist remediation

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration of EC2 instances being publicly accessible in AWS Security Groups, follow these steps using the AWS Management Console:

        1. **Login to AWS Console**: Go to the AWS Management Console ([https://aws.amazon.com/console/](https://aws.amazon.com/console/)) and log in to your account.

        2. **Navigate to EC2 Dashboard**: Go to the EC2 Dashboard by clicking on the "Services" dropdown menu at the top left corner, selecting "EC2" under the Compute section.

        3. **Identify the EC2 Instance**: Identify the EC2 instance(s) that are publicly accessible. You can do this by checking the "Instance State" and "Instance Type" columns in the EC2 Dashboard.

        4. **Identify Security Group**: Click on the EC2 instance that you want to remediate and scroll down to the "Description" tab. Under the Security group section, you will see the security group associated with the EC2 instance.

        5. **Edit Security Group Rules**: Click on the security group associated with the EC2 instance. This will take you to the "Inbound" tab of the security group.

        6. **Remove Public Access**: Identify the rule that allows public access (e.g., SSH port 22 or HTTP port 80) and click on the "Edit" button.

        7. **Modify Rule**: In the Edit inbound rules window, select the rule that allows public access and click on the "Delete" button to remove it.

        8. **Save Changes**: Click on the "Save rules" button to apply the changes to the security group.

        9. **Verify Changes**: Go back to the EC2 Dashboard, select the EC2 instance, and verify that it is no longer publicly accessible by checking the public IP address field.

        10. **Repeat for Other Instances**: Repeat the above steps for any other EC2 instances that are publicly accessible.

        By following these steps, you have successfully remediated the misconfiguration of EC2 instances being publicly accessible in AWS Security Groups.
      </Accordion>

      <Accordion title="Using CLI">
        #

        To remediate the issue of EC2 instances being publicly accessible in AWS using the AWS CLI, follow these steps:

        1. Identify the security group associated with the EC2 instance that is publicly accessible. You can do this by describing the instance and noting the security group ID.

        ```bash theme={null}
        aws ec2 describe-instances --instance-ids <instance-id> --query 'Reservations[*].Instances[*].SecurityGroups[*].GroupId' --output text
        ```

        2. Describe the inbound rules of the identified security group to check if there are any rules allowing public access.

        ```bash theme={null}
        aws ec2 describe-security-groups --group-ids <security-group-id>
        ```

        3. Remove the inbound rule that allows public access (usually with `0.0.0.0/0` as the source) using the revoke-security-group-ingress command.

        ```bash theme={null}
        aws ec2 revoke-security-group-ingress --group-id <security-group-id> --protocol tcp --port <port-number> --cidr 0.0.0.0/0
        ```

        Replace `<security-group-id>` with the actual security group ID, `<port-number>` with the specific port number (e.g., 22 for SSH, 80 for HTTP, 443 for HTTPS), and `0.0.0.0/0` with the appropriate source IP range if needed.

        4. Verify that the inbound rule has been successfully removed by describing the security group again.

        ```bash theme={null}
        aws ec2 describe-security-groups --group-ids <security-group-id>
        ```

        By following these steps, you can remediate the issue of EC2 instances being publicly accessible in AWS by updating the security group rules to restrict access as needed.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of EC2 instances being publicly accessible in AWS using Python, you can create a script that will update the security group rules to restrict access only to specific IP addresses or ranges. Here are the steps to remediate this issue:

        1. Install the Boto3 library:
           * Make sure you have the Boto3 library installed in your Python environment. You can install it using pip:
             ```
             pip install boto3
             ```

        2. Write a Python script to update the security group rules:
           * Use the following Python script as a template to update the security group rules for your EC2 instances:

             ```python theme={null}
             import boto3

             # Initialize the EC2 client
             ec2 = boto3.client('ec2')

             # Define the security group ID of the EC2 instance
             security_group_id = 'your_security_group_id'

             # Define the IP ranges that should have access to the EC2 instance
             ip_ranges = [{'CidrIp': 'x.x.x.x/32'}, {'CidrIp': 'y.y.y.y/32'}]  # Add your desired IP ranges

             # Update the security group rules
             response = ec2.authorize_security_group_ingress(
                 GroupId=security_group_id,
                 IpPermissions=[
                     {
                         'IpProtocol': '-1',
                         'IpRanges': ip_ranges
                     }
                 ]
             )

             print('Security group rules updated successfully.')
             ```

        3. Replace 'your\_security\_group\_id' with the actual security group ID of your EC2 instance.

        4. Define the IP ranges that should have access to the EC2 instance in the `ip_ranges` variable.

        5. Run the Python script:
           * Save the Python script in a file, for example, `update_security_group.py`, and run it using the Python interpreter:
             ```
             python update_security_group.py
             ```

        6. Verify the changes:
           * After running the script, verify that the security group rules have been updated to restrict access to the specified IP ranges only.

        By following these steps and customizing the script with your specific security group ID and IP ranges, you can remediate the misconfiguration of EC2 instances being publicly accessible in AWS.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "aws_security_group" "EC2_INSTANCE_SG" {
          name        = "EC2_INSTANCE_SG"
          description = "Security group for EC2 instance without public ingress"
          vpc_id      = AWS_VPC_ID  # replace AWS_VPC_ID with the ID of the VPC

          # Example: previously you might have had:
          #
          # ingress {
          #   description = "SSH from anywhere (INSECURE)"
          #   from_port   = 22
          #   to_port     = 22
          #   protocol    = "tcp"
          #   cidr_blocks = ["0.0.0.0/0"]   # REMOVE THIS
          #   ipv6_cidr_blocks = ["::/0"]   # REMOVE THIS IF PRESENT
          # }

          # Replace overly permissive rule with a restricted source
          ingress {
            description = "SSH from trusted admin network only"
            from_port   = 22
            to_port     = 22
            protocol    = "tcp"

            # choose ONE of these approaches:

            # 1) Restrict to specific IPv4 CIDR(s)
            cidr_blocks = [
              "TRUSTED_IPV4_CIDR", # e.g. "203.0.113.0/24"
            ]

            # 2) Optionally, restrict IPv6 instead of ::/0
            # ipv6_cidr_blocks = [
            #   "TRUSTED_IPV6_CIDR", # e.g. "2001:db8:1234::/64"
            # ]

            # 3) Or restrict to another security group (no public CIDR at all)
            # security_groups = [
            #   aws_security_group.admin_bastion.id,
            # ]
          }

          # keep other, already-restricted rules as needed (no 0.0.0.0/0 or ::/0)
          # e.g. an internal-only app port:
          # ingress {
          #   from_port       = 8080
          #   to_port         = 8080
          #   protocol        = "tcp"
          #   security_groups = [aws_security_group.internal_lb.id]
          # }

          egress {
            from_port   = 0
            to_port     = 0
            protocol    = "-1"
            cidr_blocks = ["0.0.0.0/0"]
            ipv6_cidr_blocks = ["::/0"]
          }

          tags = {
            Name = "EC2 Instance SG"
          }
        }

        resource "aws_instance" "EC2_INSTANCE" {
          ami                    = AMI_ID              # replace AMI_ID with the desired AMI
          instance_type          = "t3.micro"
          subnet_id              = SUBNET_ID          # replace SUBNET_ID with the target subnet
          vpc_security_group_ids = [aws_security_group.EC2_INSTANCE_SG.id]

          # other arguments as needed
        }
        ```

        This Terraform removes the ingress rule that allowed `0.0.0.0/0` or `::/0` to the instance’s ports and replaces it with a restricted CIDR or a security-group–to–security-group rule, matching the CLI remediation’s intent of revoking public ingress. It does not force replacement of the security group or instance; Terraform will update the ingress rules in place, though access to the instance on that port will change and may disrupt existing connectivity.

        Verification: `terraform plan` should show the `aws_security_group` ingress rule changing from `cidr_blocks = ["0.0.0.0/0"]` and/or `ipv6_cidr_blocks = ["::/0"]` to the new, restricted CIDR or security group references, with no `create`/`destroy` of the instance resource.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
