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

# SSH Port Should Not Be Open

### More Info:

Determines if TCP port 22 for SSH is open to the public.

### Risk Level

Medium

### Address

Security

### Compliance Standards

* APRA CPS 234 (Australia)
* BSI C5 (Germany)
* Brazil LGPD
* CCPA / CPRA (California)
* CIS Critical Security Controls v8
* CIS GCP
* CIS GCP 2.0.0
* CMMC 2.0
* CSA Cloud Controls Matrix v4
* Cloudanix Best Practice
* DPDPA
* Digital Operational Resilience Act (EU)
* Essential 8
* FedRAMP
* GDPR
* HIPAA
* HITRUST CSF
* ISO 27001
* ISO/IEC 27017
* ISO/IEC 27018
* ISO/IEC 27701
* KSA PDPL
* MAS Technology Risk Management (Singapore)
* MITRE ATT\&CK (Cloud)
* NIS2 Directive
* NIST CSF
* NIST SP 800-171
* NYDFS 23 NYCRR 500
* PCI
* Reserve Bank of India (RBI) Cyber Security Framework
* Reserve Bank of India (RBI) Master Direction – Information Technology Framework
* SOC2
* SWIFT Customer Security Controls Framework
* Sarbanes-Oxley IT General Controls
* Securities and Exchange Board of India (SEBI) - Cloud Security Adoption Framework
* UK NCSC Cyber Assessment Framework

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the SSH port open misconfiguration in GCP using the GCP console, follow the below steps:

        1. Login to the GCP console ([https://console.cloud.google.com/](https://console.cloud.google.com/)).
        2. Navigate to the Compute Engine section.
        3. Select the instance where the SSH port is open.
        4. Click on the "Edit" button at the top of the page.
        5. Scroll down to the "Firewall" section and click on "Management, security, disks, networking, sole tenancy".
        6. Under the "Firewall" section, click on "Networking".
        7. In the "Firewall rules" section, find the firewall rule that is allowing SSH access (usually named "default-allow-ssh").
        8. Click on the checkbox next to the rule to select it.
        9. Click on the "Delete" button at the top of the page.
        10. Confirm the deletion by clicking on the "Delete" button in the confirmation dialog box.

        Once the firewall rule allowing SSH access is deleted, the SSH port will no longer be open, and the misconfiguration will be remediated.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the SSH port open misconfiguration in GCP using GCP CLI, follow these steps:

        1. Open the GCP CLI and connect to your project.

        2. Run the following command to list all the instances in your project:

           ```
           gcloud compute instances list
           ```

        3. Identify the instance for which you want to remediate the misconfiguration.

        4. Run the following command to get the details of the instance:

           ```
           gcloud compute instances describe [INSTANCE_NAME]
           ```

           Replace `[INSTANCE_NAME]` with the name of your instance.

        5. Look for the `metadata` section in the output. If you see a `ssh-keys` entry, then SSH port is open. To remediate this, delete the `ssh-keys` entry.

        6. Run the following command to delete the `ssh-keys` entry:

           ```
           gcloud compute instances remove-metadata [INSTANCE_NAME] --keys ssh-keys
           ```

           Replace `[INSTANCE_NAME]` with the name of your instance.

        7. Verify that the `ssh-keys` entry has been deleted by running the `gcloud compute instances describe` command again.

           ```
           gcloud compute instances describe [INSTANCE_NAME]
           ```

           You should not see the `ssh-keys` entry in the output.

        8. Repeat steps 4-7 for all the instances in your project to ensure that SSH port is not open on any of them.

        By following these steps, you can remediate the SSH port open misconfiguration in GCP using GCP CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the SSH port being open misconfiguration in GCP using Python, you can follow these steps:

        1. Import the necessary libraries:

        ```python theme={null}
        from googleapiclient import discovery
        from oauth2client.client import GoogleCredentials
        ```

        2. Set up authentication credentials:

        ```python theme={null}
        credentials = GoogleCredentials.get_application_default()
        service = discovery.build('compute', 'v1', credentials=credentials)
        ```

        3. Retrieve the project ID:

        ```python theme={null}
        project = 'your-project-id'
        ```

        4. Retrieve the list of instances:

        ```python theme={null}
        instances = service.instances().list(project=project, zone='us-central1-a').execute()
        ```

        Note: Replace the zone with the appropriate zone for your instance.

        5. Loop through the instances and update the firewall rules to restrict SSH access:

        ```python theme={null}
        for instance in instances['items']:
            instance_name = instance['name']
            instance_zone = instance['zone'].split('/')[-1]
            firewall_name = 'ssh-' + instance_name
            firewall_body = {
                'allowed': [],
                'description': 'Restrict SSH access to specified IP ranges',
                'name': firewall_name,
                'network': 'default',
                'priority': 1000,
                'sourceRanges': [
                    '0.0.0.0/0'
                ],
                'targetTags': [
                    instance_name
                ]
            }
            firewall = service.firewalls().insert(project=project, body=firewall_body).execute()
            print('Firewall rule created for instance {}: {}'.format(instance_name, firewall['id']))
        ```

        Note: This code creates a new firewall rule for each instance to restrict SSH access to specified IP ranges. You can modify the `sourceRanges` parameter to specify the IP ranges that should be allowed to access SSH.

        6. Remove the existing firewall rule that allows SSH access:

        ```python theme={null}
        firewall_name = 'default-allow-ssh'
        firewall = service.firewalls().delete(project=project, firewall=firewall_name).execute()
        print('Firewall rule deleted: {}'.format(firewall_name))
        ```

        Note: This code removes the default firewall rule that allows SSH access from any IP address.

        7. Verify that the firewall rules have been updated:

        ```python theme={null}
        firewalls = service.firewalls().list(project=project).execute()
        for firewall in firewalls['items']:
            print(firewall['name'], firewall['sourceRanges'])
        ```

        Note: This code lists all the firewall rules in the project and their associated source IP ranges. You should see that the new firewall rules restrict SSH access to specified IP ranges.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "google_compute_firewall" "ssh_restricted" {
          name    = "SSH_FIREWALL_RULE_NAME"   # replace with existing firewall rule name
          network = "VPC_NETWORK_NAME"         # replace with your VPC name or self_link

          direction = "INGRESS"
          priority  = 1000

          # IMPORTANT: remove 0.0.0.0/0 and restrict to known IP ranges only
          source_ranges = [
            "TRUSTED_ADMIN_IP_CIDR_1",         # e.g. "203.0.113.10/32"
            "TRUSTED_ADMIN_IP_CIDR_2",         # optional additional trusted ranges
            # Optionally allow Cloud IAP for TCP forwarding:
            # "35.235.240.0/20"
          ]

          # Optionally scope to specific instances via tags or service accounts
          # target_tags        = ["SSH_ALLOWED_TAG"]
          # target_service_accounts = ["SSH_ALLOWED_SA@PROJECT_ID.iam.gserviceaccount.com"]

          allow {
            protocol = "tcp"
            ports    = ["22"]
          }

          # Optional: keep if already present
          # disabled = false
        }
        ```

        Changing `source_ranges` on an existing `google_compute_firewall` rule is an in‑place update and does not force replacement of the rule or the VPC.

        Verification: `terraform plan` should show an in-place update on the existing `google_compute_firewall` resource with `source_ranges` changing from `["0.0.0.0/0"]` (or similarly broad CIDRs) to the specific trusted CIDR(s) you configured.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://cloud.google.com/vpc/docs/using-firewalls](https://cloud.google.com/vpc/docs/using-firewalls)
