id: azure-nsg-ssh-unrestricted
info:
  name: Unrestricted SSH Access in Azure NSGs
  author: princechaddha
  severity: high
  description: |
    Ensure that Microsoft Azure network security groups (NSGs) do not allow unrestricted access on TCP port 22, used for Secure Shell (SSH), to prevent unauthorized access and potential breaches.
  impact: |
    Unrestricted SSH access can expose virtual machines and other resources to security risks such as brute force attacks, potentially compromising sensitive information.
  remediation: |
    Modify NSG rules to restrict SSH access by allowing only specific, trusted IP addresses to connect on TCP port 22.
  reference:
    - https://docs.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview
  tags: cloud,devops,azure,microsoft,nsg,azure-cloud-config

flow: |
  code(1);
  for (let NsgData of iterate(template.nsgdata)) {
    NsgData = JSON.parse(NsgData)
    set("nsg", NsgData.name)
    set("resourcegroup", NsgData.resourceGroup)
    code(2)
  }

self-contained: true
code:
  - engine:
      - sh
      - bash
    source: |
      az network nsg list --query '[*].{name:name, resourceGroup:resourceGroup}' --output json

    extractors:
      - type: json
        name: nsgdata
        internal: true
        json:
          - '.[]'

  - engine:
      - sh
      - bash
    source: |
      az network nsg rule list --nsg-name $nsg --resource-group $resourcegroup --query "[?direction=='Inbound' && access=='Allow' && protocol=='TCP' && (destinationPortRange=='22')]"

    matchers:
      - type: word
        words:
          - '"sourceAddressPrefix": "*"'
          - '"sourceAddressPrefix": "internet"'
          - '"sourceAddressPrefix": "any"'

    extractors:
      - type: dsl
        dsl:
          - 'nsg + " has unrestricted access on TCP port 22"'
# digest: 4b0a00483046022100a38b9826846e4b62a734e3f2daa7b2e6c63f2990119fdad01de703f54e75ff47022100ab091dcf5152092c10070be077a573e5853d9138f1fd9ea02bb35ad21c679cf6:922c64590222798bb761d5b6d8e72950