Common vulnerabilities and practices for safe programming in web application development (P1)
- Tram Ho
1. Control database queries to avoid SQL Injection vulnerabilities
– Risk: When querying the database, programmers often use the input string from users, these queries may be affected by SQL Injection or HQL Injection (if using Hibernate). By taking advantage of these errors, an attacker can view, edit, delete data in the database, thereby gaining admin accounts, stealing user information, etc.
– Prevention:
- SQL queries must use PrepareStatement, all parameters must be added with the function (setParam …), not using string addition in the query.
- For some cases using ORDER BY, unable to use the setParam function, it is possible to define an array containing all the columns (fields) that need to be ORDER BY called a whitelist. Whenever ORDER BY is needed, double check that the column (field) belongs to the whitelist array defined. Example 1: The login login code with the username / password entered by the user:
1 2 3 4 5 6 7 8 | String sql = "select * from users where user_name = "' + userName + '" and password = "' + encrypt(password) + '"; Statement statement = connection.createStatement(); ResultSet rs = statement.excuteQuery(sql); if (!rs.next()) { bResult = false; } else { bResult = true; } |
- With the above code, when entering the username is test ‘or’ 1 ‘=’ 1, the query will be: select from users where username = ‘test’ or ‘1’ = ‘1 ′ and password =’ … ‘ . The where clause will be equivalent to user_name = ‘test’. Thus, even without a password, you can still log into the system.
- Fix the code above as follows, with the userName and password parameterized when entering the query will avoid SQL Injection errors:
1 2 3 4 5 6 7 8 9 10 | String sql = "select * from users where user_name = ? and password = ?"; PreparedStatement statement = connection.preparedStatement(sql); statement.setString(0, userName); statement.setString(1, encrypt(password)); ResultSet rs = statement.excuteQuery(sql); if (!rs.next()) { bResult = false; } else { bResult = true; } |
Example 2: Some cases cannot prevent SQL Injection errors through the “order by” command. Because the setParam function cannot be used, the following method can be used:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | // Mảng lưu danh sách các column (field) của BO cần order by (hay gọi là whitelist) private static List columnSort = new ArrayList(); public static String getColumnSort(String sortField) { // Thực hiện 1 lần và lấy ra toàn bộ mảng column cần order và add vào whitelist if (columnSort.size() == 0) { // Danh sách BO cho phép order by String[] arrTableName = {"ActionLog", "BanPosition", "Category", ...}; }; // Lấy ra toàn bộ các column (field) BO cần order by for (String tableName : arrTableName) { try { Class class = Class.forName("com.demo.DEMO.database.BO." + tableName); Field[] fieldArr = class.getDeclaredFields(); for (int i = 0; i< fieldArr.length; i++) { String fieldName = fieldArr[i].getName(); // add các column vào 1 mảng columnSort.add(fieldName); } } catch (ClassNotFoundException ex) { } } } // Cắt ký tự "-" ở đầu field sort String sort = sortField; if (sortField != null && sortField.startsWith("-")) { sortField = sortField.substring(1); } // Kiểm tra field cần order by có nằm trong danh sách field cho phép sort hay không if (sortField != null && columnSort.contains(sortField)) { return sort; } return null; |
Maybe you are interested
67 useful tools, libraries and resources to save time for web developers
From MVC to the Modern Web Framework
2. Processing input data to avoid XSS vulnerability
– Risk: The server results returned to users mainly in HTML. The returned content usually includes values that users enter into the system that may suffer XSS errors if they do not control the input data. XSS (Cross-Site Scripting) is a technique of attack by inserting into dynamic websites (JSP, ASP, PHP …) HTML tags or dangerous scripts that can be harmful to other users. In particular, the dangerous code inserted is mostly written in Cross-Site Scrip such as JavaScript, JScript, DHTML and also HTML tags.
– Prevention:
- Encode as HTML special characters sent by the client include: <,>, &, ‘, ”, / in cases
- Client data sent to the server.
- Data retrieved from the database when returned to the client. The nature of the encode is to replace the above characters with the corresponding strings in the table below:
1 2 3 4 5 6 7 8 | | STT | Ký tự | HTML | | --- | ----- | ------- | | 1 | " | " | | 2 | & | & | | 3 | ' | ' | | 4 | / | /t; | | 5 | < | < | | 6 | > | > | |
Example 1: The JSP page below shows the greeting with the username taken from the client
1 2 3 4 5 6 7 8 9 10 11 12 13 | <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>JSP Page</title> </head> <body> <% String user = request.getParameter("user"); request.setAttribute("user", user); %> <h1> Hello ${user}! </h1> </body> </html> |
- When you enter the browser address
http://localhost/example?user=abc
, the browser will display Hello abc! - When entering the browser address
http://localhost/example?user=abc<script>alert('XSS')</script>
, the JavaScript will execute the XSS notification JavaScript in the browser. - To overcome this error we can use the JSTL library to encode the HTML variable user
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>JSP Page</title> </head> <body> <% String user = request.getParameter("user"); request.setAttribute("user", user); %> <h1> Hello ${fn:escapeXml(user)}! </h1> </body> </html> |
I would like to pause the article here! In the following article, I will continue with “Using tokens to avoid CSRF vulnerabilities” and “Controlling file uploads to the system.”
Source : Người viết: maiphuoctung