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.

14.0 KB
Raw Blame
package opensuite.ui;

import opensuite.core.SuiteContext;
import opensuite.core.Debug;

import javax.swing.*;
import java.awt.*;
import java.nio.file.Path;
import java.util.Arrays;

public class Main {
    /**
     * The build identifier, a UTC timestamp (YYYYMMDD-HHMMSS) stamped into the jar
     * manifest by release.sh, so every build is uniquely and sortably identified
     * and the running app reports exactly which one it is. A dev build has none,
     * and reports "dev".
     */
    public static final String VERSION = buildVersion();
    public static final String TITLE = "Open Suite " + VERSION;

    private static String buildVersion() {
        try {
            var res = Main.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
            while (res.hasMoreElements()) {
                try (var in = res.nextElement().openStream()) {
                    var mf = new java.util.jar.Manifest(in);
                    var at = mf.getMainAttributes();
                    if ("opensuite.ui.Main".equals(at.getValue("Main-Class"))) {
                        String v = at.getValue("Implementation-Version");
                        if (v != null && !v.isBlank()) return v;
                    }
                } catch (Exception ignore) {}
            }
        } catch (Exception ignore) {}
        return "dev";
    }

    public static volatile String[] launchArgs = new String[0];

    public static void main(String[] args) {
        // The name in the macOS menu bar, before anything starts the toolkit.
        if (opensuite.core.Os.MAC) System.setProperty("apple.awt.application.name", "Open Suite");
        // Settings kept under the product's former name come across before anything reads one.
        opensuite.core.Migration.run();
        // Headless probe: print the scale this display should use and exit. The
        // AppImage launcher calls this to choose a scale before the real JVM
        // starts, so it never relaunches inside the AppImage (relaunching there
        // would tear down the AppImage mount and kill the app).
        for (String a : args) {
            if ("--print-scale".equals(a)) {
                // Nothing when no scale was chosen, so the launcher sets none.
                System.out.println(UiScale.chosen() ? String.valueOf(UiScale.desired()) : "");
                return;
            }
        }

        launchArgs = args;

        // Capture uncaught exceptions on every thread even without --debug, so
        // a failure in a worker thread is labelled and traced rather than a
        // bare stack dump. With --debug it also lands in the log file.
        Debug.installUncaughtHandler();
        Debug.keepErrorsOnDisk();

        for (String a : args) {
            if ("--debug".equals(a)) { Debug.enable(); break; }
        }
        Debug.log("main() starting, args=" + Arrays.toString(args));

        // If a non-default interface scale is saved and this JVM has not had it
        // applied yet, relaunch with Java's real HiDPI scaling so the whole UI
        // scales uniformly (fonts, columns, borders), then exit.
        // The macOS and Windows launchers cannot read Settings > Suite > Performance >
        // Maximum memory usage, so a custom limit is applied by starting again with it.
        int limitMb = opensuite.core.Launch.memoryFileMb();
        if ((opensuite.core.Os.MAC || opensuite.core.Os.WINDOWS) && !UiScale.applied() && limitMb > 0
                && Math.abs(Runtime.getRuntime().maxMemory() / (1024 * 1024) - limitMb) > limitMb / 10
                && UiScale.relaunchWith(UiScale.desired(), args)) {
            Debug.log("relaunched with the memory limit; parent exiting");
            return;
        }
        if (!UiScale.applied() && !opensuite.core.Os.MAC) {
            double want = UiScale.desired();
            Debug.log("scale not yet applied; desired=" + want);
            if (UiScale.chosen()) {
                Debug.log("relaunching JVM with uiScale=" + want);
                if (UiScale.relaunchWith(want, args)) {
                    Debug.log("relaunched child process; parent exiting");
                    return;
                }
                Debug.log("relaunch did not happen; continuing in this process");
            }
        } else {
            Debug.log("scale already applied; no relaunch needed");
        }

        // Settings > Suite > Temporary files location, before anything makes a temporary file.
        Debug.log("temporary files in " + opensuite.core.Launch.applyTempDir(new opensuite.core.Settings()));

        // Settings > Network > TLS > Java TLS settings, which the runtime reads once.
        opensuite.core.NetworkConfig.applyStartup(new opensuite.core.Settings());
        // The SOCKS proxy's name and password, when it asks for them.
        java.net.Authenticator.setDefault(new java.net.Authenticator() {
            @Override protected java.net.PasswordAuthentication getPasswordAuthentication() {
                String protocol = getRequestingProtocol();
                if (protocol == null || !protocol.toUpperCase(java.util.Locale.ROOT).startsWith("SOCKS")) return null;
                return opensuite.core.NetworkConfig.socksLogin(getRequestingHost());
            }
        });

        Theme.install();

        // Scale the whole interface before any window is built. The factor comes
        // from -Dopensuite.scale, else the saved preference, else 1.0.
        UiScale.installDefaults();

        Path home = Path.of(System.getProperty("user.home"), ".opensuite");

        Debug.log("entering EDT to build the UI");
        SwingUtilities.invokeLater(() -> {
          try {
            // Build the whole UI and show the main window FIRST, then ask which
            // project to open. A modal dialog shown as the very first window with
            // no owner fails to map on some Linux/Wayland desktops (it blocks
            // invisibly and the process hangs); giving it a visible parent frame
            // makes it appear reliably.
            Debug.log("creating SuiteContext and SuiteFrame");
            SuiteContext ctx = new SuiteContext();
            // EXPERIMENTAL (issue #37 keystone): keep recorded traffic bodies
            // and WebSocket frame payloads on disk, not in the heap, so a long
            // proxying session stays bounded.
            ctx.store().useDiskStore(home.resolve("traffic"));
            ctx.wsStore().useDiskStore(home.resolve("ws-traffic"));
            SuiteFrame frame = new SuiteFrame(ctx, TITLE);
            ctx.restApi().sync();   // listens only if Settings > Suite > REST API has it running
            // Settings > Suite > Performance: the memory limit goes to the launchers, the log runs while ticked.
            opensuite.core.Launch.writeMemoryFile(ctx.settings(), home);
            ctx.settings().addListener(key -> {
                if (key == null || key.startsWith("perf.memory.")) opensuite.core.Launch.writeMemoryFile(ctx.settings(), home);
            });
            opensuite.core.Launch.startPerformanceLog(ctx);
            AutoBackup.start(ctx);   // Settings > Project > Automatic backup
            // Under --debug, report what the interface was doing whenever it
            // stops answering, so a freeze comes with its reason attached.
            EdtWatchdog.install();
            if (Debug.enabled()) {
                Runtime.getRuntime().addShutdownHook(new Thread(() ->
                        Debug.log("interface stalls this session:\n" + EdtWatchdog.summary())));
            }
            Debug.log("registering tools");
            opensuite.extensions.ExtensionLoader extensions = Bootstrap.registerTools(ctx, frame, home);
            Debug.log("building UI (frame.buildUi)");
            frame.buildUi();
            // The extensions listed under Installed load again, each on a thread of its own; their tabs join the strip as each is ready.
            extensions.reloadOnStartup();

            // Size to the scaled ideal, but never larger than the screen's work
            // area, so the window always fits even on a small laptop display.
            Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment()
                    .getMaximumWindowBounds();
            int w = Math.min(UiScale.px(1280), screen.width);
            int h = Math.min(UiScale.px(860), screen.height);
            frame.setSize(w, h);
            frame.setLocationRelativeTo(null);
            // If even the fitted size fills the screen, start maximised.
            if (w >= screen.width - 8 && h >= screen.height - 8) {
                frame.setExtendedState(Frame.MAXIMIZED_BOTH);
            }
            Runnable showMain = () -> {
                Debug.log("showing main window (" + w + "x" + h + ")");
                frame.setVisible(true);
                opensuite.core.FreezeWatch.start();
                frame.toFront();
                frame.requestFocus();
                Debug.log("main window is visible");
            };

            // A project path on the command line (as a .osuite file association
            // passes when one is double-clicked) opens or creates that project
            // directly, skipping the startup dialog.
            java.io.File argProject = projectArg(launchArgs);
            if (argProject != null) {
                Debug.log("opening project from the command line: " + argProject);
                showMain.run();
                openProjectFromArg(ctx, frame, argProject);
                return;
            }

            // Otherwise the project is chosen first, in a window of its own, and the main
            // window opens only once it has been: one window at a time, and nothing that
            // can sit locked behind a window the desktop failed to show.
            Debug.log("showing startup project dialog");
            ProjectStartupDialog startup = new ProjectStartupDialog(null, TITLE);
            startup.applyDefaults(ctx.settings().getBool("startup.pauseTasks", true), ctx.settings().getBool(StateIO.ALWAYS_TRUST, true));
            startup.setVisible(true);
            Debug.log("startup dialog closed: proceeded=" + startup.proceeded()
                    + " mode=" + startup.mode());
            if (!startup.proceeded()) {
                System.exit(0);
                return;
            }
            showMain.run();
            ctx.alert("suite", "Open Suite " + VERSION + " started");

            // Resolve the chosen project now that the window and its tools
            // (whose listeners repopulate on restore) are live.
            java.io.File projectFile = startup.file();
            switch (startup.mode()) {
                case NEW -> {
                    try {
                        // Create the single-file project and bind the session to it,
                        // so every exchange streams to disk and saves stay cheap.
                        StateIO.bindNew(ctx, projectFile, StateIO.SaveOptions.fromSettings(ctx));
                        ctx.setProjectFile(projectFile);
                        RecentProjects.record(startup.projectName(), projectFile);
                        ctx.alert("suite", "New project: " + projectFile.getName());
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(frame,
                                "Could not create the project file:\n" + e.getMessage(),
                                "New project", JOptionPane.ERROR_MESSAGE);
                    }
                }
                case OPEN -> {
                    // Off the event thread with a progress dialog: a large
                    // project must never freeze the window while it loads.
                    final String projectName = startup.projectName();
                    final boolean pause = startup.pauseTasks();
                    if (startup.trustFile()) StateIO.trustOnce(projectFile);
                    StateIO.restoreAsync(ctx, frame, projectFile, n -> {
                        // "Pause automated tasks": the reopened project's scans and live tasks wait to be resumed.
                        if (pause) ctx.pauseAllTasks();
                        ctx.setProjectFile(projectFile);
                        RecentProjects.record(projectName, projectFile);
                        ctx.alert("suite", "Opened project " + projectFile.getName() + " (" + n + " items)");
                    });
                }
                default -> { /* temporary in-memory project: nothing to load */ }
            }
          } catch (Throwable t) {
            Debug.error("startup failed while building the UI", t);
            handleStartupFailure(t);
          }
        });
    }

    /** The first non-flag argument that names a project file, or null. */
    private static java.io.File projectArg(String[] args) {
        for (String a : args) {
            if (a == null || a.startsWith("--")) continue;
            if (StateIO.isProjectName(a)) return new java.io.File(a);
        }
        return null;
    }

    /** Open an existing project file, or create one if it does not exist yet. */
    private static void openProjectFromArg(SuiteContext ctx, SuiteFrame frame, java.io.File projectFile) {
        String name = projectFile.getName();
        if (projectFile.exists()) {
            StateIO.restoreAsync(ctx, frame, projectFile, n -> {
                ctx.setProjectFile(projectFile);
                RecentProjects.record(name, projectFile);
                ctx.alert("suite", "Opened project " + name + " (" + n + " items)");
            });
        } else {
            try {
                StateIO.bindNew(ctx, projectFile, StateIO.SaveOptions.fromSettings(ctx));
                ctx.setProjectFile(projectFile);
                RecentProjects.record(name, projectFile);
                ctx.alert("suite", "New project: " + name);
            } catch (Exception e) {
                Debug.error("could not create the project from the command line", e);
            }
        }
    }

    private static void handleStartupFailure(Throwable t) {
        JOptionPane.showMessageDialog(null,
                "Failed to start: " + t, "error", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }
}