Page cover
githubEdit

jsJavaScript Type Coercion in Validation Logic

When JavaScript validation functions lack strict type checking, attackers can exploit automatic type coercion to bypass security controls

circle-info

Root Cause

  • JavaScript's loose typing allows objects to masquerade as other types

  • Properties like .length can be controlled on objects

  • Type coercion in comparisons and arithmetic operations behaves differently for strings vs numbers

  • The Array() constructor behaves differently based on argument type

circle-info

Identify weak type validation

  • Look for functions that check properties (.length) without verifying type

  • Find arithmetic operations on invalidated inputs

  • Spot comparisons that rely on implicit type coercion

circle-info

Craft JSON payloads with object properties

  • Instead of sending expected primitive types (string, number), send objects

  • Use property names that mimic expected behavior ("length" as string property)

  • Leverage numeric-like strings that coerce differently in different contexts

circle-info

Exploit coercion behavior

// String "1000" vs number 1000:
   "1000" < 1000        // false (string coerced to number)
   Array("1000")        // Creates array with 1 element (string treated as single item)
   "1000" - 0 - 1       // 999 (string coerced to number in arithmetic)
Attack Pattern:
{
  "field": {
    "length": "1000",     // Bypasses length < 1000 check
    "0": "value",         // First position
    "999": "value"        // Last position (calculated via coercion)
  }
}
  • object.length returns string "1000", not number

  • Comparison "1000" < 1000 coerces to 1000 < 1000 (false), passes check

  • Array("1000") creates single-element array unlike Array(1000) which creates empty array with 1000 slots

  • Loop iterates only once (i=0)

  • Arithmetic "1000" - 0 - 1 coerces to number, returns 999

  • object[0] and object[999] both defined by attacker

Last updated