Cross-Site Request Forgery in Jenkins
Research is free — Hunters explains how the bug works, the root-cause code pattern, how the fix addresses it, and how to test whether a target is affected, in chat. Investigate & write exploit is a paid run — the engine reads the advisory and fix commits, then builds and validates a working proof-of-concept exploit with reproduction steps.
Affected versions
Details
An extension point in Jenkins allows selectively disabling cross-site request forgery (CSRF) protection for specific URLs. Implementations of that extension point received a different representation of the URL path than the Stapler web framework uses to dispatch requests in Jenkins 2.227 and earlier, LTS 2.204.5 and earlier. This discrepancy allowed attackers to craft URLs that would bypass the CSRF protection of any target URL. Jenkins now uses the same representation of the URL path to decide whether CSRF protection is needed for a given URL as the Stapler web framework uses. In case of problems, administrators can disable this security fix by setting the system property `hudson.security.csrf.CrumbFilter.UNPROCESSED_PATHINFO` to `true`. As an additional safeguard, semicolon (`;`) characters in the path part of a URL are now banned by default. Administrators can disable this protection by setting the system property `jenkins.security.SuspiciousRequestFilter.allowSemicolonsInPath` to `true`.
The fix
[SECURITY-1774]
core/src/main/java/hudson/security/csrf/CrumbFilter.java+57 −1
@@ -7,6 +7,7 @@import hudson.util.MultipartFormDataParser;import jenkins.model.Jenkins;+import jenkins.util.SystemProperties;import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken;import org.kohsuke.MetaInfServices;import org.kohsuke.accmod.Restricted;@@ -15,7 +16,10 @@import org.kohsuke.stapler.interceptor.RequirePOST;import java.io.IOException;+import java.util.ArrayList;+import java.util.Arrays;import java.util.Enumeration;+import java.util.List;import java.util.logging.Level;import java.util.logging.Logger;@@ -26,6 +30,7 @@import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;+import javax.servlet.http.HttpServletRequestWrapper;import javax.servlet.http.HttpServletResponse;/**@@ -58,6 +63,54 @@ public ForwardToView getForwardView() {public void init(FilterConfig filterConfig) throws ServletException {}+private static class Security1774ServletRequest extends HttpServletRequestWrapper {+public Security1774ServletRequest(HttpServletRequest request) {+super(request);+}++@Override+public String getPathInfo() {+// see Stapler#getServletPath+return canonicalPath(getRequestURI().substring(getContextPath().length()));+}+++// Copied from Stapler#canonicalPath+private static String canonicalPath(String path) {+List<String> r = new ArrayList<String>(Arrays.asList(path.split("/+")));+for (int i=0; i<r.size(); ) {+if (r.get(i).length()==0 || r.get(i).equals(".")) {+// empty token occurs for example, "".split("/+") is [""]+r.remove(i);+} else+if (r.get(i).equals("..")) {+// i==0 means this is a broken URI.+r.remove(i);+if (i>0) {+r.remove(i-1);+i--;+}+} else {+i++;+}+}++StringBuilder buf = new StringBuilder();+if (path.startsWith("/"))+buf.append('/');+boolean first = true;+for (String token : r) {+if (!first) buf.append('/');+else first = false;+buf.append(token);+}+// translation: if (path.endsWith("/") && !buf.endsWith("/"))+if (path.endsWith("/") && (buf.length()==0 || buf.charAt(buf.length()-1)!='/'))+buf.append('/');+return buf.toString();+}+}+public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {CrumbIssuer crumbIssuer = getCrumbIssuer();if (crumbIssuer == null || !(request instanceof HttpServletRequest)) {@@ -69,8 +122,9 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterChaHttpServletResponse httpResponse = (HttpServletResponse) response;if ("POST".equals(httpRequest.getMethod())) {+HttpServletRequest wrappedRequest = UNPROCESSED_PATHINFO ? httpRequest : new Security1774ServletRequest(httpRequest);for (CrumbExclusion e : CrumbExclusion.all()) {-if (e.process(httpRequest,httpResponse,chain))+if (e.process(wrappedRequest,httpResponse,chain))return;}@@ -136,5 +190,7 @@ protected static boolean isMultipart(HttpServletRequest request) {public void destroy() {}+static /* non-final for Groovy */ boolean UNPROCESSED_PATHINFO = SystemProperties.getBoolean(CrumbFilter.class.getName() + ".UNPROCESSED_PATHINFO");+private static final Logger LOGGER = Logger.getLogger(CrumbFilter.class.getName());}
test/src/test/java/hudson/security/csrf/CrumbExclusionTest.java+120 −0
@@ -0,0 +1,120 @@+/*+* The MIT License+*+* Copyright 2020 CloudBees, Inc.+*+* Permission is hereby granted, free of charge, to any person obtaining a copy+* of this software and associated documentation files (the "Software"), to deal+* in the Software without restriction, including without limitation the rights+* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+* copies of the Software, and to permit persons to whom the Software is+* furnished to do so, subject to the following conditions:+*+* The above copyright notice and this permission notice shall be included in+* all copies or substantial portions of the Software.+*+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+* THE SOFTWARE.+*/++package hudson.security.csrf;++import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;+import com.gargoylesoftware.htmlunit.HttpMethod;+import com.gargoylesoftware.htmlunit.WebRequest;++import java.io.IOException;+import java.net.URL;++import hudson.ExtensionList;+import hudson.model.UnprotectedRootAction;+import jenkins.model.Jenkins;+import static org.hamcrest.Matchers.containsString;++import org.junit.Assert;+import org.junit.Test;+import static org.junit.Assert.*;+import org.junit.Rule;+import org.jvnet.hudson.test.Issue;+import org.jvnet.hudson.test.JenkinsRule;+import org.jvnet.hudson.test.MockAuthorizationStrategy;+import org.jvnet.hudson.test.TestExtension;+import org.kohsuke.stapler.verb.POST;++import javax.annotation.CheckForNull;+import javax.servlet.FilterChain;+import javax.servlet.ServletException;+import javax.servlet.http.HttpServletRequest;+import javax.servlet.http.HttpServletResponse;++public class CrumbExclusionTest {++@Rule+public JenkinsRule r = new JenkinsRule();++@Issue("SECURITY-1774")+@Test+public void pathInfo() throws Exception {+r.jenkins.setSecurityRealm(r.createDummySecurityRealm());+r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to("admin"));+for (String path : new String[] {/* control */ "scriptText", /* test */ "scriptText/..;/cli"}) {+try {+fail(path + " should have been rejected: " + r.createWebClient().login("admin").getPage(new WebRequest(new URL(r.getURL(), path + "?script=11*11"), HttpMethod.POST)).getWebResponse().getContentAsString());+} catch (FailingHttpStatusCodeException x) {+assertEquals("status code using " + path, 403, x.getStatusCode());+assertThat("error message using " + path, x.getResponse().getContentAsString(), containsString("No valid crumb was included in the request"));+}+}+}++@Test+public void regular() throws Exception {+r.createWebClient().getPage(new WebRequest(new URL(r.getURL(), "root/"), HttpMethod.POST));+Assert.assertTrue(ExtensionList.lookupSingleton(RootActionImpl.class).posted);+}++@TestExtension+public static class RootActionImpl implements UnprotectedRootAction {++public boolean posted = false;++@CheckForNull+public String getIconFileName() {+return null;+}++@CheckForNull+public String getDisplayName() {+return null;+}++@CheckForNull+public String getUrlName() {+return "root";+}++@POST+public void doIndex() {+posted = true;+}+}++@TestExtension+public static class CrumbExclusionImpl extends CrumbExclusion {++@Override+public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {+String pathInfo = request.getPathInfo();+if (pathInfo != null && pathInfo.startsWith("/root/")) {+chain.doFilter(request, response);+return true;+}+return false;+}+}+}
[SECURITY-1774]
core/src/main/java/jenkins/security/SuspiciousRequestFilter.java+47 −0
@@ -0,0 +1,47 @@+package jenkins.security;++import jenkins.util.SystemProperties;+import org.kohsuke.accmod.Restricted;+import org.kohsuke.accmod.restrictions.NoExternalUse;++import javax.servlet.Filter;+import javax.servlet.FilterChain;+import javax.servlet.FilterConfig;+import javax.servlet.ServletException;+import javax.servlet.ServletRequest;+import javax.servlet.ServletResponse;+import javax.servlet.http.HttpServletRequest;+import javax.servlet.http.HttpServletResponse;+import java.io.IOException;+import java.util.logging.Logger;++@Restricted(NoExternalUse.class)+public class SuspiciousRequestFilter implements Filter {++/** System property name set to true or false to indicate whether or not semicolons should be allowed in URL paths. */+public static final String ALLOW_SEMICOLONS_IN_PATH = SuspiciousRequestFilter.class.getName() + ".allowSemicolonsInPath";+public static boolean allowSemicolonsInPath = SystemProperties.getBoolean(ALLOW_SEMICOLONS_IN_PATH, false);+private static final Logger LOGGER = Logger.getLogger(SuspiciousRequestFilter.class.getName());++@Override+public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {+HttpServletRequest httpRequest = (HttpServletRequest) request;+HttpServletResponse httpResponse = (HttpServletResponse) response;+if (!allowSemicolonsInPath && httpRequest.getRequestURI().contains(";")) {+LOGGER.warning(() -> "Denying HTTP " + httpRequest.getMethod() + " to " + httpRequest.getRequestURI() ++" as it has an illegal semicolon in the path. This behavior can be overridden by setting the system property " ++ALLOW_SEMICOLONS_IN_PATH + " to true. For more information, see https://jenkins.io/redirect/semicolons-in-urls");+httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Semicolons are not allowed in the request URI");+} else {+chain.doFilter(request, response);+}+}++@Override+public void init(FilterConfig filterConfig) throws ServletException {+}++@Override+public void destroy() {+}+}
test/src/test/java/hudson/security/csrf/CrumbExclusionTest.java+13 −0
@@ -36,7 +36,10 @@import jenkins.model.Jenkins;import static org.hamcrest.Matchers.containsString;+import jenkins.security.SuspiciousRequestFilter;+import org.junit.AfterClass;import org.junit.Assert;+import org.junit.BeforeClass;import org.junit.Test;import static org.junit.Assert.*;import org.junit.Rule;@@ -57,6 +60,16 @@ public class CrumbExclusionTest {@Rulepublic JenkinsRule r = new JenkinsRule();+@BeforeClass+public static void prepare() {+SuspiciousRequestFilter.allowSemicolonsInPath = true;+}++@AfterClass+public static void cleanup() {+SuspiciousRequestFilter.allowSemicolonsInPath = false;+}+@Issue("SECURITY-1774")@Testpublic void pathInfo() throws Exception {
test/src/test/java/jenkins/security/SuspiciousRequestFilterTest.java+102 −0
@@ -0,0 +1,102 @@+package jenkins.security;++import com.gargoylesoftware.htmlunit.WebRequest;+import com.gargoylesoftware.htmlunit.WebResponse;+import hudson.ExtensionList;+import hudson.model.UnprotectedRootAction;+import org.junit.Rule;+import org.junit.Test;+import org.jvnet.hudson.test.Issue;+import org.jvnet.hudson.test.JenkinsRule;+import org.jvnet.hudson.test.TestExtension;+import org.kohsuke.stapler.QueryParameter;+import org.kohsuke.stapler.verb.GET;++import javax.annotation.CheckForNull;+import javax.servlet.http.HttpServletResponse;+import java.net.URL;++import static org.hamcrest.MatcherAssert.assertThat;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.is;+import static org.hamcrest.Matchers.nullValue;++@Issue("SECURITY-1774")+public class SuspiciousRequestFilterTest {++@Rule+public JenkinsRule j = new JenkinsRule();++private WebResponse get(String path) throws Exception {+return j.createWebClient()+.withThrowExceptionOnFailingStatusCode(false)+.getPage(new WebRequest(new URL(j.getURL(), path)))+.getWebResponse();+}++@Test+public void denySemicolonInRequestPathByDefault() throws Exception {+WebResponse response = get("foo/bar/..;/?baz=bruh");+assertThat(Foo.getInstance().baz, is(nullValue()));+assertThat(response.getStatusCode(), is(HttpServletResponse.SC_BAD_REQUEST));+assertThat(response.getContentAsString(), containsString("Semicolons are not allowed in the request URI"));+}++@Test+public void allowSemicolonsInRequestPathWhenEscapeHatchEnabled() throws Exception {+SuspiciousRequestFilter.allowSemicolonsInPath = true;+try {+WebResponse response = get("foo/bar/..;/..;/cli?baz=bruh");+assertThat(Foo.getInstance().baz, is("bruh"));+assertThat(response.getStatusCode(), is(HttpServletResponse.SC_OK));+} finally {+SuspiciousRequestFilter.allowSemicolonsInPath = false;+}+}++@Test+public void allowSemicolonsInQueryParameters() throws Exception {+WebResponse response = get("foo/bar?baz=foo;bar=baz");+assertThat(Foo.getInstance().baz, is("foo;bar=baz"));+assertThat(response.getStatusCode(), is(HttpServletResponse.SC_OK));+}++@TestExtension+public static class Foo implements UnprotectedRootAction {++private static Foo getInstance() {+return ExtensionList.lookupSingleton(Foo.class);+}++private String baz;++@CheckForNull+@Override+public String getIconFileName() {+return null;+}++@CheckForNull+@Override+public String getDisplayName() {+return "Pitied Foos";+}++@CheckForNull+@Override+public String getUrlName() {+return "foo";+}++@GET+public void doBar(@QueryParameter String baz) {+this.baz = baz;+}++@GET+public void doIndex(@QueryParameter String baz) {+this.baz = "index: " + baz;+}+}++}
war/src/main/webapp/WEB-INF/web.xml+10 −1
@@ -50,6 +50,11 @@ THE SOFTWARE.<url-pattern>/*</url-pattern></servlet-mapping>+<filter>+<filter-name>suspicious-request-filter</filter-name>+<filter-class>jenkins.security.SuspiciousRequestFilter</filter-class>+<async-supported>true</async-supported>+</filter><filter><filter-name>diagnostic-name-filter</filter-name><filter-class>org.kohsuke.stapler.DiagnosticThreadNameFilter</filter-class>@@ -125,7 +130,11 @@ THE SOFTWARE.<url-pattern>*.png</url-pattern></filter-mapping>-->-++<filter-mapping>+<filter-name>suspicious-request-filter</filter-name>+<url-pattern>/*</url-pattern>+</filter-mapping><filter-mapping><filter-name>diagnostic-name-filter</filter-name><url-pattern>/*</url-pattern>
References
- ADVISORYhttps://nvd.nist.gov/vuln/detail/CVE-2020-2160
- WEBhttps://github.com/jenkinsci/jenkins/commit/f479652171f4ab854747de64b22bf59adb35fb8f
- WEBhttps://github.com/jenkinsci/jenkins/commit/f7cf28355973df1ca6eb19066370bf70b10742f7
- PACKAGEhttps://github.com/jenkinsci/jenkins
- WEBhttps://jenkins.io/security/advisory/2020-03-25/#SECURITY-1774
- WEBhttp://www.openwall.com/lists/oss-security/2020/03/25/2