복붙노트

[SQL] ASP.Net에서 SQL 주입을 방지

SQL

ASP.Net에서 SQL 주입을 방지

이 코드를

UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''"+ Ref +"'' AND bookno = ''"+ Session("number") +"'' ') 

어떻게 SQL 주입이에 방지 할 수?

최신 정보

여기에 내가 노력하고있어입니다

SqlCommand cmd = new SqlCommand("Select * from Table where ref=@ref", con); 
cmd.Parameters.AddWithValue("@ref", 34);

어떤 이유로 모든 것을 위해 나는 시도하고 내가 SQL 명령 아래에 언급 점점 계속 작동하지 않습니다 추가 할 수 있습니다.

이 오류는 이것이다

'SqlCommand' is a type and cannot be used as an expression

이것은 나에게 모든 새로운 그래서 나는 다른 사람의 작품을 인수 그리고 난 사람이 다음을 수행하십시오 SQL 주입으로부터 안전 위 내 쿼리를 만드는 방법에 더 이상 도움을 제공 할 수 있는지 그래서 일을 올바른 방법을 싶습니다.

UPDATE NO 2

VasilP는 다음과 같이 말한대로 나는 코드에 추가

Dim dbQuery As [String] = "SELECT * FROM table WHERE ref = '" & Tools.SQLSafeString(Ref) & "' AND bookno = '" & Tools.SQLSafeString(Session("number")) & "'"

하지만 내가 작업에 대한 특정 네임 스페이스를 지정해야합니까 선언되지 않은 오류 도구를 얻을?

최신 정보

사람이 내가 겪고있어 그 오류없이 SQL 주입에서 내 쿼리의 안전을 얻을 수있는 가장 좋은에 어떤 아이디어를 가지고?

최신 정보

그것이 작동되도록 매개 변수가 여기에 비트 내 업데이트 된 소스 코드는 매개 변수 값을 추가하지 않습니다 이유는 어떤 생각하지 않고 지금 그것을 가지고?

Dim conn As SqlConnection = New SqlConnection("server='server1'; user id='w'; password='w'; database='w'; pooling='false'")
   conn.Open()


Dim query As New SqlCommand("Select * from openquery (db, 'Select * from table where investor = @investor ') ", conn)
query.Parameters.AddWithValue("@investor", 69836)

dgBookings.DataSource = query.ExecuteReader
dgBookings.DataBind()

그것은 다음과 같이 작동

Dim conn As SqlConnection = New SqlConnection("server='server1'; user id='w'; password='w'; database='w'; pooling='false'")
   conn.Open()


Dim query As New SqlCommand("Select * from openquery (db, 'Select * from table where investor = 69836') ", conn)

dgBookings.DataSource = query.ExecuteReader
dgBookings.DataBind()

내가지고있어 오류가 이것이다

An error occurred while preparing a query for execution against OLE DB provider 'MSDASQL'. 

는 69,836으로 @investor를 교체하지 않기 때문에 그리고 그것은이다

어떤 아이디어?

해결책

여기에 내 문제를 해결하는 방법입니다

Dim conn As SqlConnection = New SqlConnection("server='h'; user id='w'; password='w'; database='w'; pooling='false'")

conn.Open()

Dim query As New SqlCommand("DECLARE @investor varchar(10), @sql varchar(1000) Select @investor = 69836 select @sql = 'SELECT * FROM OPENQUERY(db,''SELECT * FROM table WHERE investor = ''''' + @investor + ''''''')' EXEC(@sql)", conn)

dgBookings.DataSource = query.ExecuteReader
dgBookings.DataBind()

지금은 SQL 주입의 걱정없이 쿼리를 작성 할 수 있습니다

해결법

  1. ==============================

    1.여기에 매개 변수가있는 쿼리를 사용하여 시도하는 링크입니다 http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/

    여기에 매개 변수가있는 쿼리를 사용하여 시도하는 링크입니다 http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/

    또한, OpenQuery를 사용하지 마십시오 ... 선택을 실행하기 위해 이것을 사용

    SELECT * FROM db...table WHERE ref = @ref AND bookno = @bookno
    

    옵션 중 일부를 설명하는 더 많은 기사 :

    http://support.microsoft.com/kb/314520

    다른 SQL 서버에 연결하는 T-SQL 구문은 무엇입니까?

    편집

    참고 : 원래의 질문이 분산 쿼리 및 연결된 서버에 대해 질문했다. 이 새로운 문은 분산 쿼리를 참조하지 않습니다. 난 단지 당신이 직접 이제 데이터베이스에 연결하는 가정 할 수 있습니다. 여기에 작동합니다 예입니다. 여기 SqlCommand.Parameters를 사용하는 또 다른 기준 위치는

    SqlCommand cmd = new SqlCommand("Select * from Table where ref=@ref", con); 
    cmd.Parameters.Add("@ref", SqlDbType.Int);
    cmd.Parameters["@ref"] = 34;
    

    편집 :

    좋아 제이미 테일러 다시 귀하의 질문에 대답하려고합니다.

    당신은 아마 링크 된 DB를 사용하고 있기 때문에 당신은 OpenQuery를를 사용하는

    기본적으로 문제는 OpenQuery를 방법은 당신이 OpenQuery를 보내 문자열의 일부로 변수를 전달할 수없는 문자열을 사용합니다.

    대신이 같은 쿼리를 포맷 할 수 있습니다. 표기법은 servername.databasename.schemaname.tablename을 따른다. 아래 그림과 같이 당신은 ODBC를 다음을 생략 databaseName을하고 스키마 명을 통해 연결된 서버를 사용하는 경우

        Dim conn As SqlConnection = New SqlConnection("your SQL Connection String")
        Dim cmd As SqlCommand = conn.CreateCommand()
        cmd.CommandText = "Select * db...table where investor = @investor"
        Dim parameter As SqlParameter = cmd.CreateParameter()
        parameter.DbType = SqlDbType.Int
        parameter.ParameterName = "@investor"
        parameter.Direction = ParameterDirection.Input
        parameter.Value = 34
    
  2. ==============================

    2.대신 SQL 쿼리을 연결의 사용 매개 변수를 설정합니다.

    대신 SQL 쿼리을 연결의 사용 매개 변수를 설정합니다.

    SQL 서버 인 데이터베이스 엔진 가정하면, 여기에 내가 의지의 도움을 희망 코드의 조각입니다.

    Using connection As SqlConnection = new SqlConnection("connectionString")
        connection.Open()
    
        Using command As SqlCommand = connection.CreateCommand()
            string sqlStatement = "select * from table where ref = @ref and bookno = @bookno";
            command.CommandText = sqlStatement
            command.CommandType = CommandType.Text
    
            Dim refParam As SqlDataParameter = command.CreateParameter()
            refParam.Direction = ParameterDirection.Input
            refParam.Name = "@ref"
            refParam.Value = Ref
    
            Dim booknoParam As SqlDataParameter = command.CreateParameter()
            booknoParam.Direction = ParameterDirection.Input
            booknoParam.Name = "@bookno"
            booknoParam.Value = Session("number")
    
            Try
                Dim reader As SqlDataReader = command.ExecuteQuery()
                ' Do your reading job here...'
            Finally
                command.Dispose()
                connection.Dispose()
            End Try
        End Using
    End Using
    

    모든 비용, 회피 SQL 문 연결을 모두 요약 및 사용은 quesries을 매개 변수화하는 방법!

    여기 MSDN의 SQL 주입 문제 해결 과정을 제공 흥미있는 링크입니다 :

    방법 : 보호 ASP.NET에서 SQL 주입에서

  3. ==============================

    3.sqlparameters를 같이 사용합니다 :

    sqlparameters를 같이 사용합니다 :

    SqlCommand cmd = new SqlCommand("Select * from Table where id=@id", con);
    cmd.Parameters.AddWithValue("@id", 34);
    
  4. ==============================

    4.당신은 매개 변수가있는 쿼리를 사용할 수 있습니다.

    당신은 매개 변수가있는 쿼리를 사용할 수 있습니다.

    http://www.functionx.com/aspnet/sqlserver/parameterized.htm

  5. ==============================

    5.

    SqlCommand cmd = new SqlCommand("Select * from Table where ref=@ref", con); 
    cmd.Parameters.AddWithValue("@ref", 34);
    

    이 VB, C #으로하지 작성된 것입니다 때문에 작동하지 않습니다.

    같은 시도

    Dim cmd As New SqlCommand("Select * from Table where ref=@ref", con)
    cmd.Parameters.AddWithValue("ref", 34)
    
  6. ==============================

    6.나의 선호하는 방법은 DAL을 만들어 비주얼 스튜디오 핸들 모두 수 있도록하는 것입니다 : http://www.asp.net/data-access/tutorials/creating-a-data-access-layer-cs

    나의 선호하는 방법은 DAL을 만들어 비주얼 스튜디오 핸들 모두 수 있도록하는 것입니다 : http://www.asp.net/data-access/tutorials/creating-a-data-access-layer-cs

  7. ==============================

    7.사용 LINQ. 에서 자동으로 쿼리를 매개 변수화.

    사용 LINQ. 에서 자동으로 쿼리를 매개 변수화.

  8. ==============================

    8.대안 (당신이 중간 크기 또는 큰 무언가를 구축하는 경우 이동하는 아주 좋은 방법)와 같은 ORM을 확인하십시오. 그것은을 구성하는 약간의 시간이 필요하지만 개발은 매우 빠르게된다. 당신은 .NET과 함께 작동 다른 ORM을 시도, 네이티브에서, Linq는 SQL 또는 엔티티 프레임 워크를 선택하거나.

    대안 (당신이 중간 크기 또는 큰 무언가를 구축하는 경우 이동하는 아주 좋은 방법)와 같은 ORM을 확인하십시오. 그것은을 구성하는 약간의 시간이 필요하지만 개발은 매우 빠르게된다. 당신은 .NET과 함께 작동 다른 ORM을 시도, 네이티브에서, Linq는 SQL 또는 엔티티 프레임 워크를 선택하거나.

  9. from https://stackoverflow.com/questions/4018174/preventing-sql-injection-in-asp-net by cc-by-sa and MIT license