IP Intelligence Tools
Attack Chain Position
graph LR
A[Target Identification] --> B[DNS Enumeration]
B --> C[IP Intelligence]
C --> D[Port Scanning]
D --> E[Service Enumeration]
C --> F[Network Mapping]
F --> D
style C fill:#f9d56e,stroke:#333,stroke-width:2px
IP Intelligence sits at the critical junction between initial target identification and active reconnaissance. Understanding the IP landscape of your target helps you:
- Map the attack surface — Identify all IP ranges, subnets, and associated infrastructure
- Understand network topology — Learn about the target’s ISP, hosting provider, and network architecture
- Discover related assets — Find other IPs owned by the same organization
- Assess reputation — Determine if IPs have been flagged for malicious activity
- Plan scanning strategies — Know which ranges to scan and which to avoid
Table of Contents
- WHOIS for IP Addresses
- Regional Internet Registries
- NetBlocks and IP Allocation Data
- IP Reputation Tools
- ASN Lookup
- IP Geolocation
- BGP Routing Information
- IP Range Discovery
- Correlating IP Intelligence with DNS Data
- Building IP Intelligence Reports
- OSCP Relevance of IP Intelligence
1. WHOIS for IP Addresses
What is WHOIS?
WHOIS is a query and response protocol used for retrieving information about the registered users or assignees of an Internet resource, such as domain names, IP addresses, and autonomous systems. For IP addresses, WHOIS provides:
- Registrant information — Organization or individual that owns the IP
- Network range — The CIDR block the IP belongs to
- Registration dates — When the allocation was created and last updated
- Contact details — Administrative and technical contacts
- Registrar/Registry — The organization managing the allocation
- Abuse contacts — Who to contact for abuse reports
WHOIS Commands
Using the whois Command-Line Tool
The whois utility is pre-installed on most Linux distributions, including Kali Linux.
# Basic WHOIS lookup for an IP address
whois 8.8.8.8
# Query a specific WHOIS server
whois -h whois.arin.net 8.8.8.8
# Query for a CIDR block
whois 192.168.0.0/24
# Limit output to specific fields using grep
whois 8.8.8.8 | grep -i "netrange\|orgname\|address\|city\|country"
# Save output to file for analysis
whois 8.8.8.8 > /tmp/whois_8.8.8.8.txt
Interpreting WHOIS Output
# Example WHOIS output for 8.8.8.8
$ whois 8.8.8.8
NetRange: 8.8.8.0 - 8.8.8.255
CIDR: 8.8.8.0/24
NetName: LVLT-GOGL-8-8-8
NetHandle: NET-8-8-8-0-1
Parent: 8.0.0.0 - 8.255.255.255
NetType: Direct Allocation
OriginAS: AS15169
Organization: Google LLC (GOGL)
RegDate: 2014-03-14
Updated: 2014-03-14
Comment: All Google Abuse reports can be submitted via http://www.google.com/a/complain.html
Ref: https://rdap.arin.net/registry/ip/8.8.8.0
OrgName: Google LLC
OrgId: GOGL
Address: 1600 Amphitheatre Parkway
City: Mountain View
StateProv: CA
PostalCode: 94043
Country: US
RegDate: 2000-03-30
Updated: 2019-10-31
Comment: Please be sure to specify which service you are contacting abuse for.
Ref: https://rdap.arin.net/registry/org/google-llc/GOGL
AdminHandle: ZG39-ARIN
AdminName: Google LLC
AdminEmail: arn-admin@google.com
TechHandle: GOOGLE48-ARIN
TechName: DOMAIN OPERATIONS
TechEmail: network-abuse@google.com
NoAgent: This Domain has been registered without an Agent.
Key Fields to Extract
| Field | Description | OSCP Relevance |
|---|---|---|
NetRange / CIDR |
IP range the target belongs to | Identify entire subnet for scanning |
OrgName |
Organization name | Confirm target ownership |
OriginAS |
Autonomous System Number | Find related infrastructure |
Country |
Country code | Understand legal jurisdiction |
RegDate |
Registration date | Assess infrastructure age |
Comment |
Additional notes | May contain useful info |
TechEmail |
Technical contact email | Potential social engineering target |
AdminEmail |
Admin contact email | Potential social engineering target |
Automated WHOIS Parsing
# Extract just the organization name
whois 8.8.8.8 | grep -i "OrgName:" | head -1 | awk '{print $2, $3, $4}'
# Extract the CIDR block
whois 8.8.8.8 | grep -i "CIDR:" | awk '{print $2}'
# Extract the ASN
whois 8.8.8.8 | grep -i "OriginAS:" | awk '{print $2}'
# Extract country
whois 8.8.8.8 | grep -i "Country:" | awk '{print $2}'
# Extract all email addresses
whois 8.8.8.8 | grep -iE "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
Using w (short for whois) with whois
# Some systems have 'w' as an alias
w 8.8.8.8
# Or use the -r flag to prevent recursive lookups
whois -r 8.8.8.8
WHOIS for Domain-to-IP Correlation
# WHOIS on a domain to find associated IPs
whois example.com
# Look for Name Servers which may reveal infrastructure
whois example.com | grep -i "nserver\|nameserver"
# Look for DNSSEC information
whois example.com | grep -i "dnssec"
2. Regional Internet Registries
Overview
The Internet Assigned Numbers Authority (IANA) delegates IP address allocation to five Regional Internet Registries (RIRs). Each RIR manages IP addresses for a specific geographic region.
RIR Reference Table
| RIR | Region | Website | WHOIS Server | IP Range Examples |
|---|---|---|---|---|
| ARIN | North America, parts of Caribbean | arin.net | whois.arin.net | 3.0.0.0/8, 8.0.0.0/8, 72.0.0.0/8 |
| RIPE NCC | Europe, Middle East, Central Asia | ripe.net | whois.ripe.net | 5.0.0.0/8, 31.0.0.0/8, 77.0.0.0/8 |
| APNIC | Asia-Pacific | apnic.net | whois.apnic.net | 1.0.0.0/8, 14.0.0.0/8, 61.0.0.0/8 |
| LACNIC | Latin America, Caribbean | lacnic.net | whois.lacnic.net | 177.0.0.0/8, 189.0.0.0/8, 191.0.0.0/8 |
| AFRINIC | Africa | afrinic.net | whois.afrinic.net | 41.0.0.0/8, 102.0.0.0/8, 196.0.0.0/8 |
Querying Each RIR
# ARIN (North America)
whois -h whois.arin.net 8.8.8.8
# RIPE NCC (Europe)
whois -h whois.ripe.net 1.1.1.1
# APNIC (Asia-Pacific)
whois -h whois.apnic.net 114.114.114.114
# LACNIC (Latin America)
whois -h whois.lacnic.net 200.10.10.10
# AFRINIC (Africa)
whois -h whois.afrinic.net 41.0.0.1
RIR-Specific Output Differences
Each RIR formats WHOIS output differently. Here’s what to look for in each:
ARIN Format
NetRange: 8.8.8.0 - 8.8.8.255
CIDR: 8.8.8.0/24
NetName: LVLT-GOGL-8-8-8
Organization: Google LLC (GOGL)
RegDate: 2014-03-14
Updated: 2014-03-14
Ref: https://rdap.arin.net/registry/ip/8.8.8.0
RIPE NCC Format
inetnum: 1.1.1.0 - 1.1.1.255
netname: CLOUDFLARENET
descr: Cloudflare, LLC
country: US
admin-c: CC12897-RIPE
tech-c: CC12897-RIPE
status: ASSIGNED PA
mnt-by: MAINT-AS13335
source: RIPE # Filtered
APNIC Format
inetnum: 114.114.114.0 - 114.114.114.255
netname: PUBLIC-DNS-CN
descr: Public DNS Project
country: CN
admin-c: PD123-AP
tech-c: PD123-AP
status: ASSIGNED PORTABLE
mnt-by: MAINT-AP-PUBLICDNS
source: APNIC # Filtered
Finding the Correct RIR
# Use the global WHOIS server to find the correct RIR
whois 8.8.8.8 | grep -i "refer\|rwhois\|remarks"
# Or use the IANA WHOIS
whois -h whois.iana.net 8.8.8.8
RIR RDAP (Registration Data Access Protocol)
RDAP is the modern replacement for WHOIS, providing structured JSON responses:
# ARIN RDAP
curl -s "https://rdap.arin.net/registry/ip/8.8.8.8" | python3 -m json.tool
# RIPE RDAP
curl -s "https://rdap.db.ripe.net/ip/1.1.1.1.json" | python3 -m json.tool
# APNIC RDAP
curl -s "https://rdap.apnic.net/ip/114.114.114.114" | python3 -m json.tool
3. NetBlocks and IP Allocation Data
What is a NetBlock?
A netblock (network block) is a contiguous range of IP addresses allocated to a specific organization. Understanding netblocks helps you:
- Discover the full attack surface — Find all IPs owned by the target
- Identify related infrastructure — Find development, staging, and production environments
- Plan comprehensive scans — Ensure you don’t miss any assets
Finding NetBlocks
# Extract netblock from WHOIS
whois 8.8.8.8 | grep -i "NetRange\|CIDR\|inetnum"
# Find all netblocks for an organization
whois -h whois.arin.net "Google LLC" | grep -i "NetRange\|CIDR"
# Use the organization handle
whois -h whois.arin.net GOGL | grep -i "NetRange\|CIDR"
CIDR Notation Reference
| CIDR | Hosts | Example | Common Use |
|---|---|---|---|
| /8 | 16,777,216 | 8.0.0.0/8 | Large organizations, ISPs |
| /12 | 1,048,576 | 10.0.0.0/12 | Enterprise networks |
| /16 | 65,536 | 192.168.0.0/16 | Medium organizations |
| /20 | 4,096 | 10.0.0.0/20 | Department networks |
| /24 | 256 | 192.168.1.0/24 | Small networks, subnets |
| /28 | 16 | 192.168.1.0/28 | Very small networks |
| /32 | 1 | 8.8.8.8/32 | Single host |
Calculating IP Ranges
# Use Python to calculate IP ranges
python3 -c "
import ipaddress
network = ipaddress.ip_network('8.8.8.0/24', strict=False)
print(f'Network: {network}')
print(f'First host: {network.network_address + 1}')
print(f'Last host: {network.broadcast_address - 1}')
print(f'Total hosts: {network.num_addresses - 2}')
print(f'Broadcast: {network.broadcast_address}')
"
# Convert CIDR to start-end range
python3 -c "
import ipaddress
net = ipaddress.ip_network('10.0.0.0/16', strict=False)
print(f'{net.network_address} - {net.broadcast_address}')
"
# Check if an IP is in a range
python3 -c "
import ipaddress
ip = ipaddress.ip_address('8.8.8.8')
net = ipaddress.ip_network('8.8.8.0/24')
print(f'Is 8.8.8.8 in 8.8.8.0/24? {ip in net}')
"
IP Allocation Types
| Type | Description | OSCP Relevance |
|---|---|---|
| Direct Allocation | Assigned directly to an organization | Target owns this infrastructure |
| Provider-Specific (PS) | Assigned by ISP to customer | May share with other customers |
| Provider-Independent (PI) | Portable across providers | Stable, organization-controlled |
| Reserved | Special purpose (loopback, private) | Not routable, skip in scanning |
| Shared/Proxy | Shared hosting environment | May contain multiple tenants |
Private IP Ranges (RFC 1918)
| Range | CIDR | Hosts |
|---|---|---|
| 10.0.0.0 – 10.255.255.255 | 10.0.0.0/8 | 16,777,216 |
| 172.16.0.0 – 172.31.255.255 | 172.16.0.0/12 | 1,048,576 |
| 192.168.0.0 – 192.168.255.255 | 192.168.0.0/16 | 65,536 |
Special IP Ranges to Know
| Range | Purpose | Notes |
|---|---|---|
| 127.0.0.0/8 | Loopback | Localhost, not routable |
| 169.254.0.0/16 | Link-local | APIPA, auto-assigned |
| 224.0.0.0/4 | Multicast | Not for unicast scanning |
| 240.0.0.0/4 | Reserved | Future use |
| 0.0.0.0/8 | “This” network | Special purpose |
4. IP Reputation Tools
Overview of IP Reputation
IP reputation tools help you understand whether an IP address has been associated with malicious activity. While more relevant for defensive security, these tools can also help attackers:
- Identify compromised infrastructure — Find IPs already flagged for attacks
- Discover related malicious activity — Understand what attacks have come from a range
- Assess target security posture — Poor reputation may indicate weak security
- Find honeypots and traps — Avoid IPs that are monitored
AbuseIPDB
AbuseIPDB is a crowdsourced database of abusive IP addresses.
# Using the AbuseIPDB API
# First, get an API key from abuseipdb.com
# Check IP reputation
curl -s "https://api.abuseipdb.com/api/v2/check?ipAddress=8.8.8.8" \
-H "Key: YOUR_API_KEY" \
-H "Accept: application/json" | python3 -m json.tool
# Key response fields:
# - data.abuseConfidenceScore (0-100)
# - data.totalReports
# - data.usageAbuseInformation (list of abuse types)
# - data.isWhitelisted
# - data.lastReportedAt
AbuseIPDB Score Interpretation
| Score Range | Meaning | Action |
|---|---|---|
| 0-20 | Low confidence | Likely legitimate |
| 21-50 | Medium confidence | Investigate further |
| 51-80 | High confidence | Likely malicious |
| 81-100 | Very high confidence | Almost certainly malicious |
VirusTotal
VirusTotal scans files and URLs against multiple antivirus engines and domain/IP reputation databases.
# Using VirusTotal API
# Get API key from virustotal.com
# Check IP reputation
curl -s "https://www.virustotal.com/api/v3/ip_addresses/8.8.8.8" \
-H "x-apikey: YOUR_API_KEY" | python3 -m json.tool
# Key response fields:
# - data.attributes.last_analysis_stats (malicious, suspicious, harmless, undetected)
# - data.attributes.reputation
# - data.attributes.tags
# - data.attributes.network (CIDR info)
# - data.attributes.as_owner
VirusTotal CLI Tool
# Install VirusTotal CLI
pip3 install virustotal-cli
# Configure API key
vt config --add apikey YOUR_API_KEY
# Check an IP
vt ip_address get 8.8.8.8
# Get relationships (whois, resolutions, etc.)
vt ip_address get 8.8.8.8 --relationships whois,resolutions
GreyNoise
GreyNoise identifies background internet noise — scanners, bots, and crawlers that are not targeting you specifically.
# GreyNoise API
# Get API key from greynoise.io
# Check if an IP is background noise
curl -s "https://api.greynoise.io/v2/noise/ip/8.8.8.8" \
-H "key: YOUR_API_KEY" | python3 -m json.tool
# Key response fields:
# - noise: true/false (is this background noise?)
# - name: Service name (e.g., "Google DNS")
# - tags: Classification tags
# - first_seen / last_seen: Detection timeline
# - cx: Contextual information
GreyNoise Classification
| Classification | Description |
|---|---|
| Noise | Background internet scanning, not targeted |
| Gone | Previously seen noise, no longer active |
| Unknown | Not in GreyNoise database |
| GNIP | GreyNoise Intelligence Platform coverage |
Shodan
Shodan is the premier search engine for internet-connected devices. It provides extensive IP intelligence.
# Shodan CLI
# Install: pip3 install shodan
# Configure: shodan init YOUR_API_KEY
# Search for an IP
shodan ip 8.8.8.8
# Get detailed information
shodan info
# Search for specific services on an IP range
shodan search "8.8.8.0/24"
# Search for specific services
shodan search "org:\"Google LLC\" http.title:\"Dashboard\""
# Search for vulnerable services
shodan search "ssl.cert.subject.cn:example.com"
# Get ports and services
shodan ip 8.8.8.8 --fields ports,hostnames,org,country_name
# Export results
shodan search "org:\"Target Corp\"" --fields ip_str,port,org --separator "," > results.csv
Shodan Search Filters
| Filter | Description | Example |
|---|---|---|
port: |
Specific port | port:22 |
org: |
Organization | org:"Google LLC" |
country: |
Country code | country:US |
city: |
City name | city:"New York" |
os: |
Operating system | os:"Ubuntu" |
product: |
Product name | product:"Apache" |
version: |
Version number | version:"2.4.49" |
has_screenshot: |
Has screenshot | has_screenshot:true |
ssl: |
SSL certificate info | ssl.cert.subject.cn:example.com |
http.title: |
HTTP page title | http.title:"Login" |
net: |
IP range | net:8.8.8.0/24 |
Shodan Python API
import shodan
API_KEY = "YOUR_API_KEY"
api = shodan.Shodan(API_KEY)
# Look up an IP
try:
results = api.ip("8.8.8.8")
print(f"Organization: {results.get('org', 'N/A')}")
print(f"Country: {results.get('country_name', 'N/A')}")
print(f"Ports: {results.get('ports', [])}")
print(f"Hostnames: {results.get('hostnames', [])}")
except shodan.APIError as e:
print(f"Error: {e}")
# Search for services
try:
results = api.search('org:"Target Corp" port:22')
print(f"Total results: {results.get('total', 0)}")
for match in results.get('matches', [])[:10]:
print(f"IP: {match.get('ip_str')} - Ports: {match.get('port')}")
except shodan.APIError as e:
print(f"Error: {e}")
IPinfo
IPinfo provides IP address geolocation, ASN, company, and carrier data.
# IPinfo CLI
# Install: pip3 install ipinfo
# Configure: ipinfo auth YOUR_TOKEN
# Look up an IP
ipinfo 8.8.8.8
# Get detailed JSON output
ipinfo 8.8.8.8 --format json
# Bulk lookup from file
ipinfo -input ips.txt
# Key fields returned:
# - ip: IP address
# - hostname: Reverse DNS
# - ansi: ASN info (asn, name, domain)
# - loc: Location (lat, lon)
# - org: Organization
# - city, region, country
# - postal, timezone
# - domains: Associated domains
BGP Toolkit
BGP Toolkit provides BGP routing information and ASN details.
# Using bgp.he.net API
curl -s "https://bgp.he.net/ip/8.8.8.8/json" | python3 -m json.tool
# Get ASN information
curl -s "https://bgp.he.net/as/15169/json" | python3 -m json.tool
# Get prefix information
curl -s "https://bgp.he.net/prefix/8.8.8.0/24/json" | python3 -m json.tool
IP Reputation Comparison Table
| Tool | Best For | Free Tier | API Available | Key Strength |
|---|---|---|---|---|
| AbuseIPDB | Abuse reports | 100 req/day | Yes | Crowdsourced abuse data |
| VirusTotal | Multi-engine scanning | 4 req/min | Yes | 70+ security vendors |
| GreyNoise | Noise vs. targeted | Limited | Yes | Background noise filtering |
| Shodan | Service discovery | 100 req/day | Yes | Internet-wide scanning |
| IPinfo | Geolocation & ASN | 50,000 req/mo | Yes | Fast, reliable data |
| BGP Toolkit | BGP routing | Free | Yes | Routing intelligence |
5. ASN Lookup
What is an ASN?
An Autonomous System Number (ASN) is a unique identifier assigned to an autonomous system — a collection of IP prefixes under the control of one or more network operators that presents a common routing policy to the internet.
Why ASN Matters for Penetration Testing
- Scope Identification — ASNs help identify all IP ranges owned by a target organization
- Infrastructure Mapping — Understand the target’s network topology and peering relationships
- Related Asset Discovery — Find other organizations or services using the same ASN
- BGP Hijack Detection — Monitor for unusual routing changes
- Cloud Provider Identification — Determine if the target uses AWS, Azure, GCP, etc.
Common Cloud Provider ASNs
| Provider | ASN | Organization |
|---|---|---|
| AWS (US East) | AS16509 | AMAZON-02 |
| AWS (Global) | AS14618 | AMAZON-AES |
| Azure | AS8075 | Microsoft Corporation |
| Google Cloud | AS15169 | Google LLC |
| DigitalOcean | AS14061 | DigitalOcean LLC |
| Cloudflare | AS13335 | Cloudflare Inc |
| Akamai | AS2898 | Akamai Technologies |
| Fastly | AS54113 | Fastly |
ASN Lookup Methods
Using whois
# Find ASN from IP
whois 8.8.8.8 | grep -i "OriginAS\|ASNumber\|route:"
# Look up ASN directly
whois AS15169
# Get all prefixes for an ASN
whois AS1569 | grep -i "route\|inetnum\|NetRange"
Using bgpq4
# Install bgpq4
sudo apt install bgpq4
# Get prefixes for an ASN
bgpq4 -4 AS15169
# Get IPv6 prefixes
bgpq4 -6 AS15169
# Get prefixes in CIDR format
bgpq4 -4 -c AS15169
Using Online Tools
# Hurricane Electric BGP Toolkit
curl -s "https://bgp.he.net/as/15169/json" | python3 -m json.tool
# Team Cymru WHOIS
whois -h whois.cymru.com "AS 15169"
# RADB (Routing Database)
whois -h radb.net AS15169
Using Python
import requests
# Hurricane Electric API
def lookup_asn(asn):
url = f"https://bgp.he.net/as/{asn}/json"
response = requests.get(url)
data = response.json()
if 'asn' in data:
print(f"ASN: {data['asn']}")
print(f"Name: {data['description']}")
print(f"Country: {data.get('country_code', 'N/A')}")
print(f"IPv4 Prefixes: {data.get('num_ipv4_prefixes', 'N/A')}")
print(f"IPv6 Prefixes: {data.get('num_ipv6_prefixes', 'N/A')}")
# Get prefixes
prefixes_url = f"https://bgp.he.net/as/{asn}/prefixes4/json"
prefixes = requests.get(prefixes_url).json()
if 'prefixes' in prefixes:
for prefix in prefixes['prefixes'][:10]:
print(f" {prefix['ip']} - {prefix.get('name', 'N/A')}")
lookup_asn(15169)
ASN Relationship Types
| Relationship | Description |
|---|---|
| Customer | Pays the ASN for transit |
| Provider | Provides transit to the ASN |
| Peer | Exchanges traffic without payment |
| Sibling | Same organization, different ASN |
Finding All IPs in an ASN
# Get all IPv4 prefixes for an ASN
bgpq4 -4 AS15169 > /tmp/google_prefixes.txt
# Count total IPs
python3 -c "
import ipaddress
total = 0
with open('/tmp/google_prefixes.txt') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
net = ipaddress.ip_network(line, strict=False)
total += net.num_addresses
print(f'Total IPs in AS15169: {total:,}')
"
# Convert to nmap scan list
bgpq4 -4 AS15169 | grep -v "^#" | grep -v "^$" > /tmp/scan_targets.txt
6. IP Geolocation
What is IP Geolocation?
IP geolocation maps an IP address to a physical location (country, region, city, coordinates). While useful for intelligence gathering, it has significant limitations.
Geolocation Accuracy
| Level | Accuracy | Reliability |
|---|---|---|
| Country | ~99% | Very High |
| Region/State | ~70-90% | High |
| City | ~50-70% | Medium |
| Coordinates | ~30-50% | Low |
| ZIP/Postal | ~20-40% | Low |
Geolocation Limitations
- VPN and Proxy — IP may be in a different location than the user
- CDN and Load Balancers — IP may be a CDN edge node, not the origin
- Cloud Hosting — Data center location ≠ business location
- Mobile Networks — Cell tower location may not match user location
- NAT and CGNAT — Multiple users share one IP
- Database Accuracy — Different databases have different accuracy rates
Geolocation Tools
Using ipinfo.io
# Command line
curl -s "https://ipinfo.io/8.8.8.8/json" | python3 -m json.tool
# Response includes:
# - ip, hostname
# - loc: "latitude,longitude"
# - city, region, country
# - postal, timezone
# - org, asn
Using ip-api.com
# Free API (no key required)
curl -s "http://ip-api.com/json/8.8.8.8" | python3 -m json.tool
# Response includes:
# - status, country, countryCode
# - regionName, city
# - lat, lon
# - timezone, isp, org, as
Using maxmind (GeoLite2)
# Download MaxMind GeoLite2 database
# Register at dev.maxmind.com for free account
# Install maxmind-db tools
pip3 install maxminddb-geolite2
# Python usage
import maxminddb
reader = maxminddb.open_database('GeoLite2-City.mmdb')
result = reader.get('8.8.8.8')
if result:
print(f"Country: {result['country'].get('names', {}).get('en', 'N/A')}")
print(f"City: {result['city'].get('names', {}).get('en', 'N/A')}")
print(f"Latitude: {result.get('location', {}).get('latitude', 'N/A')}")
print(f"Longitude: {result.get('location', {}).get('longitude', 'N/A')}")
reader.close()
Using whois for Location
# Extract location from WHOIS
whois 8.8.8.8 | grep -i "city\|state\|country\|address"
Geolocation Visualization
import json
import requests
def geolocate_ips(ip_list):
results = []
for ip in ip_list:
try:
resp = requests.get(f"http://ip-api.com/json/{ip}")
data = resp.json()
if data.get('status') == 'success':
results.append({
'ip': ip,
'city': data.get('city'),
'country': data.get('country'),
'lat': data.get('lat'),
'lon': data.get('lon'),
'isp': data.get('isp')
})
except Exception as e:
print(f"Error looking up {ip}: {e}")
return results
# Example usage
ips = ['8.8.8.8', '1.1.1.1', '9.9.9.9']
for result in geolocate_ips(ips):
print(f"{result['ip']} -> {result['city']}, {result['country']} ({result['isp']})")
7. BGP Routing Information
What is BGP?
Border Gateway Protocol (BGP) is the protocol that glues the Internet together. It’s the routing protocol used between autonomous systems (ASes) to exchange reachability information.
Why BGP Matters for Penetration Testing
- Route Hijacking Detection — Identify if routes have been hijacked
- Network Topology Understanding — Understand how traffic flows to the target
- Prefix Discovery — Find all IP prefixes announced by an ASN
- Peering Analysis — Understand the target’s network relationships
- DDoS Assessment — Understand routing resilience
BGP Tools and Resources
Looking Glass Routers
# Hurricane Electric Looking Glass
# Visit: https://www.he.net/looking_glass
# ARIN Looking Glass
# Visit: https://lg.arin.net/
# RIPE Looking Glass
# Visit: https://lg.ripe.net/
Using bgpstream
# Install bgpstream
pip3 install bgpstream
# Search BGP updates for a prefix
bgpstream -f RIPE RIS -s 2024-01-01 -e 2024-01-02 -i 8.8.8.0/24
# Search for an ASN
bgpstream -f RIPE RIS -s 2024-01-01 -e 2024-01-02 -a AS15169
Using pybgp
import requests
# Check BGP routing for a prefix
def check_bgp_route(prefix):
url = f"https://stat.ripe.net/data/routing-info/data.json?resource={prefix}"
response = requests.get(url)
data = response.json()
if 'data' in data:
info = data['data']['routing_info']
for entry in info:
print(f"Prefix: {entry.get('prefix', 'N/A')}")
print(f"Origin AS: {entry.get('origin_as', 'N/A')}")
print(f"First Seen: {entry.get('first_seen', 'N/A')}")
print(f"Last Seen: {entry.get('last_seen', 'N/A')}")
print("---")
check_bgp_route("8.8.8.0/24")
BGP Route Analysis
# Check if a prefix is being announced correctly
curl -s "https://stat.ripe.net/data/routing-info/data.json?resource=8.8.8.0/24" | python3 -m json.tool
# Check ASN details
curl -s "https://stat.ripe.net/data/as-oversight/data.json?resource=AS15169" | python3 -m json.tool
# Check prefix validity
curl -s "https://stat.ripe.net/data/prefix-overview/data.json?resource=8.8.8.0/24" | python3 -m json.tool
8. IP Range Discovery
Discovering IP Ranges Owned by a Target
Method 1: WHOIS Organization Search
# Search WHOIS by organization name
whois -h whois.arin.net "Target Corporation" | grep -i "NetRange\|CIDR"
# Search by organization handle
whois -h whois.arin.net TARGET123 | grep -i "NetRange\|CIDR"
Method 2: Reverse DNS + WHOIS
# Get all IPs from DNS, then find their ranges
for ip in $(dig +short target.com A | sort -u); do
echo "=== $ip ==="
whois $ip | grep -i "CIDR\|NetRange\|inetnum"
done
Method 3: ASN-Based Discovery
# Find the ASN of the target
TARGET_ASN=$(whois target.com | grep -i "OriginAS\|ASNumber" | head -1 | awk '{print $NF}')
# Get all prefixes for that ASN
bgpq4 -4 $TARGET_ASN > /tmp/target_prefixes.txt
# Review the prefixes
cat /tmp/target_prefixes.txt
Method 4: Certificate Transparency Logs
# Use crt.sh to find domains, then resolve to IPs
curl -s "https://crt.sh/?q=%25.target.com&output=json" | \
python3 -c "
import sys, json
data = json.load(sys.stdin)
names = set()
for entry in data:
name = entry.get('name_value', '')
if name:
names.add(name)
for name in sorted(names):
print(name)
" | while read domain; do
dig +short "$domain" A 2>/dev/null
done | sort -u
Method 5: Shodan Organization Search
# Search Shodan for all IPs in an organization
shodan search "org:\"Target Corporation\"" --fields ip_str,port --separator "," > /tmp/shodan_results.csv
# Count unique IPs
cut -d',' -f1 /tmp/shodan_results.csv | sort -u | wc -l
IP Range Consolidation Script
#!/usr/bin/env python3
"""
Consolidate IP ranges from multiple sources into a unified scan list.
"""
import ipaddress
import sys
def consolidate_ranges(ranges):
"""Merge overlapping IP ranges."""
networks = []
for r in ranges:
try:
networks.append(ipaddress.ip_network(r.strip(), strict=False))
except ValueError:
continue
# Merge overlapping networks
merged = list(ipaddress.collapse_addresses(networks))
return merged
def main():
# Read ranges from file
with open(sys.argv[1], 'r') as f:
ranges = [line.strip() for line in f if line.strip() and not line.startswith('#')]
merged = consolidate_ranges(ranges)
print(f"Original ranges: {len(ranges)}")
print(f"Consolidated ranges: {len(merged)}")
print(f"Total IPs: {sum(n.num_addresses for n in merged):,}")
for net in merged:
print(net)
if __name__ == "__main__":
main()
9. Correlating IP Intelligence with DNS Data
The Power of Correlation
Combining IP intelligence with DNS data creates a comprehensive picture of the target’s infrastructure:
graph TD
A[DNS Records] --> D[Correlation Engine]
B[WHOIS Data] --> D
C[ASN Information] --> D
D --> E[Unified Asset Map]
E --> F[Attack Surface Report]
E --> G[Network Topology]
E --> H[Related Assets]
Correlation Techniques
Reverse DNS + Forward DNS Matching
# Get forward DNS
dig +short target.com A
# Get reverse DNS for each IP
for ip in $(dig +short target.com A); do
rev=$(dig +short -x $ip)
echo "$ip -> $rev"
done
# Check for mismatches (potential shadow IT)
for ip in $(dig +short target.com A); do
rev=$(dig +short -x $ip)
fwd=$(dig +short target.com A)
if [[ ! "$rev" == *"target.com"* ]]; then
echo "MISMATCH: $ip reverse=$rev"
fi
done
WHOIS + DNS Correlation
# Get all DNS-resolved IPs
dig +short target.com A > /tmp/dns_ips.txt
# Get WHOIS info for each
while read ip; do
org=$(whois $ip | grep -i "OrgName:" | head -1 | cut -d: -f2- | xargs)
asn=$(whois $ip | grep -i "OriginAS:" | head -1 | cut -d: -f2 | xargs)
echo "$ip | $org | $asn"
done < /tmp/dns_ips.txt
Building a Correlation Matrix
#!/usr/bin/env python3
"""
Correlate DNS, WHOIS, and ASN data for comprehensive IP intelligence.
"""
import subprocess
import json
import socket
def get_dns_records(domain):
"""Get all DNS A records for a domain."""
try:
results = socket.getaddrinfo(domain, None, socket.AF_INET)
return list(set([r[4][0] for r in results]))
except socket.gaierror:
return []
def get_whois_info(ip):
"""Get WHOIS information for an IP."""
try:
result = subprocess.run(['whois', ip], capture_output=True, text=True, timeout=30)
info = {}
for line in result.stdout.split('\n'):
if 'OrgName:' in line:
info['org'] = line.split(':', 1)[1].strip()
elif 'OriginAS:' in line:
info['asn'] = line.split(':', 1)[1].strip()
elif 'Country:' in line:
info['country'] = line.split(':', 1)[1].strip()
elif 'CIDR:' in line:
info['cidr'] = line.split(':', 1)[1].strip()
return info
except Exception:
return {}
def correlate(domain):
"""Correlate DNS and WHOIS data."""
ips = get_dns_records(domain)
results = []
for ip in ips:
whois_info = get_whois_info(ip)
results.append({
'ip': ip,
'whois': whois_info
})
return results
# Example usage
if __name__ == "__main__":
import sys
domain = sys.argv[1] if len(sys.argv) > 1 else "example.com"
results = correlate(domain)
print(json.dumps(results, indent=2))
Correlation Output Example
| IP Address | Forward DNS | Reverse DNS | Organization | ASN | Country | CIDR |
|---|---|---|---|---|---|---|
| 93.184.216.34 | www.example.com | example.com | Example Inc. | AS15133 | US | 93.184.216.0/24 |
| 93.184.216.35 | mail.example.com | mail.example.com | Example Inc. | AS15133 | US | 93.184.216.0/24 |
| 104.21.45.67 | cdn.example.com | — | Cloudflare | AS13335 | US | 104.21.0.0/16 |
10. Building IP Intelligence Reports
Report Structure
A comprehensive IP intelligence report should include:
IP Intelligence Report
├── Executive Summary
│ ├── Target Overview
│ ├── Total IP Assets Found
│ └── Key Findings
├── IP Address Inventory
│ ├── Directly Owned IPs
│ ├── Cloud Provider IPs
│ └── CDN/Proxy IPs
├── Network Topology
│ ├── ASN Information
│ ├── CIDR Blocks
│ └── Peering Relationships
├── Geographic Distribution
│ ├── Country Breakdown
│ ├── Regional Presence
│ └── Data Center Locations
├── Reputation Analysis
│ ├── Abuse Reports
│ ├── Blacklist Status
│ └── Historical Incidents
├── Related Assets
│ ├── Shared Infrastructure
│ ├── Sister Organizations
│ └── Historical Allocations
└── Recommendations
├── Priority Targets
├── Scan Recommendations
└── Risk Assessment
Automated Report Generation Script
#!/usr/bin/env python3
"""
Generate a comprehensive IP intelligence report.
"""
import subprocess
import json
import socket
from datetime import datetime
from collections import defaultdict
class IPIntelligenceReport:
def __init__(self, domain):
self.domain = domain
self.results = {
'domain': domain,
'generated_at': datetime.now().isoformat(),
'ips': [],
'organizations': defaultdict(int),
'countries': defaultdict(int),
'asns': defaultdict(list),
'cidrs': set()
}
def gather_dns(self):
"""Gather DNS A records."""
try:
results = socket.getaddrinfo(self.domain, None, socket.AF_INET)
self.results['dns_ips'] = list(set([r[4][0] for r in results]))
except socket.gaierror:
self.results['dns_ips'] = []
def gather_whois(self, ip):
"""Gather WHOIS data for an IP."""
try:
result = subprocess.run(['whois', ip], capture_output=True, text=True, timeout=30)
info = {}
for line in result.stdout.split('\n'):
if 'OrgName:' in line:
info['org'] = line.split(':', 1)[1].strip()
self.results['organizations'][info['org']] += 1
elif 'OriginAS:' in line:
info['asn'] = line.split(':', 1)[1].strip()
self.results['asns'][info['asn']].append(ip)
elif 'Country:' in line:
info['country'] = line.split(':', 1)[1].strip()
self.results['countries'][info['country']] += 1
elif 'CIDR:' in line:
info['cidr'] = line.split(':', 1)[1].strip()
self.results['cidrs'].add(info['cidr'])
return info
except Exception as e:
return {'error': str(e)}
def generate_report(self):
"""Generate the full report."""
self.gather_dns()
for ip in self.results['dns_ips']:
whois_info = self.gather_whois(ip)
self.results['ips'].append({
'ip': ip,
'whois': whois_info
})
return self.results
def print_summary(self):
"""Print a summary of findings."""
print(f"\n{'='*60}")
print(f"IP INTELLIGENCE REPORT: {self.domain}")
print(f"Generated: {self.results['generated_at']}")
print(f"{'='*60}")
print(f"\nDNS-Resolved IPs: {len(self.results['dns_ips'])}")
print(f"\nOrganizations:")
for org, count in sorted(self.results['organizations'].items(), key=lambda x: -x[1]):
print(f" {org}: {count} IPs")
print(f"\nCountries:")
for country, count in sorted(self.results['countries'].items(), key=lambda x: -x[1]):
print(f" {country}: {count} IPs")
print(f"\nASNs:")
for asn, ips in self.results['asns'].items():
print(f" {asn}: {', '.join(ips[:5])}")
print(f"\nCIDR Blocks:")
for cidr in sorted(self.results['cidrs']):
print(f" {cidr}")
# Example usage
if __name__ == "__main__":
import sys
domain = sys.argv[1] if len(sys.argv) > 1 else "example.com"
report = IPIntelligenceReport(domain)
report.generate_report()
report.print_summary()
Exporting to CSV
# Export IP intelligence to CSV for further analysis
python3 -c "
import csv, subprocess, socket
domain = 'target.com'
ips = [r[4][0] for r in socket.getaddrinfo(domain, None, socket.AF_INET)]
with open('ip_intelligence.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['IP', 'Organization', 'ASN', 'Country', 'CIDR'])
for ip in set(ips):
result = subprocess.run(['whois', ip], capture_output=True, text=True, timeout=30)
org = asn = country = cidr = 'N/A'
for line in result.stdout.split('\n'):
if 'OrgName:' in line: org = line.split(':',1)[1].strip()
elif 'OriginAS:' in line: asn = line.split(':',1)[1].strip()
elif 'Country:' in line: country = line.split(':',1)[1].strip()
elif 'CIDR:' in line: cidr = line.split(':',1)[1].strip()
writer.writerow([ip, org, asn, country, cidr])
"
11. OSCP Relevance of IP Intelligence
How IP Intelligence Applies to OSCP
While OSCP labs and exams focus primarily on active exploitation, IP intelligence plays several supporting roles:
Direct OSCP Applications
| Technique | OSCP Use Case | Frequency |
|---|---|---|
| WHOIS | Identify target organization and related IPs | Medium |
| ASN Lookup | Find all IPs in the target’s ASN for broader scanning | Medium |
| Reverse DNS | Discover additional hostnames and subdomains | High |
| IP Range Discovery | Find related machines in the lab network | High |
| NetBlock Analysis | Identify the full scope of target infrastructure | Medium |
OSCP-Specific Workflow
graph TD
A[Target IP Given] --> B[WHOIS Lookup]
B --> C[Identify CIDR Block]
C --> D[Scan Entire Subnet]
D --> E[Discover Additional Hosts]
E --> F[Enumerate Services]
B --> G[Find Related IPs]
G --> D
C --> H[Check for /24 or /16]
H --> D
Practical OSCP Commands
# Given a target IP, find the full subnet
TARGET_IP="10.10.10.1"
SUBNET=$(echo $TARGET_IP | awk -F. '{print $1"."$2"."$3".0/24"}')
echo "Target subnet: $SUBNET"
# Quick WHOIS on the target
whois $TARGET_IP 2>/dev/null | grep -i "NetRange\|CIDR\|OrgName"
# Scan the discovered subnet
nmap -sn $SUBNET
# Find all live hosts in the subnet
nmap -sn $SUBNET | grep "Nmap scan report" | awk '{print $5}'
# For each live host, do a quick service scan
for host in $(nmap -sn $SUBNET | grep "Nmap scan report" | awk '{print $5}'); do
echo "=== $host ==="
nmap -sV --top-ports 20 $host
done
OSCP Lab Network Characteristics
| Characteristic | Typical Value | Notes |
|---|---|---|
| Subnet Size | /24 (256 IPs) | Most common in labs |
| IP Range | 10.10.x.0/24 or 10.11.x.0/24 | Lab-specific |
| Gateway | .1 or .254 | Usually first or last IP |
| DNS | Provided or internal | May need manual config |
| Internet Access | Limited/None | Labs are isolated |
IP Intelligence in OSCP Exam
# Typical OSCP exam IP intelligence workflow
# Step 1: Note the given IP
TARGET="10.10.10.1"
# Step 2: Determine the subnet (usually /24)
SUBNET="10.10.10.0/24"
# Step 3: Quick ping sweep to find all hosts
nmap -sn $SUBNET > /tmp/ping_sweep.txt
# Step 4: Extract live hosts
grep "Nmap scan report" /tmp/ping_sweep.txt | awk '{print $5}' > /tmp/live_hosts.txt
# Step 5: Quick port scan on all live hosts
for host in $(cat /tmp/live_hosts.txt); do
nmap -sV --top-ports 100 -oA /tmp/scan_$host $host &
done
wait
# Step 6: Review results and prioritize targets
cat /tmp/scan_*.gnmap | grep -v "^#" | grep -v "closed"
Time Management for IP Intelligence in OSCP
| Activity | Recommended Time | Notes |
|---|---|---|
| WHOIS lookup | 2-5 minutes | Quick check, don’t over-invest |
| Subnet discovery | 5-10 minutes | Ping sweep the /24 |
| ASN analysis | 2-5 minutes | Only if relevant |
| IP reputation | Skip in OSCP | Not applicable to lab environments |
| Total | 10-20 minutes | Don’t spend more than 20 min on IP intel |
Key Takeaways for OSCP
- Focus on subnet discovery — The most valuable IP intelligence in OSCP is finding all hosts in the target subnet
- Use WHOIS for context — Understand the target organization, but don’t spend too much time
- Skip reputation tools — Lab IPs won’t have reputation data
- Prioritize active scanning — IP intelligence should feed into your scanning strategy
- Document findings — Record all discovered IPs and their services for your report
Quick Reference Cheat Sheet
Essential Commands
# WHOIS
whois <IP>
whois -h whois.arin.net <IP>
whois AS<number>
# ASN Lookup
bgpq4 -4 AS<number>
whois AS<number>
# IP Geolocation
curl -s "http://ip-api.com/json/<IP>"
curl -s "https://ipinfo.io/<IP>/json"
# Shodan
shodan ip <IP>
shodan search "org:\"Organization Name\""
# IP Range Calculation
python3 -c "import ipaddress; print(list(ipaddress.ip_network('10.0.0.0/24').hosts())[:5])"
# Subnet Discovery (OSCP)
nmap -sn 10.10.10.0/24
Useful One-Liners
# Get all IPs for a domain with WHOIS org
for ip in $(dig +short target.com A); do echo "$ip - $(whois $ip | grep OrgName | head -1)"; done
# Find ASN from IP
whois <IP> | grep -i "OriginAS\|ASNumber" | head -1
# Quick subnet scan
nmap -sn 10.10.10.0/24 | grep "scan report" | awk '{print $5}'
# Export WHOIS to structured format
whois <IP> | grep -E "NetRange|CIDR|OrgName|Country|OriginAS" | sed 's/^[[:space:]]*//'
Summary
IP intelligence is a foundational skill in penetration testing that helps you understand the target’s network infrastructure before active engagement. Key takeaways:
- WHOIS is your primary tool for IP ownership and allocation data
- RIRs manage IP allocation by geographic region — know which one to query
- NetBlocks reveal the full scope of an organization’s IP holdings
- IP Reputation tools help assess risk and identify compromised infrastructure
- ASN analysis uncovers related infrastructure and cloud provider usage
- Geolocation provides context but has significant limitations
- BGP data reveals routing relationships and potential hijacking
- Correlation of IP intelligence with DNS data creates a comprehensive picture
- In OSCP, focus on subnet discovery and host enumeration rather than external reputation tools
Master these techniques to build a thorough understanding of your target’s network landscape before moving to active scanning and exploitation.