htmlspecialchars 및 mysql_real_escape_string은 PHP 코드를 주입으로부터 안전하게 유지합니까?
오늘 초 웹 애플 리케이션의 입력 유효성 검사 전략에 관한 질문이있었습니다 .
글을 쓰는 시점에서 가장 좋은 대답은 and를 PHP
사용하는 것 입니다.htmlspecialchars
mysql_real_escape_string
내 질문은 : 이것은 항상 충분합니까? 더 알아야 할 것이 있습니까? 이 기능들은 어디서 나옵니까?
데이터베이스 쿼리와 관련하여 항상 준비된 매개 변수화 된 쿼리를 사용하십시오. mysqli
및 PDO
라이브러리는이 기능을 지원. 이 같은 이스케이프 기능을 사용하는 것보다 훨씬 안전 mysql_real_escape_string
합니다.
예, mysql_real_escape_string
사실상 문자열 이스케이프 기능입니다. 마법의 총알이 아닙니다. 단일 쿼리 문자열에서 안전하게 사용할 수 있도록 위험한 문자를 이스케이프 처리하면됩니다. 그러나 입력을 미리 위생 처리하지 않으면 특정 공격 경로에 취약합니다.
다음 SQL을 상상해보십시오.
$result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']);
이것이 악용에 취약하다는 것을 알 수 있습니다. 매개 변수에 공통 공격 벡터가 포함되어
있다고 상상해보십시오 id
.
1 OR 1=1
인코딩 할 위험한 문자가 없으므로 이스케이프 필터를 통해 곧바로 전달됩니다. 우리를 떠나 :
SELECT fields FROM table WHERE id= 1 OR 1=1
이것은 멋진 SQL 주입 벡터이며 공격자가 모든 행을 반환하도록 허용합니다. 또는
1 or is_admin=1 order by id limit 1
어떤 생산
SELECT fields FROM table WHERE id=1 or is_admin=1 order by id limit 1
공격자는이 가상의 예제에서 첫 번째 관리자의 세부 정보를 반환 할 수 있습니다.
이러한 기능은 유용하지만주의해서 사용해야합니다. 모든 웹 입력이 어느 정도 검증되었는지 확인해야합니다. 이 경우 우리는 숫자로 사용하고있는 변수가 실제로 숫자인지 확인하지 않았기 때문에 악용 될 수 있습니다. PHP에서는 입력이 정수, 부동 소수점, 영숫자 등인지 확인하기 위해 일련의 함수를 광범위하게 사용해야합니다. 그러나 SQL의 경우 준비된 명령문의 값에 유의하십시오. 위의 코드는 데이터베이스 함수가 1 OR 1=1
유효한 리터럴이 아닌 것으로 알고 있으므로 준비된 명령문 인 경우 안전했을 것 입니다.
에 관해서 htmlspecialchars()
. 그것은 그 자신의 지뢰밭입니다.
PHP에는 다양한 HTML 관련 이스케이프 기능이 선택되어 있으며 어떤 기능이 정확히 어떤 기능을 수행하는지에 대한 명확한 지침이 없다는 점에서 PHP의 실제 문제가 있습니다.
첫째, HTML 태그 안에 있으면 실제로 문제가 있습니다. 보다
echo '<img src= "' . htmlspecialchars($_GET['imagesrc']) . '" />';
우리는 이미 HTML 태그 안에 있으므로 위험한 일을하기 위해 <또는>가 필요하지 않습니다. 우리의 공격 벡터는javascript:alert(document.cookie)
이제 결과 HTML은 다음과 같습니다
<img src= "javascript:alert(document.cookie)" />
공격은 곧바로 이루어집니다.
악화된다. 왜? 때문에 htmlspecialchars
(이런 식으로 전화했을 때)에만 따옴표를 인코딩 및 단일 없습니다. 만약 우리가
echo "<img src= '" . htmlspecialchars($_GET['imagesrc']) . ". />";
우리의 사악한 공격자는 이제 완전히 새로운 매개 변수를 주입 할 수 있습니다
pic.png' onclick='location.href=xxx' onmouseover='...
우리에게 주어지다
<img src='pic.png' onclick='location.href=xxx' onmouseover='...' />
이 경우에는 마법의 총알이 없으므로 입력을 직접 처리해야합니다. 당신이 나쁜 문자를 필터링하려고하면 반드시 실패합니다. 화이트리스트 접근 방식을 취하고 좋은 문자 만 통과하십시오. 다양한 벡터가 얼마나 다양한 지에 대한 예 는 XSS 치트 시트 를 참조하십시오
htmlspecialchars($string)
HTML 태그 외부에서 사용하더라도 멀티 바이트 문자 집합 공격 벡터에 여전히 취약합니다.
가장 효과적인 방법은 다음과 같이 mb_convert_encoding과 htmlentities의 조합을 사용하는 것입니다.
$str = mb_convert_encoding($str, 'UTF-8', 'UTF-8');
$str = htmlentities($str, ENT_QUOTES, 'UTF-8');
이조 차도 IE6은 UTF를 처리하는 방식 때문에 취약합니다. 그러나 IE6 사용량이 줄어들 때까지 ISO-8859-1과 같이 더 제한적인 인코딩으로 대체 할 수 있습니다.
멀티 바이트 문제에 대한 자세한 내용은 https://stackoverflow.com/a/12118602/1820을 참조 하십시오.
Cheekysoft의 탁월한 답변 외에도
- 예, 그들은 당신을 안전하게 지켜줄 것입니다. 그러나 그들이 정확하게 올바르게 사용되는 경우에만 가능합니다. 잘못 사용하면 여전히 취약하며 다른 문제 (예 : 데이터 손상)가있을 수 있습니다.
- 대신 위에서 설명한대로 매개 변수화 된 쿼리를 사용하십시오. PDO 또는 PEAR DB와 같은 래퍼를 통해 사용할 수 있습니다.
- magic_quotes_gpc 및 magic_quotes_runtime이 항상 꺼져 있고 실수로 잠깐 켜지는 않도록하십시오. 이는 보안 문제 (데이터를 파괴하는)를 방지하기 위해 PHP 개발자가 시도한 초기의 잘못된 시도입니다.
HTML 삽입을 방지 할 수있는 은색 글 머리 기호는 없지만 (예 : 크로스 사이트 스크립팅) HTML 출력에 라이브러리 또는 템플릿 시스템을 사용하는 경우보다 쉽게 달성 할 수 있습니다. 적절하게 탈출하는 방법에 대한 설명서를 읽으십시오.
HTML에서는 상황에 따라 상황을 다르게 이스케이프해야합니다. 이것은 특히 문자열이 Javascript에 배치되는 경우에 해당됩니다.
I would definitely agree with the above posts, but I have one small thing to add in reply to Cheekysoft's answer, specifically:
When it comes to database queries, always try and use prepared parameterised queries. The mysqli and PDO libraries support this. This is infinitely safer than using escaping functions such as mysql_real_escape_string.
Yes, mysql_real_escape_string is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors.
Imagine the following SQL:
$result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']);
You should be able to see that this is vulnerable to exploit. Imagine the id parameter contained the common attack vector:
1 OR 1=1
There's no risky chars in there to encode, so it will pass straight through the escaping filter. Leaving us:
SELECT fields FROM table WHERE id = 1 OR 1=1
I coded up a quick little function that I put in my database class that will strip out anything that isnt a number. It uses preg_replace, so there is prob a bit more optimized function, but it works in a pinch...
function Numbers($input) {
$input = preg_replace("/[^0-9]/","", $input);
if($input == '') $input = 0;
return $input;
}
So instead of using
$result = "SELECT fields FROM table WHERE id = ".mysqlrealescapestring("1 OR 1=1");
I would use
$result = "SELECT fields FROM table WHERE id = ".Numbers("1 OR 1=1");
and it would safely run the query
SELECT fields FROM table WHERE id = 111
Sure, that just stopped it from displaying the correct row, but I dont think that is a big issue for whoever is trying to inject sql into your site ;)
An important piece of this puzzle is contexts. Someone sending "1 OR 1=1" as the ID is not a problem if you quote every argument in your query:
SELECT fields FROM table WHERE id='".mysql_real_escape_string($_GET['id'])."'"
Which results in:
SELECT fields FROM table WHERE id='1 OR 1=1'
which is ineffectual. Since you're escaping the string, the input cannot break out of the string context. I've tested this as far as version 5.0.45 of MySQL, and using a string context for an integer column does not cause any problems.
$result = "SELECT fields FROM table WHERE id = ".(INT) $_GET['id'];
Works well, even better on 64 bit systems. Beware of your systems limitations on addressing large numbers though, but for database ids this works great 99% of the time.
You should be using a single function/method for cleaning your values as well. Even if this function is just a wrapper for mysql_real_escape_string(). Why? Because one day when an exploit to your preferred method of cleaning data is found you only have to update it one place, rather than a system-wide find and replace.
why, oh WHY, would you not include quotes around user input in your sql statement? seems quite silly not to! including quotes in your sql statement would render "1 or 1=1" a fruitless attempt, no?
so now, you'll say, "what if the user includes a quote (or double quotes) in the input?"
well, easy fix for that: just remove user input'd quotes. eg: input =~ s/'//g;
. now, it seems to me anyway, that user input would be secured...
'Programing' 카테고리의 다른 글
#if 0… #endif 블록은 정확히 무엇을합니까? (0) | 2020.07.21 |
---|---|
JOIN 조건에서 CASE 문을 사용할 수 있습니까? (0) | 2020.07.21 |
MySQL에서 타임 스탬프를 datetime으로 변환하는 방법은 무엇입니까? (0) | 2020.07.21 |
Python 요청 라이브러리의 get 메소드와 함께 헤더 사용 (0) | 2020.07.21 |
현재 노드 버전 확인 (0) | 2020.07.21 |