• Network Traffic Monitor

    from scapy.all import sniff
    
    def packet_callback(packet):
        print(f"Packet captured: {packet.summary()}")
    
    if __name__ == "__main__":
        print("Starting network traffic monitor...")
        sniff(prn=packet_callback, count=10)  # Capture 10 packets
  • Malware Behavior Simulator

    import time
    import random
    
    def simulate_keylogger():
        """Simulate a simple keylogging behavior."""
        print("Simulating keylogging... (Press Ctrl+C to stop)")
        try:
            while True:
                # Simulate capturing random key presses
                keys = ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']
                key = random.choice(keys)
                print(f"Key captured: {key}")
                time.sleep(1)  # Simulate delay between captures
        except KeyboardInterrupt:
            print("\nKeylogging simulation stopped.")
    
    def simulate_file_manipulation():
        """Simulate file manipulation behavior."""
        file_actions = ['create', 'modify', 'delete']
        for _ in range(5):  # Simulate 5 actions
            action = random.choice(file_actions)
            filename = f"malware_file_{random.randint(1, 100)}.txt"
            if action == 'create':
                print(f"Creating file: {filename}")
            elif action == 'modify':
                print(f"Modifying file: {filename}")
            elif action == 'delete':
                print(f"Deleting file: {filename}")
            time.sleep(1)  # Simulate delay between actions
    
    def simulate_network_scanning():
        """Simulate network scanning behavior."""
        print("Simulating network scanning...")
        for i in range(1, 4):  # Simulate scanning 3 'hosts'
            ip_address = f"192.168.1.{i}"
            print(f"Scanning {ip_address}...")
            time.sleep(2)  # Simulate time taken to scan
            print(f"Host {ip_address} is active.")
    
    if __name__ == "__main__":
        print("Malware Behavior Simulator")
        print("1. Simulate Keylogger")
        print("2. Simulate File Manipulation")
        print("3. Simulate Network Scanning")
        
        choice = input("Select a simulation (1, 2, or 3): ")
        
        if choice == '1':
            simulate_keylogger()
        elif choice == '2':
            simulate_file_manipulation()
        elif choice == '3':
            simulate_network_scanning()
        else:
            print("Invalid choice.")
  • Web Server Fingerprinting Tool

    import requests
    
    def fingerprint_web_server(url):
        """Identify the web server type and version from the response headers."""
        try:
            response = requests.get(url)
            server_header = response.headers.get('Server', 'Unknown')
    
            print(f"URL: {url}")
            print(f"Server Header: {server_header}")
    
            if "Apache" in server_header:
                print("Detected web server: Apache")
            elif "Nginx" in server_header:
                print("Detected web server: Nginx")
            elif "IIS" in server_header:
                print("Detected web server: Microsoft IIS")
            elif "lighttpd" in server_header:
                print("Detected web server: Lighttpd")
            else:
                print("Web server type could not be determined.")
    
        except requests.exceptions.RequestException as e:
            print(f"Error: {e}")
    
    if __name__ == "__main__":
        target_url = input("Enter the URL to fingerprint (e.g., http://example.com): ")
        fingerprint_web_server(target_url)
  • Fake User Data Generator

    import random
    import faker
    
    def generate_fake_user_data(num_profiles):
        """Generate a list of fake user profiles."""
        fake = faker.Faker()
        user_profiles = []
    
        for _ in range(num_profiles):
            profile = {
                'name': fake.name(),
                'email': fake.email(),
                'phone': fake.phone_number(),
                'address': fake.address().replace("\n", ", "),
            }
            user_profiles.append(profile)
    
        return user_profiles
    
    if __name__ == "__main__":
        num_profiles = int(input("Enter the number of fake user profiles to generate: "))
        
        fake_users = generate_fake_user_data(num_profiles)
        
        print("\nGenerated Fake User Profiles:")
        for user in fake_users:
            print(user)
  • Email Validation Script

    import re
    import dns.resolver
    
    def is_valid_email(email):
        """Validate the email format and check for MX records."""
        # Regex pattern for validating an Email
        pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        
        if not re.match(pattern, email):
            return False, "Invalid email format."
    
        domain = email.split('@')[1]
        
        try:
            # Check for MX records
            dns.resolver.resolve(domain, 'MX')
            return True, "Valid email address with a working domain."
        except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
            return False, "Valid format but no MX record found."
    
    if __name__ == "__main__":
        email = input("Enter an email address to validate: ")
        is_valid, message = is_valid_email(email)
        print(message)
  • Password Generator

    import random
    import string
    
    def generate_password(length=12, use_uppercase=True, use_lowercase=True, use_digits=True, use_symbols=True):
        """Generate a secure random password based on user preferences."""
        characters = ''
        
        if use_uppercase:
            characters += string.ascii_uppercase
        if use_lowercase:
            characters += string.ascii_lowercase
        if use_digits:
            characters += string.digits
        if use_symbols:
            characters += string.punctuation
    
        if not characters:
            raise ValueError("At least one character type must be selected!")
    
        password = ''.join(random.choice(characters) for _ in range(length))
        return password
    
    if __name__ == "__main__":
        print("--- Password Generator ---")
        length = int(input("Enter desired password length (default is 12): ") or 12)
        use_uppercase = input("Include uppercase letters? (y/n, default is y): ").strip().lower() != 'n'
        use_lowercase = input("Include lowercase letters? (y/n, default is y): ").strip().lower() != 'n'
        use_digits = input("Include digits? (y/n, default is y): ").strip().lower() != 'n'
        use_symbols = input("Include symbols? (y/n, default is y): ").strip().lower() != 'n'
    
        try:
            generated_password = generate_password(length, use_uppercase, use_lowercase, use_digits, use_symbols)
            print(f"Generated Password: {generated_password}")
        except ValueError as e:
            print(e)
  • Text-Based Adventure Game

    def start_game():
        print("Welcome to the Adventure Game!")
        print("You find yourself in a dark forest. You can go left or right.")
        choice = input("Which way do you want to go? (left/right): ").strip().lower()
        
        if choice == "left":
            encounter_wolf()
        elif choice == "right":
            encounter_river()
        else:
            print("Invalid choice. Please try again.")
            start_game()
    
    def encounter_wolf():
        print("\nYou encounter a wild wolf!")
        print("1. Try to scare it away.")
        print("2. Run away.")
        
        choice = input("What do you want to do? (1/2): ")
        
        if choice == "1":
            print("You bravely try to scare the wolf, and it runs away! You are safe.")
        elif choice == "2":
            print("You run away as fast as you can. The wolf chases you, but you manage to escape!")
        else:
            print("Invalid choice. Please try again.")
            encounter_wolf()
    
    def encounter_river():
        print("\nYou come across a serene river.")
        print("1. Try to swim across.")
        print("2. Look for a bridge.")
        
        choice = input("What do you want to do? (1/2): ")
        
        if choice == "1":
            print("You bravely swim across the river. It's cold, but you make it!")
        elif choice == "2":
            print("You find a bridge and safely cross the river.")
        else:
            print("Invalid choice. Please try again.")
            encounter_river()
    
    if __name__ == "__main__":
        start_game()
  • File Integrity Checker

    import hashlib
    import os
    import json
    
    def calculate_file_hash(file_path):
        """Calculate the SHA-256 hash of a file."""
        if not os.path.isfile(file_path):
            raise FileNotFoundError(f"The file '{file_path}' does not exist.")
    
        sha256_hash = hashlib.sha256()
        with open(file_path, "rb") as f:
            # Read and update hash string value in blocks of 4K
            for byte_block in iter(lambda: f.read(4096), b""):
                sha256_hash.update(byte_block)
        return sha256_hash.hexdigest()
    
    def save_hash(file_path, hash_value):
        """Save the hash value to a .json file."""
        if not os.path.exists("file_hashes.json"):
            with open("file_hashes.json", "w") as f:
                json.dump({}, f)
    
        with open("file_hashes.json", "r+") as f:
            try:
                data = json.load(f)
            except json.JSONDecodeError:
                data = {}
    
            data[file_path] = hash_value
            f.seek(0)
            json.dump(data, f, indent=4)
    
    def check_file_integrity(file_path):
        """Check if a file's hash matches the stored hash."""
        current_hash = calculate_file_hash(file_path)
        
        if os.path.exists("file_hashes.json"):
            with open("file_hashes.json", "r") as f:
                data = json.load(f)
                stored_hash = data.get(file_path)
    
            if stored_hash:
                if current_hash == stored_hash:
                    return "File is intact."
                else:
                    return "File has been modified!"
            else:
                return "No stored hash found for this file."
        else:
            return "No hash records found. Please save the hash first."
    
    if __name__ == "__main__":
        action = input("Enter 'save' to save a file hash or 'check' to check file integrity: ").strip().lower()
        file_path = input("Enter the path of the file: ")
    
        if action == 'save':
            file_hash = calculate_file_hash(file_path)
            save_hash(file_path, file_hash)
            print(f"Hash for '{file_path}' saved.")
        elif action == 'check':
            result = check_file_integrity(file_path)
            print(result)
        else:
            print("Invalid action. Please enter 'save' or 'check'.")
    
  • YALAT (Yet Another Log Analysis Tool)

    import re
    from collections import Counter
    
    # Define patterns for suspicious activities
    SUSPICIOUS_PATTERNS = {
        r"failed password": "Failed login attempt detected.",
        r"authentication failure": "Authentication failure detected.",
        r"root": "Root access attempt detected.",
        r"exec": "Execution of commands detected.",
        r"delete": "Delete operation detected.",
        r"unauthorized access": "Unauthorized access attempt detected.",
    }
    
    def analyze_log(file_path):
        with open(file_path, 'r') as file:
            log_data = file.readlines()
    
        findings = Counter()
    
        for line in log_data:
            for pattern, message in SUSPICIOUS_PATTERNS.items():
                if re.search(pattern, line, re.IGNORECASE):
                    findings[message] += 1
    
        return findings
    
    def display_findings(findings):
        print("\n--- Log Analysis Findings ---")
        if findings:
            for message, count in findings.items():
                print(f"{message}: {count} times")
        else:
            print("No suspicious activities detected.")
    
    if __name__ == "__main__":
        log_file_path = input("Enter the path to the log file: ")
        findings = analyze_log(log_file_path)
        display_findings(findings)
  • Basic WAF (Web Application Firewall)

    from flask import Flask, request, render_template_string
    import re
    
    app = Flask(__name__)
    
    # Define common attack patterns to block with tailored messages
    BLOCKED_PATTERNS = {
        r"' OR '1'='1'": "Detected SQL Injection attempt: This input could manipulate database queries.",
        r"'(.*?)--": "Detected SQL Injection attempt: This input could terminate a query.",
        r"<script.*?>": "Detected XSS attempt: This input could execute malicious scripts in users' browsers.",
        r"(?i)DROP\s+TABLE": "Detected SQL Injection attempt: This input could delete database tables.",
        r"(?i)SELECT\s+\*": "Detected SQL Injection attempt: This input could retrieve sensitive data from the database.",
        r"(?i)INSERT\s+INTO": "Detected SQL Injection attempt: This input could insert data into the database.",
        r"(?i)DELETE\s+FROM": "Detected SQL Injection attempt: This input could delete data from the database.",
        r"(?i)UPDATE\s+\w+\s+SET": "Detected SQL Injection attempt: This input could update database records.",
        r"(?i)UNION\s+SELECT": "Detected SQL Injection attempt: This input could combine results from multiple queries.",
        r"<iframe.*?>": "Detected XSS attempt: This input could embed malicious content.",
        r"(?i)EXEC\s+": "Detected SQL Injection attempt: This input could execute arbitrary commands.",
    }
    
    def check_input(payload):
        for pattern, message in BLOCKED_PATTERNS.items():
            if re.search(pattern, payload):
                return message, False
        return "Input received safely. Thank you!", True
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        payload = request.form.get('input', '')
        message, is_safe = check_input(payload) if payload else (None, False)
        show_refresh = True  # Always show the refresh button
        return render_template_string(render_template(message, payload, show_refresh, is_safe))
    
    def render_template(message, payload, show_refresh, is_safe):
        message_color = "green" if is_safe else "red" if message else "black"
        refresh_button = '<form action="/" method="get"><input type="submit" value="Refresh"></form>' if show_refresh else ''
        return f'''
            <h1>Web Application Firewall</h1>
            <form method="post">
                Input: <input type="text" name="input" value="{payload}">
                <input type="submit" value="Submit">
            </form>
            <h3 style="color: {message_color};">{message if message else ""}</h3>
            {refresh_button}
        '''
    
    if __name__ == "__main__":
        app.run(port=5000)