Search in sources :

Example 1 with PrintStreamInstanceWhitelist

use of hudson.plugins.emailext.groovy.sandbox.PrintStreamInstanceWhitelist in project email-ext-plugin by jenkinsci.

the class AbstractScriptTrigger method evaluate.

private Object evaluate(AbstractBuild<?, ?> build, TaskListener listener) throws IOException {
    ClassLoader loader = Jenkins.get().getPluginManager().uberClassLoader;
    JenkinsLocationConfiguration configuration = JenkinsLocationConfiguration.get();
    assert configuration != null;
    URLClassLoader urlcl = null;
    List<ClasspathEntry> cp = secureTriggerScript.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 URLClassLoader(urlList.toArray(new URL[0]), loader);
    }
    try {
        loader = GroovySandbox.createSecureClassLoader(loader);
        CompilerConfiguration cc;
        if (secureTriggerScript.isSandbox()) {
            cc = GroovySandbox.createSecureCompilerConfiguration();
        } else {
            cc = new CompilerConfiguration();
        }
        cc.addCompilationCustomizers(new ImportCustomizer().addStarImports("jenkins", "jenkins.model", "hudson", "hudson.model"));
        Binding binding = new Binding();
        binding.setVariable("build", build);
        binding.setVariable("project", build.getParent());
        binding.setVariable("rooturl", configuration.getUrl());
        PrintStream logger = listener.getLogger();
        binding.setVariable("out", logger);
        GroovyShell shell = new GroovyShell(loader, binding, cc);
        if (secureTriggerScript.isSandbox()) {
            try {
                return GroovySandbox.run(shell, secureTriggerScript.getScript(), new ProxyWhitelist(Whitelist.all(), new PrintStreamInstanceWhitelist(logger)));
            } catch (RejectedAccessException x) {
                throw ScriptApproval.get().accessRejected(x, ApprovalContext.create());
            }
        } else {
            return shell.evaluate(ScriptApproval.get().using(secureTriggerScript.getScript(), GroovyLanguage.get()));
        }
    } finally {
        if (urlcl != null) {
            urlcl.close();
        }
    }
}
Also used : Binding(groovy.lang.Binding) PrintStream(java.io.PrintStream) PrintStreamInstanceWhitelist(hudson.plugins.emailext.groovy.sandbox.PrintStreamInstanceWhitelist) JenkinsLocationConfiguration(jenkins.model.JenkinsLocationConfiguration) RejectedAccessException(org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException) ArrayList(java.util.ArrayList) URL(java.net.URL) GroovyShell(groovy.lang.GroovyShell) ProxyWhitelist(org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.ProxyWhitelist) URLClassLoader(java.net.URLClassLoader) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) URLClassLoader(java.net.URLClassLoader) ImportCustomizer(org.codehaus.groovy.control.customizers.ImportCustomizer) ClasspathEntry(org.jenkinsci.plugins.scriptsecurity.scripts.ClasspathEntry)

Example 2 with PrintStreamInstanceWhitelist

use of hudson.plugins.emailext.groovy.sandbox.PrintStreamInstanceWhitelist in project email-ext-plugin by jenkinsci.

the class ExtendedEmailPublisher method executeScript.

private boolean executeScript(String rawScript, String scriptName, ExtendedEmailPublisherContext context, MimeMessage msg, Session session, Transport transport) {
    boolean cancel = false;
    String script = ContentBuilder.transformText(rawScript, context, getRuntimeMacros(context));
    if (StringUtils.isNotBlank(script)) {
        TaskListener listener = context.getListener();
        PrintStream logger = listener.getLogger();
        debug(logger, "Executing %s script", scriptName);
        Binding binding = new Binding();
        binding.setVariable("build", context.getBuild());
        binding.setVariable("run", context.getRun());
        binding.setVariable("msg", msg);
        Properties props = null;
        if (session != null) {
            props = session.getProperties();
            binding.setVariable("props", props);
        }
        if (transport != null) {
            // Can't really figure out what to whitelist in this object
            binding.setVariable("transport", transport);
        }
        binding.setVariable("listener", listener);
        binding.setVariable("logger", logger);
        binding.setVariable("cancel", cancel);
        binding.setVariable("trigger", context.getTrigger());
        // TODO static whitelist?
        binding.setVariable("triggered", ImmutableMultimap.copyOf(context.getTriggered()));
        StringWriter out = new StringWriter();
        PrintWriter pw = new PrintWriter(out);
        try {
            ClassLoader cl = expandClasspath(context, Jenkins.get().getPluginManager().uberClassLoader);
            if (AbstractEvalContent.isApprovedScript(script, GroovyLanguage.get()) || !Jenkins.get().isUseSecurity()) {
                GroovyShell shell = new GroovyShell(cl, binding, getCompilerConfiguration(false));
                shell.parse(script).run();
                cancel = (Boolean) shell.getVariable("cancel");
            } else {
                GroovyShell shell = new GroovyShell(cl, binding, getCompilerConfiguration(true));
                try {
                    new GroovySandbox().withWhitelist(new ProxyWhitelist(Whitelist.all(), new MimeMessageInstanceWhitelist(msg), new PropertiesInstanceWhitelist(props), new TaskListenerInstanceWhitelist(listener), new PrintStreamInstanceWhitelist(logger), new EmailExtScriptTokenMacroWhitelist())).runScript(shell, script);
                    cancel = (Boolean) shell.getVariable("cancel");
                } catch (RejectedAccessException x) {
                    throw ScriptApproval.get().accessRejected(x, ApprovalContext.create());
                }
            }
            debug(logger, "%s script set cancel to %b", StringUtils.capitalize(scriptName), cancel);
        } catch (SecurityException e) {
            logger.println(StringUtils.capitalize(scriptName) + " script tried to access secured objects: " + e.getMessage());
            throw e;
        } catch (Throwable t) {
            Functions.printStackTrace(t, pw);
            logger.println(out);
        // should we cancel the sending of the email???
        }
        debug(logger, out.toString());
    }
    return !cancel;
}
Also used : Binding(groovy.lang.Binding) PrintStream(java.io.PrintStream) PropertiesInstanceWhitelist(hudson.plugins.emailext.groovy.sandbox.PropertiesInstanceWhitelist) PrintStreamInstanceWhitelist(hudson.plugins.emailext.groovy.sandbox.PrintStreamInstanceWhitelist) RejectedAccessException(org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException) Properties(java.util.Properties) GroovySandbox(org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox) EmailExtScriptTokenMacroWhitelist(hudson.plugins.emailext.groovy.sandbox.EmailExtScriptTokenMacroWhitelist) GroovyShell(groovy.lang.GroovyShell) ProxyWhitelist(org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.ProxyWhitelist) TaskListenerInstanceWhitelist(hudson.plugins.emailext.groovy.sandbox.TaskListenerInstanceWhitelist) StringWriter(java.io.StringWriter) TaskListener(hudson.model.TaskListener) MimeMessageInstanceWhitelist(hudson.plugins.emailext.groovy.sandbox.MimeMessageInstanceWhitelist) GroovyClassLoader(groovy.lang.GroovyClassLoader) PrintWriter(java.io.PrintWriter)

Example 3 with PrintStreamInstanceWhitelist

use of hudson.plugins.emailext.groovy.sandbox.PrintStreamInstanceWhitelist in project email-ext-plugin by jenkinsci.

the class ScriptContent method executeScript.

/**
 * Executes a script and returns the last value as a String
 *
 * @param build        the build to act on
 * @param scriptStream the script input stream
 * @return a String containing the toString of the last item in the script
 */
private String executeScript(Run<?, ?> build, FilePath workspace, TaskListener listener, InputStream scriptStream) throws IOException {
    String result = "";
    Map<String, Object> binding = new HashMap<>();
    ExtendedEmailPublisherDescriptor descriptor = Jenkins.get().getDescriptorByType(ExtendedEmailPublisherDescriptor.class);
    Item parent = build.getParent();
    binding.put("build", build);
    binding.put("it", new ScriptContentBuildWrapper(build));
    binding.put("project", parent);
    binding.put("rooturl", descriptor.getHudsonUrl());
    binding.put("workspace", workspace);
    PrintStream logger = listener.getLogger();
    binding.put("logger", logger);
    String scriptContent = IOUtils.toString(scriptStream, descriptor.getCharset());
    if (scriptStream instanceof UserProvidedContentInputStream) {
        ScriptApproval.get().configuring(scriptContent, GroovyLanguage.get(), ApprovalContext.create().withItem(parent));
    }
    if (scriptStream instanceof UserProvidedContentInputStream && !AbstractEvalContent.isApprovedScript(scriptContent, GroovyLanguage.get())) {
        // Unapproved script, run it in the sandbox
        GroovyShell shell = createEngine(descriptor, binding, true);
        Object res = GroovySandbox.run(shell, scriptContent, new ProxyWhitelist(Whitelist.all(), new PrintStreamInstanceWhitelist(logger), new EmailExtScriptTokenMacroWhitelist()));
        if (res != null) {
            result = res.toString();
        }
    } else {
        if (scriptStream instanceof UserProvidedContentInputStream) {
            ScriptApproval.get().using(scriptContent, GroovyLanguage.get());
        }
        // Pre approved script, so run as is
        GroovyShell shell = createEngine(descriptor, binding, false);
        Script script = shell.parse(scriptContent);
        Object res = script.run();
        if (res != null) {
            result = res.toString();
        }
    }
    return result;
}
Also used : PrintStream(java.io.PrintStream) Script(groovy.lang.Script) PrintStreamInstanceWhitelist(hudson.plugins.emailext.groovy.sandbox.PrintStreamInstanceWhitelist) ExtendedEmailPublisherDescriptor(hudson.plugins.emailext.ExtendedEmailPublisherDescriptor) HashMap(java.util.HashMap) EmailExtScriptTokenMacroWhitelist(hudson.plugins.emailext.groovy.sandbox.EmailExtScriptTokenMacroWhitelist) GroovyShell(groovy.lang.GroovyShell) ProxyWhitelist(org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.ProxyWhitelist) Item(hudson.model.Item)

Example 4 with PrintStreamInstanceWhitelist

use of hudson.plugins.emailext.groovy.sandbox.PrintStreamInstanceWhitelist in project email-ext-plugin by jenkinsci.

the class ScriptContent method renderTemplate.

/**
 * Renders the template using a SimpleTemplateEngine
 *
 * @param build the build to act on
 * @param templateStream the template file stream
 * @return the rendered template content
 */
private String renderTemplate(Run<?, ?> build, FilePath workspace, TaskListener listener, InputStream templateStream) {
    String result;
    final Map<String, Object> binding = new HashMap<>();
    ExtendedEmailPublisherDescriptor descriptor = Jenkins.get().getDescriptorByType(ExtendedEmailPublisherDescriptor.class);
    binding.put("build", build);
    binding.put("listener", listener);
    binding.put("it", new ScriptContentBuildWrapper(build));
    binding.put("rooturl", descriptor.getHudsonUrl());
    binding.put("project", build.getParent());
    binding.put("workspace", workspace);
    try {
        String text = IOUtils.toString(templateStream, StandardCharsets.UTF_8);
        boolean approvedScript = false;
        if (templateStream instanceof UserProvidedContentInputStream && !AbstractEvalContent.isApprovedScript(text, GroovyLanguage.get())) {
            approvedScript = false;
            ScriptApproval.get().configuring(text, GroovyLanguage.get(), ApprovalContext.create().withItem(build.getParent()));
        } else {
            approvedScript = true;
        }
        // we add the binding to the SimpleTemplateEngine instead of the shell
        GroovyShell shell = createEngine(descriptor, Collections.emptyMap(), !approvedScript);
        SimpleTemplateEngine engine = new SimpleTemplateEngine(shell);
        Template tmpl;
        synchronized (templateCache) {
            Reference<Template> templateR = templateCache.get(text);
            tmpl = templateR == null ? null : templateR.get();
            if (tmpl == null) {
                tmpl = engine.createTemplate(text);
                templateCache.put(text, new SoftReference<>(tmpl));
            }
        }
        final Template tmplR = tmpl;
        if (approvedScript) {
            // The script has been approved by an admin, so run it as is
            result = tmplR.make(binding).toString();
        } else {
            // unapproved script, so run in sandbox
            StaticProxyInstanceWhitelist whitelist = new StaticProxyInstanceWhitelist(build, "templates-instances.whitelist");
            result = GroovySandbox.runInSandbox(() -> {
                // TODO there is a PrintWriter instance created in make and bound to out
                return tmplR.make(binding).toString();
            }, new ProxyWhitelist(Whitelist.all(), new TaskListenerInstanceWhitelist(listener), new PrintStreamInstanceWhitelist(listener.getLogger()), new EmailExtScriptTokenMacroWhitelist(), whitelist));
        }
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        Functions.printStackTrace(e, pw);
        result = "Exception raised during template rendering: " + e.getMessage() + "\n\n" + sw;
    }
    return result;
}
Also used : PrintStreamInstanceWhitelist(hudson.plugins.emailext.groovy.sandbox.PrintStreamInstanceWhitelist) ExtendedEmailPublisherDescriptor(hudson.plugins.emailext.ExtendedEmailPublisherDescriptor) HashMap(java.util.HashMap) EmailExtScriptTokenMacroWhitelist(hudson.plugins.emailext.groovy.sandbox.EmailExtScriptTokenMacroWhitelist) GroovyShell(groovy.lang.GroovyShell) ProxyWhitelist(org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.ProxyWhitelist) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) MacroEvaluationException(org.jenkinsci.plugins.tokenmacro.MacroEvaluationException) Template(groovy.text.Template) TaskListenerInstanceWhitelist(hudson.plugins.emailext.groovy.sandbox.TaskListenerInstanceWhitelist) StringWriter(java.io.StringWriter) StaticProxyInstanceWhitelist(hudson.plugins.emailext.groovy.sandbox.StaticProxyInstanceWhitelist) SimpleTemplateEngine(groovy.text.SimpleTemplateEngine) PrintWriter(java.io.PrintWriter)

Aggregations

GroovyShell (groovy.lang.GroovyShell)4 PrintStreamInstanceWhitelist (hudson.plugins.emailext.groovy.sandbox.PrintStreamInstanceWhitelist)4 ProxyWhitelist (org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.ProxyWhitelist)4 EmailExtScriptTokenMacroWhitelist (hudson.plugins.emailext.groovy.sandbox.EmailExtScriptTokenMacroWhitelist)3 PrintStream (java.io.PrintStream)3 Binding (groovy.lang.Binding)2 ExtendedEmailPublisherDescriptor (hudson.plugins.emailext.ExtendedEmailPublisherDescriptor)2 TaskListenerInstanceWhitelist (hudson.plugins.emailext.groovy.sandbox.TaskListenerInstanceWhitelist)2 PrintWriter (java.io.PrintWriter)2 StringWriter (java.io.StringWriter)2 HashMap (java.util.HashMap)2 RejectedAccessException (org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException)2 GroovyClassLoader (groovy.lang.GroovyClassLoader)1 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)1 Script (groovy.lang.Script)1 SimpleTemplateEngine (groovy.text.SimpleTemplateEngine)1 Template (groovy.text.Template)1 Item (hudson.model.Item)1 TaskListener (hudson.model.TaskListener)1 MimeMessageInstanceWhitelist (hudson.plugins.emailext.groovy.sandbox.MimeMessageInstanceWhitelist)1