Nice programing

PHP 사이트에서 xss 공격을 방지하기위한 모범 사례는 무엇입니까?

nicepro 2020. 11. 17. 21:04
반응형

PHP 사이트에서 xss 공격을 방지하기위한 모범 사례는 무엇입니까?


마법 따옴표가 켜져 있고 전역 등록이 꺼 지도록 PHP를 구성했습니다.

사용자 입력에서 파생 된 출력에 대해 항상 htmlentities ()를 호출하기 위해 최선을 다합니다.

나는 또한 때때로 다음과 같이 첨부 된 xss에서 사용되는 일반적인 것들에 대해 데이터베이스를 검색합니다.

<script

그 밖에 무엇을해야하며 내가하려는 일이 항상 완료 되도록하려면 어떻게해야 합니다.


입력 이스케이프는 성공적인 XSS 방지를 위해 할 수있는 최선의 방법이 아닙니다. 또한 출력을 이스케이프해야합니다. Smarty 템플릿 엔진을 사용하는 경우 |escape:'htmlall'수정자를 사용 하여 모든 민감한 문자를 HTML 엔티티로 변환 할 수 있습니다 ( |e위의 별칭 인 자체 수정자를 사용 합니다).

입력 / 출력 보안에 대한 나의 접근 방식은 다음과 같습니다.

  • 수정되지 않은 사용자 입력 저장 (입력시 HTML 이스케이프 없음, PDO 준비 명령문을 통해 수행되는 DB 인식 이스케이프 만 수행)
  • 사용하는 출력 형식에 따라 출력시 이스케이프 (예 : HTML 및 JSON에는 다른 이스케이프 규칙이 필요함)

나는 입력하는 동안 아무것도 이스케이프해서는 안된다고 생각합니다. (대부분의 경우) 해당 데이터가 어디로 가는지 알고 있다고 가정 할 수 없습니다. 예를 들어 나중에 보내는 이메일에 나타나는 데이터를 가져 오는 양식이있는 경우 다른 이스케이프가 필요합니다 (그렇지 않으면 악의적 인 사용자가 이메일 헤더를 다시 작성할 수 있음).

즉, 데이터가 응용 프로그램에서 "나가는"마지막 순간에만 탈출 할 수 있습니다.

  • 목록 항목
  • XML 파일에 쓰기, XML 용 이스케이프
  • DB에 쓰기, 이스케이프 (특정 DBMS의 경우)
  • 이메일 작성, 이메일의 경우 이스케이프
  • 기타

짧게 가려면 :

  1. 데이터가 어디로 가고 있는지 모릅니다.
  2. 데이터는 실제로 둘 이상의 위치에서 끝날 수 있으며 다른 이스케이프 메커니즘이 필요하지만 둘다는 아닙니다.
  3. 잘못된 대상을 위해 이스케이프 된 데이터는 정말 좋지 않습니다. (예 : "Tommy \ 's bar로 이동"이라는 제목의 이메일을받습니다.)

Esp # 3은 입력 레이어에서 데이터를 이스케이프하거나 다시 이스케이프를 해제해야하는 경우 발생합니다.

추신 : magic_quotes를 사용하지 않는 것에 대한 충고를 두 번째로하겠습니다.


XSS를 수행하는 방법에는 여러 가지가 있으며 ( http://ha.ckers.org/xss.html 참조 ) 잡기가 매우 어렵습니다.

개인적으로 사용중인 현재 프레임 워크 (예 : Code Igniter)에 이것을 위임합니다. 완벽하지는 않지만 손으로 ​​만든 루틴보다 더 많은 것을 잡을 수 있습니다.


이것은 좋은 질문입니다.

첫째, 저장 (예 : 데이터베이스에 저장)을 위해 안전하게 만드는 것 외에는 입력시 텍스트를 이스케이프하지 마십시오. 그 이유는 입력 된 내용을 유지하여 다양한 방식과 장소에서 상황에 맞게 표현할 수 있기 때문입니다. 여기에서 변경하면 나중에 프레젠테이션이 손상 될 수 있습니다.

데이터를 제시하러 갈 때 거기에 있으면 안되는 것을 필터링하십시오. 예를 들어 javascript가 거기에있을 이유가 없다면 검색하여 제거하십시오. 이를 수행하는 쉬운 방법은 strip_tags 함수 를 사용하고 허용하는 html 태그 만 표시하는 것입니다.

다음으로, 당신이 가진 것을 가져다가 htmlentities 또는 htmlspecialchars를 전달하여 거기에있는 것을 ascii 문자로 변경하십시오. 컨텍스트와 원하는 내용에 따라이 작업을 수행하십시오.

또한 Magic Quotes를 끄는 것이 좋습니다. 그것은 PHP 6에서 제거되었고 그것을 사용하는 것은 나쁜 습관으로 간주됩니다. http://us3.php.net/magic_quotes의 세부 정보

자세한 내용은 http://ha.ckers.org/xss.html을 확인 하십시오.

이것은 완전한 대답은 아니지만 시작하는 데 도움이되기를 바랍니다.


rikh는 다음과 같이 씁니다.

사용자 입력에서 파생 된 출력에 대해 항상 htmlentities ()를 호출하기 위해 최선을 다합니다.

이에 대한 도움을 받으려면 코드를 잘못 보이게 만들기 에 대한 Joel의 에세이를 참조하십시오.


나는 그것을 위해 PHPTAL의존 합니다.

Smarty 및 일반 PHP와 달리 기본적으로 모든 출력을 이스케이프합니다. htmlspecialchars()거나 |escape어딘가에 사이트를 훔쳐 갈 수 없기 때문에 이것은 보안 측면에서 큰 승리입니다 .

XSS는 HTML 관련 공격이므로 HTML 출력이이를 방지 할 수있는 올바른 위치입니다. HTML을 허용하지 않지만 자체 위험이있는 다른 매체로 데이터를 출력해야 할 수 있으므로 데이터베이스에서 데이터를 사전 필터링하지 마십시오.


템플릿 라이브러리. 또는 적어도 그것이 템플릿 라이브러리가해야 할 일입니다. XSS를 방지하려면 모든 출력을 인코딩해야합니다. 이것은 메인 애플리케이션 / 제어 로직의 작업이 아니며, 출력 메소드에 의해서만 처리되어야합니다.

코드 전체에 htmlentities ()를 뿌린다면 전체적인 디자인이 잘못된 것입니다. 그리고 당신이 제안한 것처럼 한두 곳을 놓칠 수 있습니다. 이것이 유일한 해결책은 엄격한 html 인코딩 -> 출력 변수가 html / xml 스트림에 기록 될 때 입니다.

안타깝게도 대부분의 PHP 템플릿 라이브러리는 자체 템플릿 구문 만 추가하지만 출력 인코딩, 현지화, HTML 유효성 검사 또는 중요한 사항에 대해서는 신경 쓰지 않습니다. 다른 사람이 PHP에 적합한 템플릿 라이브러리를 알고 있습니까?


대부분의 사이트에서는 모든 사용자 입력을 이스케이프하는 것으로 충분합니다. 또한 세션 ID가 URL로 끝나지 않도록 Referer하여 다른 사이트로 링크 에서 도난 당할 수 없도록 하십시오. 또한 사용자가 링크를 제출하도록 허용하는 경우 javascript:프로토콜 링크가 허용 되지 않는지 확인하십시오 . 사용자가 링크를 클릭하자마자 스크립트를 실행합니다.


XSS 공격이 염려되는 경우 출력 문자열을 HTML로 인코딩하는 것이 해결책입니다. 모든 단일 출력 문자를 HTML 형식으로 인코딩하는 것을 기억하면 성공적인 XSS 공격을 실행할 방법이 없습니다.

더 읽기 : 사용자 데이터 삭제 : 어떻게, 어디서 수행


개인적으로 magic_quotes를 비활성화합니다. PHP5 +에서는 기본적으로 비활성화되어 있으며 모든 것을 이스케이프하지 않고 PHP6에서 제거되므로 전혀없는 것처럼 코딩하는 것이 좋습니다.

다음으로, 필터링하는 사용자 데이터의 유형에 따라 다음에 수행 할 작업 (예 : 이름과 같은 텍스트 일 ​​경우)을 지시 strip_tags(trim(stripslashes()));하거나 정규식을 사용하여 범위를 확인합니다.

특정 범위의 값이 예상되는 경우 유효한 값의 배열을 만들고 해당 값만 ( in_array($userData, array(...))) 까지 허용합니다 .

숫자를 확인하는 경우 is_numeric을 사용하여 정수를 적용하거나 특정 유형으로 캐스트하면 사람들이 대신 문자열을 보내려고 시도하는 것을 방지 할 수 있습니다.

If you have PHP5.2+ then consider looking at filter() and making use of that extension which can filter various data types including email addresses. Documentation is not particularly good, but is improving.

If you have to handle HTML then you should consider something like PHP Input Filter or HTML Purifier. HTML Purifier will also validate HTML for conformance. I am not sure if Input Filter is still being developed. Both will allow you to define a set of tags that can be used and what attributes are allowed.

Whatever you decide upon, always remember, never ever trust anything coming into your PHP script from a user (including yourself!).


All of these answers are great, but fundamentally, the solution to XSS will be to stop generating HTML documents by string manipulation.

Filtering input is always a good idea for any application.

Escaping your output using htmlentities() and friends should work as long as it's used properly, but this is the HTML equivalent of creating a SQL query by concatenating strings with mysql_real_escape_string($var) - it should work, but fewer things can validate your work, so to speak, compared to an approach like using parameterized queries.

The long-term solution should be for applications to construct the page internally, perhaps using a standard interface like the DOM, and then to use a library (like libxml) to handle the serialization to XHTML/HTML/etc. Of course, we're a long ways away from that being popular and fast enough, but in the meantime we have to build our HTML documents via string operations, and that's inherently more risky.


I find that using this function helps to strip out a lot of possible xss attacks: http://www.codebelay.com/killxss.phps


“Magic quotes” is a palliative remedy for some of the worst XSS flaws which works by escaping everything on input, something that's wrong by design. The only case where one would want to use it is when you absolutely must use an existing PHP application known to be written carelessly with regard to XSS. (In this case you're in a serious trouble even with “magic quotes”.) When developing your own application, you should disable “magic quotes” and follow XSS-safe practices instead.

XSS, a cross-site scripting vulnerability, occurs when an application includes strings from external sources (user input, fetched from other websites, etc) in its [X]HTML, CSS, ECMAscript or other browser-parsed output without proper escaping, hoping that special characters like less-than (in [X]HTML), single or double quotes (ECMAscript) will never appear. The proper solution to it is to always escape strings according to the rules of the output language: using entities in [X]HTML, backslashes in ECMAscript etc.

Because it can be hard to keep track of what is untrusted and has to be escaped, it's a good idea to always escape everything that is a “text string” as opposed to “text with markup” in a language like HTML. Some programming environments make it easier by introducing several incompatible string types: “string” (normal text), “HTML string” (HTML markup) and so on. That way, a direct implicit conversion from “string” to “HTML string” would be impossible, and the only way a string could become HTML markup is by passing it through an escaping function.

“Register globals”, though disabling it is definitely a good idea, deals with a problem entirely different from XSS.


Make you any session cookies (or all cookies) you use HttpOnly. Most browsers will hide the cookie value from JavaScript in that case. User could still manually copy cookies, but this helps prevent direct script access. StackOverflow had this problem durning beta.

This isn't a solution, just another brick in the wall


  • Don't trust user input
  • Escape all free-text output
  • Don't use magic_quotes; see if there's a DBMS-specfic variant, or use PDO
  • Consider using HTTP-only cookies where possible to avoid any malicious script being able to hijack a session

You should at least validate all data going into the database. And try to validate all data leaving the database too.

mysql_real_escape_string is good to prevent SQL injection, but XSS is trickier. You should preg_match, stip_tags, or htmlentities where possible!


The best current method for preventing XSS in a PHP application is HTML Purifier (http://htmlpurifier.org/). One minor drawback to it is that it's a rather large library and is best used with an op code cache like APC. You would use this in any place where untrusted content is being outputted to the screen. It is much more thorough that htmlentities, htmlspecialchars, filter_input, filter_var, strip_tags, etc.


Use an existing user-input sanitization library to clean all user-input. Unless you put a lot of effort into it, implementing it yourself will never work as well.


I find the best way is using a class that allows you to bind your code so you never have to worry about manually escaping your data.


It is difficult to implement a thorough sql injection/xss injection prevention on a site that doesn't cause false alarms. In a CMS the end user might want to use <script> or <object> that links to items from another site.

I recommend having all users install FireFox with NoScript ;-)

참고URL : https://stackoverflow.com/questions/71328/what-are-the-best-practices-for-avoiding-xss-attacks-in-a-php-site

반응형