# Function to find Azure services by IP address function Find-AzureServiceByIP { param ( [string]$ipAddress, [string]$jsonFilePath = ".data.json" ) # Load the JSON file into a PowerShell object $serviceTags = Get-Content $jsonFilePath | ConvertFrom-Json # Loop through each service tag in the file foreach ($serviceTag in $serviceTags.values) { foreach ($addressPrefix in $serviceTag.properties.addressPrefixes) { # TODO: extract and add IPv6 support # Check if the addressPrefix is an IP range in CIDR format if ($addressPrefix -match "\d+\.\d+\.\d+\.\d+\/\d+") { # Use the 'IPAddress' class to check if the given IP is within the CIDR block if (Test-IpInRange -IpAddress $ipAddress -CIDR $addressPrefix) { # If IP is found, output the service tag details Write-Output ([pscustomobject]@{ Service = $serviceTag.name Region = $serviceTag.properties.region IPRange = $addressPrefix }) } } } } } # Helper function to check if an IP address is within a CIDR block function Test-IpInRange { param ( [string]$IpAddress, [string]$CIDR ) # Split CIDR into base IP and subnet mask bits $cidrParts = $CIDR -split "/" $baseIP = $cidrParts[0] $subnetBits = [int]$cidrParts[1] # Convert IP addresses to byte arrays $ipBytes = [System.Net.IPAddress]::Parse($IpAddress).GetAddressBytes() $baseIpBytes = [System.Net.IPAddress]::Parse($baseIP).GetAddressBytes() # Calculate the number of full bytes and partial bits in the subnet mask $fullBytes = [math]::Floor($subnetBits / 8) $remainingBits = $subnetBits % 8 # Compare full bytes of the IP and base IP for ($i = 0; $i -lt $fullBytes; $i++) { if ($ipBytes[$i] -ne $baseIpBytes[$i]) { return $false } } # Compare the remaining bits in the last byte, if any if ($remainingBits -gt 0) { $mask = 0xFF -bxor (0xFF -shr $remainingBits) if (($ipBytes[$fullBytes] -band $mask) -ne ($baseIpBytes[$fullBytes] -band $mask)) { return $false } } return $true } function Download-ServiceTagsData { param( [string]$jsonFilePath = ".data.json" ) $url = 'https://www.microsoft.com/en-us/download/confirmation.aspx?id=56519' $pageContent = Invoke-WebRequest -Uri $url if ($pageContent.Content -match 'href="(?[a-zA-Z0-9/:\.\-_]*\.json?)"') { $jsonUrl = $matches['url'] } Write-Host "Downloading file from $jsonUrl" Invoke-RestMethod -Uri $jsonUrl -OutFile $jsonFilePath } # Example usage: # Find-AzureServiceByIP -IpAddress "X.X.X.X" -jsonFilePath "C:\path\to\ServiceTags_Public_20240909.json"