我对如何使用 Java 和 Derby sql 服务器使用 PreparedStatements 感到困惑
I am confused on how to use PreparedStatements using Java and Derby sql server
请注意,这是给 class 的。我会去 class material,但它没有解决这个问题(学校有点垃圾)。当我问老师时,他说要google。
我试过谷歌搜索,但遗憾的是我的理解还不够好。
我的设置如下。它是一个使用 DerbyDB、Glassfish 5、Java 和 javascript servlet 的 Web 应用程序。
我对使用 Prepared Statements 有点迷茫。
我的身份验证 java 代码有一个 sql 注入漏洞,我正在尝试解决它。每个人都说要使用 PreparedStatements,所以我正在尝试。
我的代码如下。这就是它的工作原理。它检查从 thesdev_users table 输入到 user_id 的用户名(电子邮件)。然后它获取 user_id 并在 user_info table 中检查它与存储在 user_id 下的密码以查看它是否匹配。
准备好的语句在底部,但我想你们都想看完整的东西,以防万一!
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 <code>GET</code> and <code>POST</code>
* 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("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
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>Servlet Authenticate at " + request.getContextPath() + "</h1>");
out.println("<h1>Results are " + username + "," + isValid +"," +user_id +"," +this.username + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> 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 <code>POST</code> 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("emailAddress");
this.pword = request.getParameter("pfield");
this.isValid = validate(this.username, this.pword);
response.setContentType("text/html;charset=UTF-8");
// Set the session variable
if (isValid) {
// Create a session object if it is already not created.
session = request.getSession(true);
session.setAttribute("UMUCUserEmail", username);
session.setAttribute("UMUCUserID", user_id);
// Send to the Welcome JSP page
RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request, response);
} else {
// Not a valid login
// refer them back to the Login screen
request.setAttribute("ErrorMessage", "Invalid Username or Password. Try again or contact Jim.");
RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
dispatcher.forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
// Method to Authenticate
public boolean validate(String name, String pass) {
boolean status = false;
int hitcnt=0;
try {
ClientDataSource ds = new ClientDataSource();
ds.setDatabaseName("SDEV425");
ds.setServerName("localhost");
ds.setPortNumber(1527);
ds.setUser("sdev425");
ds.setPassword("sdev425");
ds.setDataSourceName("jdbc:derby");
Connection conn = ds.getConnection();
String sql = "select user_id from sdev_users where email = '" + this.username + "'";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(user_id, 0);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
user_id = rs.getInt(1);
}
if (user_id > 0) {
String sql2 = "select user_id from user_info where user_id = " + user_id + "and password = '" + this.pword + "'";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
stmt2.setString(user_id, pword);
ResultSet rs2 = stmt2.executeQuery(sql2);
while (rs2.next()) {
hitcnt++;
}
// Set to true if userid/password match
if(hitcnt>0){
status=true;
}
}
} catch (Exception e) {
System.out.println(e);
}
return status;
}
}
任何用户输入都将被考虑 'tainted'。这可能是为了破解你的东西。
这意味着任何时候你只要 运行 用户输入代码,你就基本上把你的服务器交给了任何想要的人。
你在这段代码中搞砸了两次。
第一次出现在您的 HTML 回复中:
out.println("<h1>Results are " + username + "," + isValid +"," +user_id +"," +this.username + "</h1>");
out.println("</body>");
好的。我将创建一个新用户帐户,并将我的用户名设为:
rzwitserloot <script>/* haha do evil things here */
我找到你了。
你需要转义这些东西。获得一个 HTML 转义器并通过它抛出所有不安全的输入。
下一个是 SQL 语句。
String sql = "select user_id from sdev_users where email = '" + this.username + "'";
酷。我要创建我的用户名 whatever';-- DROP TABLE sdev_users;
并毁了你的一天。
这是使用准备语句转义字符串的方式:
String sql = "select user_id from sdev_users where email = ?";
// Note: The string you feed to prepareStatement must ALWAYS be a constant.
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, email); // this replaces the first (1) ?. Safely.
请注意,这是给 class 的。我会去 class material,但它没有解决这个问题(学校有点垃圾)。当我问老师时,他说要google。 我试过谷歌搜索,但遗憾的是我的理解还不够好。
我的设置如下。它是一个使用 DerbyDB、Glassfish 5、Java 和 javascript servlet 的 Web 应用程序。
我对使用 Prepared Statements 有点迷茫。 我的身份验证 java 代码有一个 sql 注入漏洞,我正在尝试解决它。每个人都说要使用 PreparedStatements,所以我正在尝试。 我的代码如下。这就是它的工作原理。它检查从 thesdev_users table 输入到 user_id 的用户名(电子邮件)。然后它获取 user_id 并在 user_info table 中检查它与存储在 user_id 下的密码以查看它是否匹配。
准备好的语句在底部,但我想你们都想看完整的东西,以防万一! 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 <code>GET</code> and <code>POST</code>
* 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("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
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>Servlet Authenticate at " + request.getContextPath() + "</h1>");
out.println("<h1>Results are " + username + "," + isValid +"," +user_id +"," +this.username + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> 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 <code>POST</code> 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("emailAddress");
this.pword = request.getParameter("pfield");
this.isValid = validate(this.username, this.pword);
response.setContentType("text/html;charset=UTF-8");
// Set the session variable
if (isValid) {
// Create a session object if it is already not created.
session = request.getSession(true);
session.setAttribute("UMUCUserEmail", username);
session.setAttribute("UMUCUserID", user_id);
// Send to the Welcome JSP page
RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request, response);
} else {
// Not a valid login
// refer them back to the Login screen
request.setAttribute("ErrorMessage", "Invalid Username or Password. Try again or contact Jim.");
RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
dispatcher.forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
// Method to Authenticate
public boolean validate(String name, String pass) {
boolean status = false;
int hitcnt=0;
try {
ClientDataSource ds = new ClientDataSource();
ds.setDatabaseName("SDEV425");
ds.setServerName("localhost");
ds.setPortNumber(1527);
ds.setUser("sdev425");
ds.setPassword("sdev425");
ds.setDataSourceName("jdbc:derby");
Connection conn = ds.getConnection();
String sql = "select user_id from sdev_users where email = '" + this.username + "'";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(user_id, 0);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
user_id = rs.getInt(1);
}
if (user_id > 0) {
String sql2 = "select user_id from user_info where user_id = " + user_id + "and password = '" + this.pword + "'";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
stmt2.setString(user_id, pword);
ResultSet rs2 = stmt2.executeQuery(sql2);
while (rs2.next()) {
hitcnt++;
}
// Set to true if userid/password match
if(hitcnt>0){
status=true;
}
}
} catch (Exception e) {
System.out.println(e);
}
return status;
}
}
任何用户输入都将被考虑 'tainted'。这可能是为了破解你的东西。
这意味着任何时候你只要 运行 用户输入代码,你就基本上把你的服务器交给了任何想要的人。
你在这段代码中搞砸了两次。
第一次出现在您的 HTML 回复中:
out.println("<h1>Results are " + username + "," + isValid +"," +user_id +"," +this.username + "</h1>");
out.println("</body>");
好的。我将创建一个新用户帐户,并将我的用户名设为:
rzwitserloot <script>/* haha do evil things here */
我找到你了。
你需要转义这些东西。获得一个 HTML 转义器并通过它抛出所有不安全的输入。
下一个是 SQL 语句。
String sql = "select user_id from sdev_users where email = '" + this.username + "'";
酷。我要创建我的用户名 whatever';-- DROP TABLE sdev_users;
并毁了你的一天。
这是使用准备语句转义字符串的方式:
String sql = "select user_id from sdev_users where email = ?";
// Note: The string you feed to prepareStatement must ALWAYS be a constant.
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, email); // this replaces the first (1) ?. Safely.