我不确定如何在我的Java项目中执行HTML转义以防止跨站脚本攻击。

huangapple go评论144阅读模式
英文:

I am not sure how to perform html escaping in my java project to prevent XSS

问题

以下是您提供的代码的中文翻译:

只是一个提示这是为了课堂我本应该查看课堂材料但那里没有解决这个问题学校有点差劲)。当我问老师时他说要谷歌搜索我尝试过谷歌搜索但可惜我的理解力还不够好

我的设置如下这是一个使用DerbyDBGlassfish 5Java和JavaScript Servlet的Web应用程序

我知道这个问题在这里已经回答了100000次但我就是理解不了...
我有一个Java Web应用程序没有使用Maven)。登录使用login.jsp并通过authenticate.java进行身份验证
当然这没有进行转义所以容易受到跨站脚本攻击XSS)。
我只是不确定如何实现这一点如果有人能指导我一下如果有一个库或什么东西可以加载如果有的话如何使用它

login.jsp

<%--
    文档login
    创建时间2015年8月10日 下午7:53:14
    作者吉姆
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>SDEV425 登录</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div id="main">
        <%@include file="WEB-INF/jspf/menus.jspf" %>
        <p></p>
        <p></p>
        <h2>登录</h2>

        <% if (session.getAttribute("UMUCUserEmail") == null) {
        %>

        <form action="Authenticate" method="post">
            <table class="center">
                <tr>
                    <td>Email: </td><td><input type="text"  name="emailAddress"  size="50" autofocus> </td>
                </tr>
                <tr>
                    <td>
                        密码 </td><td><input type="password" name="pfield" size="50" autocomplete="off"></td>
                </tr>
                <tr>
                    <td>
                        &amp;nbsp;
                    </td>
                    <td>
                        <input type="submit" name="SignIn" value="登录">
                    </td>
                </tr>
            </table>
            <p></p>
            <!-- 如果有错误消息则打印错误消息 -->
            <% String e = (String) request.getAttribute("ErrorMessage");
                if (e != null) {
                    out.print(e);
                }
            %>

        </form>
        <%
            } else {

                request.setAttribute("ErrorMessage", "您已经登录。");
                RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
                dispatcher.forward(request, response);                    
            }
        %>
    </div>
</body>
</html>

Authenticate.java

/*
 * 若要更改此许可标题,请在项目属性中选择许可标题。
 * 若要更改此模板文件,请选择工具 | 模板
 * 并打开模板在编辑器中进行编辑。
 */
package SDEV425_HW4;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.derby.jdbc.ClientDataSource;

/**
 *
 * 作者:吉姆
 */
public class Authenticate extends HttpServlet {

    // 变量    
    private String username;
    private String pword;
    private Boolean isValid;
    private int user_id;
    private HttpSession session;

    /**
     * 处理HTTP GET 和 POST 方法的请求。
     *
     * @param request servlet 请求
     * @param response servlet 响应
     * @throws ServletException 如果发生 Servlet 特定错误
     * @throws IOException 如果发生 I/O 错误
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* 输出页面内容。您可以使用以下示例代码。 */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Authenticate</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>在 " + request.getContextPath() + " 的 Servlet Authenticate</h1>");

            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. 点击左侧的 + 号以编辑代码。">
    /**
     * 处理 HTTP GET 方法。
     *
     * @param request servlet 请求
     * @param response servlet 响应
     * @throws ServletException 如果发生 Servlet 特定错误
     * @throws IOException 如果发生 I/O 错误
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * 处理 HTTP POST 方法。
     *
     * @param request servlet 请求
     * @param response servlet 响应
     * @throws ServletException 如果发生 Servlet 特定错误
     * @throws IOException 如果发生 I/O 错误
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 获取POST 输入 
        this.username = request.getParameter("emailAddress");
        this.pword = request.getParameter("pfield");
        this.isValid = validate(this.username, this.pword);
        response.setContentType("text/html;charset=UTF-8");
        // 设置会话变量
        if (isValid) {
            // 如果尚未创建会话对象,请创建一个会话对象。
            session = request.getSession(true);
            session.setAttribute("UMUCUserEmail", username);         
            session.setAttribute("UMUCUserID", user_id);

            // 发送到欢迎 JSP 页面              

            RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
            dispatcher.forward(request, response);

        } else {
            // 不是有效的登录
            // 将他们引导回登录界面

            request.setAttribute("ErrorMessage", "无效的用户名或密码。请重试或联系吉姆。");
            RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
            dispatcher.forward(request, response);
        }
    }

    /**
     * 返回 servlet 的简短描述。


<details>
<summary>英文:</summary>

Just a note, this is for class. I would go to the class material, but it doesn&#39;t address this(the school is kinda garbage). And when i ask the teacher, he says to google it. I&#39;ve tried googling it, but my understanding is not good enough yet sadly.

My setup is as follows. Its a web application that uses DerbyDB, Glassfish 5, Java and javascript servlets.

I know this is answered 100000 times on here, but being as dense as i am... i am not getting it.
i have a java web application (without maven). The login uses login.jsp and authenticates through authenticate.java
of course there is no escaping so its vulnerable to xss.
I am just not sure how to implement this. If someone could guide me there. If there is a library or something to load and if so how to use it.

login.jsp

    &lt;%-- 
        Document   : login
        Created on : Aug 10, 2015, 7:53:14 PM
        Author     : jim
    --%&gt;
    
    &lt;%@page contentType=&quot;text/html&quot; pageEncoding=&quot;UTF-8&quot;%&gt;
    &lt;!DOCTYPE html&gt;
    &lt;html&gt;
        &lt;head&gt;
            &lt;title&gt;SDEV425 Login&lt;/title&gt;
            &lt;meta charset=&quot;UTF-8&quot;&gt;
            &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
            &lt;link href=&quot;styles.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;
        &lt;/head&gt;
        &lt;body&gt;
            &lt;div id=&quot;main&quot;&gt;
                &lt;%@include file=&quot;WEB-INF/jspf/menus.jspf&quot; %&gt;
                &lt;p&gt;&lt;/p&gt;
                &lt;p&gt;&lt;/p&gt;
                &lt;h2&gt;Login&lt;/h2&gt;
    
                &lt;% if (session.getAttribute(&quot;UMUCUserEmail&quot;) == null) {
                %&gt;
    
    
    
                &lt;form action=&quot;Authenticate&quot; method=&quot;post&quot;&gt;
                    &lt;table class=&quot;center&quot;&gt;
                        &lt;tr&gt;
                        &lt;td&gt;Email: &lt;/td&gt;&lt;td&gt;&lt;input type=&quot;text&quot;  name=&quot;emailAddress&quot;  size=&quot;50&quot; autofocus&gt; &lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;
                                Password: &lt;/td&gt;&lt;td&gt;&lt;input type=&quot;password&quot; name=&quot;pfield&quot; size=&quot;50&quot; autocomplete=&quot;off&quot;&gt;&lt;/td&gt;
                        &lt;/tr&gt;
                        &lt;tr&gt;
                            &lt;td&gt;
                                &amp;nbsp;
                            &lt;/td&gt;
                            &lt;td&gt;
                                &lt;input type=&quot;submit&quot; name=&quot;SignIn&quot; value=&quot;Sign In&quot;&gt;
                            &lt;/td&gt;
                        &lt;/tr&gt;
                    &lt;/table&gt;
                    &lt;p&gt;&lt;/p&gt;
                    &lt;!-- Print Error Message if any --&gt;
                    &lt;% String e = (String) request.getAttribute(&quot;ErrorMessage&quot;);
                        if (e != null) {
                            out.print(e);
                        }
                    %&gt;
    
                &lt;/form&gt;
                &lt;%
                    } else {
    
                        request.setAttribute(&quot;ErrorMessage&quot;, &quot;You are already logged in.&quot;);
                        RequestDispatcher dispatcher = request.getRequestDispatcher(&quot;welcome.jsp&quot;);
                        dispatcher.forward(request, response);                    
                    }
                %&gt;
            &lt;/div&gt;
        &lt;/body&gt;
    &lt;/html&gt;

Authenticate.java

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package SDEV425_HW4;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.PreparedStatement;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import org.apache.derby.jdbc.ClientDataSource;
    
    
    
    /**
     *
     * @author jim
     */
    public class Authenticate extends HttpServlet {
    
        // variables    
        private String username;
        private String pword;
        private Boolean isValid;
        private int user_id;
        private HttpSession session;
    
        
        /**
         * Processes requests for both HTTP &lt;code&gt;GET&lt;/code&gt; and &lt;code&gt;POST&lt;/code&gt;
         * methods.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType(&quot;text/html;charset=UTF-8&quot;);
            try (PrintWriter out = response.getWriter()) {
                /* TODO output your page here. You may use following sample code. */
                out.println(&quot;&lt;!DOCTYPE html&gt;&quot;);
                out.println(&quot;&lt;html&gt;&quot;);
                out.println(&quot;&lt;head&gt;&quot;);
                out.println(&quot;&lt;title&gt;Servlet Authenticate&lt;/title&gt;&quot;);
                out.println(&quot;&lt;/head&gt;&quot;);
                out.println(&quot;&lt;body&gt;&quot;);
                out.println(&quot;&lt;h1&gt;Servlet Authenticate at &quot; + request.getContextPath() + &quot;&lt;/h1&gt;&quot;);
                
                out.println(&quot;&lt;/body&gt;&quot;);
                out.println(&quot;&lt;/html&gt;&quot;);
            }
        }
    
        // &lt;editor-fold defaultstate=&quot;collapsed&quot; desc=&quot;HttpServlet methods. Click on the + sign on the left to edit the code.&quot;&gt;
        /**
         * Handles the HTTP &lt;code&gt;GET&lt;/code&gt; method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }
    
        /**
         * Handles the HTTP &lt;code&gt;POST&lt;/code&gt; method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            // Get the post input 
            this.username = request.getParameter(&quot;emailAddress&quot;);
            this.pword = request.getParameter(&quot;pfield&quot;);
            this.isValid = validate(this.username, this.pword);
             response.setContentType(&quot;text/html;charset=UTF-8&quot;);
            // Set the session variable
            if (isValid) {
                // Create a session object if it is already not  created.
                session = request.getSession(true);
                session.setAttribute(&quot;UMUCUserEmail&quot;, username);         
                session.setAttribute(&quot;UMUCUserID&quot;, user_id);
    
                // Send to the Welcome JSP page              
                
                RequestDispatcher dispatcher = request.getRequestDispatcher(&quot;welcome.jsp&quot;);
                dispatcher.forward(request, response);
    
            } else {
                // Not a valid login
                // refer them back to the Login screen
    
                request.setAttribute(&quot;ErrorMessage&quot;, &quot;Invalid Username or Password. Try again or contact Jim.&quot;);
                RequestDispatcher dispatcher = request.getRequestDispatcher(&quot;login.jsp&quot;);
                dispatcher.forward(request, response);
            }
        }
    
        /**
         * Returns a short description of the servlet.
         *
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return &quot;Short description&quot;;
        }// &lt;/editor-fold&gt;
    
        // Method to Authenticate
        public boolean validate(String name, String pass) {
            boolean status = false;
            int hitcnt=0;
    
            try {
                ClientDataSource ds = new ClientDataSource();
                ds.setDatabaseName(&quot;SDEV425&quot;);
                ds.setServerName(&quot;localhost&quot;);
                ds.setPortNumber(1527);
                ds.setUser(&quot;sdev425&quot;);
                ds.setPassword(&quot;sdev425&quot;);
                ds.setDataSourceName(&quot;jdbc:derby&quot;);
    
                Connection conn = ds.getConnection();
    
               
                
                String sql = &quot;select user_id from sdev_users  where EMAIL = ?&quot;;
                PreparedStatement stmt = conn.prepareStatement(sql);
                stmt.setString(1, this.username); 
                
                
                ResultSet rs = stmt.executeQuery();
                
                while (rs.next()) {
                    user_id = rs.getInt(1);
                }
                if (user_id&gt; 0) {                
                    
                    String sql2 = &quot;select user_id from user_info where user_id = &quot; + user_id + &quot;and password = ?&quot;;
    
                    
                    PreparedStatement stmt2 = conn.prepareStatement(sql2);
                    stmt2.setString(1, this.pword);
                    
                    ResultSet rs2 = stmt2.executeQuery();
                    
                    while (rs2.next()) {
                        hitcnt++;
                    }   
                    // Set to true if userid/password match
                   if(hitcnt&gt;0){
                       status=true;
                   }
                }
    
            } catch (Exception e) {
                System.out.println(e);
            }
            return status;
        }
    
    }



</details>


# 答案1
**得分**: 2

可以使用StringEscapeUtils.escapeHtml4()方法

```java
import org.apache.commons.text.StringEscapeUtils;

public class HTMLEscapeExample 
{
    public static void main(String[] args) 
    {
        String unEscapedString = "&quot;&lt;html&gt;some-random-text&lt;/html&gt;&quot;";
         
        String escapedHTML = StringEscapeUtils.escapeHtml4(unEscapedString);
         
        System.out.println(escapedHTML);    //浏览器现在可以解析并打印
    }
}

//输出:

&amp;lt;html&amp;gt;some-random-text&amp;lt;/html&amp;gt;
英文:

You can use StringEscapeUtils.escapeHtml4() method.

import org.apache.commons.text.StringEscapeUtils;
public class HTMLEscapeExample 
{
public static void main(String[] args) 
{
String unEscapedString = &quot;&lt;html&gt;some-random-text&lt;/html&gt;&quot;;
String escapedHTML = StringEscapeUtils.escapeHtml4(unEscapedString);
System.out.println(escapedHTML);    //Browser can now parse this and print
}
}
//Output:
&amp;lt;html&amp;gt;some-random-text&amp;lt;/html&amp;gt;

huangapple
  • 本文由 发表于 2020年8月12日 04:58:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63366287.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定