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

# Default sg unrestricted remediation

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Below are concise, console-based steps to remediate “Default Security Groups allow unrestricted inbound access” in AWS.

        ***

        ### 1. Identify default security groups with open inbound access

        1. Sign in to the **AWS Management Console**.
        2. Go to **EC2**.
        3. In the left navigation pane, choose **Security Groups**.
        4. In the filter/search bar, type `default` and press Enter.
        5. In the **Group Name** column, look for security groups named **default** (one per VPC).
        6. For each default SG:
           * Select it and check the **Inbound rules** tab.
           * Look for rules with:
             * **Type** = *All traffic*, *All ICMP*, *SSH*, *RDP*, *Custom TCP/UDP*, etc.
             * **Source** = `0.0.0.0/0` and/or `::/0` (unrestricted).

        ***

        ### 2. Remove unrestricted inbound rules on the default security group

        For each default security group that has `0.0.0.0/0` or `::/0` in inbound rules:

        1. Select the **default** security group.
        2. Choose the **Inbound rules** tab.
        3. Click **Edit inbound rules**.
        4. For each rule where:
           * **Source** is `0.0.0.0/0` or `::/0`, and
           * It is not needed for VPC-internal communication:
             * Click the **X** at the end of the row to remove it.
        5. Make sure that if you need instances in the same security group to talk to each other, you keep (or add) a rule like:
           * **Type**: All traffic (or the specific required ports)
           * **Protocol**: All (or needed)
           * **Port range**: All (or needed)
           * **Source**: The security group itself (select from dropdown under **Custom** → SG ID).
        6. Click **Save rules**.

        > Note: You cannot delete a default security group, only modify its rules.

        ***

        ### 3. Create and use dedicated security groups for external access

        To avoid using the default SG for internet-exposed services:

        1. In **Security Groups**, click **Create security group**.
        2. Enter:
           * **Security group name**: e.g., `web-servers-sg`.
           * **Description**: e.g., `Security group for public web servers (HTTP/HTTPS only)`.
           * **VPC**: Select the correct VPC.
        3. Under **Inbound rules**, add *only* what’s needed, with limited source ranges, for example:
           * Rule 1:
             * **Type**: HTTP
             * **Port**: 80
             * **Source**: Your office IP /32 or specific CIDR (not `0.0.0.0/0` if possible).
           * Rule 2:
             * **Type**: HTTPS
             * **Port**: 443
             * **Source**: As above.
           * For SSH/RDP, use:
             * **Type**: SSH / RDP
             * **Source**: Admin IPs only (never `0.0.0.0/0`).
        4. Click **Create security group**.

        Attach this new SG to instances instead of using the default:

        1. Go to **Instances**.
        2. Select the instance currently using the default security group.
        3. Choose **Actions** → **Security** → **Change security groups**.
        4. Check your new SG (e.g., `web-servers-sg`) and uncheck the **default** SG (if safe to do so).
        5. Click **Apply**.

        ***

        ### 4. Confirm remediation

        1. Return to **Security Groups**.
        2. For each **default** SG:
           * Confirm there are **no inbound rules** with `0.0.0.0/0` or `::/0`.
        3. Optionally, use **Reachability Analyzer** or test from the internet to ensure ports are no longer globally open.

        This ensures default security groups no longer allow unrestricted inbound access while preserving required internal communication and moving internet exposure to dedicated, controlled security groups.
      </Accordion>

      <Accordion title="Using CLI">
        Below is a concise, CLI‑only way to lock down default Security Groups so they don’t allow unrestricted inbound (0.0.0.0/0 or ::/0).

        ### 1. Identify default Security Groups that allow unrestricted inbound

        ```bash theme={null}
        # Example region; change as needed
        REGION=us-east-1

        aws ec2 describe-security-groups \
          --region "$REGION" \
          --filters "Name=group-name,Values=default" \
          --query "SecurityGroups[].[GroupId,GroupName,VpcId,IpPermissions]" \
          --output json
        ```

        Look for:

        * `IpRanges` with `CidrIp: "0.0.0.0/0"`
        * `Ipv6Ranges` with `CidrIpv6: "::/0"`

        These are the rules to remove.

        ***

        ### 2. Revoke all inbound rules on default Security Groups (safer baseline)

        If you’re okay with removing **all** inbound rules from all default SGs in a region:

        ```bash theme={null}
        REGION=us-east-1

        for SG in $(aws ec2 describe-security-groups \
          --region "$REGION" \
          --filters "Name=group-name,Values=default" \
          --query "SecurityGroups[].GroupId" \
          --output text); do

          # Get IpPermissions as JSON
          IP_PERMS=$(aws ec2 describe-security-groups \
            --region "$REGION" \
            --group-ids "$SG" \
            --query "SecurityGroups[0].IpPermissions" \
            --output json)

          # If there are any inbound rules, revoke them all
          if [ "$IP_PERMS" != "[]" ]; then
            echo "Revoking all inbound rules on $SG"
            aws ec2 revoke-security-group-ingress \
              --region "$REGION" \
              --group-id "$SG" \
              --ip-permissions "$IP_PERMS"
          fi
        done
        ```

        This ensures the default SG has **no** inbound rules (i.e., nothing is allowed in).

        ***

        ### 3. (Optional) Only remove “unrestricted” inbound rules

        If you want to keep other, more restricted rules and only remove 0.0.0.0/0 or ::/0, you need to filter the permissions. One straightforward approach is to manually revoke specific rules once you’ve inspected them.

        Example: remove a specific inbound rule (TCP 22 from 0.0.0.0/0) from a known default SG:

        ```bash theme={null}
        SG_ID=sg-xxxxxxxxxxxxxxxx
        REGION=us-east-1

        aws ec2 revoke-security-group-ingress \
          --region "$REGION" \
          --group-id "$SG_ID" \
          --ip-permissions '[
            {
              "IpProtocol": "tcp",
              "FromPort": 22,
              "ToPort": 22,
              "IpRanges": [{"CidrIp": "0.0.0.0/0"}]
            }
          ]'
        ```

        Similarly for IPv6:

        ```bash theme={null}
        aws ec2 revoke-security-group-ingress \
          --region "$REGION" \
          --group-id "$SG_ID" \
          --ip-permissions '[
            {
              "IpProtocol": "tcp",
              "FromPort": 22,
              "ToPort": 22,
              "Ipv6Ranges": [{"CidrIpv6": "::/0"}]
            }
          ]'
        ```

        Repeat for each protocol/port combination you find with unrestricted access.

        ***

        ### 4. (Optional) Add safer, restricted inbound rules

        After cleanup, if you need access from a known IP/CIDR:

        ```bash theme={null}
        SG_ID=sg-xxxxxxxxxxxxxxxx
        REGION=us-east-1
        MY_IP_CIDR="203.0.113.10/32"   # replace with your IP/CIDR

        aws ec2 authorize-security-group-ingress \
          --region "$REGION" \
          --group-id "$SG_ID" \
          --ip-permissions "[
            {
              \"IpProtocol\": \"tcp\",
              \"FromPort\": 22,
              \"ToPort\": 22,
              \"IpRanges\": [{\"CidrIp\": \"$MY_IP_CIDR\", \"Description\": \"SSH from admin\"}]
            }
          ]"
        ```

        This leaves the default Security Groups without any 0.0.0.0/0 or ::/0 inbound access.
      </Accordion>

      <Accordion title="Using Python">
        Below is one straightforward way to remediate this using Python and boto3: identify default security groups that allow 0.0.0.0/0 or ::/0 inbound, then remove those rules.

        ***

        ### 1. Prerequisites

        1. Install boto3:
           ```bash theme={null}
           pip install boto3
           ```
        2. Configure AWS credentials with sufficient permissions:

           * `ec2:DescribeSecurityGroups`
           * `ec2:RevokeSecurityGroupIngress`

           For example:

           ```bash theme={null}
           aws configure
           ```

        ***

        ### 2. Python script to remove unrestricted inbound from default security groups

        This script:

        * Enumerates all regions.
        * Finds default security groups.
        * Detects inbound rules with:
          * IPv4: `0.0.0.0/0`
          * IPv6: `::/0`
        * Revokes only those offending rules (leaves other rules intact).

        ```python theme={null}
        import boto3

        def get_all_regions():
            ec2 = boto3.client("ec2")
            regions = ec2.describe_regions(AllRegions=False)["Regions"]
            return [r["RegionName"] for r in regions]

        def remove_unrestricted_inbound_from_default_sg(region):
            ec2 = boto3.client("ec2", region_name=region)

            # Get all default security groups in this region
            response = ec2.describe_security_groups(
                Filters=[{"Name": "group-name", "Values": ["default"]}]
            )
            sgs = response.get("SecurityGroups", [])

            for sg in sgs:
                group_id = sg["GroupId"]
                group_name = sg["GroupName"]
                vpc_id = sg.get("VpcId")

                print(f"Checking SG {group_id} ({group_name}) in VPC {vpc_id} in {region}")

                # Build list of offending ingress rules to revoke
                permissions_to_revoke = []

                for perm in sg.get("IpPermissions", []):
                    # Copy the permission skeleton
                    perm_to_revoke = {
                        "IpProtocol": perm["IpProtocol"],
                        "FromPort": perm.get("FromPort"),
                        "ToPort": perm.get("ToPort"),
                        "UserIdGroupPairs": [],
                        "IpRanges": [],
                        "Ipv6Ranges": [],
                        "PrefixListIds": perm.get("PrefixListIds", [])
                    }

                    # Check IPv4 ranges
                    for ip_range in perm.get("IpRanges", []):
                        if ip_range.get("CidrIp") == "0.0.0.0/0":
                            perm_to_revoke["IpRanges"].append(ip_range)

                    # Check IPv6 ranges
                    for ipv6_range in perm.get("Ipv6Ranges", []):
                        if ipv6_range.get("CidrIpv6") == "::/0":
                            perm_to_revoke["Ipv6Ranges"].append(ipv6_range)

                    # Only add permission if we actually found something to revoke
                    if perm_to_revoke["IpRanges"] or perm_to_revoke["Ipv6Ranges"]:
                        permissions_to_revoke.append(perm_to_revoke)

                # Revoke offending rules if any
                if permissions_to_revoke:
                    print(f"Revoking unrestricted inbound rules from {group_id} in {region}")
                    ec2.revoke_security_group_ingress(
                        GroupId=group_id,
                        IpPermissions=permissions_to_revoke
                    )
                else:
                    print(f"No unrestricted inbound on {group_id} in {region}")

        def main():
            regions = get_all_regions()
            for region in regions:
                print(f"\n=== Region: {region} ===")
                remove_unrestricted_inbound_from_default_sg(region)

        if __name__ == "__main__":
            main()
        ```

        ***

        ### 3. Notes / Adjustments

        * If you only want to operate in a single region, replace `get_all_regions()` with a hard-coded list, e.g. `regions = ["us-east-1"]`.
        * This script **only removes** the `0.0.0.0/0` or `::/0` inbound rules. It does not add replacement rules; if you need specific allowed CIDRs, add them explicitly with `authorize_security_group_ingress`.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # Remediate the default security group so it does NOT allow unrestricted inbound access.
        # Replace VPC_ID with the ID of the VPC whose default security group you are managing.

        resource "aws_default_security_group" "this" {
          vpc_id = "VPC_ID"  # e.g. aws_vpc.main.id

          # Remove all default ingress rules (no inbound allowed by default)
          ingress = []

          # Option 1: allow all outbound (common default)
          egress {
            from_port   = 0
            to_port     = 0
            protocol    = "-1"
            cidr_blocks = ["0.0.0.0/0"]
            ipv6_cidr_blocks = ["::/0"]
          }

          # OR Option 2: restrict outbound to specific destinations/ports instead of 0.0.0.0/0
          # egress {
          #   from_port   = 443
          #   to_port     = 443
          #   protocol    = "tcp"
          #   cidr_blocks = ["ALLOWED_CIDR"]
          # }
        }
        ```

        This change updates the in‑place default security group (no replacement is forced, but rules will be revoked and recreated as needed).

        Verification: `terraform plan` should show the `aws_default_security_group` ingress rules from `0.0.0.0/0` (and/or `::/0`) being removed and no new unrestricted inbound rules added.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
