简体   繁体   中英

Fortify security finding — CWE 22 Path Manipulation

I have the below code to get the lastest modified file by given directory and the prefix of the filename. When I ran the HPE fortify analysis it gave me "Path manipulation" findings. Can you guys guide me how to fix this finding? What is the best and secure approach to access filesystem for a web application?

public static File getLatestFilefromDirWithFileName(String archivesDirectoryPath, String fileStartWith){    
    File archivesDirectory = new File(archivesDirectoryPath);

    FilenameFilter textFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            if (name.startsWith(fileStartWith)) {
                return true;
            } else {
                return false;
            }
        }
    };

    File[] filesInArchiveDir = archivesDirectory.listFiles(textFilter);
    if (filesInArchiveDir == null || filesInArchiveDir.length == 0) {
        return null;
    }

    File lastModifiedFile = filesInArchiveDir[0];
    for (int i = 1; i < filesInArchiveDir.length; i++) {
       if (lastModifiedFile.lastModified() < filesInArchiveDir[i].lastModified()) {
           lastModifiedFile = filesInArchiveDir[i];
       }
    }

    return lastModifiedFile;
}

You must ensure that archivesDirectoryPath do not allow to access sensible folders.

One way to do it, is to validate that the specified folder will be located in a white list of location. This white list could either be define in your code or configurable by "administrator" users. Trying to process a folder that is not on this list should raise Exception.

You can check that no /../ are used in folder name, but checking that the resulting folder is part of your white list should be enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM