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.

26.6 KB
Raw Blame
package opensuite.ui;

import opensuite.comparer.ComparerTool;
import opensuite.core.*;
import opensuite.decoder.DecoderTool;
import opensuite.intruder.IntruderTool;
import opensuite.organizer.OrganizerItem;
import opensuite.repeater.RepeaterTool;
import opensuite.session.Cookie;
import opensuite.session.Extraction;
import opensuite.session.Macro;
import opensuite.session.SessionRule;
import opensuite.target.TargetTool;
import opensuite.testkit.Expect;
import opensuite.testkit.Harness;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InvalidClassException;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * The single-file project format (issue #37): a bound session records every
 * exchange to the one file as it arrives, updates and removes are kept, the file
 * reopens with the whole session, and a crash mid-write costs at most the last
 * record rather than the project.
 */
public final class ProjectFileTest {

    private static final HttpService SVC = new HttpService("example.com", 443, true);

    private static LogEntry entry(String path, int bodyLen) {
        LogEntry e = new LogEntry("proxy", SVC,
                new HttpMessage(Bytes.bytes("GET " + path + " HTTP/1.1\r\nHost: example.com\r\n\r\n")));
        e.setResponse(new HttpMessage(Bytes.bytes(
                "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n" + "x".repeat(bodyLen))));
        return e;
    }

    private static File tmp() throws Exception {
        File f = Files.createTempFile("opensuite-projfile", ".osuite").toFile();
        f.delete();   // bindNew/open create it fresh
        f.deleteOnExit();   // and the test run leaves nothing behind
        return f;
    }

    private interface ThrowingAction {
        void run() throws Exception;
    }

    private static byte[] serialize(Object o) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(o);
        }
        return baos.toByteArray();
    }

    private static void assertRejected(ThrowingAction action, String message) throws Exception {
        boolean rejected = false;
        try {
            action.run();
        } catch (InvalidClassException expected) {
            rejected = true;
        }
        Expect.isTrue(rejected, message);
    }

    private static Map<String, ToolModule> registerTools(SuiteContext ctx) {
        TargetTool target = new TargetTool();
        target.init(ctx);
        ComparerTool comparer = new ComparerTool();
        DecoderTool decoder = new DecoderTool();
        IntruderTool intruder = new IntruderTool(ctx);
        RepeaterTool repeater = new RepeaterTool();
        repeater.init(ctx);
        repeater.tabs();
        ctx.registerTool(target);
        ctx.registerTool(comparer);
        ctx.registerTool(decoder);
        ctx.registerTool(intruder);
        ctx.registerTool(repeater);
        Map<String, ToolModule> byName = new LinkedHashMap<>();
        for (ToolModule t : ctx.tools()) {
            byName.put(t.name(), t);
        }
        return byName;
    }

    private static void assertSessionStatePreserved(
            SuiteContext restored, Map<String, ToolModule> tools, int expectedExcludes, String prefix) {
        Expect.equal(restored.scope().include().size(), 1, prefix + " scope include preserved");
        Expect.equal(restored.scope().exclude().size(), expectedExcludes, prefix + " scope exclude preserved");
        Expect.equal(restored.settings().get("filter.test.key", ""), "ok", prefix + " settings preserved");
        Expect.equal(restored.sessions().jar().size(), 1, prefix + " cookie jar preserved");
        // The manager starts with a rule of its own, so the one that was saved is looked for by name.
        Expect.equal(restored.sessions().rules().stream().filter(r -> "r1".equals(r.name)).count(), 1L,
                prefix + " session rule preserved");
        Expect.equal(restored.sessions().macros().size(), 1, prefix + " macro preserved");
        Expect.equal(restored.organizer().all().size(), 1, prefix + " organizer item preserved");
        Expect.equal(restored.issues().size(), 1, prefix + " issue preserved");
        Expect.equal(restored.issues().get(0).locationCount(), 2, prefix + " issue locations preserved");
        Expect.equal(restored.tasks().size(), 1, prefix + " scan task snapshot preserved");
        Expect.notNull(tools.get("target").saveState(), prefix + " target state restored");
        Expect.notNull(tools.get("comparer").saveState(), prefix + " comparer state restored");
        Expect.equal(tools.get("decoder").saveState(), "decoded-input", prefix + " decoder state restored");
        // Intruder saves a row per tab; the marked request is the third field of each.
        Object intruderState = tools.get("intruder").saveState();
        String marked = intruderState instanceof java.util.List<?> rows && !rows.isEmpty()
                && rows.get(rows.size() - 1) instanceof String[] row && row.length > 2 ? row[2] : String.valueOf(intruderState);
        Expect.equal(marked.replace("\r\n", "\n"),
                "GET /?x=§1§ HTTP/1.1\nHost: example.com\n\n", prefix + " intruder state restored");
        Expect.notNull(tools.get("repeater").saveState(), prefix + " repeater tab state restored");
    }

    /** Wait for the frame offloader to spill every payload, as the disk tests do. */
    private static void awaitWsOffload(SuiteContext ctx) {
        long deadline = System.currentTimeMillis() + 5000;
        while (ctx.wsStore().residentBytes() > 0 && System.currentTimeMillis() < deadline) {
            try { Thread.sleep(5); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; }
        }
    }

    public void run() {
        Harness.suite("single-file project");

        Harness.test("a bound session records to the file and reopens with everything", () -> {
            try {
                SuiteContext ctx = new SuiteContext();
                File f = tmp();
                StateIO.bindNew(ctx, f, StateIO.SaveOptions.fromSettings(ctx));
                LogEntry a = entry("/a", 1000), b = entry("/b/c?q=1", 2000), c = entry("/d.js", 500);
                byte[] bodyA = a.response().raw().clone();
                byte[] bodyB = b.request().raw().clone();
                ctx.store().add(a); ctx.store().add(b); ctx.store().add(c);
                ctx.alert("note", "state change");   // some session state to snapshot
                StateIO.save(ctx, f);                 // cheap snapshot append
                ctx.store().closeStore();             // drains the index records and fsyncs

                SuiteContext back = new SuiteContext();
                int n = StateIO.restore(back, f);
                Expect.equal(n, 3, "all three entries reopen");
                List<LogEntry> all = back.store().all();
                Expect.equal(all.get(0).pathAndQuery(), "/a", "order and metadata preserved");
                Expect.equal(all.get(1).pathAndQuery(), "/b/c?q=1", "second entry preserved");
                Expect.equal(all.get(2).fileExtension(), "js", "extension from the reopened index");
                Expect.isTrue(Arrays.equals(all.get(0).response().raw(), bodyA), "response bytes reopen exactly");
                Expect.isTrue(Arrays.equals(all.get(1).request().raw(), bodyB), "request bytes reopen exactly");
                back.store().closeStore();
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("another project's history is read for a comparison, and a site map deletion is kept", () -> {
            try {
                SuiteContext ctx = new SuiteContext();
                File f = tmp();
                StateIO.bindNew(ctx, f, StateIO.SaveOptions.fromSettings(ctx));
                LogEntry a = entry("/same", 300), b = entry("/changed", 300), c = entry("/gone", 300);
                ctx.store().add(a); ctx.store().add(b); ctx.store().add(c);
                c.setOffSiteMap(true);
                ctx.store().updated(c);
                StateIO.save(ctx, f);
                ctx.store().closeStore();

                List<java.io.Closeable> keep = new ArrayList<>();
                List<LogEntry> other = StateIO.readHistory(f, keep::add);
                Expect.equal(other.size(), 3, "the other project's items are read");
                Expect.isTrue(other.get(0).response().raw().length > 300, "with their bodies, from the file");
                LogEntry gone = null;
                for (LogEntry e : other) if (e.pathAndQuery().equals("/gone")) gone = e;
                Expect.isTrue(gone != null && gone.offSiteMap(), "an item deleted from the site map is still marked so");

                // Measured against a current map where one answer differs and one item is missing.
                LogEntry same = entry("/same", 300), changed = entry("/changed", 900);
                opensuite.target.SiteMapDiff.Options o = new opensuite.target.SiteMapDiff.Options();
                int[] n = opensuite.target.SiteMapDiff.counts(opensuite.target.SiteMapDiff.compare(List.of(same, changed), other, o));
                Expect.isTrue(n[opensuite.target.SiteMapDiff.State.MODIFIED.ordinal()] == 1, "one item differs");
                Expect.isTrue(n[opensuite.target.SiteMapDiff.State.ADDED.ordinal()] == 1, "one item is only in the file");
                for (java.io.Closeable k : keep) k.close();
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("an update and a remove survive a reopen", () -> {
            try {
                SuiteContext ctx = new SuiteContext();
                File f = tmp();
                StateIO.bindNew(ctx, f, StateIO.SaveOptions.fromSettings(ctx));
                LogEntry a = entry("/keep", 400), b = entry("/edit", 400), c = entry("/drop", 400);
                ctx.store().add(a); ctx.store().add(b); ctx.store().add(c);
                b.setNotes("look here");
                ctx.store().updated(b);
                ctx.store().remove(c);
                ctx.store().closeStore();

                SuiteContext back = new SuiteContext();
                StateIO.restore(back, f);
                List<LogEntry> all = back.store().all();
                Expect.equal(all.size(), 2, "the removed entry is gone");
                boolean sawEdit = false;
                for (LogEntry e : all) {
                    Expect.isFalse(e.pathAndQuery().equals("/drop"), "the dropped entry does not come back");
                    if (e.pathAndQuery().equals("/edit")) { sawEdit = true; Expect.equal(e.notes(), "look here", "the edit is kept"); }
                }
                Expect.isTrue(sawEdit, "the edited entry is present");
                back.store().closeStore();
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("websocket frames round-trip through a save and reopen", () -> {
            try {
                SuiteContext ctx = new SuiteContext();
                File f = tmp();
                StateIO.bindNew(ctx, f, StateIO.SaveOptions.fromSettings(ctx));
                ctx.wsStore().add(new WebSocketMessage(7, "example.com",
                        WebSocketMessage.Direction.S2C, WebSocketMessage.Op.TEXT,
                        "server frame one".getBytes(StandardCharsets.UTF_8), false));
                ctx.wsStore().add(new WebSocketMessage(7, "example.com",
                        WebSocketMessage.Direction.C2S, WebSocketMessage.Op.TEXT,
                        "client frame two".getBytes(StandardCharsets.UTF_8), true));
                awaitWsOffload(ctx);                // the payloads leave the heap
                StateIO.save(ctx, f);               // cheap snapshot append
                ctx.wsStore().closeStore();         // drains the frame records and fsyncs
                ctx.store().closeStore();

                SuiteContext back = new SuiteContext();
                StateIO.restore(back, f);
                Expect.equal(back.wsStore().size(), 2, "both frames reopen");
                List<WebSocketMessage> frames = back.wsStore().all();
                Expect.equal(frames.get(0).text(), "server frame one", "order and payload preserved");
                Expect.equal(frames.get(1).text(), "client frame two", "the second frame preserved");
                Expect.isTrue(frames.get(0).offloaded(), "the payloads reopen on disk, not in the heap");
                Expect.isTrue(frames.get(1).edited, "frame metadata preserved");
                Expect.equal(frames.get(0).connectionId, 7, "the connection id preserved");

                // A saved copy to another file (the full rewrite path) carries
                // the frames too, payloads included.
                File copy = tmp();
                StateIO.save(back, copy);
                SuiteContext third = new SuiteContext();
                StateIO.restore(third, copy);
                Expect.equal(third.wsStore().size(), 2, "a saved copy carries the frames");
                Expect.equal(third.wsStore().all().get(0).text(), "server frame one", "payloads whole in the copy");
                third.wsStore().closeStore();
                third.store().closeStore();
                copy.delete();

                back.wsStore().closeStore();
                back.store().closeStore();
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("an old-format project migrates to the single file on open", () -> {
            try {
                File f = tmp();
                List<LogEntry> history = new ArrayList<>();
                history.add(entry("/old/a", 500));
                history.add(entry("/old/b", 700));
                // Hand-write a project in the previous zip format (version 6).
                try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f)))) {
                    zos.putNextEntry(new ZipEntry("opensuite"));
                    ObjectOutputStream oos = new ObjectOutputStream(zos);
                    oos.writeInt(6);
                    oos.writeObject(history);
                    oos.writeObject(new Scope());
                    oos.writeObject(new HashMap<String, String>());
                    oos.writeObject(null); // session
                    oos.writeObject(null); // organizer
                    oos.writeObject(null); // issues
                    oos.writeObject(null); // tool states
                    oos.writeObject(null); // tasks
                    oos.flush();
                    zos.closeEntry();
                }
                Expect.isFalse(ProjectStore.looksLikeStore(f), "starts in the old zip format");

                SuiteContext back = new SuiteContext();
                int n = StateIO.restore(back, f);
                Expect.equal(n, 2, "both old entries load");
                Expect.isTrue(ProjectStore.looksLikeStore(f), "the file is now the single-file format");
                Expect.notNull(back.store().diskStore(), "the migrated session is disk-backed");
                Expect.isTrue(back.store().all().get(0).response().length() > 0, "bodies survive the migration");
                Expect.equal(back.store().all().get(1).pathAndQuery(), "/old/b", "order preserved through migration");
                back.store().closeStore();
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("a torn tail from a crash is dropped, the rest of the project opens", () -> {
            try {
                SuiteContext ctx = new SuiteContext();
                File f = tmp();
                StateIO.bindNew(ctx, f, StateIO.SaveOptions.fromSettings(ctx));
                for (int i = 0; i < 5; i++) ctx.store().add(entry("/r/" + i, 300));
                ctx.store().closeStore();
                long before = f.length();
                // A crash leaves a half-written record at the end.
                try (RandomAccessFile raf = new RandomAccessFile(f, "rw")) { raf.setLength(before - 7); }

                SuiteContext back = new SuiteContext();
                int n = StateIO.restore(back, f);
                Expect.isTrue(n >= 4 && n <= 5, "the intact records open; at most the last is lost (" + n + ")");
                for (LogEntry e : back.store().all()) {
                    Expect.notNull(e.response(), "every reopened entry still has its body");
                }
                back.store().closeStore();
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("all session state types round-trip through the object input filter", () -> {
            try {
                SuiteContext ctx = new SuiteContext();
                ctx.scope().includeUrl(SVC, "/api", true);
                ctx.scope().exclude().add(new Scope.Rule("https", "example\\.com", "443", "^/logout$"));
                ctx.settings().set("filter.test.key", "ok");

                ctx.sessions().jar().set(new Cookie("sid", "xyz", "example.com", "/", true, 0));
                SessionRule sr = new SessionRule();
                sr.name = "r1";
                sr.tools.add("repeater");
                sr.macroName = "login";
                ctx.sessions().rules().add(sr);
                Macro macro = new Macro("login");
                macro.items.add(new Macro.Item(SVC, entry("/login", 10).request()));
                macro.extractions.add(new Extraction("csrf", Extraction.From.REGEX, "tok=([a-z]+)"));
                ctx.sessions().macros().add(macro);

                LogEntry orgEntry = entry("/org", 20);
                ctx.organizer().add(new OrganizerItem(
                        SVC, orgEntry.request(), orgEntry.response(), "interesting", "proxy"));

                LogEntry issueEntry = entry("/x", 10);
                Issue issue = Issue.builder("XSS")
                        .high().certain().service(SVC).path("/x").param("q")
                        .tags("owasp-a03", "xss")
                        .dedupe(Issue.Dedupe.SITE)
                        .request(issueEntry.request())
                        .response(issueEntry.response())
                        .build();
                issue.setSource("Scan 1");
                issue.addLocation("/y", "p");
                ctx.addIssue(issue);

                ScanTask task = new ScanTask(ScanTask.Type.AUDIT, "Audit of example.com", "Balanced");
                task.setScope("https://example.com");
                task.log("done");
                task.setState(ScanTask.State.FINISHED);
                ctx.addTask(task);

                ctx.store().add(entry("/a", 100));
                ctx.wsStore().add(new WebSocketMessage(1, "example.com",
                        WebSocketMessage.Direction.C2S, WebSocketMessage.Op.TEXT,
                        "hi".getBytes(StandardCharsets.UTF_8), false));

                Map<String, ToolModule> tools = registerTools(ctx);
                tools.get("comparer").restoreState(new ArrayList<>(List.of("cmp-data".getBytes(StandardCharsets.UTF_8))));
                tools.get("decoder").restoreState("decoded-input");
                tools.get("intruder").restoreState("GET /?x=§1§ HTTP/1.1\r\nHost: example.com\r\n\r\n");

                int expectedExcludes = ctx.scope().exclude().size();

                // 1. v7 snapshot + store round-trip
                File v7 = tmp();
                try {
                    StateIO.save(ctx, v7);
                    SuiteContext back = new SuiteContext();
                    Map<String, ToolModule> backTools = registerTools(back);
                    int count = StateIO.restore(back, v7);
                    Expect.equal(count, 1, "v7 history entry reopened");
                    Expect.equal(back.wsStore().size(), 1, "v7 websocket frame preserved");
                    assertSessionStatePreserved(back, backTools, expectedExcludes, "v7");
                    back.wsStore().closeStore();
                    back.store().closeStore();
                } finally {
                    v7.delete();
                }

                // 2. Non-null v6 zip archive round-trip
                File v6 = tmp();
                try {
                    Map<String, Serializable> toolStates = new LinkedHashMap<>();
                    for (ToolModule t : ctx.tools()) {
                        Serializable s = t.saveState();
                        if (s != null) toolStates.put(t.name(), s);
                    }
                    try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(v6)))) {
                        zos.putNextEntry(new ZipEntry("opensuite"));
                        ObjectOutputStream oos = new ObjectOutputStream(zos);
                        oos.writeInt(6);
                        oos.writeObject(new ArrayList<>(ctx.store().all()));
                        oos.writeObject(ctx.scope());
                        oos.writeObject(ctx.settings().snapshot());
                        oos.writeObject(ctx.sessions().snapshot());
                        oos.writeObject(ctx.organizer().snapshot());
                        oos.writeObject(new ArrayList<>(ctx.issues()));
                        oos.writeObject(toolStates);
                        oos.writeObject(new ArrayList<>(ctx.taskSnapshots()));
                        oos.flush();
                        zos.closeEntry();
                    }
                    SuiteContext backV6 = new SuiteContext();
                    Map<String, ToolModule> backV6Tools = registerTools(backV6);
                    int n = StateIO.restore(backV6, v6);
                    Expect.equal(n, 1, "v6 archive entry restored");
                    assertSessionStatePreserved(backV6, backV6Tools, expectedExcludes, "v6");
                    backV6.wsStore().closeStore();
                    backV6.store().closeStore();
                } finally {
                    v6.delete();
                }
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("project deserialization rejects non-allowlisted classes", () -> {
            try {
                byte[] badObj = serialize(new Properties());

                assertRejected(() -> StateIO.applySessionState(new SuiteContext(), badObj),
                        "applySessionState rejects non-allowlisted class with InvalidClassException");
                assertRejected(() -> StateIO.applySessionState(new SuiteContext(), serialize(ResourcePool.defaultPool())),
                        "applySessionState rejects removed unused domain class ResourcePool");

                File badZip = tmp();
                try {
                    try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(badZip)))) {
                        zos.putNextEntry(new ZipEntry("opensuite"));
                        ObjectOutputStream oos = new ObjectOutputStream(zos);
                        oos.writeInt(6);
                        ArrayList<Object> nested = new ArrayList<>();
                        nested.add(new Properties());
                        oos.writeObject(nested);
                        oos.flush();
                        zos.closeEntry();
                    }
                    assertRejected(() -> StateIO.restoreV6(new SuiteContext(), badZip),
                            "restoreV6 rejects non-allowlisted nested class with InvalidClassException");
                } finally {
                    badZip.delete();
                }

                assertRejected(() -> LogEntry.fromIndex(badObj, null),
                        "LogEntry.fromIndex rejects non-allowlisted class with InvalidClassException");
                assertRejected(() -> LogEntry.fromIndex(serialize(new Scope()), null),
                        "LogEntry.fromIndex rejects snapshot-only class Scope");
                assertRejected(() -> WebSocketMessage.fromIndex(badObj, null),
                        "WebSocketMessage.fromIndex rejects non-allowlisted class with InvalidClassException");
                assertRejected(() -> WebSocketMessage.fromIndex(serialize(entry("/x", 1)), null),
                        "WebSocketMessage.fromIndex rejects entry-only class LogEntry");

                File badV7 = tmp();
                try {
                    try (ProjectStore ps = new ProjectStore(badV7.toPath(), 1024 * 1024)) {
                        ps.append(ProjectStore.ENTRY, badObj);
                        ps.sync();
                    }
                    // One refused history record is left out and reported; the good one beside it still opens.
                    try (ProjectStore ps = new ProjectStore(badV7.toPath(), 1024 * 1024)) {
                        ps.append(ProjectStore.ENTRY, entry("/kept", 3).indexBytes());
                        ps.sync();
                    }
                    SuiteContext opened = new SuiteContext();
                    Expect.equal(StateIO.restore(opened, badV7), 1, "the good record opens beside a refused one");
                    Expect.isTrue(opened.alerts().stream().anyMatch(a -> a.message.contains("excluded")),
                            "the refused record is reported");
                    opened.wsStore().closeStore();
                    opened.store().closeStore();
                } finally {
                    badV7.delete();
                }

                // A refused class in the settings block stops the whole file from opening.
                File badBlock = tmp();
                try {
                    try (ProjectStore ps = new ProjectStore(badBlock.toPath(), 1024 * 1024)) {
                        ps.append(ProjectStore.SNAPSHOT, badObj);
                        ps.sync();
                    }
                    assertRejected(() -> StateIO.restore(new SuiteContext(), badBlock),
                            "a project whose settings block holds a refused class does not open");
                } finally {
                    badBlock.delete();
                }

                Expect.isTrue(StateIO.isProjectName("a.osuite") && StateIO.isProjectName("OLD.OTRAP")
                        && !StateIO.isProjectName("a.txt"), "both extensions are project files");
                Expect.isTrue(StateIO.defaultProjectFileName().endsWith(".osuite"), "new projects take the new extension");
            } catch (AssertionError ae) {
                throw ae;
            } catch (Exception e) {
                throw new AssertionError("expected InvalidClassException, got: " + e, e);
            }
        });
    }
}