一千萬個為什麽

搜索

JSP/Servlet Web應用程序中的XSS預防

如何在JSP/Servlet Web應用程序中防止XSS攻擊?

最佳答案

XSS can be prevented in JSP by using JSTL tag or fn:escapeXml() EL function when (re)displaying user-controlled input. This includes request parameters, headers, cookies, URL, body, etc. Anything which you extract from the request object. Also the user-controlled input from previous requests which is stored in a database needs to be escaped during redisplaying.

例如:





<input name="foo" value="${fn:escapeXml(param.foo)}">

This will escape characters which may malform the rendered HTML such as <, >, ", ' and & into HTML/XML entities such as <, >, ", ' and &.

Note that you don't need to escape them in the Java (Servlet) code, since they are harmless over there. Some may opt to escape them during request processing (as you do in Servlet or Filter) instead of response processing (as you do in JSP), but this way you may risk that the data unnecessarily get double-escaped (e.g. & becomes &amp; instead of & and ultimately the enduser would see & being presented), or that the DB-stored data becomes unportable (e.g. when exporting data to JSON, CSV, XLS, PDF, etc which doesn't require HTML-escaping at all). You'll also lose social control because you don't know anymore what the user has actually filled in. You'd as being a site admin really like to know which users/IPs are trying to perform XSS, so that you can easily track them and take actions accordingly. Escaping during request processing should only and only be used as latest resort when you really need to fix a train wreck of a badly developed legacy web application in the shortest time as possible. Still, you should ultimately rewrite your JSP files to become XSS-safe.

If you'd like to redisplay user-controlled input as HTML wherein you would like to allow only a specific subset of HTML tags like , , , etc, then you need to sanitize the input by a whitelist. You can use a HTML parser like Jsoup for this. But, much better is to introduce a human friendly markup language such as Markdown (also used here on Stack Overflow). Then you can use a Markdown parser like CommonMark for this. It has also builtin HTML sanitizing capabilities. See also I'm looking for a Java HTML encoder.

服務器端關於數據庫的唯一問題是 SQL註入預防。您需要確保在SQL或JPQL查詢中永遠不會直接串聯用戶控制的輸入,並且您一直在使用參數化查詢。在JDBC術語中,這意味著您應該使用 PreparedStatement 而不是 Statement 。在JPA術語中,使用 <�代碼>查詢</代碼>


另一種方法是從JSP/Servlet遷移到Java EE的MVC框架 JSF 。它已在所有地方內置了XSS(和CSRF!)預防。另請參閱 JSF中的CSRF,XSS和SQL註入攻擊預防</一>。

轉載註明原文: JSP/Servlet Web應用程序中的XSS預防