1.拒绝服务
问题1:攻击者对程序发起大量请求,这种会被网络层排除掉
问题2:攻击者让程序过载的bug,这种bug回去指定请求使用系统资源的数量,或持续使用系统资源的时间
解决措施:使用IOUtils处理流的相关细节会避免代码被检查到
具体方式将流复制到一个缓冲区然后处理,当流的长度超过2GB时会返回-1,具体参考copyLager()方法
错误代码实例:
StringBuffer tokerbuffer = new StringBuffer();
BufferedReader reader = null;
try{
//获取输入流
//处理输入流
Reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String lines = null;
while((lines = reader.readLine()) != null){
tokerBuffer.append(lines);
}
}catch(Exception e){
//异常处理
}finally{
//关闭等操作
}
下面为网银系统解决此问题的实例代码:
//IOUtils类对此问题的实例代码之前事例中的IoUtils.toString方法就调用该方法赋值流到字符串
InputStream input = new FeilInputStream(new File("D:\test.txt"));
OutputStream output = new OutputStream(new File("D:\copy.txt","UTF-8"));
int inputOffset = 0;//复制前忽略的字节数
long length = 1024;//可指定每次赋值的字节数
IOUtils.copyLager(input,output,inputOffset,length);
StringBuffer resBodyBuf = new StringBuffer();
byte[] responserBody = new byte[1024];
int readCount = 0;
is = new BufferedInputStream(new FileInputStream(new File("D:\test.txt")));
while((readCount = is.read(responseBody,0,responseBody.length)) != -1){
resBodyBuf.append(new String(responseBody,0,readCount,ENCODING));
}
2.SQL注入
通过用户输入构造动态sql,攻击者修改指令执行任意sql
SQL injection 错误在以下情况下出现:
1.数据从一个不可信赖的数据源进去程序,这种情况下无法判断数据源的可信性‘
2.数据用于动态地构造一个sql查询
错误代码实例:
public void invoke(HttpServletRequest request,HttpServletResponse response){
Connection conn = null;
ResultSet rs = null;
InputStream inBin = null;
OutputStream outBin = null;
PreparedStatement ps = null;
try{
conn = LianaDBAccess.getConnection();
ps = conn.prepareStatement(daoTemplate);
...
}
}
正确实例代码:
private static final String daoTemplate = "INSERT INTO table VALUES(?,?)";
public void invoke(HttpServletRequest request,HttpServletResponse response){
Connection conn = null;
ResultSet rs = null;
InputStream inBin = null;
OutputStream outBin = null;
PreparedStatement ps = null;
String s1 = "123";
String s2 = "1234";
try{
conn = LianaDBAccess.getConnection();
//执行的sql语句以常量给出
ps = conn.prepareStatement(daoTemplate);
//指令参数作为变量赋值
ps = set(1,s1);
ps = ser(2.s2);
...
}
}
3.可移植性
File()会导致可移植性问题,因为它使用硬编码文件分隔符,不同的操作系统使用不同的分隔符
Microsoft Windows 系统使用 “”,UNIX 系统使用 “/”,应用程序如果需要在不同的平台上运行,使用硬编码文件分隔符会导致引用程序逻辑执行错误,并有可能导致程序拒绝服务。
错误代码实例:
UploadExecuter ue = new UploadExecuter(0,config,"C:\\pic\\Desert.jpg","lixue","tag","C1","1.0.0","1");
为编写可移植代码,不应使用硬编码文件分隔符,而使用语言库提供的独立于平台的API
正确实例代码:
UploadExecuter ue = new UploadExecuter(0,config,"C:" + File.separator + "pic" + File.separator + "Desert.jpg","lixue","tag","C1","1.0.0","1");
4.JSON注入
因为JSON是根据引号(“)、冒号(:)、逗号(,)、花括号({})区分字符串的意义的
JSON注入类似XML注入,攻击者向JSON中注入恶意字符,破坏JSON串的结构,使JSON解析失败
例如,如果输入的PassWord为 admin"888,则组装成的JSON数据为 “PassWord”:” admin"888"
推荐解决措施
/**
* 防止JSON注入
*/
static boolean checkJSONPCallbackName(String name){
try{
for(byte c : name.getBytes("US-ASCII")){
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c = '_') || (c >= '0' && c <= '9')){
continue;
}else{
return false;
}
}
return true;
}catch(Throwable t){
return false;
}
}