Microsoft finds USB worm that steals cryptocurrency through clipboard hijacking and Tor
Back to Tutorials
techTutorialintermediate

Microsoft finds USB worm that steals cryptocurrency through clipboard hijacking and Tor

June 20, 202639 views4 min read

Learn to build a Python-based clipboard monitoring tool that detects cryptocurrency theft attempts by monitoring clipboard changes and identifying suspicious patterns like wallet addresses and seed phrases.

Introduction

In this tutorial, we'll explore how to detect and analyze clipboard hijacking malware like the one identified by Microsoft, which steals cryptocurrency data from Windows systems. While this tutorial focuses on defensive analysis, understanding these techniques helps cybersecurity professionals build better protection systems. We'll create a Python-based monitoring tool that watches for suspicious clipboard activity and logs potential threats.

Prerequisites

  • Python 3.8 or higher installed
  • Basic understanding of Windows clipboard operations
  • Knowledge of Python's threading and event handling
  • Access to a Windows machine (for testing)
  • Optional: Virtual environment setup knowledge

Step-by-Step Instructions

1. Setting Up the Development Environment

1.1 Create a Virtual Environment

First, we'll set up a clean Python environment to avoid conflicts with system packages:

python -m venv clipboard_monitor_env
clipboard_monitor_env\Scripts\activate

Why: Isolating our project dependencies ensures we don't interfere with other Python installations and makes deployment easier.

1.2 Install Required Libraries

We need several libraries to interact with the Windows clipboard and handle logging:

pip install pywin32 python-clipboard

Why: pywin32 provides low-level Windows API access for clipboard monitoring, while python-clipboard offers a cross-platform interface for clipboard operations.

2. Implementing Clipboard Monitoring

2.1 Create the Main Monitoring Class

We'll create a class that monitors clipboard changes and checks for cryptocurrency-related patterns:

import win32clipboard
import time
import logging
import re
from datetime import datetime

class ClipboardMonitor:
    def __init__(self):
        self.last_clipboard_content = ""
        self.cryptocurrency_patterns = [
            r"\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b",  # Bitcoin addresses
            r"\b[4][a-zA-HJ-NP-Z1-9]{94}\b",         # Monero addresses
            r"\b[0-9a-fA-F]{64}\b",                   # Ethereum private keys
            r"\b[0-9a-zA-Z]{58}\b"                   # Stellar addresses
        ]
        self.setup_logging()

    def setup_logging(self):
        logging.basicConfig(
            filename='clipboard_monitor.log',
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s'
        )
        logging.info("Clipboard monitor initialized")

    def get_clipboard_text(self):
        try:
            win32clipboard.OpenClipboard()
            data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
            win32clipboard.CloseClipboard()
            return data
        except Exception as e:
            logging.error(f"Error accessing clipboard: {e}")
            return ""

    def is_crypto_related(self, text):
        for pattern in self.cryptocurrency_patterns:
            if re.search(pattern, text):
                return True
        return False

    def check_clipboard(self):
        current_content = self.get_clipboard_text()
        if current_content and current_content != self.last_clipboard_content:
            if self.is_crypto_related(current_content):
                logging.warning(f"Suspicious clipboard content detected: {current_content[:100]}...")
                # Here you could add more advanced analysis or alerting
            self.last_clipboard_content = current_content

Why: This setup creates a foundation for detecting potential cryptocurrency theft attempts by monitoring clipboard changes and matching against known address patterns.

2.2 Add Threading for Continuous Monitoring

Now we'll implement a continuous monitoring loop using threading:

import threading

class ClipboardMonitor:
    # ... previous code ...
    
    def start_monitoring(self, interval=1):
        def monitor_loop():
            while True:
                self.check_clipboard()
                time.sleep(interval)
        
        monitor_thread = threading.Thread(target=monitor_loop, daemon=True)
        monitor_thread.start()
        logging.info("Clipboard monitoring started")
        return monitor_thread

Why: Threading allows us to continuously monitor clipboard changes without blocking the main program flow, which is essential for real-time threat detection.

3. Enhancing Detection Capabilities

3.1 Add Advanced Pattern Detection

To improve detection accuracy, we'll add more sophisticated pattern matching:

class ClipboardMonitor:
    # ... previous code ...
    
    def is_crypto_related(self, text):
        # Check for seed phrase patterns
        seed_phrase_patterns = [
            r"\b[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+\b",
            r"\b\d{4}\s\d{4}\s\d{4}\s\d{4}\b"
        ]
        
        # Check for wallet addresses
        for pattern in self.cryptocurrency_patterns:
            if re.search(pattern, text):
                return True
        
        # Check for seed phrases
        for pattern in seed_phrase_patterns:
            if re.search(pattern, text):
                return True
        
        return False

Why: Adding seed phrase detection helps identify when users might be copying sensitive wallet information that could be stolen.

3.2 Implement Alerting System

Let's add a simple alert system that notifies users of potential threats:

import os

class ClipboardMonitor:
    # ... previous code ...
    
    def alert_user(self, content):
        alert_msg = f"ALERT: Suspicious clipboard content detected!\nContent: {content[:100]}..."
        logging.warning(alert_msg)
        
        # Optional: Display system notification
        try:
            os.system(f"msg * {alert_msg}")
        except:
            pass

    def check_clipboard(self):
        current_content = self.get_clipboard_text()
        if current_content and current_content != self.last_clipboard_content:
            if self.is_crypto_related(current_content):
                self.alert_user(current_content)
            self.last_clipboard_content = current_content

Why: A notification system ensures that users are immediately aware of potential threats, allowing for rapid response.

4. Testing the Implementation

4.1 Create a Test Script

Finally, let's create a script to test our clipboard monitor:

from clipboard_monitor import ClipboardMonitor
import time

# Initialize and start monitoring
monitor = ClipboardMonitor()
monitor.start_monitoring(interval=2)

print("Clipboard monitor started. Press Ctrl+C to stop.")
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print("\nStopping clipboard monitor...")

Why: This test script allows us to verify that our monitoring system works correctly and can detect clipboard changes in real-time.

5. Deployment Considerations

When deploying this tool in production environments, consider:

  • Running with appropriate Windows permissions
  • Implementing additional logging and reporting features
  • Adding integration with security information and event management (SIEM) systems
  • Ensuring the tool doesn't interfere with legitimate clipboard usage

Summary

In this tutorial, we've built a Python-based clipboard monitoring tool that can detect potential cryptocurrency theft attempts by monitoring clipboard changes. We've implemented pattern matching for various cryptocurrency addresses and seed phrases, used threading for continuous monitoring, and added alerting capabilities. This tool demonstrates how to analyze clipboard hijacking malware behavior, which is crucial for understanding and defending against threats like the one identified by Microsoft.

While this implementation focuses on detection, real-world deployment would require additional features like network traffic analysis, integration with endpoint protection systems, and more sophisticated threat intelligence feeds.

Source: TNW Neural

Related Articles