差異處

這裏顯示兩個版本的差異處。

連向這個比對檢視

Both sides previous revision 前次修改
java:sonarlint:fixbug:s2275 [2020/08/02 23:43]
tony
java:sonarlint:fixbug:s2275 [2020/08/02 23:58]
tony
行 1: 行 1:
 {{tag>​SonarLint}} {{tag>​SonarLint}}
-====== SonarLint | XML parsers ​should not be vulnerable ​to XXE attacks ​(java:S2755) ======+====== SonarLint | Printf-style format strings ​should not lead to unexpected behavior at runtime ​(java:S2275) ======
 ===== Problem ===== ===== Problem =====
-這個問題是由於XML Parser有禁止引用外部資源而讓駭客以做XXE(XML eXternal Entity Injection)攻擊。這可能會導致伺服器訪問外部網站、造成RCE (Remote Code Execute)、SSRF(Server-Side Request Forgery,讓伺服器訪問外部無法存取的內部網站)、也可以竊取伺服器的敏感資訊。+這個問題是發生在print、formatter、log4j等API,當你該傳入參數是傳入時能會被SonarLint找出來以我的範例來說,是發生在logger.warn的誤用,這會導致輸出的內容將會是{}:​
 <code java> <code java>
-InputSource src = new InputSource(new StringReader(fileContent)); +}catch ​(Exception ex){ 
-DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + logger.warn("get system property error :​{}",​ex); 
-dbFactory.setNamespaceAware(true);​ + return ​aDefaultValue
-try { +}
- return ​dbFactory.newDocumentBuilder().parse(src)+
-catch (SAXException | IOException | ParserConfigurationException e) { +
- // skip +
-}     ​+
 </​code>​ </​code>​
 ===== How to fix? ===== ===== How to fix? =====
-這段程式碼除了被SonarLint找到問題以,也被SpotBugs發現一樣問題。在SpotBugs建議解法是啟用FEATURE_SECURE_PROCESSING但SonarLint認為這個方法並不完全,而去Disable了外部資源存取:+假如你只是要印例外的call stack把{}拿掉即可:
 <code java> <code java>
-InputSource src = new InputSource(new StringReader(fileContent));​ +logger.warn("get system property error",​ex); 
-DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); +</​code>​ 
-dbFactory.setNamespaceAware(true);​ +假如你是要印訊息,就直接getMessage:​ 
-try { +<code java> 
- dbFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,​ ""​);​ +logger.warn("get system property error :{}",ex.getMessage());
- dbFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ​""​); +
- dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSINGtrue); +
- return dbFactory.newDocumentBuilder().parse(src); +
-} catch (SAXException | IOException | ParserConfigurationException e) { +
- // skip +
-}     ​+
 </​code>​ </​code>​
-因此如果要解決SonarLint與SpotBugs上的問題,可以一起搭配服用;因為FEATURE_SECURE_PROCESSING還可以避免你消耗過多的記憶體資源。 
-===== Reference ===== 
-  * [[https://​rules.sonarsource.com/​java/​RSPEC-2755|sonarsource - RSPEC-2755]] 
-  * [[https://​stackoverflow.com/​questions/​40649152/​how-to-prevent-xxe-attack|How to prevent XXE attack?]] 
-  * [[https://​www.digicentre.com.tw/​industry_detail.php?​id=38|來自外部的威脅 - XXE漏洞攻擊成因]] 
-  * [[https://​find-sec-bugs.github.io/​bugs.htm#​XXE_DOCUMENT|SpotBugs - XML parsing vulnerable to XXE]] 
- 
 =====    ===== =====    =====
 ---- ----
 \\ \\
 ~~DISQUS~~ ~~DISQUS~~