Skip to content

Commit 76a7681

Browse files
committed
[SECURITY-359]
1 parent 6bd4e8b commit 76a7681

File tree

4 files changed

+343
-2
lines changed

4 files changed

+343
-2
lines changed

src/main/java/org/jenkinsci/plugins/workflow/cps/CpsGroovyShellFactory.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ private ImportCustomizer makeImportCustomizer() {
111111

112112
private ClassLoader makeClassLoader() {
113113
ClassLoader cl = Jenkins.get().getPluginManager().uberClassLoader;
114-
return GroovySandbox.createSecureClassLoader(cl);
114+
return new GroovySourceFileAllowlist.ClassLoaderImpl(execution, GroovySandbox.createSecureClassLoader(cl));
115115
}
116116

117117
public CpsGroovyShell build() {
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
/*
2+
* The MIT License
3+
*
4+
* Copyright 2022 CloudBees, Inc.
5+
*
6+
* Permission is hereby granted, free of charge, to any person obtaining a copy
7+
* of this software and associated documentation files (the "Software"), to deal
8+
* in the Software without restriction, including without limitation the rights
9+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
* copies of the Software, and to permit persons to whom the Software is
11+
* furnished to do so, subject to the following conditions:
12+
*
13+
* The above copyright notice and this permission notice shall be included in
14+
* all copies or substantial portions of the Software.
15+
*
16+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22+
* THE SOFTWARE.
23+
*/
24+
25+
package org.jenkinsci.plugins.workflow.cps;
26+
27+
import edu.umd.cs.findbugs.annotations.CheckForNull;
28+
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
29+
import hudson.Extension;
30+
import hudson.ExtensionList;
31+
import hudson.ExtensionPoint;
32+
import hudson.Main;
33+
import java.io.BufferedReader;
34+
import java.io.IOException;
35+
import java.io.InputStream;
36+
import java.io.InputStreamReader;
37+
import java.net.URL;
38+
import java.nio.charset.StandardCharsets;
39+
import java.util.ArrayList;
40+
import java.util.Arrays;
41+
import java.util.Collections;
42+
import java.util.Enumeration;
43+
import java.util.List;
44+
import java.util.logging.Level;
45+
import java.util.logging.Logger;
46+
import jenkins.util.SystemProperties;
47+
import org.apache.commons.lang.StringUtils;
48+
49+
/**
50+
* Determines what Groovy source files can be loaded in Pipelines.
51+
*
52+
* In Pipeline, the standard behavior of {@code GroovyClassLoader} would allow Groovy source files from core or plugins
53+
* to be loaded as long as they are somewhere on the classpath. This includes things like Groovy views, which are not
54+
* intended to be available to pipelines. When these files are loaded, they are loaded by the trusted
55+
* {@link CpsGroovyShell} and are not sandbox-transformed, which means that allowing arbitrary Groovy source files to
56+
* be loaded is potentially unsafe.
57+
*
58+
* {@link ClassLoaderImpl} blocks all Groovy source files from being loaded by default unless they are allowed by an
59+
* implementation of this extension point.
60+
*/
61+
public abstract class GroovySourceFileAllowlist implements ExtensionPoint {
62+
private static final Logger LOGGER = Logger.getLogger(GroovySourceFileAllowlist.class.getName());
63+
private static final String DISABLED_PROPERTY = GroovySourceFileAllowlist.class.getName() + ".DISABLED";
64+
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Non-final for script console access")
65+
static boolean DISABLED = SystemProperties.getBoolean(DISABLED_PROPERTY);
66+
67+
/**
68+
* Checks whether a given Groovy source file is allowed to be loaded by {@link CpsFlowExecution#getTrustedShell}.
69+
*
70+
* @param groovySourceFileUrl the absolute URL to the Groovy source file as returned by {@link ClassLoader#getResource}
71+
* @return {@code true} if the Groovy source file may be loaded, {@code false} otherwise
72+
*/
73+
public abstract boolean isAllowed(String groovySourceFileUrl);
74+
75+
public static List<GroovySourceFileAllowlist> all() {
76+
return ExtensionList.lookup(GroovySourceFileAllowlist.class);
77+
}
78+
79+
/**
80+
* {@link ClassLoader} that acts normally except for returning {@code null} from {@link #getResource} and
81+
* {@link #getResources} when looking up Groovy source files if the files are not allowed by
82+
* {@link GroovySourceFileAllowlist}.
83+
*/
84+
static class ClassLoaderImpl extends ClassLoader {
85+
private static final String LOG_MESSAGE_TEMPLATE =
86+
"Preventing {0} from being loaded without sandbox protection in {1}. " +
87+
"To allow access to this file, add any suffix of its URL to the system property ‘" +
88+
DefaultAllowlist.ALLOWED_SOURCE_FILES_PROPERTY + "’ (use commas to separate multiple files). If you " +
89+
"want to allow any Groovy file on the Jenkins classpath to be accessed, you may set the system " +
90+
"property ‘" + DISABLED_PROPERTY + "’ to true.";
91+
92+
private final String owner;
93+
94+
public ClassLoaderImpl(@CheckForNull CpsFlowExecution execution, ClassLoader parent) {
95+
super(parent);
96+
this.owner = describeOwner(execution);
97+
}
98+
99+
private static String describeOwner(@CheckForNull CpsFlowExecution execution) {
100+
if (execution != null) {
101+
try {
102+
return execution.getOwner().getExecutable().toString();
103+
} catch (IOException e) {
104+
// Not significant in this context.
105+
}
106+
}
107+
return "unknown";
108+
}
109+
110+
@Override
111+
public URL getResource(String name) {
112+
URL url = super.getResource(name);
113+
if (DISABLED || url == null || !endsWithIgnoreCase(name, ".groovy") || isAllowed(url)) {
114+
return url;
115+
}
116+
// Note: This message gets printed twice because of https://github.com/apache/groovy/blob/41b990d0a20e442f29247f0e04cbed900f3dcad4/src/main/org/codehaus/groovy/control/ClassNodeResolver.java#L184-L186.
117+
LOGGER.log(Level.WARNING, LOG_MESSAGE_TEMPLATE, new Object[] { url, owner });
118+
return null;
119+
}
120+
121+
@Override
122+
public Enumeration<URL> getResources(String name) throws IOException {
123+
Enumeration<URL> urls = super.getResources(name);
124+
if (DISABLED || !urls.hasMoreElements() || !endsWithIgnoreCase(name, ".groovy")) {
125+
return urls;
126+
}
127+
List<URL> filteredUrls = new ArrayList<>();
128+
while (urls.hasMoreElements()) {
129+
URL url = urls.nextElement();
130+
if (isAllowed(url)) {
131+
filteredUrls.add(url);
132+
} else {
133+
LOGGER.log(Level.WARNING, LOG_MESSAGE_TEMPLATE, new Object[] { url, owner });
134+
}
135+
}
136+
return Collections.enumeration(filteredUrls);
137+
}
138+
139+
private static boolean isAllowed(URL url) {
140+
String urlString = url.toString();
141+
for (GroovySourceFileAllowlist allowlist : GroovySourceFileAllowlist.all()) {
142+
if (allowlist.isAllowed(urlString)) {
143+
return true;
144+
}
145+
}
146+
return false;
147+
}
148+
149+
private static boolean endsWithIgnoreCase(String value, String suffix) {
150+
int suffixLength = suffix.length();
151+
return value.regionMatches(true, value.length() - suffixLength, suffix, 0, suffixLength);
152+
}
153+
}
154+
155+
/**
156+
* Allows Groovy source files used to implement DSLs in plugins that were created before
157+
* {@link GroovySourceFileAllowlist} was introduced.
158+
*/
159+
@Extension
160+
public static class DefaultAllowlist extends GroovySourceFileAllowlist {
161+
private static final Logger LOGGER = Logger.getLogger(DefaultAllowlist.class.getName());
162+
private static final String ALLOWED_SOURCE_FILES_PROPERTY = DefaultAllowlist.class.getCanonicalName() + ".ALLOWED_SOURCE_FILES";
163+
/**
164+
* A list containing suffixes of known-good Groovy source file URLs that need to be accessible to Pipeline code.
165+
*/
166+
/* Note: Actual ClassLoader resource URLs depend on environmental factors such as webroot settings and whether
167+
* we are currently testing one of the plugins in the list, so default-allowlist only contains the path
168+
* component of the resource URLs, and we allow any resource URL that ends with one of the entries in the list.
169+
*
170+
* We could try to load the exact URLs at runtime, but then we would have to account for dynamic plugin loading
171+
* (especially when a new Jenkins controller is initialized) and the fact that workflow-cps is always a
172+
* dependency of these plugins.
173+
*/
174+
static final List<String> ALLOWED_SOURCE_FILES = new ArrayList<>();
175+
176+
public DefaultAllowlist() throws IOException {
177+
// We load custom entries first to improve performance in case .groovy is used for the property.
178+
String propertyValue = SystemProperties.getString(ALLOWED_SOURCE_FILES_PROPERTY, "");
179+
for (String groovyFile : propertyValue.split(",")) {
180+
groovyFile = StringUtils.trimToNull(groovyFile);
181+
if (groovyFile != null) {
182+
if (groovyFile.endsWith(".groovy")) {
183+
ALLOWED_SOURCE_FILES.add(groovyFile);
184+
LOGGER.log(Level.INFO, "Allowing Pipelines to access {0}", groovyFile);
185+
} else {
186+
LOGGER.log(Level.WARNING, "Ignoring invalid Groovy source file: {0}", groovyFile);
187+
}
188+
}
189+
}
190+
loadDefaultAllowlist(ALLOWED_SOURCE_FILES);
191+
// Some plugins use test-specific Groovy DSLs.
192+
if (Main.isUnitTest) {
193+
ALLOWED_SOURCE_FILES.addAll(Arrays.asList(
194+
// pipeline-model-definition
195+
"/org/jenkinsci/plugins/pipeline/modeldefinition/agent/impl/LabelAndOtherFieldAgentScript.groovy",
196+
"/org/jenkinsci/plugins/pipeline/modeldefinition/parser/GlobalStageNameTestConditionalScript.groovy"
197+
));
198+
}
199+
}
200+
201+
private static void loadDefaultAllowlist(List<String> allowlist) throws IOException {
202+
try (InputStream is = GroovySourceFileAllowlist.class.getResourceAsStream("GroovySourceFileAllowlist/default-allowlist");
203+
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));) {
204+
String line;
205+
while ((line = reader.readLine()) != null) {
206+
line = line.trim();
207+
if (!line.isEmpty() && !line.startsWith("#")) {
208+
allowlist.add(line);
209+
}
210+
}
211+
}
212+
}
213+
214+
@Override
215+
public boolean isAllowed(String groovySourceFileUrl) {
216+
for (String sourceFile : ALLOWED_SOURCE_FILES) {
217+
if (groovySourceFileUrl.endsWith(sourceFile)) {
218+
return true;
219+
}
220+
}
221+
return false;
222+
}
223+
}
224+
225+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# This list is ordered from most popular to least popular plugin to minimize performance impact.
2+
# pipeline-model-definition
3+
/org/jenkinsci/plugins/pipeline/modeldefinition/ModelInterpreter.groovy
4+
/org/jenkinsci/plugins/pipeline/modeldefinition/agent/impl/AnyScript.groovy
5+
/org/jenkinsci/plugins/pipeline/modeldefinition/agent/impl/LabelScript.groovy
6+
/org/jenkinsci/plugins/pipeline/modeldefinition/agent/impl/NoneScript.groovy
7+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/AbstractChangelogConditionalScript.groovy
8+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/AllOfConditionalScript.groovy
9+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/AnyOfConditionalScript.groovy
10+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/BranchConditionalScript.groovy
11+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/ChangeLogConditionalScript.groovy
12+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/ChangeRequestConditionalScript.groovy
13+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/ChangeSetConditionalScript.groovy
14+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/EnvironmentConditionalScript.groovy
15+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/EqualsConditionalScript.groovy
16+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/ExpressionConditionalScript.groovy
17+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/IsRestartedRunConditionalScript.groovy
18+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/NotConditionalScript.groovy
19+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/TagConditionalScript.groovy
20+
/org/jenkinsci/plugins/pipeline/modeldefinition/when/impl/TriggeredByConditionalScript.groovy
21+
# pipeline-model-extensions
22+
/org/jenkinsci/plugins/pipeline/modeldefinition/agent/CheckoutScript.groovy
23+
# docker-workflow
24+
/org/jenkinsci/plugins/docker/workflow/Docker.groovy
25+
/org/jenkinsci/plugins/docker/workflow/declarative/AbstractDockerPipelineScript.groovy
26+
/org/jenkinsci/plugins/docker/workflow/declarative/DockerPipelineFromDockerfileScript.groovy
27+
/org/jenkinsci/plugins/docker/workflow/declarative/DockerPipelineScript.groovy
28+
# kubernetes
29+
/org/csanchez/jenkins/plugins/kubernetes/pipeline/KubernetesDeclarativeAgentScript.groovy
30+
# amazon-ecs
31+
/com/cloudbees/jenkins/plugins/amazonecs/pipeline/ECSDeclarativeAgentScript.groovy
32+
# workflow-remote-loader:
33+
/org/jenkinsci/plugins/workflow/remoteloader/FileLoaderDSL/FileLoaderDSLImpl.groovy
34+
# confluence-publisher
35+
/com/myyearbook/hudson/plugins/confluence/publishConfluence.groovy
36+
# openshift-client
37+
/com/openshift/jenkins/plugins/OpenShiftDSL.groovy
38+
# ownership:
39+
/org/jenkinsci/plugins/ownership/model/workflow/OwnershipGlobalVariable/Impl.groovy
40+
# templating-engine:
41+
/org/boozallen/plugins/jte/init/primitives/hooks/AnnotatedMethod.groovy
42+
/org/boozallen/plugins/jte/init/primitives/hooks/Hooks.groovy
43+
# datetime-constraint
44+
/org/jenkinsci/plugins/curfew/Checkpoint.groovy
45+
/org/jenkinsci/plugins/curfew/Curfew.groovy
46+
# redis-notifier
47+
/com/tsoft/jenkins/plugin/RedisClient.groovy
48+
# alauda-pipeline
49+
/io/alauda/jenkins/plugins/pipeline/AlaudaDSL.groovy
50+
# alauda-devops-pipeline
51+
/com/alauda/jenkins/plugins/AlaudaDevopsDSL.groovy
52+
/com/alauda/jenkins/plugins/AlaudaPlatformDSL.groovy
53+
/com/alauda/jenkins/plugins/StorageDSL.groovy

src/test/java/org/jenkinsci/plugins/workflow/cps/CpsFlowExecutionTest.java

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
import org.hamcrest.Matchers;
5151
import org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException;
5252
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
53+
import org.jenkinsci.plugins.workflow.cps.GroovySourceFileAllowlist.DefaultAllowlist;
5354
import org.jenkinsci.plugins.workflow.flow.FlowExecution;
5455
import org.jenkinsci.plugins.workflow.flow.FlowExecutionOwner;
5556
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
@@ -61,6 +62,8 @@
6162
import org.jenkinsci.plugins.workflow.support.pickles.TryRepeatedly;
6263
import org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep;
6364
import static org.hamcrest.MatcherAssert.assertThat;
65+
import static org.hamcrest.Matchers.containsString;
66+
import static org.hamcrest.Matchers.hasItem;
6467
import static org.junit.Assert.assertEquals;
6568
import static org.junit.Assert.assertFalse;
6669
import static org.junit.Assert.assertNotNull;
@@ -71,6 +74,7 @@
7174
import org.junit.Rule;
7275
import org.junit.Test;
7376
import org.jvnet.hudson.test.BuildWatcher;
77+
import org.jvnet.hudson.test.FlagRule;
7478
import org.jvnet.hudson.test.Issue;
7579
import org.jvnet.hudson.test.JenkinsRule;
7680
import org.jvnet.hudson.test.JenkinsSessionRule;
@@ -83,6 +87,10 @@ public class CpsFlowExecutionTest {
8387
@ClassRule public static BuildWatcher buildWatcher = new BuildWatcher();
8488
@Rule public JenkinsSessionRule sessions = new JenkinsSessionRule();
8589
@Rule public LoggerRule logger = new LoggerRule();
90+
@Rule public FlagRule<Boolean> secretField = new FlagRule<>(() -> CpsFlowExecutionTest.SECRET, v -> CpsFlowExecutionTest.SECRET = v);
91+
// We intentionally avoid using the static fields so that tests can call setProperty before the classes are initialized.
92+
@Rule public FlagRule<String> groovySourceFileAllowlistDisabled = FlagRule.systemProperty("org.jenkinsci.plugins.workflow.cps.GroovySourceFileAllowlist.DISABLED");
93+
@Rule public FlagRule<String> groovySourceFileAllowlistFiles = FlagRule.systemProperty("org.jenkinsci.plugins.workflow.cps.GroovySourceFileAllowlist.DefaultAllowlist.ALLOWED_SOURCE_FILES");
8694

8795
@Test public void getCurrentExecutions() throws Throwable {
8896
sessions.then(r -> {
@@ -441,7 +449,6 @@ public void configureShell(@CheckForNull CpsFlowExecution context, GroovyShell s
441449
}
442450

443451
private void trustedShell(final boolean pos) throws Throwable {
444-
SECRET = false;
445452
sessions.then(r -> {
446453
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
447454
p.setDefinition(new CpsFlowDefinition("new foo().attempt()", true));
@@ -464,4 +471,60 @@ private void trustedShell(final boolean pos) throws Throwable {
464471
* This field shouldn't be visible to regular script.
465472
*/
466473
public static boolean SECRET;
474+
475+
@Issue("SECURITY-359")
476+
@Test public void groovySourcesCannotBeUsedByDefault() throws Throwable {
477+
logger.record(GroovySourceFileAllowlist.class, Level.INFO).capture(100);
478+
sessions.then(r -> {
479+
WorkflowJob p = r.createProject(WorkflowJob.class);
480+
p.setDefinition(new CpsFlowDefinition(
481+
"new hudson.model.View.main()", true));
482+
WorkflowRun b = r.buildAndAssertStatus(Result.FAILURE, p);
483+
r.assertLogContains("unable to resolve class hudson.model.View.main", b);
484+
assertThat(logger.getMessages(), hasItem(containsString("/hudson/model/View/main.groovy from being loaded without sandbox protection in " + b)));
485+
});
486+
}
487+
488+
@Issue("SECURITY-359")
489+
@Test public void groovySourcesCanBeUsedIfAllowlistIsDisabled() throws Throwable {
490+
System.setProperty("org.jenkinsci.plugins.workflow.cps.GroovySourceFileAllowlist.DISABLED", "true");
491+
sessions.then(r -> {
492+
WorkflowJob p = r.createProject(WorkflowJob.class);
493+
p.setDefinition(new CpsFlowDefinition(
494+
"new hudson.model.View.main()", true));
495+
WorkflowRun b = r.buildAndAssertSuccess(p);
496+
});
497+
}
498+
499+
@Issue("SECURITY-359")
500+
@Test public void groovySourcesCanBeUsedIfAddedToSystemProperty() throws Throwable {
501+
System.setProperty("org.jenkinsci.plugins.workflow.cps.GroovySourceFileAllowlist.DefaultAllowlist.ALLOWED_SOURCE_FILES", "/just/an/example.groovy,/hudson/model/View/main.groovy");
502+
logger.record(DefaultAllowlist.class, Level.INFO).capture(100);
503+
sessions.then(r -> {
504+
WorkflowJob p = r.createProject(WorkflowJob.class);
505+
p.setDefinition(new CpsFlowDefinition(
506+
"new hudson.model.View.main()", true));
507+
WorkflowRun b = r.buildAndAssertSuccess(p);
508+
assertThat(logger.getMessages(), hasItem(containsString("Allowing Pipelines to access /hudson/model/View/main.groovy")));
509+
});
510+
}
511+
512+
@Issue("SECURITY-359")
513+
@Test public void groovySourcesCanBeUsedIfAllowed() throws Throwable {
514+
sessions.then(r -> {
515+
WorkflowJob p = r.createProject(WorkflowJob.class);
516+
p.setDefinition(new CpsFlowDefinition(
517+
"(new trusted.foo()).attempt()", true));
518+
WorkflowRun b = r.buildAndAssertSuccess(p);
519+
assertTrue(SECRET);
520+
});
521+
}
522+
523+
@TestExtension("groovySourcesCanBeUsedIfAllowed")
524+
public static class TestAllowlist extends GroovySourceFileAllowlist {
525+
@Override
526+
public boolean isAllowed(String groovyResourceUrl) {
527+
return groovyResourceUrl.endsWith("/trusted/foo.groovy");
528+
}
529+
}
467530
}

0 commit comments

Comments
 (0)