
Detecting Credit Card Skimmers with Python Network Monitoring
Black Friday shoppers just got an unwelcome surprise. Security researchers discovered credit card skimming scripts using WebRTC data channels on popular shopping sites—exfiltrating payment data through peer-to-peer connections that bypass traditional security monitoring. The technique is clever: instead of sending stolen credit card numbers to a suspicious third-party server via HTTP (which security tools might catch), these skimmers establish direct WebRTC connections to attacker-controlled browsers, making the data flow nearly invisible to conventional detection methods.
This isn’t just another “update your antivirus” story. For IT professionals responsible for e-commerce infrastructure or client-side security, this represents a fundamental shift in how we need to think about monitoring. The good news? Python gives us the tools to detect these attacks through automated network traffic analysis and behavioral monitoring. Let’s build something practical.
Table of Contents
- Understanding WebRTC Skimmers
- Monitoring WebRTC Traffic with Python
- Building Automated Detection Scripts
- Real-World Deployment Strategies
Understanding WebRTC Skimmers
WebRTC was designed for legitimate peer-to-peer communication—video calls, file sharing, real-time collaboration. It creates direct connections between browsers without routing through intermediate servers. That’s exactly what makes it attractive to attackers: once a WebRTC data channel is established, it operates outside the normal HTTP request/response cycle that web application firewalls and content security policies typically monitor.
Traditional skimmers inject malicious JavaScript that captures form data and POSTs it to attacker servers. Those requests show up in network logs, trigger CORS warnings, and can be blocked by CSP headers. WebRTC skimmers? They’re establishing what looks like a legitimate peer connection. The data doesn’t traverse your backend infrastructure at all—it goes directly from the victim’s browser to the attacker’s endpoint.
The attack chain works like this: compromised JavaScript on a checkout page initiates a WebRTC connection when the payment form loads. As users type credit card details, the malicious code captures keystrokes or form values and sends them through the WebRTC data channel. No HTTP request. No server log entry. Just peer-to-peer data exfiltration hiding in plain sight.
Monitoring WebRTC Traffic with Python
Detection starts with visibility. We need to monitor what WebRTC connections are being established from our web properties. While you can’t directly intercept WebRTC traffic from Python on the server side (it’s peer-to-peer, after all), you can instrument browser sessions using Selenium with traffic capture capabilities, or analyze frontend behavior patterns.
Here’s a practical approach using Selenium with Chrome DevTools Protocol to capture network activity including WebRTC initialization. This script monitors a checkout page and flags any WebRTC peer connections:
# Monitor checkout page for WebRTC peer connections using Selenium CDP
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json
import time
chrome_options = Options()
chrome_options.add_argument('--enable-logging')
chrome_options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
driver = webdriver.Chrome(options=chrome_options)
driver.get('https://example-shop.com/checkout')
time.sleep(3) # Let page fully load
logs = driver.get_log('performance')
webrtc_connections = []
for entry in logs:
log = json.loads(entry['message'])['message']
# Detect RTCPeerConnection creation
if log.get('method') == 'Network.webSocketCreated' or \
('RTCPeerConnection' in str(log)):
webrtc_connections.append(log)
print(f"⚠️ WebRTC activity detected: {log}")
if webrtc_connections:
print(f"\n🚨 Found {len(webrtc_connections)} potential WebRTC connections on checkout page")
# Trigger alert, log to SIEM, etc.
driver.quit()
This is a starting point for automated checkout page security audits. Run this against your e-commerce properties on a schedule, and you’ll catch when unauthorized WebRTC connections appear. For deeper learning on web automation techniques like this, platforms like Coursera offer comprehensive courses on Selenium and browser automation that go far beyond basic testing.
Building Automated Detection Scripts
Detection isn’t just about spotting WebRTC connections—it’s about identifying suspicious ones. Legitimate sites use WebRTC for chat widgets, support features, even some payment processors use it for fraud prevention. The key is baseline behavior and anomaly detection.
Here’s a more sophisticated approach that establishes a baseline of normal WebRTC behavior and alerts on deviations. This script could run continuously in a monitoring environment:
# Baseline and anomaly detection for WebRTC connections on checkout pages
import json
import hashlib
from collections import defaultdict
from datetime import datetime
class WebRTCMonitor:
def __init__(self):
self.baseline = {} # Store known-good WebRTC fingerprints
self.alerts = []
def fingerprint_connection(self, connection_data):
# Create fingerprint from STUN/TURN servers, timing, initiating script
relevant_fields = {
'stun_servers': connection_data.get('stun', []),
'initiator_url': connection_data.get('initiator', ''),
'timing': connection_data.get('timestamp', '')
}
fingerprint = hashlib.sha256(
json.dumps(relevant_fields, sort_keys=True).encode()
).hexdigest()
return fingerprint
def analyze_connection(self, page_url, connection_data):
fp = self.fingerprint_connection(connection_data)
if page_url not in self.baseline:
self.baseline[page_url] = set()
if fp not in self.baseline[page_url]:
# New WebRTC connection pattern detected
alert = {
'timestamp': datetime.now().isoformat(),
'page': page_url,
'fingerprint': fp,
'details': connection_data,
'severity': 'HIGH' if 'checkout' in page_url else 'MEDIUM'
}
self.alerts.append(alert)
print(f"🚨 ALERT: Anomalous WebRTC on {page_url}")
print(f" Fingerprint: {fp[:16]}...")
return True
return False
def approve_baseline(self, page_url, fingerprint):
# After verification, add to baseline
if page_url not in self.baseline:
self.baseline[page_url] = set()
self.baseline[page_url].add(fingerprint)
# Usage in continuous monitoring
monitor = WebRTCMonitor()
# Simulate detection of connection (in practice, from Selenium/CDP)
suspicious_connection = {
'stun': ['stun.suspicious-domain.com:3478'],
'initiator': 'https://cdn.evil-scripts.net/collector.js',
'timestamp': '2024-11-27T15:23:11Z'
}
if monitor.analyze_connection('https://shop.com/checkout', suspicious_connection):
# Send to SIEM, PagerDuty, security team, etc.
pass
This pattern-based approach is crucial because you need context. A single WebRTC connection isn’t inherently malicious—but a WebRTC connection initiated by a script from an unexpected CDN domain, using STUN servers you don’t recognize, specifically on checkout pages? That’s worth investigating immediately.
Integrating with Your Security Stack
These detection scripts become far more valuable when integrated into existing security workflows. Push alerts to your SIEM, trigger incident response playbooks, or even automatically inject CSP headers that restrict WebRTC functionality on payment pages. If you’re building out these integration skills, DataCamp has practical courses on API integration and security automation that translate directly to real-world defensive programming.
The monitoring scripts above can be wrapped in containerized workers that continuously scan your checkout flows. Run them in Kubernetes alongside your applications, feeding results into Prometheus for alerting or Elasticsearch for analysis. Python’s ecosystem makes this integration straightforward—requests for webhooks, boto3 for AWS services, google-cloud libraries for GCP, whatever your infrastructure looks like.
Real-World Deployment Strategies
Detection is one piece; response is another. When your Python monitoring catches a suspicious WebRTC connection on a checkout page, what happens next? Speed matters—every minute that skimmer runs means more stolen cards.
Your deployment strategy should include automated response capabilities. The moment an anomaly is detected, your script can trigger several actions: notify security teams via PagerDuty or Slack, create a ticket in your incident management system, capture full browser state and network logs for forensics, and potentially inject temporary CSP restrictions that disable WebRTC on affected pages until the investigation completes.
Here’s the architecture pattern that works: lightweight Python workers running in your infrastructure, each monitoring specific checkout flows. They use Selenium Grid for distributed browser sessions, capture CDP logs, run the anomaly detection logic we built above, and publish findings to a message queue. Your security team subscribes to that queue, and automated responders can take immediate action based on severity.
The code we’ve written isn’t theoretical—it’s production-grade foundation. You’d want to add retry logic, proper logging with structured output, metrics collection, and integration with your specific security tools. But the core detection mechanism—monitoring WebRTC initialization on sensitive pages and flagging unknown patterns—that’s ready to deploy.
Beyond checkout pages, consider monitoring any page that handles sensitive data: account settings where users update payment methods, subscription management, even profile pages if you store payment information. Skimmers go where the data is, and WebRTC exfiltration can work anywhere JavaScript runs.
Building a Culture of Defensive Automation
The WebRTC skimmer story is a reminder that attack techniques evolve faster than our manual processes can keep up. That’s why automation isn’t optional—it’s the only way to maintain defensive coverage at scale. Python gives us the flexibility to quickly prototype detection logic, the performance to run it continuously, and the ecosystem to integrate with everything else in our stack.
Start small. Pick your highest-risk checkout flow and implement basic WebRTC monitoring this week. Expand from there. As you build out your defensive automation, you’ll find the patterns repeat: establish baselines, detect anomalies, automate responses. Whether it’s WebRTC skimmers today or whatever technique emerges tomorrow, the fundamental approach remains constant.
Master Security Automation Today
Build production-ready Python scripts that detect payment skimmers, automate threat response, and integrate with enterprise security tools—skills that protect revenue and customers.