「Java/Tomcat/クロスサイトスクリプティング脆弱性を体験してみるサンプル」の編集履歴(バックアップ)一覧に戻る

Java/Tomcat/クロスサイトスクリプティング脆弱性を体験してみるサンプル - (2013/11/04 (月) 01:19:45) の編集履歴(バックアップ)


Tomcatでクロスサイトスクリプティングの脆弱性があるアプリを作成して、クロスサイトスクリプティングを体験、それからクロスサイトスクリプティング対策を実施するサンプルです。

まずは脆弱性のあるサンプル

xss.jsp
<%@ page language="java" contentType="text/html; charset=UTF8" pageEncoding="UTF-8" %>
<html>
 <head>
   <title>Xssサンプル</title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
 </head>
 <body>
 名前:<%= request.getAttribute("name") %><br>
 内容:<%= request.getAttribute("content")  %>
 <hr>
 <form action='<%=request.getContextPath()+"/xss"%>' method='GET'>
   お名前:<input type="text" name="name" value=''><br>
   内容:<textarea name="content"></textarea><br>
 </form>
 </body>
</html>

Xss.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Xss extends HttpServlet {
 @Override
 protected void doGet(HttpServletRequest req,
 HttpServletResponse resp) throws ServletException,
     IOException {
   // JSPに渡すパラメータ
   req.setAttribute("name", "");
   req.setAttribute("content", "");

   // クッキー設定
   resp.addCookie(new Cookie("userid", "hogehoge"));
   resp.addCookie(new Cookie("xss", "sample"));
   
   RequestDispatcher disp = req.getRequestDispatcher("/jsp/xss.jsp");
   disp.forward(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req,
 HttpServletResponse resp) throws ServletException,
     IOException {
   // パラメータを処理
   req.setCharacterEncoding("UTF-8");
   String name = req.getParameter("name");
   if (name == null) name = "";
   String content = req.getParameter("content");
   if (content == null) content = "";
   content = content.replaceAll("\n", "<br>");

   // JSPに渡す
   req.setAttribute("name", name);
   req.setAttribute("content", content);

   RequestDispatcher disp = req.getRequestDispatcher("/jsp/xss.jsp");
   disp.forward(req, resp);
 }
}