我面臨一個 SonarQube 錯誤,無法弄清楚是什么問題。SonnarQube 的問題是,更改此代碼以不從用戶控制的資料構造 URL。
@Value("${...}")
String apiKey;
@Value("${...}")
String apiUrl;
public Response apiResponse(String location) {
HttpHeaders headers = new HttpHeaders();
headers.add("x-apikey", apiKey);
HttpEntity<Object> entity = new HttpEntity<>(headers);
String url = apiUrl location; // SonarQube issue: tainted value is propagated
Response response = null;
try {
ResponseEntity<Response> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Response.class); // SonarQube issue: Tainted value is used to perform a security- sensitive operation.
response = responseEntity.getBody();
} catch(Exception){
// doesn't throw anything
}
return response;
}
@Cacheable(...)
Response cacheResponse(String location, String tokenKey) {
return apiResponse(location); // SonarQube issue: tainted value is propagated
}
這解決了問題,但為什么會這樣?以及如何在上面的代碼中應用它?
String url = apiUrl location; // SonarQube issue: tainted
相反,我只是嘗試硬編碼 location 的值并解決了問題。
String url = apiUrl "location";
太奇怪了...
uj5u.com熱心網友回復:
我為 Location 變數添加了驗證,這解決了問題
if(!location.matches(...)) {
throw error.....
}
String url = apiUrl location;
uj5u.com熱心網友回復:
SonarQube 試圖告訴您的是,您將邏輯暴露給客戶端的輸入。更好的解決方案是重構您的代碼,使其不依賴于來自客戶端的特定標頭來執行某些操作。很難在沒有看到更多代碼庫的情況下建議示例代碼。
uj5u.com熱心網友回復:
您正在使用來自客戶端/用戶的輸入(即在變數位置)來構建 URL。因此,如果客戶端/用戶向 location 提供惡意值,他可能會形成無效的 URL。
在第二個示例中,String url = apiUrl "location";您沒有使用用戶輸入,因為“位置”是一個硬編碼的字串。
我不知道你試圖用代碼實作什么。但也許最好保存一個可能的 URL 串列以及映射到 URL 的用戶提供和列舉值。
uj5u.com熱心網友回復:
String url = "https://someurl/%s";
url = String.format(url,location);
sendRequest(url);
也許這種方法不會出錯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/346363.html
下一篇:Java程式結構
