This article represents top 4 security vulnerabilities related coding practice to avoid while you are programming withJava language. Recently, I came across few Java projects where these instances were found. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.
 
Following are the key points described later in this article:

  • Executing a dynamically generated SQL statement
  • Directly writing an Http Parameter to Servlet output
  • Creating an SQL PreparedStatement from dynamic string
  • Array is stored directly
Executing a Dynamically Generated SQL Statement

This is most common of all. One can find mention of this vulenrability at several places. As a matter of fact, many developers are also aware of this vulnerability, although this is a different thing they end up making mistakes once in a while. In several DAO classes, the instances such as following code were found which could lead to SQL injection attacks.

StringBuilder query = new StringBuilder();
query.append( "select * from user u where u.name in (" + namesString + ")" );
try {
Connection connection = getConnection();
Statement statement = connection.createStatement();
resultSet = statement.executeQuery(query.toString());
}

Instead of above query, one could as well make use of prepared statement such as that demonstrated in the code below. It not only makes code less vulnerable to SQL injection attacks but also makes it more efficient.

StringBuilder query = new StringBuilder();
query.append( "select * from user u where u.name in (?)" );
try {
Connection connection = getConnection();
PreparedStatement statement = connection.prepareCall(query.toString());
statement.setString( 1, namesString );
resultSet = statement.execute();
}
Directly writing an Http Parameter to Servlet Output

In Servlet classes, I found instances where the Http request parameter was written as it is, to the output stream, without any validation checks. Following code demonstrate the same:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String content = request.getParameter("some_param");
//
// .... some code goes here
//
response.getWriter().print(content);
}

Note that above code does not persist anything. Code like above may lead to what is called reflected (or non-persistent) cross site scripting (XSS) vulnerability. Reflected XSS occur when an attacker injects browser executable code within a single HTTP response. As it goes by definition (being non-persistent), the injected attack does not get stored within the application; it manifests only users who open a maliciously crafted link or third-party web page. The attack string is included as part of the crafted URI or HTTP parameters, improperly processed by the application, and returned to the victim. You could read greater details on following OWASP page on reflect XSS

Creating an SQL PreparedStatement from Dynamic Query String

What it essentially means is the fact that although PreparedStatement was used, but the query was generated as a string buffer and not in the way recommended for prepared statement (parametrized). If unchecked, tainted data from a user would create a String where SQL injection could make it behave in unexpected and undesirable manner. One should rather make the query statement parametrized and, use the PreparedStatement appropriately. Take a look at following code to identify the vulenarble code.

StringBuilder query = new StringBuilder();
query.append( "select * from user u where u.name in (" + namesString + ")" );
try {
Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement(query.toString());
resultSet = statement.executeQuery();
}
Array is Stored Directly

Instances of this vulnerability, Array is stored directly, could help the attacker change the objects stored in array outside of program, and the program behave in inconsistent manner as the reference to the array passed to method is held by the caller/invoker. The solution is to make a copy within the object when it gets passed. In this manner, a subsequent modification of the collection won’t affect the array stored within the object. You could read the details on followingstackoverflow page. Following code represents the vulnerability:

// Note that values is a String array in the code below.
//
public void setValues(String[] somevalues) {
this.values = somevalues;
}

reference from:http://vitalflux.com/java-4-security-vulnerabilities-related-coding-practices-avoid/

appendix:

There is a Sonar Violation:

Sonar Violation: Security - Array is stored directly

public void setMyArray(String[] myArray) {
this.myArray = myArray;
}

Solution:

public void setMyArray(String[] newMyArray) {
if(newMyArray == null) {
this.myArray = new String[0];
} else {
this.myArray = Arrays.copyOf(newMyArray, newMyArray.length);
}
}

It's complaining that the array you're storing is the same array that is held by the caller. That is, if the caller subsequently modifies this array, the array stored in the object (and hence the object itself) will change.

The solution is to make a copy within the object when it gets passed. This is called defensive copying. A subsequent modification of the collection won't affect the array stored within the object.

It's also good practice to normally do this when returning a collection (e.g. in a corresponding getMyArray() call). Otherwise the receiver could perform a modification and affect the stored instance.

Note that this obviously applies to all mutable collections (and in fact all mutable objects) - not just arrays. Note also that this has a performance impact which needs to be assessed alongside other concerns.

reference from:http://stackoverflow.com/questions/11580948/sonar-violation-security-array-is-stored-directly

Java – 4 Security Vulnerabilities Related Coding Practices to Avoid---reference的更多相关文章

  1. Java – Top 5 Exception Handling Coding Practices to Avoid

    This article represents top 5 coding practices related with Java exception handling that you may wan ...

  2. Java Tips and Best practices to avoid NullPointerException

    A NullPointerException in Java application is best way to solve it and that is also key to write rob ...

  3. Types of Security Vulnerabilities

    1)内存空间安全.2)参量级别数据安全:3)通信级别数据安全:4)数据访问控制:5)通信对象身份确认. https://developer.apple.com/library/content/docu ...

  4. Java Basic&Security Tools

    JDK Tools and Utilities Basic Tools These tools are the foundation of the JDK. They are the tools yo ...

  5. We found potential security vulnerabilities in your dependencies. Only the owner of this reposito...

    删除package-lock.json并同步到git 定义的依赖项./package-lock.json具有已知的安全漏洞 找到一个叫做.gitignore,把package-lock.json贴在这 ...

  6. How Will Java Technology Change My Life?

    How Will Java Technology Change My Life? We can't promise you fame, fortune, or even a job if you le ...

  7. BlackArch-Tools

    BlackArch-Tools 简介 安装在ArchLinux之上添加存储库从blackarch存储库安装工具替代安装方法BlackArch Linux Complete Tools List 简介 ...

  8. Find out when memory leaks are a concern and how to prevent them

    Handling memory leaks in Java programs Find out when memory leaks are a concern and how to prevent t ...

  9. malloc(50) 内存泄露 内存溢出 memory leak会最终会导致out of memory

    https://en.wikipedia.org/wiki/Memory_leak In computer science, a memory leak is a type of resource l ...

随机推荐

  1. IOS开发常用的linux命令

    pwd 在Linux层次结构中,用户可以在被授权的任意目录下利用mkdir命令创建新目录,也可以利用cd命令从一个目录转换到另一个目录.然而,没有提示符来告知用户目前处于哪一个目录中.想要知道当前所处 ...

  2. 苹果新政,禁止开发者在App中加入检查更新功能

    今天妥妥的被拒了,苹果更新了新政策,不能在应用中出现检测更新的功能.AppStore会自动提醒用户更新. 去掉更新按钮,之后再尝试下看能通过不能

  3. 想加入一行代码吗?使用<code>标签

    在介绍语言技术的网站中,避免不了在网页中显示一些计算机专业的编程代码,当代码为一行代码时,你就可以使用<code>标签了,如下面例子: <code>var i=i+300;&l ...

  4. c#求slope线性回归斜率

    public class mySlope { // public List<double> Values { get; set; } public double SlopeResult { ...

  5. 简单总结焦点事件、Event事件对象、冒泡事件

    每学习一些新的东西,要学会复习,总结和记录. 今天来简单总结一下学到的几个事件:焦点事件.Event事件对象.冒泡事件 其实这几个事件应该往深的说是挺难的,但今天主要是以一个小菜的角度去尝试理解一些基 ...

  6. C# Trim方法去除字符串两端的指定字符

    var str= ",2,3,4,6,7,"; var str2 = str.Trim(new char[] { ',' }); //去除字符串str两端的','字符. //则st ...

  7. gulpfile的结构

    使用了      yargs     用于获取启动参数,针对不同参数,切换任务执行过程时需要,本项目中的useCache和useSess      path     不明,貌似是用来将某个目录中的文件 ...

  8. php中的双引号和单引号的区别?

    1.单引号里面的字符串直接全部转义,原样输出(即:单引号内部的变量不会被执行) 2.双引号里面的变量会被替换(即:变量会执行) 例如:$name = 'hello';echo "the $n ...

  9. 2015 偶数求和 AC 杭电

    偶数求和 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submi ...

  10. UVa 673 Parentheses Balance(栈的使用)

     栈 Time Limit:3000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu   Description You are ...