Okay, this is a much safer and extremely useful area for a cybersecurity project! OSINT (Open Source Intelligence) is crucial for reconnaissance, digital forensics, and incident response.
Here are Python scripts for OSINT on images and links. These scripts leverage publicly available information and services.
Important Notes:
- Ethical Use: These scripts are for educational and ethical OSINT purposes only. Do not use them for illegal activities or to harass/harm others.
- Rate Limiting: Public services might have rate limits. Excessive use could lead to temporary bans.
- Dependencies: You'll need to install the required Python libraries using
pip.
- Accuracy: OSINT results depend on the availability and accuracy of public data.
1. OSINT for Images (Reverse Image Search)
Direct programmatic access to major reverse image search engines (like Google Images, TinEye, Yandex) is often restricted or requires specific API keys (which are usually not free or easy to obtain for general use).
The most common way to perform reverse image search programmatically for OSINT without complex setups is to simulate the browser behavior or open the search in a web browser.
Here's a Python script that generates the Google Reverse Image Search URL and opens it in your default web browser. This is often sufficient for a project to demonstrate the concept.
# osint_image_reverse_engineer.py
import webbrowser
import os
import sys
def reverse_image_search_google(image_path):
"""
Performs a reverse image search on Google Images.
This function will open the search results in your default web browser.
"""
if not os.path.exists(image_path):
print(f"Error: Image file not found at '{image_path}'")
return
print(f"[*] Attempting Google Reverse Image Search for: {image_path}")
print("[*] Uploading image to Google Images...")
# Google's reverse image search requires uploading the image.
# Programmatic upload is complex (requires WebDriver/Selenium or direct POST requests).
# For a simple OSINT script, it's common to tell the user to manually upload
# or use a pre-existing URL (if the image is already online).
# For demonstration, we'll open the Google Images search page,
# and the user would manually upload the image.
# A more advanced script would use Selenium to automate the upload.
# Alternative for images already online:
# If the image is already hosted somewhere, you can provide its URL:
# google_search_url = f"https://www.google.com/searchbyimage?image_url={image_url}"
# For a local file, the easiest is to direct the user to the upload page.
google_upload_url = "https://images.google.com/?gws_rd=ssl" # Directs to the Google Images page
print(f"\n[!] Please manually drag and drop '{image_path}' (or click the camera icon to upload) into the opened Google Images page.")
webbrowser.open_new_tab(google_upload_url)
print("[*] Opened Google Images in your web browser. Check the new tab/window.")
def main():
if len(sys.argv) < 2:
print("Usage: python osint_image_reverse_engineer.py <path_to_image_file>")
print("Example: python osint_image_reverse_engineer.py my_evidence.jpg")
sys.exit(1)
image_file = sys.argv[1]
reverse_image_search_google(image_file)
if __name__ == "__main__":
main()
How to use osint_image_reverse_engineer.py:
- Save the code as
osint_image_reverse_engineer.py.
- Run from your terminal:
python osint_image_reverse_engineer.py /path/to/your/image.jpg
- It will open Google Images in your browser. You then need to manually upload the image file to perform the search.
For a more advanced (but complex) solution:
You would need to use a browser automation tool like Selenium with a WebDriver (e.g., ChromeDriver) to programmatically upload the image and interact with the search results. This adds significant complexity (installing browser, WebDriver, managing browser versions) for a simple OSINT script.
2. OSINT for Links/URLs
This script will take a URL and perform various OSINT checks:
- Redirects: Checks where a URL actually leads.
- Whois Lookup: Gets registration information for the domain.
- DNS Information: Resolves IP addresses and other DNS records.
- Page Content Analysis: Extracts title, meta description, and other links from the page.
- URL Reputation (Conceptual): Mentions how to integrate with services like VirusTotal (though direct API calls usually require keys).
Dependencies:
requests: pip install requests
beautifulsoup4: pip install beautifulsoup4
python-whois: pip install python-whois
# osint_link_reverse_engineer.py
import requests
from bs4 import BeautifulSoup
import whois # pip install python-whois
import socket
import re
from urllib.parse import urlparse, urljoin
import sys
def get_url_info(url):
"""Fetches URL content and performs basic checks."""
print(f"\n[+] Analyzing URL: {url}")
try:
response = requests.get(url, allow_redirects=True, timeout=10)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
print(f" -> Final URL after redirects: {response.url}")
print(f" -> Status Code: {response.status_code}")
return response
except requests.exceptions.RequestException as e:
print(f" -> Error fetching URL: {e}")
return None
def extract_domain(url):
"""Extracts the domain from a URL."""
parsed_url = urlparse(url)
return parsed_url.netloc
def get_whois_info(domain):
"""Performs a WHOIS lookup for a domain."""
print(f"\n[+] Performing WHOIS lookup for domain: {domain}")
try:
w = whois.whois(domain)
# Convert whois object to dict for easier printing
if w:
for key, value in w.items():
if isinstance(value, list):
print(f" -> {key}: {', '.join(map(str, value))}")
else:
print(f" -> {key}: {value}")
else:
print(" -> No WHOIS information found (or domain doesn't exist).")
except Exception as e:
print(f" -> Error during WHOIS lookup: {e}")
def get_dns_info(domain):
"""Performs DNS lookups (A, CNAME, MX, NS records)."""
print(f"\n[+] Performing DNS lookup for domain: {domain}")
try:
# A records (IP addresses)
ip_addresses = socket.gethostbyname_ex(domain)[2]
print(f" -> IP Addresses (A): {', '.join(ip_addresses)}")
except socket.gaierror:
print(" -> No A records found.")
try:
# CNAME records (Aliases) - more complex, needs dnspython
# For simplicity, we'll just check if it's an alias via gethostbyname_ex for now.
# A more robust solution would use 'dnspython' library.
pass # print(" -> CNAME (Alias): Requires 'dnspython' library for easy lookup.")
except Exception as e:
pass # print(f" -> CNAME Error: {e}")
try:
# MX records (Mail Exchangers)
mx_records = socket.getaddrinfo(domain, 25, socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_CANONNAME)
# mx_records will contain many details, filter for hostnames.
# This is a simplified approach. A more robust one uses 'dnspython'.
mx_hosts = list(set([res[4][0] for res in mx_records if res[0] == socket.AF_INET and res[2] == socket.SOCK_STREAM]))
if mx_hosts:
print(f" -> Mail Exchangers (MX): {', '.join(mx_hosts)}")
else:
print(" -> No MX records found.")
except socket.gaierror:
print(" -> No MX records found.")
except Exception as e:
print(f" -> MX lookup error: {e}")
try:
# NS records (Name Servers) - requires dnspython for easy lookup
# For a basic script, skipping direct NS/CNAME lookup without 'dnspython'
pass # print(" -> Name Servers (NS): Requires 'dnspython' library for easy lookup.")
except Exception as e:
pass # print(f" -> NS Error: {e}")
def parse_html_content(response, base_url):
"""Parses HTML content to extract title, meta description, and links."""
print(f"\n[+] Parsing HTML content from: {response.url}")
soup = BeautifulSoup(response.text, 'html.parser')
# Extract Title
title = soup.find('title')
print(f" -> Page Title: {title.string.strip() if title else 'N/A'}")
# Extract Meta Description
meta_description = soup.find('meta', attrs={'name': 'description'})
print(f" -> Meta Description: {meta_description.get('content', 'N/A') if meta_description else 'N/A'}")
# Extract all links (internal and external)
print("\n[+] Extracted Links:")
internal_links = set()
external_links = set()
base_domain = urlparse(base_url).netloc
for link in soup.find_all('a', href=True):
href = link['href']
full_url = urljoin(base_url, href)
parsed_link = urlparse(full_url)
if parsed_link.scheme in ['http', 'https']: # Only process web links
link_domain = parsed_link.netloc
if link_domain == base_domain:
internal_links.add(full_url)
else:
external_links.add(full_url)
if internal_links:
print(" -> Internal Links:")
for link in sorted(list(internal_links)):
print(f" {link}")
else:
print(" -> No internal links found.")
if external_links:
print("\n -> External Links:")
for link in sorted(list(external_links)):
print(f" {link}")
else:
print(" -> No external links found.")
return list(internal_links), list(external_links)
def check_url_reputation(url):
"""
Conceptual function to show how URL reputation might be checked.
Requires API keys for services like VirusTotal or URLScan.io.
"""
print("\n[+] Checking URL Reputation (Conceptual):")
print(" -> For real-time reputation, integrate with services like:")
print(" - VirusTotal (requires API key)")
print(" - URLScan.io (requires API key)")
print(" - PhishTank (requires API key)")
print(" -> Also consider checking domain age via WHOIS and blacklist checks.")
def main():
if len(sys.argv) < 2:
print("Usage: python osint_link_reverse_engineer.py <URL>")
print("Example: python osint_link_reverse_engineer.py https://www.example.com")
sys.exit(1)
target_url = sys.argv[1]
# Ensure URL has a scheme for requests library
if not re.match(r'^[a-zA-Z]+://', target_url):
target_url = "http://" + target_url
response = get_url_info(target_url)
if response:
final_url = response.url # Use the final URL after redirects
domain = extract_domain(final_url)
get_whois_info(domain)
get_dns_info(domain)
internal_links, external_links = parse_html_content(response, final_url)
check_url_reputation(final_url)
if __name__ == "__main__":
main()
How to use osint_link_reverse_engineer.py:
- Install dependencies:
pip install requests beautifulsoup4 python-whois
- Save the code as
osint_link_reverse_engineer.py.
- Run from your terminal:
python osint_link_reverse_engineer.py https://www.google.com
or
python osint_link_reverse_engineer.py badsite.com (for a non-existent or problematic site to see error handling)
This script provides a solid foundation for your OSINT project. You can expand it by:
- Adding more DNS record types: (CNAME, NS records) using the
dnspython library.
- Integrating with public APIs: (e.g., VirusTotal, URLScan.io) if you can get API keys (be mindful of API usage policies).
- Screenshotting the page: Using libraries like
Playwright or Selenium to get a visual artifact.
- Checking for specific keywords: on the page content that might indicate phishing or malware.
- Analyzing SSL certificate information: using the
ssl module.
Good luck with your project! This is a fascinating and practical area of cybersecurity.