-
Notifications
You must be signed in to change notification settings - Fork 161
/
SecureGroovyScript.java
468 lines (414 loc) · 20.5 KB
/
SecureGroovyScript.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/*
* The MIT License
*
* Copyright 2014 Jesse Glick.
*
* 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 org.jenkinsci.plugins.scriptsecurity.sandbox.groovy;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import hudson.Extension;
import hudson.PluginManager;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.util.FormValidation;
import java.beans.Introspector;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.SourceUnit;
import org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException;
import org.jenkinsci.plugins.scriptsecurity.scripts.ApprovalContext;
import org.jenkinsci.plugins.scriptsecurity.scripts.ClasspathEntry;
import org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval;
import org.jenkinsci.plugins.scriptsecurity.scripts.UnapprovedClasspathException;
import org.jenkinsci.plugins.scriptsecurity.scripts.UnapprovedUsageException;
import org.jenkinsci.plugins.scriptsecurity.scripts.languages.GroovyLanguage;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Convenience structure encapsulating a Groovy script that may either be approved whole or sandboxed.
* May be kept as the value of a field and passed in a {@link DataBoundConstructor} parameter;
* you <strong>must</strong> call {@link #configuring} or a related method from your own constructor.
* Use {@code <f:property field="…"/>} to configure it from Jelly.
*/
public final class SecureGroovyScript extends AbstractDescribableImpl<SecureGroovyScript> implements Serializable {
private static final long serialVersionUID = -4347442065624787928L;
private final @NonNull String script;
private final boolean sandbox;
private final @CheckForNull List<ClasspathEntry> classpath;
private transient String oldScript;
private transient boolean calledConfiguring;
static final Logger LOGGER = Logger.getLogger(SecureGroovyScript.class.getName());
@DataBoundConstructor public SecureGroovyScript(@NonNull String script, boolean sandbox, @CheckForNull List<ClasspathEntry> classpath) {
this.script = script;
this.sandbox = sandbox;
this.classpath = classpath;
}
@Deprecated public SecureGroovyScript(@NonNull String script, boolean sandbox) {
this(script, sandbox, null);
}
private Object readResolve() {
configuring(ApprovalContext.create());
return this;
}
public @NonNull String getScript() {
return script;
}
public boolean isSandbox() {
return sandbox;
}
public @NonNull List<ClasspathEntry> getClasspath() {
return classpath != null ? classpath : Collections.emptyList();
}
public String getOldScript() {
return oldScript;
}
@DataBoundSetter
public void setOldScript(String oldScript) {
this.oldScript = oldScript;
}
@Restricted(NoExternalUse.class)
public boolean isScriptAutoApprovalEnabled() {
return ScriptApproval.ADMIN_AUTO_APPROVAL_ENABLED;
}
/**
* To be called in your own {@link DataBoundConstructor} when storing the field of this type.
* @param context an approval context
* @return this object
*/
public SecureGroovyScript configuring(ApprovalContext context) {
calledConfiguring = true;
if (!sandbox) {
ScriptApproval.get().configuring(script, GroovyLanguage.get(), context, !StringUtils.equals(this.oldScript, this.script));
}
for (ClasspathEntry entry : getClasspath()) {
ScriptApproval.get().configuring(entry, context);
}
return this;
}
private static @CheckForNull Item currentItem() {
StaplerRequest req = Stapler.getCurrentRequest();
return req != null ? req.findAncestorObject(Item.class) : null;
}
/** Convenience form of {@link #configuring} that calls {@link ApprovalContext#withCurrentUser} and {@link ApprovalContext#withItemAsKey}. */
public SecureGroovyScript configuringWithKeyItem() {
ApprovalContext context = ApprovalContext.create();
context = context.withCurrentUser().withItemAsKey(currentItem());
return configuring(context);
}
/** Convenience form of {@link #configuring} that calls {@link ApprovalContext#withCurrentUser} and {@link ApprovalContext#withItem}. */
public SecureGroovyScript configuringWithNonKeyItem() {
ApprovalContext context = ApprovalContext.create();
context = context.withCurrentUser().withItem(currentItem());
return configuring(context);
}
private static void cleanUpLoader(ClassLoader loader, Set<ClassLoader> encounteredLoaders, Set<Class<?>> encounteredClasses) throws Exception {
if (!encounteredLoaders.add(loader)) {
return;
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "found {0}", String.valueOf(loader));
}
if (loader instanceof GroovyClassLoader) {
GroovyClassLoader gcl = (GroovyClassLoader) loader;
for (Class<?> clazz : gcl.getLoadedClasses()) {
cleanUpClass(clazz, encounteredLoaders, encounteredClasses);
}
gcl.clearCache();
} else if (loader instanceof SandboxResolvingClassLoader) {
// OK, just check its parent
} else if (loader instanceof ClasspathURLClassLoader) {
Collection<Class<?>> loadedClasses = ((ClasspathURLClassLoader) loader).loadedClasses;
synchronized (loadedClasses) {
loadedClasses = new ArrayList<>(loadedClasses);
}
for (Class<?> clazz : loadedClasses) {
cleanUpClass(clazz, encounteredLoaders, encounteredClasses);
}
} else {
LOGGER.log(Level.FINER, "ignoring {0}", loader);
return;
}
cleanUpGlobalClassValue(loader);
cleanUpLoader(loader.getParent(), encounteredLoaders, encounteredClasses);
}
private static void cleanUpClass(Class<?> clazz, Set<ClassLoader> encounteredLoaders, Set<Class<?>> encounteredClasses) throws Exception {
if (encounteredClasses.add(clazz)) {
LOGGER.log(Level.FINER, "found {0}", clazz.getName());
Introspector.flushFromCaches(clazz);
cleanUpGlobalClassSet(clazz);
cleanUpClassHelperCache(clazz);
cleanUpLoader(clazz.getClassLoader(), encounteredLoaders, encounteredClasses);
}
}
// TODO copied with modifications from CpsFlowExecution; need to find a way to share commonalities
private static void cleanUpGlobalClassValue(@NonNull ClassLoader loader) throws Exception {
Class<?> classInfoC = Class.forName("org.codehaus.groovy.reflection.ClassInfo");
// TODO switch to MethodHandle for speed
Field globalClassValueF = classInfoC.getDeclaredField("globalClassValue");
globalClassValueF.setAccessible(true);
Object globalClassValue = globalClassValueF.get(null);
Class<?> groovyClassValuePreJava7C = Class.forName("org.codehaus.groovy.reflection.GroovyClassValuePreJava7");
if (!groovyClassValuePreJava7C.isInstance(globalClassValue)) {
return; // using GroovyClassValueJava7 due to -Dgroovy.use.classvalue or on IBM J9, fine
}
Field mapF = groovyClassValuePreJava7C.getDeclaredField("map");
mapF.setAccessible(true);
Object map = mapF.get(globalClassValue);
Class<?> groovyClassValuePreJava7Map = Class.forName("org.codehaus.groovy.reflection.GroovyClassValuePreJava7$GroovyClassValuePreJava7Map");
Collection entries = (Collection) groovyClassValuePreJava7Map.getMethod("values").invoke(map);
Method removeM = groovyClassValuePreJava7Map.getMethod("remove", Object.class);
Class<?> entryC = Class.forName("org.codehaus.groovy.util.AbstractConcurrentMapBase$Entry");
Method getValueM = entryC.getMethod("getValue");
List<Class<?>> toRemove = new ArrayList<>(); // not sure if it is safe against ConcurrentModificationException or not
try {
Field classRefF = classInfoC.getDeclaredField("classRef"); // 2.4.8+
classRefF.setAccessible(true);
for (Object entry : entries) {
Object value = getValueM.invoke(entry);
toRemove.add(((WeakReference<Class<?>>) classRefF.get(value)).get());
}
} catch (NoSuchFieldException x) {
Field klazzF = classInfoC.getDeclaredField("klazz"); // 2.4.7-
klazzF.setAccessible(true);
for (Object entry : entries) {
Object value = getValueM.invoke(entry);
toRemove.add((Class) klazzF.get(value));
}
}
Iterator<Class<?>> it = toRemove.iterator();
while (it.hasNext()) {
Class<?> klazz = it.next();
ClassLoader encounteredLoader = klazz.getClassLoader();
if (encounteredLoader != loader) {
it.remove();
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "ignoring {0} with loader {1}", new Object[] {klazz, /* do not hold from LogRecord */String.valueOf(encounteredLoader)});
}
}
}
LOGGER.log(Level.FINE, "cleaning up {0} associated with {1}", new Object[] {toRemove.toString(), loader.toString()});
for (Class<?> klazz : toRemove) {
removeM.invoke(map, klazz);
}
}
private static void cleanUpGlobalClassSet(@NonNull Class<?> clazz) throws Exception {
Class<?> classInfoC = Class.forName("org.codehaus.groovy.reflection.ClassInfo"); // or just ClassInfo.class, but unclear whether this will always be there
Field globalClassSetF = classInfoC.getDeclaredField("globalClassSet");
globalClassSetF.setAccessible(true);
Object globalClassSet = globalClassSetF.get(null);
try {
classInfoC.getDeclaredField("classRef");
return; // 2.4.8+, nothing to do here (classRef is weak anyway)
} catch (NoSuchFieldException x2) {} // 2.4.7-
// Cannot just call .values() since that returns a copy.
Field itemsF = globalClassSet.getClass().getDeclaredField("items");
itemsF.setAccessible(true);
Object items = itemsF.get(globalClassSet);
Method iteratorM = items.getClass().getMethod("iterator");
Field klazzF = classInfoC.getDeclaredField("klazz");
klazzF.setAccessible(true);
synchronized (items) {
Iterator<?> iterator = (Iterator) iteratorM.invoke(items);
while (iterator.hasNext()) {
Object classInfo = iterator.next();
if (classInfo == null) {
LOGGER.finer("JENKINS-41945: ignoring null ClassInfo from ManagedLinkedList.Iter.next");
continue;
}
if (klazzF.get(classInfo) == clazz) {
iterator.remove();
LOGGER.log(Level.FINER, "cleaning up {0} from GlobalClassSet", clazz.getName());
}
}
}
}
private static void cleanUpClassHelperCache(@NonNull Class<?> clazz) throws Exception {
Field classCacheF = Class.forName("org.codehaus.groovy.ast.ClassHelper$ClassHelperCache").getDeclaredField("classCache");
classCacheF.setAccessible(true);
Object classCache = classCacheF.get(null);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "cleaning up {0} from ClassHelperCache? {1}", new Object[] {clazz.getName(), classCache.getClass().getMethod("get", Object.class).invoke(classCache, clazz) != null});
}
classCache.getClass().getMethod("remove", Object.class).invoke(classCache, clazz);
}
/** @deprecated use {@link #evaluate(ClassLoader, Binding, TaskListener)} */
@Deprecated
public Object evaluate(ClassLoader loader, Binding binding) throws Exception {
return evaluate(loader, binding, null);
}
/**
* Runs the Groovy script, using the sandbox if so configured.
* @param loader a class loader for constructing the shell, such as {@link PluginManager#uberClassLoader} (will be augmented by {@link #getClasspath} if nonempty)
* @param binding Groovy variable bindings
* @param listener a way to print messages
* @return the result of evaluating script using {@link GroovyShell#evaluate(String)}
* @throws Exception in case of a general problem
* @throws RejectedAccessException in case of a sandbox issue
* @throws UnapprovedUsageException in case of a non-sandbox issue
* @throws UnapprovedClasspathException in case some unapproved classpath entries were requested
*/
@SuppressFBWarnings(value = "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED", justification = "Managed by GroovyShell.")
public Object evaluate(ClassLoader loader, Binding binding, @CheckForNull TaskListener listener) throws Exception {
if (!calledConfiguring) {
throw new IllegalStateException("you need to call configuring or a related method before using GroovyScript");
}
URLClassLoader urlcl = null;
ClassLoader memoryProtectedLoader = null;
List<ClasspathEntry> cp = getClasspath();
if (!cp.isEmpty()) {
List<URL> urlList = new ArrayList<>(cp.size());
for (ClasspathEntry entry : cp) {
ScriptApproval.get().using(entry);
urlList.add(entry.getURL());
}
loader = urlcl = new ClasspathURLClassLoader(urlList.toArray(new URL[urlList.size()]), loader);
}
boolean canDoCleanup = false;
try {
loader = GroovySandbox.createSecureClassLoader(loader);
Field loaderF = null;
try {
loaderF = GroovyShell.class.getDeclaredField("loader");
loaderF.setAccessible(true);
canDoCleanup = true;
} catch (NoSuchFieldException nsme) {
LOGGER.log(Level.FINE, "GroovyShell fields have changed, field loader no longer exists -- memory leak fixes won't work");
}
GroovyShell sh;
if (sandbox) {
CompilerConfiguration cc = GroovySandbox.createSecureCompilerConfiguration();
sh = new GroovyShell(loader, binding, cc);
if (canDoCleanup) {
memoryProtectedLoader = new CleanGroovyClassLoader(loader, cc);
loaderF.set(sh, memoryProtectedLoader);
}
return new GroovySandbox().withTaskListener(listener).runScript(sh, script);
} else {
sh = new GroovyShell(loader, binding);
if (canDoCleanup) {
memoryProtectedLoader = new CleanGroovyClassLoader(loader);
loaderF.set(sh, memoryProtectedLoader);
}
return sh.evaluate(ScriptApproval.get().using(script, GroovyLanguage.get()));
}
} finally {
try {
if (canDoCleanup) {
cleanUpLoader(memoryProtectedLoader, new HashSet<>(), new HashSet<>());
}
} catch (Exception x) {
LOGGER.log(Level.WARNING, "failed to clean up memory " , x);
}
if (urlcl != null) {
urlcl.close();
}
}
}
/**
* Both serves as a marker that we should clean classes from here, and tracks which classes were loaded.
*/
private static final class ClasspathURLClassLoader extends URLClassLoader {
private final Collection<Class<?>> loadedClasses = new ArrayList<>();
ClasspathURLClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
@Override protected Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> c = super.findClass(name);
synchronized (loadedClasses) {
loadedClasses.add(c);
}
return c;
}
}
/**
* Disables the weird and unreliable {@link groovy.lang.GroovyClassLoader.InnerLoader}.
* This is apparently only necessary when you are using class recompilation, which we are not.
* We want the {@linkplain Class#getClassLoader defining loader} of {@code *.groovy} to be this one.
* Otherwise the defining loader will be an {@code InnerLoader}, and not necessarily the same instance from load to load.
* @see GroovyClassLoader#getTimeStamp
*/
static final class CleanGroovyClassLoader extends GroovyClassLoader {
CleanGroovyClassLoader(ClassLoader loader, CompilerConfiguration config) {
super(loader, config);
}
CleanGroovyClassLoader(ClassLoader loader) {
super(loader);
}
@Override protected ClassCollector createCollector(CompilationUnit unit, SourceUnit su) {
// Super implementation is what creates the InnerLoader.
return new CleanClassCollector(unit, su);
}
private final class CleanClassCollector extends ClassCollector {
CleanClassCollector(CompilationUnit unit, SourceUnit su) {
// Cannot override {@code final cl} field so have to do it this way.
super(null, unit, su);
}
@Override public GroovyClassLoader getDefiningClassLoader() {
return CleanGroovyClassLoader.this;
}
}
}
@Extension public static final class DescriptorImpl extends Descriptor<SecureGroovyScript> {
@NonNull
@Override public String getDisplayName() {
return ""; // not intended to be displayed on its own
}
@SuppressFBWarnings(value = "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED", justification = "Irrelevant without SecurityManager.")
@RequirePOST
public FormValidation doCheckScript(@QueryParameter String value, @QueryParameter boolean sandbox, @QueryParameter String oldScript) {
FormValidation validationResult = GroovySandbox.checkScriptForCompilationErrors(value,
new GroovyClassLoader(Jenkins.get().getPluginManager().uberClassLoader));
if (validationResult.kind != FormValidation.Kind.OK) {
return validationResult;
}
return sandbox ? FormValidation.ok() : ScriptApproval.get().checking(value, GroovyLanguage.get(), !StringUtils.equals(oldScript, value));
}
}
}