Okay, let's create a simple, menu-driven OSINT (Open-Source Intelligence) tool for your homelab using Python. This tool will focus on gathering publicly available information from various online sources.
Important Considerations Before You Start:
- Legality & Ethics: Only gather information that is publicly available and ensure you are not violating any terms of service, privacy laws, or performing any unauthorized access. This tool is for educational and personal research purposes within your homelab. Do not use it for malicious activities.
- Rate Limiting: Many services (APIs, websites) have rate limits. Making too many requests too quickly can get your IP blocked. We'll add
time.sleep() calls, but be mindful of your usage.
- API Keys: For some advanced OSINT tasks (like checking for data breaches on HaveIBeenPwned), you'd typically need an API key. For this basic tool, we'll stick to methods that don't strictly require them, or use free, unauthenticated APIs where possible.
- Dynamic Content: This tool primarily uses
requests and BeautifulSoup. If a website heavily relies on JavaScript to load content, these methods might not suffice, and you'd need tools like Selenium. For a basic homelab OSINT tool, we'll focus on static content.
Homelab OSINT Tool Features:
- IP Address Information: Get geo-location, ISP, ASN, etc., using a public API.
- Domain Information:
- WHOIS lookup (registration details).
- DNS records (A, MX, NS, TXT).
- Username Availability Check: Check if a username is taken on a few popular social media sites.
- Web Page Metadata: Extract title, meta description, and keywords from a URL.
- Basic HTTP Header Analysis: Get server, X-Powered-By, etc.
Required Libraries:
You'll need to install these:
pip install requests beautifulsoup4 python-whois dnspython
Python Code:
import requests
from bs4 import BeautifulSoup
import whois
import dns.resolver
import time
import socket # For reverse DNS lookup
# --- Configuration ---
# User-Agent to mimic a browser, helps prevent some blocks
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
# Social media sites for username checks (add more as needed)
SOCIAL_MEDIA_SITES = {
"GitHub": "https://github.com/{}",
"Twitter": "https://twitter.com/{}",
"Instagram": "https://www.instagram.com/{}",
"Reddit": "https://www.reddit.com/user/{}",
"LinkedIn": "https://www.linkedin.com/in/{}" # LinkedIn is tricky, often requires login or specific patterns
}
# --- Helper Functions ---
def print_section_header(title):
print("\n" + "=" * 50)
print(f" {title.upper()} ")
print("=" * 50)
def handle_request_error(e, target_type, target):
print(f"Error fetching {target_type} '{target}': {e}")
if "403" in str(e) or "401" in str(e):
print(" -> Access Denied. The target might be blocking your request or require authentication.")
elif "404" in str(e):
print(" -> Not Found. The target might not exist or the URL is incorrect.")
elif "Connection refused" in str(e):
print(" -> Connection Refused. The target server might be down or blocking connections.")
elif "timeout" in str(e):
print(" -> Request Timed Out. Check your internet connection or try again later.")
return None
# --- OSINT Functions ---
def get_ip_info(ip_address):
"""Fetches public information about an IP address using ipinfo.io API."""
print_section_header(f"IP Address Information for {ip_address}")
api_url = f"https://ipinfo.io/{ip_address}/json"
try:
response = requests.get(api_url, headers=HEADERS, timeout=10)
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
data = response.json()
if data:
print(f" IP: {data.get('ip', 'N/A')}")
print(f" Hostname: {data.get('hostname', 'N/A')}")
print(f" City: {data.get('city', 'N/A')}")
print(f" Region: {data.get('region', 'N/A')}")
print(f" Country: {data.get('country', 'N/A')}")
print(f" Location: {data.get('loc', 'N/A')}")
print(f" Organization: {data.get('org', 'N/A')}")
print(f" Postal: {data.get('postal', 'N/A')}")
print(f" Timezone: {data.get('timezone', 'N/A')}")
# Attempt Reverse DNS (separate lookup for more reliability)
try:
rev_dns = socket.gethostbyaddr(ip_address)[0]
print(f" Reverse DNS: {rev_dns}")
except socket.herror:
print(" Reverse DNS: Not found or error.")
else:
print(" No data found for this IP address.")
except requests.exceptions.RequestException as e:
handle_request_error(e, "IP", ip_address)
except ValueError:
print(f" Invalid JSON response from {api_url}.")
except Exception as e:
print(f" An unexpected error occurred: {e}")
time.sleep(1) # Be polite
def get_domain_info(domain):
"""Fetches WHOIS and DNS information for a domain."""
print_section_header(f"Domain Information for {domain}")
# --- WHOIS Lookup ---
print("\n--- WHOIS Data ---")
try:
w = whois.whois(domain)
if isinstance(w, dict): # Sometimes returns a dict, sometimes an object
for key, value in w.items():
if value:
print(f" {key.replace('_', ' ').title()}: {value}")
else: # Older versions or specific outputs might be object-like
for key in ['domain_name', 'registrar', 'whois_server', 'referral_url',
'updated_date', 'creation_date', 'expiration_date',
'name_servers', 'status', 'emails', 'org', 'address',
'city', 'state', 'zipcode', 'country']:
value = getattr(w, key, None)
if value:
print(f" {key.replace('_', ' ').title()}: {value}")
if not w:
print(" No WHOIS data found or domain does not exist.")
except Exception as e:
print(f" Error fetching WHOIS data: {e}")
time.sleep(1) # Be polite
# --- DNS Lookup ---
print("\n--- DNS Records ---")
record_types = ['A', 'MX', 'NS', 'TXT', 'AAAA']
for r_type in record_types:
try:
answers = dns.resolver.resolve(domain, r_type)
print(f" {r_type} Records:")
for rdata in answers:
print(f" - {rdata}")
except dns.resolver.NoAnswer:
print(f" {r_type} Records: No records found.")
except dns.resolver.NXDOMAIN:
print(f" {r_type} Records: Domain does not exist.")
break # No need to check other records if domain doesn't exist
except dns.resolver.Timeout:
print(f" {r_type} Records: DNS query timed out.")
except Exception as e:
print(f" Error fetching {r_type} records: {e}")
time.sleep(1) # Be polite
def check_username(username):
"""Checks for username availability on specified social media sites."""
print_section_header(f"Username Check for '{username}'")
found_on = []
not_found_on = []
for site_name, url_template in SOCIAL_MEDIA_SITES.items():
profile_url = url_template.format(username)
print(f" Checking {site_name} ({profile_url})...")
try:
response = requests.get(profile_url, headers=HEADERS, timeout=5)
# A 200 OK generally means the page exists. Some sites return 200 with "user not found"
# so a simple status code check is not always 100% accurate, but good for quick checks.
if response.status_code == 200:
# Basic content check for common "not found" phrases
if "page not found" in response.text.lower() or "user not found" in response.text.lower():
not_found_on.append(site_name)
else:
found_on.append(f"{site_name} ({profile_url})")
elif response.status_code == 404:
not_found_on.append(site_name)
else:
print(f" -> Unexpected status code {response.status_code} for {site_name}. Might indicate presence or a redirect.")
found_on.append(f"{site_name} (Status {response.status_code}, check manually: {profile_url})")
except requests.exceptions.RequestException as e:
print(f" -> Error checking {site_name}: {e}")
time.sleep(0.5) # Short delay
print("\n--- Results ---")
if found_on:
print(" Possible presence on:")
for site in found_on:
print(f" - {site}")
else:
print(" No strong indication of presence found on checked sites.")
if not_found_on:
print("\n Likely NOT found on (or explicit 404/not found message):")
for site in not_found_on:
print(f" - {site}")
else:
print(" No sites explicitly returned 'not found'.")
time.sleep(1) # Be polite
def get_website_metadata(url):
"""Extracts basic metadata (title, meta tags) and HTTP headers from a URL."""
print_section_header(f"Website Metadata and Headers for {url}")
if not url.startswith('http'):
url = 'http://' + url # Prepend http:// if missing for requests to work
try:
response = requests.get(url, headers=HEADERS, timeout=15)
response.raise_for_status() # Raise an exception for HTTP errors
soup = BeautifulSoup(response.content, 'html.parser')
# --- HTTP Headers ---
print("\n--- HTTP Response Headers ---")
for header, value in response.headers.items():
print(f" {header}: {value}")
# --- HTML Metadata ---
print("\n--- HTML Metadata ---")
title = soup.title.string if soup.title else "N/A"
print(f" Title: {title}")
meta_description = soup.find("meta", attrs={"name": "description"})
if meta_description and meta_description.get("content"):
print(f" Meta Description: {meta_description['content']}")
else:
print(" Meta Description: N/A")
meta_keywords = soup.find("meta", attrs={"name": "keywords"})
if meta_keywords and meta_keywords.get("content"):
print(f" Meta Keywords: {meta_keywords['content']}")
else:
print(" Meta Keywords: N/A")
# Generator (e.g., WordPress, Joomla)
meta_generator = soup.find("meta", attrs={"name": "generator"})
if meta_generator and meta_generator.get("content"):
print(f" Generator: {meta_generator['content']}")
else:
print(" Generator: N/A")
# Open Graph (Facebook/LinkedIn previews)
og_title = soup.find("meta", property="og:title")
if og_title and og_title.get("content"):
print(f" OG Title: {og_title['content']}")
og_description = soup.find("meta", property="og:description")
if og_description and og_description.get("content"):
print(f" OG Description: {og_description['content']}")
except requests.exceptions.RequestException as e:
handle_request_error(e, "URL", url)
except Exception as e:
print(f" An unexpected error occurred: {e}")
time.sleep(1) # Be polite
# --- Main Menu and Loop ---
def display_menu():
print("\n" + "=" * 50)
print(" Python OSINT Homelab Tool ")
print("=" * 50)
print("1. Get IP Address Information")
print("2. Get Domain Information (WHOIS + DNS)")
print("3. Check Username Availability")
print("4. Get Website Metadata & HTTP Headers")
print("5. Exit")
print("=" * 50)
def main():
while True:
display_menu()
choice = input("Enter your choice (1-5): ").strip()
if choice == '1':
target = input("Enter IP Address: ").strip()
if target:
get_ip_info(target)
else:
print("IP Address cannot be empty.")
elif choice == '2':
target = input("Enter Domain Name (e.g., example.com): ").strip()
if target:
get_domain_info(target)
else:
print("Domain name cannot be empty.")
elif choice == '3':
target = input("Enter Username to check: ").strip()
if target:
check_username(target)
else:
print("Username cannot be empty.")
elif choice == '4':
target = input("Enter URL (e.g., https://example.com or example.com): ").strip()
if target:
get_website_metadata(target)
else:
print("URL cannot be empty.")
elif choice == '5':
print("Exiting OSINT tool. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")
input("\nPress Enter to continue...") # Pause for user to read output
if __name__ == "__main__":
main()
How to Use:
- Save: Save the code above as a Python file (e.g.,
osint_tool.py).
- Install Dependencies: Open your terminal or command prompt and run:
pip install requests beautifulsoup4 python-whois dnspython
- Run: Execute the script from your terminal:
python osint_tool.py
- Interact: Follow the menu prompts.
Further Enhancements for Your Homelab:
- GUI: For a more user-friendly experience, you could wrap this with a simple GUI library like
Tkinter, PyQt, or Streamlit.
- Data Export: Add options to save the gathered information to a file (e.g., JSON, CSV, text file).
- Error Logging: Implement proper logging instead of just
print() statements for errors.
- Proxy Support: Integrate proxy support (e.g., Tor, commercial proxies) for anonymity, though this adds complexity.
- More OSINT Sources:
- Email Breach Check: Requires API keys from services like HaveIBeenPwned.
- Shodan/Censys: For device scanning and open ports on the internet (requires API keys).
- Google Dorks: Automate specific Google searches (though Google can block automated queries).
- Subdomain Enumeration: Using tools like
sublist3r or by querying Certificate Transparency logs.
- Configuration File: Store API keys, user-agents, or list of social media sites in a separate
config.ini or .env file.
- Threading/Async: For checking multiple usernames or domains concurrently, consider
threading or asyncio to speed things up (but be careful with rate limits!).
- Better Username Check: The username check is basic. More robust checks involve looking for specific text on a page (e.g., "User not found") instead of just HTTP status codes.
- Local Caching: Store results locally for a short period to avoid re-querying the same target.
This tool provides a solid foundation for your OSINT explorations in your homelab. Remember to always use it responsibly and ethically!