我有我的安全软件开发课程的代码。我们在这个任务中的目标是通过使用准备好的语句验证输入或从可能的攻击输入中解析整数来防止sql注入攻击。现在我对编程还比较陌生,我在学习java的同时还学习了这门课程(安全软件开发基础),我真的不能很有效地解决这个问题。然而,我已经想出了一个代码,从一个可能的攻击输入解析整数,并只使用作为参数的文件名在代码中,但我真的不知道如何和在哪里插入到原来的易受攻击的代码是安全的。以下是易受sql注入攻击的原始代码:
<%@page import="java.io.DataInputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.ResultSetMetaData"%>
<%@page import="java.sql.ResultSet"%>
<%@ page import="java.util.*,java.io.*"%>
<%@ page import="org.cysecurity.cspf.jvl.model.DBConnect"%>
<%@page import="java.io.File"%>
<%
String path = request.getContextPath();
try
{
String fileid=request.getParameter("fileid");
if(fileid!=null && !fileid.equals(""))
{
Connection con=new DBConnect().connect(getServletContext().getRealPath("/WEB-INF/config.properties"));
Statement stmt = con.createStatement();
ResultSet rs =null;
// the following code is vulnerable to injection attack:
rs=stmt.executeQuery("select * from FilesList where fileid="+fileid);
if(rs != null && rs.next())
{
int BUFSIZE = 4096;
String filePath=rs.getString("path");
File file = new File(getServletContext().getRealPath(path));
file = new File(file.getParent()+filePath);
int length = 0;
ServletOutputStream outStream = response.getOutputStream();
response.setContentType("text/html");
response.setContentLength((int)file.length());
String fileName = (new File(filePath)).getName();
response.setHeader("Content-Disposition", "attachment; filename=\"" +new Random().nextInt(10000)+ "\"");
byte[] byteBuffer = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(file));
while ((in != null) && ((length = in.read(byteBuffer)) != -1))
{
outStream.write(byteBuffer,0,length);
}
in.close();
outStream.close();
}
else
{
out.print("File Not Found");
}
}
else
{
out.print("File Parameter is missing");
}
}
catch(Exception e)
{
out.print("Oops, Something Went wrong");
}
%>
因此,我编写了这段代码,它只从可能的攻击中提取第一个整数,并将其用作fileid参数。它还建议是否可能正在进行攻击:
package parseInt;
import java.text.NumberFormat;
import java.text.ParsePosition;
public class testParseInt {
public static void main(String[] args) {
//String value = "1".trim();
//String value = "1%20and%20char_length(database())=1".trim();
String value = "a1%20and%20char_length(database())=1".trim();
NumberFormat formatter = NumberFormat.getNumberInstance();
ParsePosition pos = new ParsePosition(0);
Number parsed = formatter.parse(value, pos);
if ( pos.getIndex() != value.length() || pos.getErrorIndex() != -1) {
System.out.println("Parsed value=" + parsed + " but parameter value=" + value);
System.out.println("Possible SQL Injection attack in progress!!!");
}
else {
System.out.println("Parsed value=" + parsed);
System.out.println("This is a safe request");
}
if (parsed == null) {
}
}
}
如何以及在何处将我的代码(经过修改)插入到原始代码中,以便保护代码并防止sql注入攻击?
暂无答案!
目前还没有任何答案,快来回答吧!