AdSense

網頁

2025/3/5

Java Spring Fortify Path Manipulation by injected properties

Fortify弱點掃描出現Path Manipulation(路徑操縱)問題的解決方式如下。


CICD執行Fortify弱點掃描時,出現Path Manipulation漏洞,是屬於高嚴重性(High priority order)。

因為即使是由Spring的application.properties注入成員變數的檔案路徑值仍是有可能被惡意竄改,例如下面範例:

application.properties

tmp.path=/tmp/demo/

DemoService

@Service
public class DemoService {

    @Value("${tmp.path}")
    private String tmpPath;

    public File createFile(String filename) {
        File file = new File(tmpPath, filename); // <-- Fortify Path Manipulation
        // ...
    } 

}

問題在於application.properties仍是屬於一種外部配置,且Java和Spring有多種讀取屬性值的方式和先後順序,這邊設定的屬性值是可成被後面其他方式設定同樣名稱的屬性值給覆寫(override)掉的。


解決

解決Path Manipulation方式如下:


寫死路徑

最簡單的方式,把檔案路徑寫死在程式中,不要由properties取得。

File file = new File("/tmp/demo/", filename)

不過可能無法適用properties的值是動態設定的情況,例如:

application.properties

tmp.path=/tmp/${app.name}/


消除危險字元

將注入的properties路徑值進行過濾,移除有危險的字元例如...和多餘的路徑分隔符\等,例如使用org.apache.commons.io.FilenameUtils.normalize

File file = new File(FilenameUtils.normalize(tmpPath), filename);


白名單

建立properties值與可允許存取資源路徑的對映表,即白名單,實際使用的檔案路徑是從對白名單中取得,而非直接使用properties路徑值。

Map<String, String> whiteMap = new HashMap<>();
whiteMap.put(tmpPath, "/tmp/demo");
// ...
File file = new File(whiteMap.get(tmpPath), filename);

但這作法和前面直接寫死好像沒什麼差別,不過這非本篇要關心的問題。


沒有留言:

AdSense