Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

5.9 KB
Raw Blame
package opensuite.script;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

import opensuite.core.Debug;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.script.api.HttpRequest;
import opensuite.script.api.HttpRequestResponse;
import opensuite.script.api.HttpResponse;
import opensuite.script.api.Utilities;

/**
 * Compiles and runs the script library's scripts for the whole suite, one run
 * at a time, never on the caller's thread and within a time limit.
 */
public final class ScriptEngine {

    private static final long TIMEOUT_MILLIS = 10_000;
    private static final String STILL_RUNNING = "; it is still running, restart Open Suite to stop it";

    private final ScriptCompiler compiler;
    private final ScriptRunner runner;
    private final ReentrantLock oneAtATime = new ReentrantLock(true);
    private final AtomicBoolean warmed = new AtomicBoolean();
    private volatile Consumer<String> libraryOpener = name -> { };

    public ScriptEngine() { this(ToolProvider.getSystemJavaCompiler(), TIMEOUT_MILLIS); }

    /** @param compiler the Java compiler, or null when the runtime has none */
    public ScriptEngine(JavaCompiler compiler, long timeoutMillis) {
        this.compiler = new ScriptCompiler(compiler);
        this.runner = new ScriptRunner(timeoutMillis);
    }

    public ScriptCompiler compiler() { return compiler; }

    int abandonedThreads() { return runner.abandoned(); }

    /** Load the compiler in the background, once, so the first run does not wait for it. */
    public void warmUp() {
        if (!compiler.available() || !warmed.compareAndSet(false, true)) return;
        Thread t = new Thread(() -> compiler.compileCustomAction("int a = 0;"), "opensuite-script-warmup");
        t.setDaemon(true);
        t.start();
    }

    /** How the script library shows a script by name; set by the tool that holds the library. */
    public void setLibraryOpener(Consumer<String> opener) { libraryOpener = opener; }

    public void openInLibrary(String name) { libraryOpener.accept(name); }

    /**
     * Run a custom action on copies of a request and its response. Blocks until
     * the run ends, so call it off the event thread. It never throws.
     *
     * @param response  the response beside the request, or null
     * @param clipboard where the script's clipboard text goes
     * @param stop      set to end this run; a stop given before the run starts is kept
     */
    public RunResult runCustomAction(String source, HttpService svc, HttpMessage request, HttpMessage response,
                                     Consumer<String> clipboard, AtomicBoolean stop) {
        try {
            return run(source, svc, request, response, clipboard, stop);
        } catch (RuntimeException | LinkageError e) {
            Debug.error("script engine failed", e);
            return RunResult.failed(RunResult.Status.FAILED, "internal error: " + describe(e, null));
        }
    }

    private RunResult run(String source, HttpService svc, HttpMessage request, HttpMessage response,
                          Consumer<String> clipboard, AtomicBoolean stop) {
        oneAtATime.lock();
        try {
            if (runner.abandoned() >= ScriptRunner.MAX_ABANDONED) {
                return RunResult.failed(RunResult.Status.FAILED, ScriptRunner.MAX_ABANDONED
                        + " scripts are still running and could not be stopped; restart Open Suite to stop them");
            }
            if (stop.get()) return RunResult.failed(RunResult.Status.STOPPED, "stopped");
            Compiled c = compiler.compileCustomAction(source);
            if (!c.ok()) return RunResult.failed(RunResult.Status.FAILED, String.join("\n", c.errors()));
            if (stop.get()) return RunResult.failed(RunResult.Status.STOPPED, "stopped");

            HttpRequestResponse rr = new HttpRequestResponse(HttpRequest.of(svc, request),
                    response == null ? null : HttpResponse.of(response));
            Utilities utilities = new Utilities(clipboard);
            Throwable[] thrown = new Throwable[1];
            int abandonedBefore = runner.abandoned();
            long start = System.nanoTime();
            ScriptRunner.Outcome outcome = runner.run(() -> {
                try {
                    c.fn().action(rr, utilities);
                } catch (Throwable t) {
                    thrown[0] = t;
                }
            }, stop::get);
            long millis = (System.nanoTime() - start) / 1_000_000;
            String still = runner.abandoned() > abandonedBefore ? STILL_RUNNING : "";

            RunResult.Status status = switch (outcome) {
                case DONE -> thrown[0] == null ? RunResult.Status.OK : RunResult.Status.FAILED;
                case TIMEOUT -> RunResult.Status.TIMEOUT;
                case STOPPED -> RunResult.Status.STOPPED;
            };
            String error = switch (outcome) {
                case DONE -> thrown[0] == null ? null : describe(thrown[0], c.className());
                case TIMEOUT -> "stopped after " + Math.max(1, (runner.timeoutMillis() + 999) / 1000) + " s (time limit)" + still;
                case STOPPED -> "stopped" + still;
            };
            HttpMessage newRequest = status == RunResult.Status.OK && rr.replacement() != null ? rr.replacement().message() : null;
            return new RunResult(status, utilities.logLines(), utilities.logCut(), error, millis, newRequest);
        } finally {
            oneAtATime.unlock();
        }
    }

    private static String describe(Throwable t, String className) {
        int line = ScriptCompiler.scriptLine(className, t.getStackTrace());
        return t.getClass().getSimpleName() + (t.getMessage() == null ? "" : ": " + t.getMessage())
                + (line > 0 ? " at line " + line : "");
    }
}