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

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

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

问题

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

  1. 只是一个提示这是为了课堂我本应该查看课堂材料但那里没有解决这个问题学校有点差劲)。当我问老师时他说要谷歌搜索我尝试过谷歌搜索但可惜我的理解力还不够好
  2. 我的设置如下这是一个使用DerbyDBGlassfish 5JavaJavaScript ServletWeb应用程序
  3. 我知道这个问题在这里已经回答了100000但我就是理解不了...
  4. 我有一个Java Web应用程序没有使用Maven)。登录使用login.jsp并通过authenticate.java进行身份验证
  5. 当然这没有进行转义所以容易受到跨站脚本攻击XSS)。
  6. 我只是不确定如何实现这一点如果有人能指导我一下如果有一个库或什么东西可以加载如果有的话如何使用它
  7. login.jsp
  8. <%--
  9. 文档login
  10. 创建时间2015810 下午7:53:14
  11. 作者吉姆
  12. --%>
  13. <%@page contentType="text/html" pageEncoding="UTF-8"%>
  14. <!DOCTYPE html>
  15. <html>
  16. <head>
  17. <title>SDEV425 登录</title>
  18. <meta charset="UTF-8">
  19. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  20. <link href="styles.css" rel="stylesheet" type="text/css">
  21. </head>
  22. <body>
  23. <div id="main">
  24. <%@include file="WEB-INF/jspf/menus.jspf" %>
  25. <p></p>
  26. <p></p>
  27. <h2>登录</h2>
  28. <% if (session.getAttribute("UMUCUserEmail") == null) {
  29. %>
  30. <form action="Authenticate" method="post">
  31. <table class="center">
  32. <tr>
  33. <td>Email: </td><td><input type="text" name="emailAddress" size="50" autofocus> </td>
  34. </tr>
  35. <tr>
  36. <td>
  37. 密码 </td><td><input type="password" name="pfield" size="50" autocomplete="off"></td>
  38. </tr>
  39. <tr>
  40. <td>
  41. &amp;nbsp;
  42. </td>
  43. <td>
  44. <input type="submit" name="SignIn" value="登录">
  45. </td>
  46. </tr>
  47. </table>
  48. <p></p>
  49. <!-- 如果有错误消息则打印错误消息 -->
  50. <% String e = (String) request.getAttribute("ErrorMessage");
  51. if (e != null) {
  52. out.print(e);
  53. }
  54. %>
  55. </form>
  56. <%
  57. } else {
  58. request.setAttribute("ErrorMessage", "您已经登录。");
  59. RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
  60. dispatcher.forward(request, response);
  61. }
  62. %>
  63. </div>
  64. </body>
  65. </html>
  66. Authenticate.java
  67. /*
  68. * 若要更改此许可标题,请在项目属性中选择许可标题。
  69. * 若要更改此模板文件,请选择工具 | 模板
  70. * 并打开模板在编辑器中进行编辑。
  71. */
  72. package SDEV425_HW4;
  73. import java.io.IOException;
  74. import java.io.PrintWriter;
  75. import java.sql.Connection;
  76. import java.sql.ResultSet;
  77. import java.sql.PreparedStatement;
  78. import javax.servlet.RequestDispatcher;
  79. import javax.servlet.ServletException;
  80. import javax.servlet.http.HttpServlet;
  81. import javax.servlet.http.HttpServletRequest;
  82. import javax.servlet.http.HttpServletResponse;
  83. import javax.servlet.http.HttpSession;
  84. import org.apache.derby.jdbc.ClientDataSource;
  85. /**
  86. *
  87. * 作者:吉姆
  88. */
  89. public class Authenticate extends HttpServlet {
  90. // 变量
  91. private String username;
  92. private String pword;
  93. private Boolean isValid;
  94. private int user_id;
  95. private HttpSession session;
  96. /**
  97. * 处理HTTP GET 和 POST 方法的请求。
  98. *
  99. * @param request servlet 请求
  100. * @param response servlet 响应
  101. * @throws ServletException 如果发生 Servlet 特定错误
  102. * @throws IOException 如果发生 I/O 错误
  103. */
  104. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  105. throws ServletException, IOException {
  106. response.setContentType("text/html;charset=UTF-8");
  107. try (PrintWriter out = response.getWriter()) {
  108. /* 输出页面内容。您可以使用以下示例代码。 */
  109. out.println("<!DOCTYPE html>");
  110. out.println("<html>");
  111. out.println("<head>");
  112. out.println("<title>Servlet Authenticate</title>");
  113. out.println("</head>");
  114. out.println("<body>");
  115. out.println("<h1>在 " + request.getContextPath() + " 的 Servlet Authenticate</h1>");
  116. out.println("</body>");
  117. out.println("</html>");
  118. }
  119. }
  120. // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. 点击左侧的 + 号以编辑代码。">
  121. /**
  122. * 处理 HTTP GET 方法。
  123. *
  124. * @param request servlet 请求
  125. * @param response servlet 响应
  126. * @throws ServletException 如果发生 Servlet 特定错误
  127. * @throws IOException 如果发生 I/O 错误
  128. */
  129. @Override
  130. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  131. throws ServletException, IOException {
  132. processRequest(request, response);
  133. }
  134. /**
  135. * 处理 HTTP POST 方法。
  136. *
  137. * @param request servlet 请求
  138. * @param response servlet 响应
  139. * @throws ServletException 如果发生 Servlet 特定错误
  140. * @throws IOException 如果发生 I/O 错误
  141. */
  142. @Override
  143. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  144. throws ServletException, IOException {
  145. // 获取POST 输入
  146. this.username = request.getParameter("emailAddress");
  147. this.pword = request.getParameter("pfield");
  148. this.isValid = validate(this.username, this.pword);
  149. response.setContentType("text/html;charset=UTF-8");
  150. // 设置会话变量
  151. if (isValid) {
  152. // 如果尚未创建会话对象,请创建一个会话对象。
  153. session = request.getSession(true);
  154. session.setAttribute("UMUCUserEmail", username);
  155. session.setAttribute("UMUCUserID", user_id);
  156. // 发送到欢迎 JSP 页面
  157. RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
  158. dispatcher.forward(request, response);
  159. } else {
  160. // 不是有效的登录
  161. // 将他们引导回登录界面
  162. request.setAttribute("ErrorMessage", "无效的用户名或密码。请重试或联系吉姆。");
  163. RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
  164. dispatcher.forward(request, response);
  165. }
  166. }
  167. /**
  168. * 返回 servlet 的简短描述。
  169. <details>
  170. <summary>英文:</summary>
  171. 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.
  172. My setup is as follows. Its a web application that uses DerbyDB, Glassfish 5, Java and javascript servlets.
  173. I know this is answered 100000 times on here, but being as dense as i am... i am not getting it.
  174. i have a java web application (without maven). The login uses login.jsp and authenticates through authenticate.java
  175. of course there is no escaping so its vulnerable to xss.
  176. 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.
  177. login.jsp
  178. &lt;%--
  179. Document : login
  180. Created on : Aug 10, 2015, 7:53:14 PM
  181. Author : jim
  182. --%&gt;
  183. &lt;%@page contentType=&quot;text/html&quot; pageEncoding=&quot;UTF-8&quot;%&gt;
  184. &lt;!DOCTYPE html&gt;
  185. &lt;html&gt;
  186. &lt;head&gt;
  187. &lt;title&gt;SDEV425 Login&lt;/title&gt;
  188. &lt;meta charset=&quot;UTF-8&quot;&gt;
  189. &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
  190. &lt;link href=&quot;styles.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;
  191. &lt;/head&gt;
  192. &lt;body&gt;
  193. &lt;div id=&quot;main&quot;&gt;
  194. &lt;%@include file=&quot;WEB-INF/jspf/menus.jspf&quot; %&gt;
  195. &lt;p&gt;&lt;/p&gt;
  196. &lt;p&gt;&lt;/p&gt;
  197. &lt;h2&gt;Login&lt;/h2&gt;
  198. &lt;% if (session.getAttribute(&quot;UMUCUserEmail&quot;) == null) {
  199. %&gt;
  200. &lt;form action=&quot;Authenticate&quot; method=&quot;post&quot;&gt;
  201. &lt;table class=&quot;center&quot;&gt;
  202. &lt;tr&gt;
  203. &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;
  204. &lt;/tr&gt;
  205. &lt;tr&gt;
  206. &lt;td&gt;
  207. 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;
  208. &lt;/tr&gt;
  209. &lt;tr&gt;
  210. &lt;td&gt;
  211. &amp;nbsp;
  212. &lt;/td&gt;
  213. &lt;td&gt;
  214. &lt;input type=&quot;submit&quot; name=&quot;SignIn&quot; value=&quot;Sign In&quot;&gt;
  215. &lt;/td&gt;
  216. &lt;/tr&gt;
  217. &lt;/table&gt;
  218. &lt;p&gt;&lt;/p&gt;
  219. &lt;!-- Print Error Message if any --&gt;
  220. &lt;% String e = (String) request.getAttribute(&quot;ErrorMessage&quot;);
  221. if (e != null) {
  222. out.print(e);
  223. }
  224. %&gt;
  225. &lt;/form&gt;
  226. &lt;%
  227. } else {
  228. request.setAttribute(&quot;ErrorMessage&quot;, &quot;You are already logged in.&quot;);
  229. RequestDispatcher dispatcher = request.getRequestDispatcher(&quot;welcome.jsp&quot;);
  230. dispatcher.forward(request, response);
  231. }
  232. %&gt;
  233. &lt;/div&gt;
  234. &lt;/body&gt;
  235. &lt;/html&gt;
  236. Authenticate.java
  237. /*
  238. * To change this license header, choose License Headers in Project Properties.
  239. * To change this template file, choose Tools | Templates
  240. * and open the template in the editor.
  241. */
  242. package SDEV425_HW4;
  243. import java.io.IOException;
  244. import java.io.PrintWriter;
  245. import java.sql.Connection;
  246. import java.sql.ResultSet;
  247. import java.sql.PreparedStatement;
  248. import javax.servlet.RequestDispatcher;
  249. import javax.servlet.ServletException;
  250. import javax.servlet.http.HttpServlet;
  251. import javax.servlet.http.HttpServletRequest;
  252. import javax.servlet.http.HttpServletResponse;
  253. import javax.servlet.http.HttpSession;
  254. import org.apache.derby.jdbc.ClientDataSource;
  255. /**
  256. *
  257. * @author jim
  258. */
  259. public class Authenticate extends HttpServlet {
  260. // variables
  261. private String username;
  262. private String pword;
  263. private Boolean isValid;
  264. private int user_id;
  265. private HttpSession session;
  266. /**
  267. * Processes requests for both HTTP &lt;code&gt;GET&lt;/code&gt; and &lt;code&gt;POST&lt;/code&gt;
  268. * methods.
  269. *
  270. * @param request servlet request
  271. * @param response servlet response
  272. * @throws ServletException if a servlet-specific error occurs
  273. * @throws IOException if an I/O error occurs
  274. */
  275. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  276. throws ServletException, IOException {
  277. response.setContentType(&quot;text/html;charset=UTF-8&quot;);
  278. try (PrintWriter out = response.getWriter()) {
  279. /* TODO output your page here. You may use following sample code. */
  280. out.println(&quot;&lt;!DOCTYPE html&gt;&quot;);
  281. out.println(&quot;&lt;html&gt;&quot;);
  282. out.println(&quot;&lt;head&gt;&quot;);
  283. out.println(&quot;&lt;title&gt;Servlet Authenticate&lt;/title&gt;&quot;);
  284. out.println(&quot;&lt;/head&gt;&quot;);
  285. out.println(&quot;&lt;body&gt;&quot;);
  286. out.println(&quot;&lt;h1&gt;Servlet Authenticate at &quot; + request.getContextPath() + &quot;&lt;/h1&gt;&quot;);
  287. out.println(&quot;&lt;/body&gt;&quot;);
  288. out.println(&quot;&lt;/html&gt;&quot;);
  289. }
  290. }
  291. // &lt;editor-fold defaultstate=&quot;collapsed&quot; desc=&quot;HttpServlet methods. Click on the + sign on the left to edit the code.&quot;&gt;
  292. /**
  293. * Handles the HTTP &lt;code&gt;GET&lt;/code&gt; method.
  294. *
  295. * @param request servlet request
  296. * @param response servlet response
  297. * @throws ServletException if a servlet-specific error occurs
  298. * @throws IOException if an I/O error occurs
  299. */
  300. @Override
  301. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  302. throws ServletException, IOException {
  303. processRequest(request, response);
  304. }
  305. /**
  306. * Handles the HTTP &lt;code&gt;POST&lt;/code&gt; method.
  307. *
  308. * @param request servlet request
  309. * @param response servlet response
  310. * @throws ServletException if a servlet-specific error occurs
  311. * @throws IOException if an I/O error occurs
  312. */
  313. @Override
  314. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  315. throws ServletException, IOException {
  316. // Get the post input
  317. this.username = request.getParameter(&quot;emailAddress&quot;);
  318. this.pword = request.getParameter(&quot;pfield&quot;);
  319. this.isValid = validate(this.username, this.pword);
  320. response.setContentType(&quot;text/html;charset=UTF-8&quot;);
  321. // Set the session variable
  322. if (isValid) {
  323. // Create a session object if it is already not created.
  324. session = request.getSession(true);
  325. session.setAttribute(&quot;UMUCUserEmail&quot;, username);
  326. session.setAttribute(&quot;UMUCUserID&quot;, user_id);
  327. // Send to the Welcome JSP page
  328. RequestDispatcher dispatcher = request.getRequestDispatcher(&quot;welcome.jsp&quot;);
  329. dispatcher.forward(request, response);
  330. } else {
  331. // Not a valid login
  332. // refer them back to the Login screen
  333. request.setAttribute(&quot;ErrorMessage&quot;, &quot;Invalid Username or Password. Try again or contact Jim.&quot;);
  334. RequestDispatcher dispatcher = request.getRequestDispatcher(&quot;login.jsp&quot;);
  335. dispatcher.forward(request, response);
  336. }
  337. }
  338. /**
  339. * Returns a short description of the servlet.
  340. *
  341. * @return a String containing servlet description
  342. */
  343. @Override
  344. public String getServletInfo() {
  345. return &quot;Short description&quot;;
  346. }// &lt;/editor-fold&gt;
  347. // Method to Authenticate
  348. public boolean validate(String name, String pass) {
  349. boolean status = false;
  350. int hitcnt=0;
  351. try {
  352. ClientDataSource ds = new ClientDataSource();
  353. ds.setDatabaseName(&quot;SDEV425&quot;);
  354. ds.setServerName(&quot;localhost&quot;);
  355. ds.setPortNumber(1527);
  356. ds.setUser(&quot;sdev425&quot;);
  357. ds.setPassword(&quot;sdev425&quot;);
  358. ds.setDataSourceName(&quot;jdbc:derby&quot;);
  359. Connection conn = ds.getConnection();
  360. String sql = &quot;select user_id from sdev_users where EMAIL = ?&quot;;
  361. PreparedStatement stmt = conn.prepareStatement(sql);
  362. stmt.setString(1, this.username);
  363. ResultSet rs = stmt.executeQuery();
  364. while (rs.next()) {
  365. user_id = rs.getInt(1);
  366. }
  367. if (user_id&gt; 0) {
  368. String sql2 = &quot;select user_id from user_info where user_id = &quot; + user_id + &quot;and password = ?&quot;;
  369. PreparedStatement stmt2 = conn.prepareStatement(sql2);
  370. stmt2.setString(1, this.pword);
  371. ResultSet rs2 = stmt2.executeQuery();
  372. while (rs2.next()) {
  373. hitcnt++;
  374. }
  375. // Set to true if userid/password match
  376. if(hitcnt&gt;0){
  377. status=true;
  378. }
  379. }
  380. } catch (Exception e) {
  381. System.out.println(e);
  382. }
  383. return status;
  384. }
  385. }
  386. </details>
  387. # 答案1
  388. **得分**: 2
  389. 可以使用StringEscapeUtils.escapeHtml4()方法
  390. ```java
  391. import org.apache.commons.text.StringEscapeUtils;
  392. public class HTMLEscapeExample
  393. {
  394. public static void main(String[] args)
  395. {
  396. String unEscapedString = "&quot;&lt;html&gt;some-random-text&lt;/html&gt;&quot;";
  397. String escapedHTML = StringEscapeUtils.escapeHtml4(unEscapedString);
  398. System.out.println(escapedHTML); //浏览器现在可以解析并打印
  399. }
  400. }

//输出:

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

You can use StringEscapeUtils.escapeHtml4() method.

  1. import org.apache.commons.text.StringEscapeUtils;
  2. public class HTMLEscapeExample
  3. {
  4. public static void main(String[] args)
  5. {
  6. String unEscapedString = &quot;&lt;html&gt;some-random-text&lt;/html&gt;&quot;;
  7. String escapedHTML = StringEscapeUtils.escapeHtml4(unEscapedString);
  8. System.out.println(escapedHTML); //Browser can now parse this and print
  9. }
  10. }
  11. //Output:
  12. &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:

确定