Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions its/ruling/src/test/resources/expected/xml-S5734.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"project:asp.net-web-application/web.config": [
1
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import org.sonar.plugins.xml.checks.security.web.BasicAuthenticationCheck;
import org.sonar.plugins.xml.checks.security.web.CrossOriginResourceSharingCheck;
import org.sonar.plugins.xml.checks.security.web.HttpOnlyOnCookiesCheck;
import org.sonar.plugins.xml.checks.security.web.MimeNosniffCheck;
import org.sonar.plugins.xml.checks.security.web.ValidationFiltersCheck;
import org.sonar.plugins.xml.checks.spring.DefaultMessageListenerContainerCheck;
import org.sonar.plugins.xml.checks.spring.SingleConnectionFactoryCheck;
Expand Down Expand Up @@ -89,7 +90,8 @@ public static List<Class<?>> getCheckClasses() {
FixmeCommentCheck.class,
ValidationFiltersCheck.class,
DisallowedDependenciesCheck.class,
CommentedOutCodeCheck.class
CommentedOutCodeCheck.class,
MimeNosniffCheck.class
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,28 @@ protected void scanWebConfig(XmlFile file) {
private static boolean isWebXmlFile(XmlFile file) {
return "web.xml".equalsIgnoreCase(file.getInputFile().filename());
}

/**
* Builds an XPath expression that matches the deepest existing node.
*
* For example, for segments "a", "b", "c", the resulting expression is:
* <pre>
* /a/b/c | /a/b[not(c)] | /a[not(b)]
* </pre>
*/
protected String getDeepestExistingNode(String ... segments) {
StringBuilder expression = new StringBuilder();
for (int len = segments.length; len > 0; len--) {
for (int i = 0; i < len; i++) {
expression.append("/").append(segments[i]);
}
if (len < segments.length) {
expression.append("[not(").append(segments[len]).append(")]");
}
if (len > 1) {
expression.append("|");
}
}
return expression.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ public class HttpOnlyOnCookiesCheck extends BaseWebCheck {

/// Closest existing node if the global `<httpCookies>` is missing or misconfigured.
private final XPathExpression reportNodeExpression = XPathBuilder
.forExpression(
"/configuration/system.web/httpCookies | " +
"/configuration/system.web[not(httpCookies)] | " +
"/configuration[not(system.web)]")
.forExpression(getDeepestExistingNode("configuration", "system.web", "httpCookies"))
.build();

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* SonarQube XML Plugin
* Copyright (C) 2010-2025 SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.plugins.xml.checks.security.web;

import org.sonar.check.Rule;
import org.sonarsource.analyzer.commons.xml.XPathBuilder;
import org.sonarsource.analyzer.commons.xml.XmlFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.xpath.XPathExpression;
import java.util.Collections;

/**
* Ensure that the X-Content-Type-Options header is set to "nosniff" to prevent MIME type sniffing.
* The check applies to .NET web.config files.
*/
@Rule(key = "S5734")
public class MimeNosniffCheck extends BaseWebCheck {
private final XPathExpression httpCookiesExpression = XPathBuilder
.forExpression(
"/configuration"
+ "/system.webServer"
+ "/httpProtocol"
+ "/customHeaders"
+ "/add[@name=\"X-Content-Type-Options\" and @value=\"nosniff\"]")
.build();

/** Attach the issue to the closest existing node. */
private final XPathExpression reportNodeExpression = XPathBuilder
.forExpression(getDeepestExistingNode("configuration", "system.webServer", "httpProtocol", "customHeaders"))
.build();

@Override
protected void scanWebConfig(XmlFile file) {
Document document = file.getDocument();
NodeList expectedNodes = evaluate(httpCookiesExpression, document);

// null is returned on internal errors, and we don't want to raise a false positive in that case.
if (expectedNodes != null && expectedNodes.getLength() == 0) {
evaluateAsList(reportNodeExpression, document)
.stream()
.findFirst()
.ifPresent(target ->
reportIssue(
XmlFile.nameLocation((Element) target),
"Set the \"X-Content-Type-Options\" HTTP header to \"nosniff\" to mitigate MIME Confusion Attacks.",
Collections.emptyList()));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<p><a href="https://blog.mozilla.org/security/2016/08/26/mitigating-mime-confusion-attacks-in-firefox/">MIME confusion</a> attacks occur when an
attacker successfully tricks a web-browser to interpret a resource as a different type than the one expected. To correctly interpret a resource
(script, image, stylesheet …​) web browsers look for the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type">Content-Type
header</a> defined in the HTTP response received from the server, but often this header is not set or is set with an incorrect value. To avoid
content-type mismatch and to provide the best user experience, web browsers try to deduce the right content-type, generally by inspecting the content
of the resources (the first bytes). This "guess mechanism" is called <a href="https://en.wikipedia.org/wiki/Content_sniffing">MIME type
sniffing</a>.</p>
<p>Attackers can take advantage of this feature when a website ("example.com" here) allows to upload arbitrary files. In that case, an attacker can
upload a malicious image <em>fakeimage.png</em> (containing malicious JavaScript code or <a
href="https://docs.microsoft.com/fr-fr/archive/blogs/ieinternals/script-polyglots">a polyglot content</a> file) such as:</p>
<pre>
&lt;script&gt;alert(document.cookie)&lt;/script&gt;
</pre>
<p>When the victim will visit the website showing the uploaded image, the malicious script embedded into the image will be executed by web browsers
performing MIME type sniffing.</p>
<h2>Ask Yourself Whether</h2>
<ul>
<li> <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type">Content-Type</a> header is not systematically set for all
resources. </li>
<li> Content of resources can be controlled by users. </li>
</ul>
<p>There is a risk if you answered yes to any of those questions.</p>
<h2>Recommended Secure Coding Practices</h2>
<p>Implement <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options">X-Content-Type-Options</a> header with
<em>nosniff</em> value (the only existing value for this header) which is supported by all modern browsers and will prevent browsers from performing
MIME type sniffing, so that in case of Content-Type header mismatch, the resource is not interpreted. For example within a &lt;script&gt; object
context, JavaScript MIME types are expected (like <em>application/javascript</em>) in the Content-Type header.</p>
<h2>Sensitive Code Example</h2>
<p>The following ASP.NET website configuration is sensitive, because it does not set the <code>X-Content-Type-Options</code> HTTP response header to
<code>nosniff</code>:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;configuration&gt; &lt;!-- Sensitive --&gt;
&lt;system.webServer&gt;
&lt;!-- ... --&gt;
&lt;/system.webServer&gt;
&lt;/configuration&gt;
</pre>
<h2>Compliant Solution</h2>
<p>To mitigate this finding, set <code>nosniff</code> globally for all pages in the application in the <code>web.config</code> file. While it is also
possible to configure the header individually in the application code, or per <code>&lt;location&gt;</code> element, setting it globally is less
error-prone and therefore recommended.</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;configuration&gt;
&lt;system.webServer&gt;
&lt;httpProtocol&gt;
&lt;customHeaders&gt;
&lt;add name="X-Content-Type-Options" value="nosniff"/&gt;
&lt;/customHeaders&gt;
&lt;/httpProtocol&gt;
&lt;!-- ... --&gt;
&lt;/system.webServer&gt;
&lt;/configuration&gt;
</pre>
<h2>See</h2>
<ul>
<li> OWASP - <a href="https://owasp.org/Top10/A05_2021-Security_Misconfiguration/">Top 10 2021 Category A5 - Security Misconfiguration</a> </li>
<li> OWASP - <a href="https://owasp.org/www-project-top-ten/2017/A6_2017-Security_Misconfiguration">Top 10 2017 Category A6 - Security
Misconfiguration</a> </li>
<li> <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options">developer.mozilla.org</a> - X-Content-Type-Options
</li>
<li> <a href="https://blog.mozilla.org/security/2016/08/26/mitigating-mime-confusion-attacks-in-firefox/">blog.mozilla.org</a> - Mitigating MIME
Confusion Attacks in Firefox </li>
</ul>

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"title": "Allowing browsers to sniff MIME types is security-sensitive",
"type": "SECURITY_HOTSPOT",
"code": {
"impacts": {
"SECURITY": "LOW"
},
"attribute": "COMPLETE"
},
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [],
"defaultSeverity": "Minor",
"ruleSpecification": "RSPEC-5734",
"sqKey": "S5734",
"scope": "Main",
"securityStandards": {
"OWASP": [
"A6"
],
"OWASP Top 10 2021": [
"A5"
]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"S5322",
"S5332",
"S5604",
"S5734",
"S6358",
"S6359",
"S6361",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* SonarQube XML Plugin
* Copyright (C) 2010-2025 SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.plugins.xml.checks.security.web;

import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;

class BaseWebCheckTest {
@Test
void testGetDeepestExistingNode() {
BaseWebCheck baseWebCheck = new BaseWebCheck();

assertThat(baseWebCheck.getDeepestExistingNode("a"))
.isEqualTo("/a");

assertThat(baseWebCheck.getDeepestExistingNode("a", "b"))
.isEqualTo("/a/b|/a[not(b)]");

assertThat(baseWebCheck.getDeepestExistingNode("a", "b", "c"))
.isEqualTo("/a/b/c|/a/b[not(c)]|/a[not(b)]");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* SonarQube XML Plugin
* Copyright (C) 2010-2025 SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.plugins.xml.checks.security.web;

import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.sonarsource.analyzer.commons.xml.checks.SonarXmlCheckVerifier;

class MimeNosniffCheckTest {

@Test
void compliant() {
String path = Paths.get("webconfig-compliant", "web.config").toString();
SonarXmlCheckVerifier.verifyNoIssue(path, new MimeNosniffCheck());
}

@ParameterizedTest
@ValueSource(strings = {
"webconfig-no-custom-headers",
"webconfig-missing-nosniff",
"webconfig-other-value"
})
void noncompliant(String dirName) {
String path = Paths.get(dirName, "web.config").toString();
SonarXmlCheckVerifier.verifyIssues(path, new MimeNosniffCheck());
}

@ParameterizedTest
@ValueSource(strings = {
"webconfig-add-remove",
"webconfig-add-clear",
})
void false_negatives(String dirName) {
String path = Paths.get(dirName, "web.config").toString();
SonarXmlCheckVerifier.verifyNoIssue(path, new MimeNosniffCheck());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Content-Type-Options" value="nosniff"/> <!-- FN, please Sonar, but don't turn it on -->
<clear />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Content-Type-Options" value="nosniff"/> <!-- FN, please Sonar, but don't turn it on -->
<remove name="X-Content-Type-Options" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="X-Content-Type-Options" value="nosniff"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders> <!-- Noncompliant {{Set the "X-Content-Type-Options" HTTP header to "nosniff" to mitigate MIME Confusion Attacks.}} -->
<!-- ^^^^^^^^^^^^^ -->
<remove name="X-Powered-By" />
<add name="X-Frame-Options" value="SAMEORIGIN" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration> <!-- Noncompliant {{Set the "X-Content-Type-Options" HTTP header to "nosniff" to mitigate MIME Confusion Attacks.}} -->
<!-- ^[sc=2;ec=14] -->
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders> <!-- Noncompliant {{Set the "X-Content-Type-Options" HTTP header to "nosniff" to mitigate MIME Confusion Attacks.}} -->
<!-- ^^^^^^^^^^^^^ -->
<add name="X-Content-Type-Options" value="yes"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Loading