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.

10.1 KB
Raw Blame
package opensuite.script;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.lang.classfile.ClassFile;
import java.lang.classfile.CodeElement;
import java.lang.classfile.MethodModel;
import java.lang.classfile.instruction.InvokeInstruction;
import java.lang.classfile.instruction.LineNumber;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;

import opensuite.core.Bytes;

/**
 * Compiles a script body in memory with the JDK's compiler. The body is
 * wrapped in a generated class with the script API imported, errors are given
 * at the script's own lines, and results are cached by the source's SHA-256.
 * Each script is loaded by a class loader of its own, so a replaced one can
 * be collected.
 */
public final class ScriptCompiler {

    private static final String PACKAGE = "opensuite.script.gen";
    private static final String HEADER_TEMPLATE = "package " + PACKAGE + ";\n"
            + "import opensuite.script.api.*;\n"
            + "import opensuite.script.CustomActionFn;\n"
            + "import java.util.*;\n"
            + "import java.nio.charset.*;\n"
            + "public final class %s implements CustomActionFn {\n"
            + "public void action(HttpRequestResponse requestResponse, Utilities utilities) throws Exception {\n";
    /** Lines the generated class has before the script's first line. */
    static final int HEADER_LINES = (int) HEADER_TEMPLATE.chars().filter(c -> c == '\n').count();
    private static final int CACHE_SIZE = 32;
    static final String EXIT_MESSAGE = "a script may not exit Open Suite (System.exit / Runtime.halt)";
    static final String NO_COMPILER = "no Java compiler is available in this runtime";

    private final JavaCompiler compiler;
    private StandardJavaFileManager files;   // one for every compile, under the compiler's lock
    private final Map<String, Compiled> cache = new LinkedHashMap<>(16, 0.75f, true) {
        @Override protected boolean removeEldestEntry(Map.Entry<String, Compiled> eldest) { return size() > CACHE_SIZE; }
    };

    /** @param compiler the JDK compiler, or null when the runtime has none */
    public ScriptCompiler(JavaCompiler compiler) { this.compiler = compiler; }

    public boolean available() { return compiler != null; }

    /** Compile a custom action, or take it from the cache. */
    public Compiled compileCustomAction(String source) {
        String key = sha256(source);
        synchronized (cache) {
            Compiled hit = cache.get(key);
            if (hit != null) return hit;
        }
        Compiled c = compile(source, key);
        synchronized (cache) { cache.put(key, c); }
        return c;
    }

    /** The script line of the first frame of {@code className} in a stack trace, or -1. */
    static int scriptLine(String className, StackTraceElement[] trace) {
        if (className == null) return -1;
        for (StackTraceElement e : trace) {
            String c = e.getClassName();
            if ((c.equals(className) || c.startsWith(className + "$")) && e.getLineNumber() > 0) {
                return Math.max(1, e.getLineNumber() - HEADER_LINES);
            }
        }
        return -1;
    }

    private Compiled compile(String source, String key) {
        if (compiler == null) return new Compiled(null, null, List.of(NO_COMPILER));
        String className = PACKAGE + ".S" + key.substring(0, 16);
        String full = String.format(HEADER_TEMPLATE, className.substring(PACKAGE.length() + 1)) + source + "\n}}\n";
        int scriptLines = Math.max(1, (int) source.lines().count());

        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
        Map<String, ByteArrayOutputStream> classes = new HashMap<>();
        boolean ok;
        synchronized (compiler) {
            if (files == null) files = compiler.getStandardFileManager(null, Locale.ROOT, StandardCharsets.UTF_8);
            List<String> options = List.of("-g", "-proc:none", "-classpath", System.getProperty("java.class.path", ""));
            ok = compiler.getTask(new StringWriter(), new MemoryFiles(files, classes), diagnostics, options, null,
                    List.of(new Source(className, full))).call();
        }
        if (!ok) {
            Set<String> errors = new LinkedHashSet<>();
            for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
                if (d.getKind() != Diagnostic.Kind.ERROR) continue;
                long line = Math.max(1, Math.min(scriptLines, d.getLineNumber() - HEADER_LINES));
                errors.add("line " + line + ": " + summary(d.getMessage(Locale.ROOT)));
            }
            if (errors.isEmpty()) errors.add("line 1: the script did not compile");
            return new Compiled(null, null, List.copyOf(errors));
        }
        int exitAt = exitCall(classes.values());
        if (exitAt > 0) {
            return new Compiled(null, null, List.of("line " + Math.max(1, Math.min(scriptLines, exitAt - HEADER_LINES)) + ": " + EXIT_MESSAGE));
        }
        try {
            ClassLoader loader = new MemoryLoader(classes, ScriptCompiler.class.getClassLoader());
            CustomActionFn fn = (CustomActionFn) loader.loadClass(className).getDeclaredConstructor().newInstance();
            return new Compiled(fn, className, List.of());
        } catch (ReflectiveOperationException | LinkageError e) {
            return new Compiled(null, null, List.of("line 1: the script could not be loaded: " + e));
        }
    }

    /**
     * The generated line of a call that would end the whole program
     * (System.exit, Runtime.exit or Runtime.halt), or 0. Read from the
     * compiled code, so a comment or a string that names them does not count.
     */
    private static int exitCall(Iterable<ByteArrayOutputStream> classes) {
        for (ByteArrayOutputStream b : classes) {
            for (MethodModel m : ClassFile.of().parse(b.toByteArray()).methods()) {
                if (m.code().isEmpty()) continue;
                int line = 0;
                for (CodeElement e : m.code().get()) {
                    if (e instanceof LineNumber ln) line = ln.line();
                    if (e instanceof InvokeInstruction call) {
                        String owner = call.owner().asInternalName(), name = call.name().stringValue();
                        if (owner.equals("java/lang/System") && name.equals("exit")
                                || owner.equals("java/lang/Runtime") && (name.equals("exit") || name.equals("halt"))) {
                            return Math.max(1, line);
                        }
                    }
                }
            }
        }
        return 0;
    }

    /** javac's first line, with the name it could not find when it gives one. */
    private static String summary(String message) {
        List<String> lines = message.lines().toList();
        String first = lines.isEmpty() ? "error" : lines.get(0).strip();
        for (String l : lines) {
            String t = l.strip();
            if (t.startsWith("symbol:")) return first + " (" + t.substring(7).strip().replace("java.lang.", "") + ")";
        }
        return first;
    }

    private static String sha256(String s) {
        try {
            return Bytes.toHex(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
    }

    /** The generated source, held in memory. */
    private static final class Source extends SimpleJavaFileObject {
        private final String code;
        Source(String className, String code) {
            super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
            this.code = code;
        }
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; }
    }

    /** Class files written to memory instead of disk. */
    private static final class MemoryFiles extends ForwardingJavaFileManager<JavaFileManager> {
        private final Map<String, ByteArrayOutputStream> classes;
        MemoryFiles(JavaFileManager standard, Map<String, ByteArrayOutputStream> classes) {
            super(standard);
            this.classes = classes;
        }
        @Override public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) {
            return new SimpleJavaFileObject(URI.create("mem:///" + className.replace('.', '/') + kind.extension), kind) {
                @Override public OutputStream openOutputStream() {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    classes.put(className, out);
                    return out;
                }
            };
        }
        // The standard manager is shared by every compile; this wrapper must not close it.
        @Override public void close() { }
    }

    /** Loads one script's classes; everything else comes from the suite. */
    private static final class MemoryLoader extends ClassLoader {
        private final Map<String, ByteArrayOutputStream> classes;
        MemoryLoader(Map<String, ByteArrayOutputStream> classes, ClassLoader parent) {
            super(parent);
            this.classes = classes;
        }
        @Override protected Class<?> findClass(String name) throws ClassNotFoundException {
            ByteArrayOutputStream b = classes.get(name);
            if (b == null) throw new ClassNotFoundException(name);
            byte[] bytes = b.toByteArray();
            return defineClass(name, bytes, 0, bytes.length);
        }
    }
}