2017-10-04 1 views
0

개발자가 SQL 문의 취약점을 완화하기 위해 URL의 매개 변수가있는 쿼리 을 설정할 수 있음을 알고 싶습니다. 예를 들어URL의 매개 변수 쿼리를 설정할 수 있습니까?

는 :

https://example.com/somefile.php?id=1 

어떻게 개발자는 그에 대한 매개 변수화 쿼리를 만들 수 있습니까? 응용 프로그램의 매개 변수 에서처럼?

답변

0

예 할 수 있습니다. 매개 변수화 된 쿼리는 간단하며 미리 SQL 쿼리를 정의해야하며 쿼리에서 사용자가 제공 한 변수에 자리 표시자를 사용해야합니다. 그런 다음 SQL 문이 정의 된 후 각 매개 변수를 쿼리에 전달하여 데이터베이스에서 사용자가 입력 한 SQL 명령과 데이터를 구별 할 수있게합니다. 침입자가 SQL 명령을 입력하면 매개 변수화 된 쿼리는이를 신뢰할 수없는 입력으로 처리하고 삽입 된 SQL 명령은 절대로 실행되지 않습니다. 더 많은 이해를 위해 아래 제공된 예를보십시오.

if (isset($_GET['id'])){ 
    $id = $_GET['id']; 
    /** 
    * Validate data before it enters the database. In this case, we need to check that 
    * the value of the 'id' GET parameter is numeric 
    */ 
    if (is_numeric($id) == true){ 
    try{ 
     $dbh = new PDO('mysql:host=localhost;dbname=sql_injection_example', 'dbuser', 'dbpasswd'); 

     $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

     /** 
     * Before executing our SQL statement, we need to prepare it by 'binding' parameters. 
     * We will bind our validated user input (in this case, it's the value of $id) to our 
     * SQL statement before sending it to the database server. 
     * 
     * This fixes the SQL injection vulnerability. 
     */ 
     $q = "SELECT username 
      FROM users 
      WHERE id = :id"; 
     // Prepare the SQL query 
     $sth = $dbh->prepare($q); 
     // Bind parameters to statement variables 
     $sth->bindParam(':id', $id); 
     // Execute statement 
     $sth->execute(); 

     $sth->setFetchMode(PDO::FETCH_ASSOC); 
     // Fetch result 
     $result = $sth->fetchColumn(); 
     /** 
     * HTML encode our result using htmlentities() to prevent stored XSS and print the 
     * result to the page 
     */ 
     print(htmlentities($result)); 

     $dbh = null; 
    } 
    catch(PDOException $e){ 
     /** 
     * You can log PDO exceptions to PHP's system logger, using the Operating System's 
     * system logging mechanism 
     * 
     * For more logging options visit http://php.net/manual/en/function.error-log.php 
     */ 
     error_log('PDOException - ' . $e->getMessage(), 0); 
     /** 
     * Stop executing, return an 'Internal Server Error' HTTP status code (500), 
     * and display an error 
     */ 
     http_response_code(500); 
     die('Error establishing connection with database'); 
    } 
    } else{ 
    /** 
    * If the value of the 'id' GET parameter is not numeric, stop executing, return 
    * a 'Bad request' HTTP status code (400), and display an error 
    */ 
    http_response_code(400); 
    die('Error processing bad or malformed request'); 
    } 
} 
?> 
+1

은 기본적으로 단순한 언어를 의미합니다. 즉, id 매개 변수에 변수를 제공하기 만하면 해당 변수에 쿼리가 포함됩니다. 따라서 공격자가 입력 한 내용을 어딘가에 저장하려고 시도하지만 원래 쿼리에는 영향을 미치지 않습니다. 그래서 우리의 SQL 주입 작동하지 않을 것입니다? 내가 틀렸다면 나를 명확히하십시오? –

+0

@ 재규어와 검은 색 정확히 무슨 일이 일어나고 있니? –

+0

오 고맙습니다 @ 수 베탄 난샤. –

0

문제는 URL에 없지만 나중에 URL에서 전달 된 매개 변수를 사용하는 방법입니다.

가장 좋은 방법은 바인드 변수를 사용하는 것이다 :

탈출 및/또는 의심스러운 데이터를 제거하여 매개 변수를 설정합니다. 이것은 일반적으로 실수하기 쉽도록 구현하는 것은 매우 까다로운 일입니다. 따라서 바인드 변수는 사용하기 간단하고 안전합니다.

+0

@YoYo에 감사하지만 너무 혼란 스럽습니다. 그러나 나는 그것을 이해하려고 노력할 것이다. –

+0

안녕하세요, 제발 당신이 그것을 확인하시기 바랍니다, 나는 그것에 대해 이해가 무엇인지 보여주는 아래의 코멘트를 올렸습니다. –

+0

잘 설명해 주셨습니다. 또한, 받아 들인 대답은 바인드 변수를 어떻게 사용할 수 있는지에 대한 훌륭한 예를 보여줍니다. 그러나 실제로는 다른 게시물의 중복입니다. 가장 주목할만한이 하나 - https://stackoverflow.com/a/60496/744133 – YoYo

관련 문제