Code Vulnerability Scanning Common Vulnerabilities

Code Vulnerability Scanning Common Vulnerabilities

1. Log Injection (Log Forging Vulnerability)

  1. Vulnerability Description

    Writing unauthenticated user input to a log file can cause an attacker to forge log entries or inject malicious information into the log.

    A bug in log forgery occurs when:

    1. Data enters the application from an untrusted data source.

    2. Data is written to the application or system log file.

    Influence:

    1. Misleading interpretation of log files;

    2. If the log file is processed automatically, it may affect the log processing application.

      Log injection generally does not impair service functionality, but rather serves as a secondary attack tool

  2. Vulnerability Cases

    Example 1: Login module, logs all login results or failed users

    [2021-04-17 16:50:35][INFO][main] [Login:308] login success,userName=zhangsan
    [2021-04-17 16:50:35][WARN][main] [Login:308] username is wrong,userName=zhangsan
        
    // If the username parameter in the request is as follows:
    username=zhangsan
    [2021-04-17 16:50:35][INFO][main] [Login:308] login success,userName=zhangsan
    [2021-04-17 16:50:35][INFO][main] [Login:308] login success,userName=zhangsan
    [2021-04-17 16:50:35][INFO][main] [Login:308] login success,userName=zhangsan
    [2021-04-17 16:50:35][INFO][main] [Login:308] login success,userName=zhangsan
    
  3. Repair Suggestions

    Use an indirect method to prevent log forgery attacks: Create a set of legitimate log entries corresponding to different events that must be logged and only logged. To capture dynamic content, such as a user logoff system, it is important to use server-controlled values rather than user-provided data. This ensures that user-provided input is never used directly in log entries.

    A common way to filter sensitive characters that cause Log Forging vulnerabilities

        /**
    	 * Log Forging Vulnerability Check
    	 * @param logs
    	 * @return
    	 */
    	public static String vaildLog(String logs) {
    		List<String> list=new ArrayList<String>();
    		list.add("%0d");
    		list.add("%0a");
            list.add("%0A");
    		list.add("%0D");
    		list.add("\r");
    		list.add("\n");
    		String normalize = Normalizer.normalize(logs, Normalizer.Form.NFKC);
    		for (String str : list) {
    			normalize=normalize.replace(str, "");
    		}
    		return normalize;
    	}
    

2. Null pointer reference

  1. Vulnerability Description

    A function that indirectly references a null pointer will cause the program to crash.

    The dereference-after-store error occurs if the program explicitly sets the object to null but later references it indirectly. This error is usually caused by a programmer initializing a variable to null when declaring it. In this case, when the variable is indirectly referenced, it may be null, causing a null pointer exception. Most null pointer problems only cause general software reliability problems, but if an attacker can deliberately trigger null pointer indirect references, it is possible for an attacker to use the exception thrown to bypass security logic or cause the application to leak debugging information, which is useful for planning subsequent attacks.

  2. Vulnerability Cases
    // 01 Operate on generic objects
    String str = null;
    for (String item : list) {
        str = item;
    }
    // If the list is an empty array, str remains null after the loop ends. The program crashes at this time.
    return str.length(); 
    
    // 02 Operational Resources
    InputStream is = null;
    OutputStream os = null;
    try {
    	//...
    } catch (IOException e) {
    	//...
    }finally{	
    	os.close();
    	is.close(); //If os, is is null, program crashes
    }
    
  3. Repair Suggestions

    Be sure to check carefully before indirectly referencing objects that may have null values. If possible, include null checks in the wrapper around the code that handles the resource, ensuring that null checks are performed in all cases and minimizing errors.

    // 01 =>Recommendations 
    String str = "";//initialize value
    ----------------------------
    if(str != null){
        //Increase judgment when calling object methods
        str.length();
    }
    =============================
    
    // 02 =>Suggested Writing 1 Increase!= null's judgment, try catch catches exceptions
    InputStream is = null;
    OutputStream os = null;
    try {
    	//...
    } catch (IOException e) {
    	//...
    }finally{
    	try {
    		if(os!=null){
    			os.close();
    		}
    		if(is!=null){
    			is.close();
    		}
    	} catch (IOException e2) {
    		//...
    	}
    }
    
    // 02 =>Suggest a new exception handling mechanism in Write 2 java7  
    // Multiple line declarations can be written in parentheses of try(), and the variable type of each declaration must be a subclass of Closeable, separated by semicolons
    // try(Resource res = xxx), when a try block exits, the res.close() method is automatically called to close the resource
    try(
    	InputStream is = new FileInputStream("...");
    	OutputStream os = new FileOutputStream("...");
    ){
    	//...
    }catch (IOException e) {
    	//...
    }
    

3. Path tampering

  1. Vulnerability Description

    Allowing users to enter the path used to control file system operations will allow attackers to access or modify other protected system resources.

    Path tampering errors occur when the following two conditions are met:

    1. An attacker can specify the path used in a file system operation.

    2. An attacker can gain some privilege by specifying a specific resource, which is not normally possible.

      For example, in a program, an attacker can gain specific privileges to override a specified file or run the program in a configuration environment under its control

  2. Vulnerability Cases
    // The following code creates a file name using input from an HTTP request.
    // A file name like'. /.. /tomcat/conf/server.xml'causes the application to delete its own configuration file.
    
    String rName = request.getParameter("reportName");
    
    File rFile = new File("/usr/local/apfr/reports/" + rName);
    ...
    rFile.delete()
    
  3. Repair Suggestions

The best way to prevent path tampering is through indirect means, such as creating a list of legitimate resource names and specifying that users can only choose the file names. In this way, the user cannot specify the name of the resource directly by himself. In some cases, however, this approach is not feasible because such a list of legitimate resource names is too large to track. Thus, programmers often use blacklisting in this case. Before entering, blacklists selectively reject or avoid potentially dangerous characters. However, any such blacklist cannot be complete and will become obsolete over time. ** A better way is to create a whitelist that allows characters to appear in the resource name** and only accepts input consisting entirely of these recognized characters.

//Whitelist
private final static Map<String, String> pathCharWhiteList = new HashMap<String, String>();

    static {
        //White List of Path Characters
        String pathCharWhiteListResources = "abcdefghijklmnopqrstuvwxyz_123457890ABCDEFGHIJKLMNOPQRSTUVWXYZ./\\";

        for (int i = 0; i < pathCharWhiteListResources.length(); i++) {
            String c = String.valueOf(pathCharWhiteListResources.charAt(i));
            pathCharWhiteList.put(c, c);

        }
    }

//filter
public static String validFilePath2(String filePath) {
        String temp = "";
        for (int i = 0; i < filePath.length() - 1; i++) {

            Character curChar = null;
            Character nextChar = null;

            try {
                curChar = filePath.charAt(i);
                nextChar = filePath.charAt(i + 1);
            } catch (Exception e) {
            }
            if (pathCharWhiteList.get(filePath.charAt(i) + "") != null && curChar == '\\') {
                String sysFileSeparator = File.separator;
                if (null != sysFileSeparator && sysFileSeparator.equals(curChar + "")) {
                    temp += pathCharWhiteList.get(filePath.charAt(i) + "");
                }
            } else if (pathCharWhiteList.get(filePath.charAt(i) + "") != null && curChar != '.') {
                temp += pathCharWhiteList.get(filePath.charAt(i) + "");
            } else if (pathCharWhiteList.get(filePath.charAt(i) + "") != null && curChar == '.' && nextChar != '.') {
                temp += pathCharWhiteList.get(filePath.charAt(i) + "");
            }
        }

        filePath = temp;
        return filePath;
    }

4. Any file upload

1. Vulnerability Description

Malicious users or attackers can use this vulnerability to upload files or Trojan horse viruses that do not meet the requirements.

2. Vulnerability Recommendations

1. The service side uses the white list method to check file suffixes, and does not recommend the blacklist method to check suffixes. Blacklist method may cause attackers to bypass attacks by using file characteristics, system characteristics, incomplete blacklist, etc.

2. The server renames the uploaded files to prevent the use of directory jump to control the uploaded directory;

3. The server uses system functions to judge whether the file type and contents are legal or not; md5, keyword

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //Add Interceptor
        registry.addInterceptor(new FileTypeInterceptor())
                .addPathPatterns("/**");
    }
}

/**
 * Global File Type Interceptor
 */
public class FileTypeInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        boolean flag = true;
        // Determine whether it is a file upload request
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> files = multipartRequest.getFileMap();

            for (Map.Entry<String, MultipartFile> entry : files.entrySet()) {
                MultipartFile multipartFile = entry.getValue();
                String filename = multipartFile.getOriginalFilename();

                if (filename == null || checkFile(filename)) {
                    continue;
                }

                //Restrict file type
                request.setAttribute("errormessage", "Unsupported file type!");
                response.sendError(500, "Unsupported file type!");
                flag = false;
            }

        }
        return flag;
    }

    /**
     * Determines whether the upload file type is allowed, true means allowed
     */
    private boolean checkFile(String fileName) {
        //Set file type allowed to upload
        String suffixList = "xls,xlsx,docx,doc,pdf";
        // Get File Suffix
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffixList.contains(suffix.trim().toLowerCase());
    }
}

Tags: Java Spring server security Web Security

Posted on Sun, 05 Dec 2021 14:57:20 -0500 by AaZmaN