申明:本文非笔者原创,原文转载自:https://github.com/SecurityPaper/SecurityPaper-web/blob/master/_posts/2.SDL%E8%A7%84%E8%8C%83%E6%96%87%E6%A1%A3/2018-08-17-SDL-3-java%E5%AE%89%E5%85%A8%E7%BC%96%E7%A0%81%E8%A7%84%E8%8C%83.md
1输入验证和数据合法性校验
程序接受数据可能来源于未经验证的用户,网络连接和其他不受信任的来源,如果未对程序接受数据进行校验,则可能会引发安全问题。
1.1避免SQL注入
使用PreparedStatement预编译SQL,解决SQL注入问题,传递给PreparedStatement对象的参数可以被强制进行类型转换,确保在插入或查询数据时与底层的数据库格式匹配。
String sqlString = "select * from db_user where username=? and password=?";
PreparedStatement stmt = connection.prepareStatement(sqlString);
stmt.setString(1, username);
stmt.setString(2, pwd);
ResultSet rs = stmt.executeQuery();
1.2避免XML注入
通过StringBulider 或 StringBuffer 拼接XML文件时,需对输入数据进行合法性校验。 对数量quantity 进行合法性校验,控制只能传入0-9的数字:
if (!Pattern.matches("[0-9]+", quantity)) {
// Format violation
}
String xmlString = "\nWidget\n" +
"500\n" +
"" + quantity + "";
outStream.write(xmlString.getBytes());
outStream.flush();
1.3避免跨站点脚本(XSS)
对产生跨站的参数进行严格过滤,禁止传入
//定义需过滤的字段串
String s = "\uFE64" + "script" + "\uFE65";
// 过滤字符串标准化
s = Normalizer.normalize(s, Form.NFKC);
// 使用正则表达式匹配inputStr是否存在
Pattern pattern = Pattern.compile(inputStr);
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
// Found black listed tag
throw new IllegalStateException();
} else {
// ...
}
2声明和初始化
2.1避免类初始化的相互依赖
例:
错误的写法:
public class Cycle {
private final int balance;
private static final Cycle c = new Cycle();
private static final int deposit = (int) (Math.random() * 100); // Random deposit
public Cycle() {
balance = deposit - 10; // Subtract processing fee
}
public static void main(String[] args) {
System.out.println("The account balance is: " + c.balance);
}
}
类加载时初始化指向Cycle类的静态变量c,而类Cycle的无参构造方法又依赖静态变量deposit,导致无法预期的结果。 正确的写法:
public class Cycle {
private final int balance;
private static final int deposit = (int) (Math.random() * 100); // Random deposit
private static final Cycle c = new Cycle(); // Inserted after initialization of required fields
public Cycle() {
balance = deposit - 10; // Subtract processing fee
}
public static void main(String[] args) {
System.out.println("The account balance is: " + c.balance);
}
}
3表达式
3.1不可忽略方法的返回值
忽略方法的放回值可能会导致无法预料的结果。
错误的写法:
public void deleteFile(){
File someFile = new File("someFileName.txt");
someFile.delete();
}
正确的写法:
public void deleteFile(){
File someFile = new File("someFileName.txt");
if (!someFile.delete()) {
// handle failure to delete the file
}
}
3.2不要引用空指针
当一个变量指向一个NULL值,使用这个变量的时候又没有检查,这时会导致。NullPointerException。
在使用变量前一定要做是否为NULL值的校验。
3.3使用Arrays.equals()来比较数组的内容
数组没有覆盖的Object. equals()方法,调用Object. equals()方法实际上是比较数组的引用,而不是他们的内容。程序必须使用两个参数Arrays.equals()方法来比较两个数组的内容
public void arrayEqualsExample() {
int[] arr1 = new i