Unconfigured Ad Widget

Collapse

Anúncio

Collapse
No announcement yet.

Proteção contra SQL Injection no ASP.NET

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

  • Font Size
    #1

    Tutorial Proteção contra SQL Injection no ASP.NET

    Saudações a todos. Hoje explico a vocês como aumentar segurança em autenticação, SQL Injection é uma brecha grave na segurança que toda via deve obrigatóriamente tratada, dificultando assim o acesso de usuários nao cadastrados.

    Para este exemplo será necessário:

    * SQL SERVER :
    * Criar um Banco de Dados (dbTeste);
    * Criar uma Tabela (tbLogin), abaixo script da tabela;
    * Inserir um usuario e uma senha;

    * Visual Studio :
    * Criar um novo Web Site
    * Digitar código na pagina Default.ASPX e Default.ASPX.CS
    * No arquivo Default.ASPX.CS configurar linha de conexão com banco de dados, segundo sua realidade.

    * Forma de Testar
    * 1º Teste, informe o login e senha cadastrados no banco e teste com as duas formas de conexao;
    * 2º Teste, no campo login digite ' or 1=1 -- e teste com as duas forma de conexao;
    nesta forma será efetuado a autenticação com SQL Injection, pois como pode notar eu insiro uma aspas simples
    esta tem a função de fechar a primeira aspas simples aberta na instrução sql o restante (OR 1=1 --)faz retornar sempre uma
    condição verdadeira e os dois sinais de menos, cancelam o restante da linha;

    Eis abaixo o código da aplicação:

    Código:
    * SQL SERVER : 
    	Criar Tabela tbLogin
    		USE [dbTestes]
    		GO
    		/****** Object:  Table [dbo].[tbLogin]    Script Date: 02/19/2009 17:54:36 ******/
    
    		CREATE TABLE [dbo].[tbLogin]
    		(
    			[Login] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
    			[Senha] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
    			CONSTRAINT [PK_tbLogin] PRIMARY KEY CLUSTERED 
    			( [Login] ASC )
    			WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
    		) ON [PRIMARY]
    		GO
      * Visual Studio:
    -- DEFAULT.ASPX
    
    	<body>
    	    <form id="form1" runat="server">
    	    <div>
    		<asp:Label ID="lblLogin" runat="server" Text="Login"></asp:Label>&nbsp;&nbsp;
    		    <asp:TextBox 
    			ID="txtLogin" 
    			runat="server" 
    			TextMode="SingleLine" 
    			MaxLength="15" 
    			Width="180px">
    		    </asp:TextBox>
    		<br />
    		<asp:Label ID="lblSenha" runat="server" Text="Senha"></asp:Label>&nbsp;&nbsp;
    		    <asp:TextBox 
    			ID="txtSenha" 
    			runat="server" 
    			TextMode="Password" 
    			MaxLength="8" >
    		    </asp:TextBox>
    		 <br />
    		<asp:Button ID="btLogin1" runat="server" Text="Login (SQL Injection)" 
    		    onclick="btLogin1_Click"/>
    		&nbsp;&nbsp;&nbsp;
    		<asp:Button ID="btLogin2" runat="server" Text="Login (Don't SQL Injection)" 
    		    onclick="btLogin2_Click"  />
    		<br /><hr />
    		<asp:Label ID="lblMsg"   runat="server" Text="lblMsg"></asp:Label>
    	    </div>
    	    </form>
    	</body>
    
    
    
    -- DEFAULT.ASPX;CS
    
    	using System.Data;
    	using System.Data.SqlClient;
    
        protected void btLogin1_Click(object sender, EventArgs e)
        {
            /* Este representa o botao Login (SQL Injection) ou 
               seja por este botao e´ permitido efetuar SQL Injection
            */
            string cs = "Data Source=WXPRO-001\\SQLEXPRESS;Initial Catalog=dbTestes;Integrated Security=True";
            SqlConnection conn = new SqlConnection(cs);
            try
            {
                conn.Open();
                string comando = "Select Count(*) From tbLogin where Login ='" + this.txtLogin.Text.ToString() + "' and Senha = '" + this.txtSenha.Text.ToString() + "'";
                System.Data.SqlClient.SqlCommand comm = new SqlCommand(comando, conn);
                int nroUsuarios = Convert.ToInt32(comm.ExecuteScalar());
                if (nroUsuarios > 0)
                {
                    this.lblMsg.Text = "Usuario Autenticado!";
                }
                else
                {
                    this.lblMsg.Text = "Usuario Invalido!";
                }
            }
            catch(Exception ex)
            {
                this.lblMsg.Text= ex.ToString();
            }
            finally 
            {
                conn.Close();
            }
        }
        protected void btLogin2_Click(object sender, EventArgs e)
        {
            /* Este representa o botao Login (Don't SQL Injection) ou 
               seja por este botao NAO e´ permitido efetuar SQL Injection.
            */
            string cs = "Data Source=WXPRO-001\\SQLEXPRESS;Initial Catalog=dbTestes;Integrated Security=True";
            SqlConnection conn = new SqlConnection(cs);
            try
            {
                conn.Open();
                // Aqui esta a diferenca, o conteudo dos campos serao passados por parametros
                // tratados pelo proprio FrameWork
                string comando = "Select Count(*) From tbLogin where Login =@Login and Senha = @Senha";
                System.Data.SqlClient.SqlCommand comm = new SqlCommand(comando, conn);
                comm.Parameters.AddWithValue("@Login", this.txtLogin.Text);
                comm.Parameters.AddWithValue("@Senha", this.txtSenha.Text);
    
                int nroUsuarios = Convert.ToInt32(comm.ExecuteScalar());
                if (nroUsuarios > 0)
                {
                    this.lblMsg.Text = "Usuario Autenticado!";
                }
                else
                {
                    this.lblMsg.Text = "Usuario Invalido!";
                }
    
            }
            catch (Exception ex)
            {
                this.lblMsg.Text = ex.ToString();
            }
            finally
            {
                conn.Close();
            }
        }
    
    -- // FIM
    ~# Criado pela [IN]Segurança #~

  • Font Size
    #2
    interessante
    vlw kra
    Obrigado por COmpartilhar!

    Comment

    X
    Working...
    X