Scan Azure VMs in the same subnet with Nmap

Last weekend I made a small PoC to use Nmap to scan an Azure VM. I then came up with an idea to write a script to get scan all live hosts in the same subnet from the given VM.

This article is just to share with you the script I wrote.

Below is the script:

#!/bin/bash
# This script is used with nmap (https://nmap.org/) to discover live host in the same subnet.
# Use this script for testing purpose only.
# You need Reader role to get VM's and network info before scanning with Nmap.

target_vm_resource_id="$1"

echo "[+] Target resource id: ${target_vm_resource_id}"
# Get network interface card (nic) resource Id
target_vm_nic_id=$(az vm show --ids "${target_vm_resource_id}" --query 'networkProfile.networkInterfaces[].id' -o tsv)

if [ -z "${target_vm_nic_id}" ]; then
  echo "[!] Fail to get the nic resource Id"
  exit
else
  # Get subnet Id of the nic resource id
  subnet_resource_id=$(az network nic show --ids "${target_vm_nic_id}" --query 'ipConfigurations[].subnet.id' -o tsv)
  if [ -z "${subnet_resource_id}" ]; then
    echo "[!] Fail to get the nic resource Id"
    exit
  else
    echo "[+] Start retrieving address prefix"
    # Get address prefix for nmap scan
    address_prefix=$(az network vnet subnet show --ids "${subnet_resource_id}" --query 'addressPrefix' -o tsv)
    if [ -z "${address_prefix}" ]; then
      echo "[!] Fail to get the nic resource Id"
      exit
    else
      echo "[+] Found an address prefix: $address_prefix"
    fi
  fi
fi

# Construct nmap scan command line
# Use -Pn to by pass blocking ICMP
# Use -Sv to determine the version of the service running on port
# Use --script=vuln to scan vulnerability
# Use -F to scan 100 common ports
nmap_scan='nmap -Pn -sV --script=vuln -F'
scan_cmd="${nmap_scan} ${address_prefix}"

echo "[+] Scan cmd is: ${scan_cmd}"
eval "${scan_cmd}"

You just need to provide the resource Id of the target VM. You also need Az CLI to work with Azure VM and Azure Networking resources. Reader role is needed as well.

You can modify the script to make a list of targets and create a loop.

This entry was posted in Network Security, Security Automation and tagged . Bookmark the permalink.

2 Responses to Scan Azure VMs in the same subnet with Nmap

  1. wangh says:

    Is there a special configuration I need to be aware?

    Thanks for the article and script.

    • azsec says:

      Hi wangh,

      In my lab environment I used default NSG rules and attached them to the same subnet. In that case I was able to use general nmap to scan hosts in the same subnet. If you attach your NSG at network interface card (nic) level you need different scan flag for nmap (e.g using Null or FIN scan if you feel that your package is dropped by backend Azure infrastructure network.

      Please let me know if you’d like to have further discussion.

Leave a Reply

Your email address will not be published.