terça-feira, 25 de janeiro de 2011

CRITICAL LOG REVIEW CHECKLIST FOR SECURITY INCIDENTS


Download aqui.

by Osvaldo H Peixoto

UNIX / Linux Shell Cheat Sheet


Download aqui.




Download aqui.

by Osvaldo H Peixoto

Barrando o Ultrasurf - política de conscientização

Ok. Todo mundo sabe para que serve o UltraSurf, se não sabe dê uma olhada nesse vídeos:



Muitas pessoas me perguntam como detectar e impedir o uso do ultrasurf na rede, basicamente existem 3 maneiras para realizar esta tarefa, segue abaixo:

- Bloqueie todo acesso a porta 443 e libere só o acesso para os sites permitidos pela empresa
- Use algum IPS como o Suricata
- Política de Conscientização

Neste post vou considerar que você tem uma rede de pequeno porte, não mais do que 50 máquinas e para isso vou utilizar a terceira opção da nossa lista acima. Vamos detectar os servidores do Ultrasurf e depois com a ajuda do comando tcpdump vamos detectar quais máquinas da nossa rede estão usando o ultrasurf.
A rede de servidores do UltraSurf é muito vasta, o número de servidores praticamente cresce a cada dia, por isso não vamos nos preocupar em detectar “todos” os servidos, só o suficiente para que possamos rastrear os usuários da nossa rede que estejam utilizando o ultrasurf.

Detectando os Servidores do Ultrasurf

Realizei este teste em uma máquina virtual, mas você pode realizar no seu desktop ou laptop. No meu cenário de teste usei a máquina virtual para usar o ultrasurf e na máquina hospedeira (que é a máquina onde foi instalado o sistema virtual) utilizei o comando tcpdump para capturar o tráfego da máquina virtual com destino a porta 443, que é a porta que o ultrasurf usa para se conectar a sua rede. Segue abaixo uma pequena lista do que fiz:

1- Baixe aqui o Ultrasurf para a máquina virtual

2- Rode o comando tcpdump na máquina real como mostra abaixo:
                #tcpdump dst port 443 and src host 10.1.4.136 -w ultrasurf-1006
                Port 443: porta que o ultrasurf usa
                Src host 10.1.4.136: ip da máquina virtual
                -w ultrasurf-1006: salva todo o tráfego no arquivo ultrasurf-1006

O comando acima vai salvar no arquivo ultrasurf-1006 todo tráfego vindo do host 10.1.4.136 com destino a porta 443.

3- Execute o UltraSurf e comece a navegar pela Internet


Fazendo alguns filtros no arquivo ultrasurf-1006

Este arquivo não pode ser lido com um simples cat, você precisa usar a opção -r do tcpdump, veja abaixo:


#tcpdump -r ultrasurf-1006
reading from file ultrasurf-1006, link-type EN10MB (Ethernet)
15:29:19.741572 IP 10.1.4.136.45508 > 65.49.2.15.https: S 3413938700:3413938700(0) win 8192
15:29:19.932453 IP 10.1.4.136.45508 > 65.49.2.15.https: . ack 2316726788 win 16660
15:29:19.934076 IP 10.1.4.136.45508 > 65.49.2.15.https: F 0:0(0) ack 1 win 16660
15:29:20.126435 IP 10.1.4.136.45508 > 65.49.2.15.https: . ack 2 win 16660
15:29:22.711555 IP 10.1.4.136.45509 > 65.49.2.15.https: S 1368444892:1368444892(0) win 8192
15:29:22.900488 IP 10.1.4.136.45509 > 65.49.2.15.https: . ack 2326060616 win 16660

Vamos salvar este arquivo em texto puro:

#tcpdump -r ultrasurf-1006 > ultrasurf-1006.txt   

Vamos aplicar nosso filtro para pegarmos apenas os servidores do ultrasurf que são aqueles com o IP.https, nosso filtro deverá também eliminar os IP´s repetidos.
O comando abaixo irar filtrar o nosso arquivo ultrasurf-1006.txt e mostrar apenas os IP´s da rede do ultrasurf:

#cat ultrasurf-1006.txt | awk -F " " '{print $5" "}'
65.49.14.47.https:
65.49.2.15.https:
65.49.2.15.https:
65.49.14.47.https:
65.49.14.47.https:
65.49.2.15.https:
65.49.2.15.https:
65.49.2.15.https:
65.49.2.15.https:
65.49.14.47.https:
65.49.2.15.https:

Essa lista é bem maior, apenas estou colocando alguns servidores para ilustrar. Bom, ainda temos alguns filtros para criar. Agora devemos tirar da nossa lista a string “.https:” e eliminar os IP´s repetidos.  Veja como ficou nosso comando final abaixo:

# cat ultrasurf-1006.txt | awk -F " " '{print $5" "}' | cut -f1,2,3,4 -d. | sort | uniq
65.49.14.47
65.49.2.15

Uma breve explicação do comando acima:

O comando awk vai filtrar o arquivo ultrasurf-1006.txt e mostrar apenas o IP dos servidores, como foi mostrado acima. O cut vai filtrar a saída do awk e tirar a string “.https:” para mostrar apenas os IP´s. O comando sort irá ordenar o resultado e o uniq ira eliminar os IP´s repetidos, com isso teremos o resultado esperado que são os IP´s dos servidores.

Como não executei o Ultrasurf nossa lista de servidores se resume em apenas dois IP´s.

Detectando os usuários que usam o UltraSurf

Agora temos nossa lista de servidores do UltraSurf, vamos executar nosso tcpdump para detectar os usuários da rede que utilizam o programa. Veja o comando abaixo:

#tcpdump -nn dst port 443 and dst host 65.49.14.47 or dst host 65.49.2.15

Quando o ultrasurf tentar se conectar nesses servidores nosso tcpdump ira capturar o IP do usuário. Podemos salvar todo o conteúdo em um arquivo com a opção -w. Agora podemos tentar aplicar nossa Política de Conscientização, que seria identificar os usuários e chamar os mesmos para uma reunião notificando que a utilização deste tipo de programa é inaceitável e fere a política de segurança da empresa e que a continuação do uso desta ferramenta pode acarretar consequências para ele. Segundo nossa legislação isso pode ser demissão por justa causa.

by Osvaldo H Peixoto


segunda-feira, 24 de janeiro de 2011

Camuflagem x Esteganografia

O que é esteganografia? Veja abaixo a definição que encontrei na Internet para o termo:

“é uma palavra que vem do grego e significa “escrita oculta”. Trata-se do estudo de técnicas que permitam esconder informações dentro de outros arquivos, sejam imagens, músicas, vídeos ou mesmo textos.”

Veja este vídeo que fala sobre esteganografia:




Para quem quiser aprofundar e realizar alguns testes recomendo 3 programas ótimos para esteganografia. Segue abaixo o link para os 3 programas:

Segundo o site da Wikipedia Camuflagem:

“é o conjunto de técnicas e métodos que permitem a um dado organismo ou objeto permanecer indistinto do ambiente que o cerca. Têm-se como exemplos desde as cores amadeiradas do bicho-pau até as manchas verdes-marrons nos uniformes dos soldados modernos”. Veja a figura abaixo:





Trazendo os dois termos para a Segurança da Informação, diríamos que a esteganografia permite com que você possa esconder uma informação dentro de uma foto e quando você abre a foto a única coisa que irar aparecer é a imagem, para que você possa ver o que foi escondido na foto será necessário abrir o arquivo usando o programa que utilizou para esconder aquela informação. Com a camuflagem assim que você executa o arquivo de imagem, tanto a imagem como o segundo arquivo, que pode ser outra imagem ou um aplicativo, são executados.

Neste post vou mostrar como usar a camuflagem para esconder uma backdoor dentro de um arquivo de imagem, quando a pessoa abrir a imagem a backdoor será rodado em background, permitindo nosso acesso remoto.

Você deve estar se perguntando e o AV? Pois é, ele vai detectar a nossa backdoor, por isso irei mostrar também como fazer para burlar o AV.

Vamos fazer uma pequena lista do que temos que realizar no nosso LAB:

1- escolher nosso backdoor – um que seja detectado pelo AV, assim possamos mostrar como burlar o AV

2- nossa backdoor deverá escutar em alguma porta acima de 1024, porque abaixo de 1024 só o administrador pode executar

3- “limpar” o nosso backdoor para que ele não seja detectado pelo AV

4- utilizar a técnica de camuflagem para esconder a nossa backdoor em uma imagem

5- TESTAR

Agora vamos escolher nossa backdoor. Existem várias maneiras de criar uma backdoor, uma ótima escolha seria utilizando o metasploit. Se você fizer uma busca pela Internet não vai faltar opção. Neste post vou utilizar o famoso NetBus, porém recomendo também o Back Orifice.

Não vou mostrar aqui como instalar e configurar o servidor do NetBus, faça uma busca pelo Google para isso.  Já estou com o servidor configurado, agora vou fazer um teste online para ver se os AV´s irão detectar o meu trojan. O site http://www.virustotal.com/ permite com que possamos carregar um arquivo para que seja analisado comparando com a base de dados dos AV´s mais famosos.

De 43 AV´s checados, 42 detectaram o NetBus. Agora vamos usar um programa muito bom chamado Petite para “limpar” o servidor do NetBus e assim burlarmos o AV.

O Petite compacta o executável, fazendo com que o mesmo mude suas características com isso podendo burlar os AV´s. Na imagem abaixo veja em “Options” e em Level, é neste campo que você escolhe o nível de compressão. Dependendo do nível pode ser que você burle o AV porém deixe o servidor do trojan bugado, por isso você tem que testar.



Fiz alguns testes usando o Level 1 e 2, porém nos dois casos o executável não pode ser executado, já com o nível 0 não houve problemas, agora vou carregar o arquivo para ser checado junto com o site www.virustotal.com, se o mesmo tiver um bom resultado, que seria em não ser detectado pela maioria ou pelos principais AV´s, então podemos passar para a próxima fase do nosso LAB. Carreguei o arquivo e o resultado foi aceitável, 29 de 43. Agora vamos juntar nosso trojan com alguma imagem.

Para fazer a camuflagem vamos usar o programa Cactus Joiner, como mostra a figura abaixo:



Primeiro carregue o arquivo da imagem e depois o trojan. Agora clique com o botão direito do mouse em cima dos arquivos (um de cada vez) e faça como mostra a figura abaixo:


 Depois de fazer o mesmo procedimento para os dois arquivos clique em “Opciones Generales” e faça como esta mostrando a figura abaixo:



Habilite a opção “Habilitar Firewall Killer XP” e “Con Icono”, depois clique em “Cerrar Opciones Avanzadas”. Depois disso, abrir a imagem e em background nosso trojan foi executado permitido assim o acesso remoto.

Com isso temos nosso trojan camuflado em uma imagem e que pode facilmente burlar um antivírus e ser despercebido pelo usuário, nos dando acesso remoto à máquina infectada.

links interessantes sobre o assunto: Escondendo Backdoors e Rootkits no Windows, Windows 7 AV bypass e Make All Files Undetected.

by Osvaldo H Peixoto


quarta-feira, 19 de janeiro de 2011

Esse vídeo é nota 1000

Sei que este blog foca seus assuntos em segurança, linux, backtrack, exploit e etc. Mas não resistir em compartilhar com vocês este vídeo que mostra a vida de uma forma e visão extraordinária e humana.




by Osvaldo ------- A VIDA é incrível na sua simplicidade e essência.

segunda-feira, 17 de janeiro de 2011

sábado, 15 de janeiro de 2011

Descubra o tipo de HASH

Descobriu alguma senha por ai, porém não sabe qual é o tipo de HASH? Bom, abaixo segue uma lista com os tipos de HASH com base no número de caracteres, não é 100%, mas chega nos 99%.

8 :  ('A sua hash é ADLER32 ou CRC-32 ou GHash-32');

4 :  ('A sua hash é CRC-16 ou CRC-16-CCITT ou ainda FCS-16 ');

13 :  ('A sua hash é DES (unix) ');

40 :  ('A sua hash é sha-1 ou MySql v5.x ');

28 :  ('A sua hash é SHA-1 (base64) ');

46 :  ('A sua hash é SHA-1 (Django) ');

64 :  ('A sua hash é SHA-256 ');

56 :  ('A sua hash é SHA-224');

96 :  ('A sua hash é SHA-384');

128 :  ('A sua hash é SHA-512 ou Whirlpool');

48 :  ('A sua hash é Haval-192');

224 :  ('A sua hash é Haval-224');

34 :  ('A sua hash é MD5(Unix) ou MD5(phpBB3) Oou MD5(Wordpress)');

32 :  ('A sua hash é MD5 ou MD4 ou MD2');

16 :  ('A sua hash é MySQL Under 5');

57 :  ('A sua hash é Snefru ou Gost')

Peguei de um script que achei na Internet.
 
Osvaldo
 

sexta-feira, 14 de janeiro de 2011

quinta-feira, 13 de janeiro de 2011

Excelente HOWTO sobre o netfilter

Descrição tirada do HOWTO:

This document describes the netfilter architecture for Linux, how to hack it, and some of the major systems which sit on top of it, such as packet filtering, connection tracking and Network Address Translation.


LINK: http://security.maruhn.com/netfilter-hacking-howto/

Osvaldo H Peixoto
osvaldohp.blogspot.com

segunda-feira, 10 de janeiro de 2011

SQL Injection Tools

Bom, estou realizando alguns testes de sql injection, testando algumas ferramentas para automatizar o processo de descoberta de vulnerabilidade de SQLi. Apesar de apoiar o conhecimento e a utilização manual da técnica usada para explorar uma vulnerabilidade de SQli as ferramentas são de grande utilidade para agilizar todo o processo e lhe dá um pouco de tempo para a exploração manual de servidores mais seguros.

Por isso, reuni neste post algumas ferramentas que julgo ser importante e fundamentais para auxiliar no processo de descoberta de falhas de injection. Ainda não tive tempo de traduzir, por isso segue abaixo exatamente como copiei dos sites dos desenvolvedores.

1- Havij v1.13 Advanced SQL Injection

Havij is an automated SQL Injection tool that helps penetration testers to find and exploit SQL Injection vulnerabilities on a web page.

It can take advantage of a vulnerable web application. By using this software user can perform back-end database fingerprint, retrieve DBMS users and  password hashes, dump tables and columns, fetching data from the database, running SQL  statements and even accessing the underlying file system and executing commands on the  operating system.

The power of Havij that makes it different from similar tools is its injection methods. The success rate is more than 95% at injectiong vulnerable targets using Havij.

The user friendly GUI (Graphical User Interface) of Havij and automated settings and detections makes it easy to use for everyone even amateur users.

What's New?
  • Oracle error based database added with ability to execute query.
  • Getting tables and column when database name is unknown added (mysql)
  • Another method added for finding columns count and string column in PostgreSQL
  • Automatic keyword finder optimized and some bugs fixed.
  • A bug in finding valid string column in mysql fixed.
  • 'Key is not unique' bug fixed
  • Getting data starts from row 2 when All in One fails - bug fixed
  • Run time error when finding keyword fixed.
  • False table finding in access fixed.
  • keyword correction method made better
  • A bug in getting current data base in mssql fixed.
  • A secondary method added when input value doesn't return a normal page (usually 404 not found)
  • Data extraction bug in html-encoded pages fixed.
  • String or integer type detection made better.
  • A bug in https injection fixed.
Features:

Items
Free version
Commercial version
1. Supported Databases with injection methods:


          a. MsSQL 2000/2005 with error
sim
sim
          b. MsSQL 2000/2005 no error union based
sim
sim
          c. MsSQL Blind
nao
sim
          d. MySQL union based
sim
sim
          e. MySQL Blind
sim
sim
          f. MySQL error based
sim
sim
          g. Oracle union based
sim
sim
          h. Oracle error based
não
sim
          i. PostgreSQL union based
não
sim
          j. MsAccess union based
sim
sim
          k. MsAccess Blind
não
sim
2. HTTPS Support
não
sim
3. Proxy support
sim
sim
4. Automatic database detection
sim
sim
5. Automatic type detection (string or integer)
sim
sim
6. Automatic keyword detection (finding difference between the positive and negative response)
sim
sim
7. Trying different injection syntaxes
sim
sim
8. Options for replacing space by /**/,+,... against IDS or filters
sim
sim
9. Avoid using strings (magic_quotes similar filters bypass)
sim
sim
10. Manual injection syntax support
sim
sim
11. Manual queries with result
não
sim
12. Bypassing illegal union
sim
sim
13. Full customizable http headers (like referer,user agent and ...)
sim
sim
14. Load cookie from site for authentication
sim
sim
15. Real time result
sim
sim
16. Guessing tables and columns in mysql<5 (also in blind) and MsAccess
sim
sim
17. Fast getting tables and columns for mysql
sim
sim
18. Executing SQL query in Oracle database
não
sim
19. Getting one row in one request (all in one request)
não
sim
20. Dumping data into file
não
sim
21. Saving data as XML format
não
sim
22. View every injection request sent by program
não
sim
23. Enabling xp_cmdshell and remote desktop
não
sim
24. Multi thread Admin page finder
sim
sim
25. Multi thread Online MD5 cracker
sim
sim
26. Getting DBMS Informations
sim
sim
27. Getting tables, columns and data
sim
sim
28. Command executation (mssql only)
sim
sim
29. Reading system files (mysql only)
sim
sim
30. insert/update/delete data
sim
sim

2 - Sqlmap
sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of back-end database servers. It comes with a broad range of features lasting from database fingerprinting, over data fetching from the database, to accessing the underlying file system and executing commands on the operating system via out-of-band connections.
Features implemented in sqlmap include:
Generic features
·         Full support for MySQLOraclePostgreSQL and Microsoft SQL Server back-end database management systems. Besides these four database management systems software, sqlmap can also identify Microsoft Access, DB2, Informix, Sybase and Interbase.

·         Full support for three SQL injection techniques: inferential blind SQL injectionUNION query (inband) SQL injection and batched queries support. sqlmap can also test for time based blind SQL injection.

·         It is possible to provide a single target URL, get the list of targets from Burp proxy requests log file or WebScarab proxy conversations/ folder, get the whole HTTP request from a text file or get the list of targets by providing sqlmap with a Google dork which queries Google search engine and parses its results page. You can also define a regular-expression based scope that is used to identify which of the parsed addresses to test.
·         Automatically tests all provided GET parameters, POST parameters, HTTP Cookie header values and HTTP User-Agent header value to find the dynamic ones, which means those that vary the HTTP response page content. On the dynamic ones sqlmap automatically tests and detects the ones affected by SQL injection. Each dynamic parameter is tested for numericsingle quoted stringdouble quoted string and all of these three data-types with zero to two parenthesis to correctly detect which is the SELECT statement syntax to perform further injections with. It is also possible to specify the only parameter(s) that you want to perform tests and use for injection on.

·         Option to specify the maximum number of concurrent HTTP requests to speed up the inferential blind SQL injection algorithms (multi-threading). It is also possible to specify the number of seconds to wait between each HTTP request.

·         HTTP Cookie header string support, useful when the web application requires authentication based upon cookies and you have such data or in case you just want to test for and exploit SQL injection on such header. You can also specify to always URL-encode the Cookie header.

·         Automatically handle HTTP Set-Cookie header from the application, re-establishing of the session if it expires. Test and exploit on these values is supported too. You can also force to ignore any Set-Cookie header.

·         HTTP Basic, Digest, NTLM and Certificate authentications support.

·         Anonymous HTTP proxy support to pass by the requests to the target application that works also with HTTPS requests.

·         Options to fake the HTTP Referer header value and the HTTP User-Agent header value specified by user or randomly selected from a text file.

·         Support to increase the verbosity level of output messages: there exist six levels. The default level is 1 in which information, warnings, errors and tracebacks (if any occur) will be shown.
·         Granularity in the user's options.

·         Estimated time of arrival support for each query, updated in real time while fetching the information to give to the user an overview on how long it will take to retrieve the output.

·         Automatic support to save the session (queries and their output, even if partially retrieved) in real time while fetching the data on a text file and resume the injection from this file in a second time.

·         Support to read options from a configuration INI file rather than specify each time all of the options on the command line. Support also to save command line options on a configuration INI file.

·         Option to update sqlmap as a whole to the latest development version from the Subversion repository.

·         Integration with other IT security open source projects, Metasploit and w3af.

Fingerprint and enumeration features

·         Extensive back-end database software version and underlying operating system fingerprint based upon inband error messagesbanner parsing,functions output comparison and specific features such as MySQL comment injection. It is also possible to force the back-end database management system name if you already know it.

·         Basic web server software and web application technology fingerprint.

·         Support to retrieve the DBMS bannersession user and current database information. The tool can also check if the session user is a database administrator (DBA).

·         Support to enumerate database usersusers' password hashesusers' privilegesdatabasestables and columns.

·         Support to dump database tables as a whole or a range of entries as per user's choice. The user can also choose to dump only specific column(s).

·         Support to automatically dump all databases' schemas and entries. It is possibly to exclude from the dump the system databases.

·         Support to enumerate and dump all databases' tables containing user provided column(s). Useful to identify for instance tables containing custom application credentials.

·         Support to run custom SQL statement(s) as in an interactive SQL client connecting to the back-end database. sqlmap automatically dissects the provided statement, determines which technique to use to inject it and how to pack the SQL payload accordingly.

Takeover features
Some of these techniques are detailed in the white paper Advanced SQL injection to operating system full control and in the slide deck Expanding the control over the operating system from the database.
·         Support to inject custom user-defined functions: the user can compile shared object then use sqlmap to create within the back-end DBMS user-defined functions out of the compiled shared object file. These UDFs can then be executed, and optionally removed, via sqlmap too.

·         Support to read and upload any file from the database server underlying file system when the database software is MySQL, PostgreSQL or Microsoft SQL Server.

·         Support to execute arbitrary commands and retrieve their standard output on the database server underlying operating system when the database software is MySQL, PostgreSQL or Microsoft SQL Server.

o    On MySQL and PostgreSQL via user-defined function injection and execution.

o    On Microsoft SQL Server via xp_cmdshell() stored procedure. Also, the stored procedure is re-enabled if disabled or created from scratch if removed.

·       Support to establish an out-of-band stateful TCP connection between the user machine and the database server underlying operating system. This channel can be an interactive command prompt, a Meterpreter session or a graphical user interface (VNC) session as per user's choice. sqlmap relies on Metasploit to create the shellcode and implements four different techniques to execute it on the database server. These techniques are:

o    Database in-memory execution of the Metasploit's shellcode via sqlmap own user-defined function sys_bineval(). Supported on MySQL and PostgreSQL.

o    Upload and execution of a Metasploit's stand-alone payload stager via sqlmap own user-defined function sys_exec() on MySQL and PostgreSQL or via xp_cmdshell() on Microsoft SQL Server.

o    Execution of Metasploit's shellcode by performing a SMB reflection attack ( MS08-068) with a UNC path request from the database server to the user's machine where the Metasploit smb_relay server exploit runs.

o    Database in-memory execution of the Metasploit's shellcode by exploiting Microsoft SQL Server 2000 and 2005 sp_replwritetovarbin stored procedure heap-based buffer overflow ( MS09-004) with automatic DEP bypass.

·        Support for database process' user privilege escalation via Metasploit's getsystem command which include, among others, the kitrap0d technique (MS10-015) or via Windows Access Tokens kidnapping by using Meterpreter's incognito extension.

·         Support to access (read/add/delete) Windows registry hives.

3- SQLiX
SQLiX, coded in Perl, is a SQL Injection scanner, able to crawl, detect SQL injection vectors, identify the back-end database and grab function call/UDF results (even execute system commands for MS-SQL). The concepts in use are different than the one used in other SQL injection scanners. SQLiX is able to find normal and blind SQL injection vectors and doesn't need to reverse engineer the original SQL request (using only function calls).
If you are a developer interested in remediating or avoiding the kinds of SQL Injection vulnerabilities this tool can find, check out the OWASP SQL Injection Prevention Cheat Sheet.
SQLiX is a SQL Injection scanner which attempts to fill the gap between what commercial software available on the market can do and what can really be done to detect and identify SQL injection.
Current injection methods used by commercial web assessment software are based on error generation or statement injections.

error generation:
The error generation method is quite simple and is based on meta characters like single quotes or double quotes. By injecting these characters in the original SQL request, you generate a syntax error which could result in an SQL error message displayed in the HTTP reply. The main issue with this technique is the fact that it's only based on pattern matching. There is no way to handle multiple languages or complex behaviors when the error message is filtered by the server-side scripts.

statement injection:
The second method used is statement injection. Let's look at an example:
The target URL
The scanner will try to compare the HTML content of the original request with the HTML content of
If the request (1) provides the same result as request (0) and request (2) doesn't, the scanner will conclude that SQL injection is possible. This method works fine, but is very limited by the syntax of the original request. If the original request contains parentheses, store procedures or function calls, this method will rarely work. Worse, if the variable is used by multiple SQL requests, all with different syntaxes, there is no automatic way to make them all work simultaneously.

Frequently you will see more advanced scanners like SQLBrute from www.justinclarke.com trying to reverse engineer the original SQL syntax by injecting multiple requests with different sets of parentheses or comas. This method is a little more time consuming but does provide better results (for free), especially when error messages are not displayed.
Another global issue concerning SQL injection is the fact that pen testers frequently conclude that a given SQL injection vulnerability can't be exploited. By concluding this incorrect statement they are inviting their customers to not patch the vulnerability.

How could SQLiX help to fill the gap?
§  SQLiX uses multiple techniques to determine if the current server-side script is vulnerable to SQL Injection
§  conditional errors injection
§  blind injection based on integers, strings or statements
§  MS-SQL verbose error messages ("taggy" method)
§  SQLiX using UDF (User defined functions) or function calls thus no need to reverse engineer the original SQL syntax
§  SQLix is able to identify the database version and gather sensitive information for the following SQL servers: MS-Access, MS-SQL, MySQL, Oracle and PostgreSQL.
§  The comparison module of SQLiX is able to deal with complex HTML contents even when they include dynamic ads
§  SQLiX contains an exploit module to demonstrate how a hacker could exploit the found SQL injection to gather sensitive information

4- SQLninja

Sqlninja 0.2.5 is finally available!! It's been 2 years since the previous release, and in this time I have been working on completely different things (see the FAQ for more info on this). However, there were some things that really needed to be added to this tool, so here are the new features:

·         Upload mode is not limited to files of 64k bytes anymore
·         Uploading files is also *massively* faster
·         Proxy support (it was ***ing time!)
·         Support for token kidnapping (thanks Cesar!)
·         Lots of other minor improvements

The TODO list is not empty yet, and I am already working on 0.2.6 which should be out fairly soon.

Fancy going from a SQL Injection on Microsoft SQL Server to a full GUI access on the DB? Take a few new SQL Injection tricks, add a couple of remote shots in the registry to disable Data Execution Prevention, mix with a little Perl that automatically generates a debug script, put all this in a shaker with a Metasploit wrapper, shake well and you have just one of the attack modules of sqlninja!

Sqlninja is a tool targeted to exploit SQL Injection vulnerabilities on a web application that uses Microsoft SQL Server as its back-end.

Its main goal is to provide a remote access on the vulnerable DB server, even in a very hostile environment. It should be used by penetration testers to help and automate the process of taking over a DB Server when a SQL Injection vulnerability has been discovered.

Have a look at the 
flash demo and then feel free to download. It is released under the GPLv2

The full documentation can be found in the tarball and also here, but here's a list of what the Ninja does:
·         Fingerprint of the remote SQL Server (version, user performing the queries, user privileges, xp_cmdshell availability, DB authentication mode)
·         Bruteforce of 'sa' password (in 2 flavors: dictionary-based and incremental)
·         Privilege escalation to sysadmin group if 'sa' password has been found
·         Creation of a custom xp_cmdshell if the original one has been removed
·         Upload of netcat (or any other executable) using only normal HTTP requests (no FTP/TFTP needed)
·         TCP/UDP portscan from the target SQL Server to the attacking machine, in order to find a port that is allowed by the firewall of the target network and use it for a reverse shell
·         Direct and reverse bindshell, both TCP and UDP
·         DNS-tunneled pseudo-shell, when no TCP/UDP ports are available for a direct/reverse shell, but the DB server can resolve external hostnames (check the documentation for details about how this works) 
·         Evasion techniques to confuse a few IDS/IPS/WAF
·         Integration with Metasploit3, to obtain a graphical access to the remote DB server through a VNC server injection
·         Integration with churrasco.exe, to escalate privileges to SYSTEM on w2k3 via token kidnapping
Platforms supported

Sqlninja is written in Perl and should run on any UNIX based platform with a Perl interpreter, as long as all needed modules have been installed. So far it has been successfully tested on:

·         Linux
·         FreeBSD
·         Mac OS X

5- SQLBrute

SQLBrute is a tool for brute forcing data out of databases using blind SQL injection vulnerabilities. It supports time based and error based exploit types on Microsoft SQL Server, and error based exploit on Oracle. It is written in Python, uses multi-threading, and doesn’t require non-standard libraries (there is some code in there for pycurl, but it is disabled because it isn’t finished).

Details

§  Website  : www.justinclarke.com/archives/.../sqlbrute.html
§  Discussion Forum  :
§  Mailing List  :
§  Platforms  : Windows, Linux, Unix
§  License  :
§  Author  : Justin Clarke
§  Contact Email  : http://www.justinclarke.com

 

Sample Usage

 Usage: ./sqlbrute.py options url
            [--help|-h]                        
            [--verbose|-v]                    
            [--server|-d oracle|sqlserver]     
            [--error|-e regex]                 
            [--threads|-s number]             
            [--cookie|-k string]              
            [--time|-n]                       
            [--data|-p string]                
            [--database|-f database]          
            [--table|-t table]                 
            [--column|-c column]               
            [--where|-w column=data]           
            [--header|-x header::val]      
 
 
 
--data allows you to specify POST data for a form post. Takes a string containing all the data as an argument
 
--cookie allows you to specify the cookies to be supplied. Takes a string containing all the cookies as an argument
 
--header allows you to specify arbitrary HTTP headers to include in the request (e.g. Accepts headers or similar).
 The header name and value need to be supplied as a single argument of the form header::value
Other options modify the default behaviour of the tool:
 
--server forces the tool to use Oracle or SQL Server exploit techniques. This is needed because the tool 
defaults to SQL Server, and won't intelligently detect that Oracle is in use
 
--threads specifies how many worker threads the tool will use to send requests. This defaults to 5, however 
this should be reduced if you are getting unreliable results (especially when doing time based testing). 
Setting this too high has a tendency to max the CPU on your machine, and have bad effects on the machine you're testing
 
--time forces the tool to use time based testing instead of error based testing
 
--verbose turns on verbose output. By default the tool doesn't output anything until it has completely 
enumerated an entry, which can lead to wondering whether it is actually doing anything. Using verbose
 once will output preliminary results - allowing you to see that its working. Using verbose twice will output 
requests and responses to allow debug issues with the tool
 
--output allows us to specify an output file for the results. Otherwise the only results we will get will be to stdout
The remainder of the options specify the data to be brute forced from the database:
 
--error specifies a regular expression to look for that appears in one of the AND or OR cases noted above. 
Usually this will be something identifiable such as an error message, or a message noting that no results were found
 
--database (SQL Server only) specifies what database to use for enumerating data
--table specifies what table to use for enumerating data
 
--column specifies what column to use for enumerating data
 
--where allows us to filter what data to brute force out by specifying a WHERE clause when enumerating a column.
 The where data must be in the form column_name=data (i.e. WHERE foo=bar)
The tool is designed to be used in a logical progression:
Running the tool without specifying a database, table, or column parameter will enumerate the list of databases for 
SQL Server, and the list of user tables for Oracle
Running the tool with the name of a database (SQL Server only) will enumerate the list of tables
Running the tool with a table parameter (plus database parameter for SQL Server) will enumerate the columns in that table
Running the tool with a column parameter (with table and database parameters if applicable) will enumerate the data 
in that column of that parameter. You can then find matching values in other columns of the table through 
using a --where command line option
 

 

 

Tutorials and Demos

Text Tutorials

 Books


6- BlindSQL

Bash script para realizar ataques ciegos SQL inject a bases de datos, normalmente MySQL. Ataca por fuerza bruta obteniendo datos de configuración, tablas, campos y datos de la BD. Utiliza el navegador lynx. 

Download: http://www.enye-sec.org/programas/blindsql.v1.0.tar.gz

7- MySploit

MySqloit is a SQL Injection takeover tool focused on LAMP (Linux, Apache,MySql,PHP) and WAMP (Windows, Apache,MySql,PHP) platforms. It has an ability to upload and execute Metasploit shellcodes through the MySql SQL Injection vulnerability.

Platform supported
1) Linux

Key Features
§  SQL Injection detection using time based injection method
§  Database fingerprint
§  Web server directory fingerprint
§  Payload creation and execution

Requirements
§  FILE privilege
§  Web server and database server must be in the same machine
§  Prior knowledge of the web server directory
§  For the LAMP platform, if the mysqld runs as a non root user, a writable web server directory is required
Sample Usage
[penguin]$ ./mysqloit.py -h
    -h --help                  Help
    -t --test                  Test the SQL Injection
    -o --os                    Fingerprint the operating system
    -f --fingerprint           Fingerprint the working directory
    -e --exploit               Exploit. Enter 'help' as argument for more options
    -p --payload               Create payload. Enter 'help' as argument for more options

8- ProxyStrike

ProxyStrike is an active Web Application Proxy, is a tool designed to find vulnerabilities while browsing an application. It was created because the problems we faced in the pentests of web applications that depends heavily on Javascript, not many web scanners did it good in this stage, so we came with this proxy.

Right now it has available Sql injection and XSS modules. Both modules are designed to catch as many vulnerabilities as we can, it's that why the SQL Injection module is a Python port of the great DarkRaver "Sqlibf". The XSS module is made by us, using our library Gazpacho (soon will be released as standalone tool).
The process is very simple, ProxyStrike runs like a passive proxy listening in port 8008 by default, so you have to browse the desired web site setting your browser to use ProxyStrike as a proxy, and ProxyStrike will analyze all the paremeters in background mode. For the user is a passive proxy because you won't see any different in the behaviour of the application, but in the background is very active. :)
Features:
·         Plugin engine (Create your own plugins!)
·         Request interceptor
·         Request diffing
·         Request repeater
·         Automatic crawl process
·         Save/restore session
·         Http request/response history
·         Request parameter stats
·         Request parameter values stats
·         Request url parameter signing and header field signing
·         Use of an alternate proxy (tor for example ;D )
·         Sql attacks (plugin)
·         Server Side Includes (plugin)
·         Xss attacks (plugin)
·         Attack logs
·         Export results to HTML or XML

9- Pangolin

Pangolin is an automatic SQL injection penetration testing tool developed by NOSEC. Its goal is to detect and take advantage of SQL injection vulnerabilities on web applications. Once it detects one or more SQL injections on the target host, the user can choose among a variety of options to perform an extensive back-end database management system fingerprint, retrieve DBMS session user and database, enumerate users, password hashes, privileges, databases, dump entire or user’s specific DBMS tables/columns, run his own SQL statement, read specific files on the file system and more.

Database Support
  • Access: Informations (Database Path; Root Path; Drivers); Data
  • MSSql: Informations; Data; FileReader; RegReader; FileWriter; Cmd; DirTree
  • MySql: Informations; Data; FileReader; FileWriter;
  • Oracle: Inforatmions (Version; IP; Database; Accounts ……); Data; and any others;
  • Informix: Informatons; Data
  • DB2: Informatons; Data; and more;
  • Sybase: Informatons; Data; and more;
  • PostgreSQL: Informatons; Data; FileReader;
  • Sqlite: Informatons; Data
At present, most of the functions are directed at MSSQL and MySql coupled with Oracle and Access. Other small and medium-sized companies are using DB2, Informix, Sybase, PostgreSQL, as well as Sqlite which isn’t so common.

Or read more here.

10- Absinthe

Absinthe is a gui-based tool that automates the process of downloading the schema & contents of a database that is vulnerable to Blind SQL Injection. 

Absinthe does not aid in the discovery of SQL Injection holes. This tool will only speed up the process of data recovery.

Features:
  • Automated SQL Injection
  • Supports MS SQL Server, MSDE, Oracle, Postgres
  • Cookies / Additional HTTP Headers
  • Query Termination
  • Additional text appended to queries
  • Supports Use of Proxies / Proxy Rotation
  • Multiple filters for page profiling
  • Custom Delimiters

11- bsqlbfv1.2-th.pl

This is a modified version of 'bsqlbfv1.2-th.pl'. This perl script allows extraction of data from Blind SQL Injections. It accepts custom SQL queries as a command line parameter and it works for both integer and string based injections.

Databases supported:

0. MS-SQL
1. MySQL
2. PostgreSQL
3. Oracle

The tool supports 8 attack modes(-type switch):-


Type 0: Blind SQL Injection based on true and false conditions returned by back-end server
Type 1: Blind SQL Injection based on true and error(e.g syntax error) returned by back-end server.
Type 2: Blind SQL Injection in "order by" and "group by".
Type 3: extracting data with SYS privileges (ORACLE dbms_export_extension exploit)
Type 4: is O.S code execution (ORACLE dbms_export_extension exploit)
Type 5: is reading files (ORACLE dbms_export_extension exploit, based on java)
Type 6: is O.S code execution DBMS_REPCAT_RPC.VALIDATE_REMOTE_RC exploit
Type 7: is O.S code execution SYS.KUPP$PROC.CREATE_MASTER_PROCESS(), DBA Privs
Type 8: is O.S code execution DBMS_JAVA_TEST.FUNCALL, with JAVA IO Permissions


For Type 4(O.S code execution) the following methods are supported:
-stype: How you want to execute command:
SType 0 (default) is based on java..will NOT work against XE.
SType 1 is against oracle 9 with plsql_native_make_utility.
SType 2 is against oracle 10 with dbms_scheduler.


Usage example:
$./bsqlbf-v2.pl -url http://192.168.1.1/injection_string_post/1.asp?p=1 -method post -match true -database 0 -sql "select top 1 name from sysobjects where xtype='U'"
./bsqlbf-v2.3.pl -url http://192.168.1.1/injection_string_post/1.jsp?p=1 -type 4 -match "true" -cmd "ping notsosecure.com"


User Interface:
ubuntu@ubuntu:~$ ./bsqlbf-v2-3.pl

 // Blind SQL injection brute forcer \\
  //originally written by...aramosf@514.es  \\
 
  // mofified by sid-at-notsosecure.com \\
  ---------------------usage:-------------------------------------------

Integer based Injection-->./bsqlbf-v2-3.pl - url http://www.host.com/path/script.php?foo=1000 (options)
 
 String Based Injection-->./bsqlbf-v2-3.pl - url http://www.host.com/path/script.php?foo=bar' (options)
  
  ------------------------------------options:--------------------------
  -sql:          valid SQL syntax to get; version(), database(),
                 (select  table_name from inforamtion_schema.tables limit 1 offset 0)
  -get:          If MySQL user is root, supply word readable file name
  -blind:        parameter to inject sql. Default is last value of url
  -match:        RECOMMENDED string to match in valid query, Default is auto
  -start:        if you know the beginning of the string, use it.
  -length:       maximum length of value. Default is 32.
  -time:         timer options:
         0:      dont wait. Default option.
         1:      wait 15 seconds
         2:      wait 5 minutes

 -type:         Type of injection:
         0:      Type 0 (default) is blind injection based on True and False responses
         1:      Type 1 is blind injection based on True and Error responses
         2:      Type 2 is injection in order by and group by
         3:      Type 3 !!New!! is extracting data with SYS privileges (ORACLE dbms_export_extension exploit)
         4:      Type 4 !!New!! is O.S code execution (ORACLE dbms_export_extension exploit)
         5:      Type 5 !!New!! is reading files (ORACLE dbms_export_extension exploit, based on java)

 -file: File to read (default C:\boot.ini)

 -stype:        How you want to execute command:
         0:      SType 0 (default) is based on java..will NOT work against XE
         1:      SType 1 is against oracle 9 with plsql_native_make_utility
         2:      SType 2 is against oracle 10 with dbms_scheduler
  -database:     Backend database:
         0:      MS-SQL (Default)
         1:      MYSQL
         2:      POSTGRES
         3:      ORACLE
  -rtime:        wait random seconds, for example: "10-20".
  -method:       http method to use; get or post. Default is GET.
  -cmd:          command to execute(type 4 only). Default is "ping 127.0.0.1."
  -uagent:       http UserAgent header to use. Default is bsqlbf 2.3
  -ruagent:      file with random http UserAgent header to use.
  -cookie:       http cookie header to use
  -rproxy:       use random http proxy from file list.
  -proxy:        use proxy http. Syntax -proxy=http://proxy:port/  -proxy_user:   proxy http user
  -proxy_pass:   proxy http password

---------------------------- examples:-------------------------------
 bash# ./bsqlbf-v2-3.pl -url http://www.somehost.com/blah.php?u=5 -blind u -sql "select table_name from imformation_schema.tables limit 1 offset 0" -database 1 -type 1

bash# ./bsqlbf-v2-3.pl -url http://www.buggy.com/bug.php?r=514&p=foo' -method post -get "/etc/passwd" -match "foo"



11- Blind Cat

There are some and then there are some more! What we meant to say is that there are some blind SQL injection tools and then there are some more. This tool is a result of the author wanting to program a tool with a different approach to blind SQL injection. Before we actually get to the tool, lets see what blind SQL injection is. I know we must have described this a lot of time, but doing so will save us sometime going back to the first post that tells you about blind SQL injection.

So, blind SQL injection is identical to normal SQL Injection except that when an attacker attempts to exploit an application, rather then getting a useful error message, they get a generic page (or sometimes are redirected to some page) specified by the developer instead. This makes exploiting a potential SQL Injection attack more difficult but not impossible. Now that we know what blind SQL injection is, it will be a bit easier for use to see what this tool can do.

Back to this tool now – Blind Cat is not a fully automated tool, the ones we call – “one clickownage“. You are the driving force behind this tool. Once, you understand how this tool works, you will be able to exploit a lot more difficult SQL injections easily. Consider this tool as an automation tool/front-end for manualblind SQL injections. It helps you to send custom HTTP requests, get the response, modify the request, re-send, get the response again and compare and slowly exploit! This front-end has been programmed in Delphi and uses cURL to get its work done.

This tool supports almost all databases – MS SQL, MySQL, Oracle, DB2, Firebird, etc., while supporting both – HTTP and HTTPS! In addition to that, it can transmit custom HTTP requests.

In other words, Blind Cat runs multiple instances of CURL, to send parametrized HTTP requests to the vulnerable web application. The responses are analyzed and other requests with modified parameters are issued until the correct characters in SQL response are detected.

The author has not added a readme file as such that might help you know more about the program, but with a bit of trial and error, you sure will be able to get this little demon to work!Download Blind Cat v0.0.1.0 here.

by Osvaldo H Peixoto