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.

21.9 KB
Raw Blame
package opensuite.extensions;

import opensuite.ui.Glyphs;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Extensions > Installed: the loaded extensions table with Add / Remove / Up /
 * Down, and Details / Output / Errors for the selected one. Add opens the
 * {@link LoadExtensionDialog}; a loaded entry records its type, file and
 * status. The panel shows what the {@link ExtensionLoader} holds and owns
 * nothing of its own: loading an extension runs its declared entry point, on a
 * thread of the extension's own, and adds the tabs and menus it declares.
 */
public final class InstalledPanel extends JPanel {

    private static final String[] COLUMNS = {"Loaded", "Type", "Name", "System impact", "Auto-reload"};

    private final ExtensionLoader loader;
    /** The entries the table's rows show, in row order; replaced whenever the loader's list changes. */
    private List<LoadedExtension> rows = new ArrayList<>();
    private boolean syncing;

    private final DefaultTableModel model = new DefaultTableModel(COLUMNS, 0) {
        @Override public Class<?> getColumnClass(int c) {
            return (c == 0 || c == 4) ? Boolean.class : c == 3 ? Integer.class : String.class;
        }
        @Override public boolean isCellEditable(int r, int c) { return c == 0 || c == 4; }
    };
    private final JTable table = new JTable(model);
    private final DefaultTableModel details = new DefaultTableModel(new Object[]{"Item", "Detail"}, 0) {
        @Override public boolean isCellEditable(int r, int c) { return false; }
    };
    private final JTextArea output = console();
    private final JTextArea errors = console();
    private final JCheckBox loadedBox = Ui.check("Extension loaded", false);
    private final JButton resume = Ui.button("Resume", "Start sending events to this extension again");

    public InstalledPanel(ExtensionLoader loader) {
        super(new BorderLayout());
        this.loader = loader;
        setOpaque(true);
        setBackground(Theme.BG);

        JButton add = Ui.button("Add", "Load an extension from a file");
        JButton remove = Ui.button("Remove", "Unload the selected extension");
        JButton up = Ui.button("Up");
        JButton down = Ui.button("Down");
        // Nothing to remove or move until a row is picked, as in the reference.
        Runnable picked = () -> { boolean on = selected() != null; remove.setEnabled(on); up.setEnabled(on); down.setEnabled(on);
            LoadedExtension x = selected(); resume.setEnabled(x != null && x.unresponsive && x.module != null); };
        add.addActionListener(e -> {
            LoadExtensionDialog.Result r = LoadExtensionDialog.show(this);
            if (r == null) return;
            // An extension is a program: it runs with everything Open Suite can
            // reach. That is said, and agreed to, before a jar is loaded.
            if (!trusted(r.file())) return;
            select(loader.add(r.type(), r.file(), true));
        });
        remove.addActionListener(e -> { LoadedExtension x = selected(); if (x != null) loader.remove(x); });
        up.addActionListener(e -> { LoadedExtension x = selected(); if (x != null) loader.move(x, -1); });
        down.addActionListener(e -> { LoadedExtension x = selected(); if (x != null) loader.move(x, 1); });
        resume.addActionListener(e -> { LoadedExtension x = selected(); if (x != null) loader.resume(x); });

        Ui.styleTable(table);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // Name takes the room the reference gives its name and two unshipped columns.
        Ui.exactWidths(table, 64, 97, 549, 194, 64);
        if (Ui.fontGrowth() > 0) {
            // As measured at the usual 13px.
            int[] at13 = { 75, 112, 637, 225, 75 };
            for (int i = 0; i < at13.length; i++) table.getColumnModel().getColumn(i).setPreferredWidth(at13[i]);
        }
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.putClientProperty(Ui.KEEP_WIDTHS, Boolean.TRUE);
        table.getColumnModel().getColumn(3).setCellRenderer(new MeterRenderer());
        // An extension the watchdog has marked shows so in the table itself, not only in its details.
        table.getColumnModel().getColumn(2).setCellRenderer(new javax.swing.table.DefaultTableCellRenderer() {
            @Override public Component getTableCellRendererComponent(JTable t, Object v, boolean sel, boolean focus, int r, int c) {
                Component cell = super.getTableCellRendererComponent(t, v, sel, focus, r, c);
                int row = table.convertRowIndexToModel(r);
                LoadedExtension x = row >= 0 && row < rows.size() ? rows.get(row) : null;
                if (x != null && x.unresponsive) {
                    setText(v + " (unresponsive)");
                    setForeground(Ui.SEV_HIGH);
                    setToolTipText(x.module != null
                            ? "It is unresponsive: new events to it are paused. Remove it, or resume it from Details."
                            : "It is unresponsive, and " + Character.toLowerCase(x.status.charAt(0)) + x.status.substring(1) + ".");
                } else {
                    setForeground(sel ? Theme.TEXT : Theme.MUTED);
                    setToolTipText(null);
                }
                return cell;
            }
        });
        model.addTableModelListener(e -> {
            if (syncing) return;
            int r = e.getFirstRow();
            if (r < 0 || r >= rows.size()) return;
            // The loader changes the row, and the table is then brought back into step with it.
            syncing = true;
            try {
                if (e.getColumn() == 0) loader.setLoaded(rows.get(r), Boolean.TRUE.equals(model.getValueAt(r, 0)));
                if (e.getColumn() == 4) loader.setAutoReload(rows.get(r), Boolean.TRUE.equals(model.getValueAt(r, 4)));
            } finally { syncing = false; }
        });
        table.getSelectionModel().addListSelectionListener(e -> { if (!e.getValueIsAdjusting()) { showSelected(); picked.run(); } });
        picked.run();

        // The heading with the help mark at the far right, then the one-line
        // description with the search box at its right.
        JLabel blurb = Ui.label("Extensions let you customise Open Suite's behaviour using your own or third-party code.");
        blurb.setForeground(Theme.TEXT);
        JTextField find = Ui.searchField(18);
        javax.swing.table.TableRowSorter<DefaultTableModel> sorter = new opensuite.ui.NumberSorter<>(model);
        table.setRowSorter(sorter);
        find.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            void go() {
                String q = find.getText().strip();
                sorter.setRowFilter(q.isEmpty() ? null
                        : RowFilter.regexFilter("(?i)" + java.util.regex.Pattern.quote(q), 1, 2));
            }
            public void insertUpdate(javax.swing.event.DocumentEvent e)  { go(); }
            public void removeUpdate(javax.swing.event.DocumentEvent e)  { go(); }
            public void changedUpdate(javax.swing.event.DocumentEvent e) { go(); }
        });
        find.setColumns(0);
        Ui.sized(find, Ui.fontGrowth() > 0 ? 230 : 233);
        JButton help = Ui.helpButton("Extensions",
                "An extension is a jar whose classes implement the suite's tool-module contract. "
                + "Loading an extension runs its entry point and adds the tabs and menus it declares.");
        help.setIcon(Glyphs.help(Ui.fontGrowth() > 0 ? 22 : 21, Theme.TEXT));
        help.setBorder(Ui.fontGrowth() > 0 ? Ui.pad(0, 0, 0, 1) : null);
        JPanel headRow = new JPanel(new BorderLayout());
        headRow.setOpaque(false);
        JLabel title = Ui.heading("Open Suite extensions");
        title.setBorder(Ui.fontGrowth() > 0 ? Ui.pad(0, 0, 2, 0) : Ui.pad(1, 0, 1, 0));
        headRow.add(title, BorderLayout.WEST);
        headRow.add(help, BorderLayout.EAST);
        headRow.setPreferredSize(new Dimension(10, Ui.fontGrowth() > 0 ? 22 : 21));
        JPanel blurbRow = new JPanel(new BorderLayout());
        blurbRow.setOpaque(false);
        blurbRow.setBorder(Ui.pad(0, 0, 9, 0));
        blurbRow.add(blurb, BorderLayout.CENTER);
        blurbRow.add(find, BorderLayout.EAST);
        Ui.sized(blurbRow, 10);

        for (JButton b : new JButton[] { add, remove, up, down }) b.setBorder(Ui.pad(Ui.fontGrowth() > 0 ? 2 : 0, 0, 0, 0));
        final boolean big = Ui.fontGrowth() > 0;
        JPanel block = new JPanel(new GridLayout(4, 1, 0, big ? 6 : 5));
        block.setOpaque(false);
        block.add(add); block.add(remove); block.add(up); block.add(down);
        block.setPreferredSize(big ? new Dimension(Ui.buttonBlock(4).width, 4 * 23 + 3 * 6) : Ui.buttonBlock(4));
        // At 13px the table is taller than the four buttons, which keep their height at its top.
        JPanel buttons = new JPanel(new BorderLayout());
        buttons.setOpaque(false);
        buttons.add(block, BorderLayout.NORTH);
        JScrollPane sp = Ui.scroll(table);
        sp.setPreferredSize(new Dimension(600, 103 + Math.round(23.5f * Ui.fontGrowth())));   // 150 at 13px, as measured
        JPanel tableRow = new JPanel(new BorderLayout(10, 0));
        tableRow.setOpaque(false);
        tableRow.add(buttons, BorderLayout.WEST);
        tableRow.add(sp, BorderLayout.CENTER);

        JPanel centre = opensuite.ui.Sections.column(0, opensuite.ui.Sections.fill(headRow), opensuite.ui.Sections.gap(big ? 11 : 10),
                opensuite.ui.Sections.fill(blurbRow), opensuite.ui.Sections.gap(15), opensuite.ui.Sections.fill(tableRow));
        centre.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, Theme.BORDER), Ui.pad(big ? 11 : 10, 15, 17, 15)));

        add(top(buildImpactStrip(), centre), BorderLayout.NORTH);

        // Details: whether the chosen extension is loaded, then what is known about it.
        loadedBox.setBorder(null);
        loadedBox.setOpaque(false);
        loadedBox.addActionListener(e -> {
            LoadedExtension x = selected();
            if (x != null) loader.setLoaded(x, loadedBox.isSelected());
        });
        JButton loadedHelp = Ui.helpButton("Extension loaded",
                "Clear the checkbox to disable the extension without removing it from the list; select it to load the extension again.");
        loadedHelp.setIcon(Glyphs.help(Ui.fontGrowth() > 0 ? 22 : 21, Theme.TEXT));
        loadedHelp.setBorder(Ui.fontGrowth() > 0 ? Ui.pad(0, 0, 0, 1) : null);
        resume.setEnabled(false);
        JPanel east = new JPanel(new BorderLayout(8, 0));
        east.setOpaque(false);
        east.add(resume, BorderLayout.WEST);
        east.add(loadedHelp, BorderLayout.EAST);
        JPanel loadedRow = new JPanel(new BorderLayout());
        loadedRow.setOpaque(false);
        loadedRow.setBorder(big ? Ui.pad(11, 2, 11, 0) : Ui.pad(10, 2, 10, 0));
        loadedRow.add(loadedBox, BorderLayout.WEST);
        loadedRow.add(east, BorderLayout.EAST);
        loadedRow.setPreferredSize(new Dimension(10, big ? 44 : 41));

        JTable dt = new JTable(details);
        Ui.styleTable(dt);
        Ui.exactWidths(dt, 210, 480);
        dt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        dt.putClientProperty(Ui.KEEP_WIDTHS, Boolean.TRUE);
        JPanel detailsTab = new JPanel(new BorderLayout());
        detailsTab.setBackground(Theme.BG);
        detailsTab.setBorder(Ui.pad(0, 15, 0, 15));
        detailsTab.add(loadedRow, BorderLayout.NORTH);
        detailsTab.add(Ui.scroll(dt), BorderLayout.CENTER);

        JTabbedPane detail = new JTabbedPane();
        detail.setFont(Ui.PLAIN);
        detail.setBorder(Ui.pad(2, 0, 0, 0));
        detail.putClientProperty(opensuite.ui.theme.FlatTabbedPaneUI.LEFT_INSET, 15);
        // These three are underlined in the text's own grey, not the accent.
        detail.putClientProperty(opensuite.ui.theme.FlatTabbedPaneUI.UNDERLINE,
                Theme.dark ? new Color(0xBB, 0xBB, 0xBB) : new Color(0x4B, 0x4B, 0x4B));
        detail.addTab("Details", detailsTab);
        detail.addTab("Output", padded(Ui.scroll(output)));
        detail.addTab("Errors", padded(Ui.scroll(errors)));

        add(detail, BorderLayout.CENTER);
        updateTotalImpact();
        loader.addListener(this::changed);
        sync();
    }

    /** Ask before a jar is loaded: its code runs with the same access as Open Suite itself. */
    private boolean trusted(java.io.File jar) {
        int go = JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor(this),
                "An extension runs with the same access as Open Suite itself: your files,\n"
                + "your network and everything in this project. It also loads again each\n"
                + "time Open Suite starts, while its Auto-reload box is ticked.\n\n"
                + "Load " + jar.getName() + " only if you trust where it came from.",
                "Load extension", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
                new Object[]{ "Load", "Cancel" }, "Cancel");
        return go == 0;
    }

    private static JPanel top(JComponent north, JComponent centre) {
        JPanel top = new JPanel(new BorderLayout());
        top.setOpaque(false);
        top.add(north, BorderLayout.NORTH);
        top.add(centre, BorderLayout.CENTER);
        return top;
    }

    private static JComponent padded(JComponent c) {
        JPanel p = new JPanel(new BorderLayout());
        p.setBackground(Theme.BG);
        p.setBorder(Ui.pad(10, 15, 0, 15));
        p.add(c, BorderLayout.CENTER);
        return p;
    }

    /** The meter of the impact strip: a rounded track 324 by 10 with the fill over it. */
    private static final class Meter extends JComponent {
        int value;
        Color fill = Theme.CONTROL;
        Meter() { setPreferredSize(new Dimension(324 + Math.round(24.5f * Ui.fontGrowth()), 10)); }
        @Override protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(Theme.SURFACE);
            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 4, 4);
            if (value > 0) {
                g2.setColor(fill);
                g2.fillRoundRect(0, 0, Math.max(6, getWidth() * value / 100), getHeight(), 4, 4);
            }
            g2.dispose();
        }
    }

    /** The mark of the impact strip: a small dial with its needle. */
    private static Icon dial() {
        return new Icon() {
            @Override public int getIconWidth() { return 14; }
            @Override public int getIconHeight() { return 14; }
            @Override public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
                g2.setColor(Theme.TEXT);
                g2.setStroke(new BasicStroke(1.2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
                g2.draw(new java.awt.geom.Arc2D.Double(x + 0.8, y + 2.2, 12.4, 12.4, 0, 180, java.awt.geom.Arc2D.OPEN));
                g2.draw(new java.awt.geom.Line2D.Double(x + 7, y + 8.6, x + 10.2, y + 5.2));
                g2.fill(new java.awt.geom.Ellipse2D.Double(x + 5.8, y + 7.4, 2.4, 2.4));
                g2.dispose();
            }
        };
    }

    private Meter totalImpactBar;
    private JLabel totalImpactWord;

    /**
     * The strip the reference shows above the table: the combined estimated
     * system impact of every loaded extension, as a word and a meter.
     */
    private JComponent buildImpactStrip() {
        // A 50px band with a hairline beneath: the mark at 15, the caption at
        // 39, the word at 219 and the meter at 259.
        JPanel strip = new JPanel(null) {
            @Override public void doLayout() {
                int n = 0;
                // At the usual 13px: 15, 41, 248 and 295, in a band two pixels shorter.
                int g = Ui.fontGrowth(), band = 50 - g;
                int[] xs = { 15, 39 + g, 219 + Math.round(14.5f * g), 259 + 18 * g };
                for (Component c : getComponents()) {
                    Dimension d = c.getPreferredSize();
                    c.setBounds(xs[n++], (band - d.height) / 2, n == 2 ? 175 + 15 * g : d.width, d.height);
                }
            }
        };
        strip.setOpaque(false);
        strip.setPreferredSize(new Dimension(10, 51 - Ui.fontGrowth()));
        strip.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Theme.BORDER));
        totalImpactWord = Ui.bold("None");
        totalImpactWord.setForeground(Theme.TEXT);
        totalImpactBar = new Meter();
        strip.add(new JLabel(dial()));
        strip.add(Ui.label("Total estimated system impact:"));
        strip.add(totalImpactWord);
        strip.add(totalImpactBar);
        return strip;
    }

    /** Recompute the combined impact from the loaded extensions and show it. */
    private void updateTotalImpact() {
        if (totalImpactBar == null) return;
        int total = 0;
        for (LoadedExtension x : rows) if (x.loaded) total += x.impact;
        total = Math.min(100, total);
        totalImpactBar.value = total;
        totalImpactBar.fill = total < 25 ? Theme.CONTROL : total < 60 ? Ui.SEV_MEDIUM : Ui.SEV_HIGH;
        totalImpactBar.repaint();
        totalImpactWord.setText(total == 0 ? "None" : impactLabel(total));
    }

    private static String impactLabel(int score) {
        return score < 25 ? "Low" : score < 60 ? "Medium" : "High";
    }

    /** The system-impact cell: a short bar with its Low / Medium / High word. */
    private static final class MeterRenderer extends javax.swing.table.DefaultTableCellRenderer {
        private final JPanel row = new JPanel(new BorderLayout(6, 0));
        private final JProgressBar bar = new JProgressBar(0, 100);
        private final JLabel word = new JLabel();
        MeterRenderer() {
            bar.setBorderPainted(false);
            bar.setPreferredSize(new Dimension(56, 6));
            word.setFont(Ui.PLAIN);
            row.setBorder(Ui.pad(0, 4, 0, 4));
            row.add(bar, BorderLayout.CENTER);
            row.add(word, BorderLayout.EAST);
        }
        @Override public Component getTableCellRendererComponent(JTable t, Object v, boolean sel,
                boolean focus, int r, int c) {
            int score = v instanceof Integer i ? i : 0;
            bar.setValue(score);
            bar.setForeground(score < 25 ? Theme.CONTROL : score < 60 ? Ui.SEV_MEDIUM : Ui.SEV_HIGH);
            word.setText(impactLabel(score));
            word.setForeground(sel ? Theme.TEXT : Theme.MUTED);
            row.setBackground(sel ? t.getSelectionBackground() : t.getBackground());
            row.setOpaque(true);
            return row;
        }
    }

    private static JTextArea console() {
        JTextArea a = new JTextArea();
        a.setEditable(false);
        a.setFont(Ui.MONO);
        return a;
    }

    // ---- showing the loader's list ----

    private LoadedExtension selected() {
        int r = table.getSelectedRow();
        if (r < 0) return null;
        int m = table.convertRowIndexToModel(r);
        return m >= 0 && m < rows.size() ? rows.get(m) : null;
    }

    private void select(LoadedExtension x) {
        int r = viewRow(x);
        if (r >= 0) table.setRowSelectionInterval(r, r);
    }

    private int viewRow(LoadedExtension x) {
        for (int m = 0; m < rows.size(); m++) if (rows.get(m) == x) return table.convertRowIndexToView(m);
        return -1;
    }

    /** The loader says something changed: bring the table back into step with its list, keeping the selection, and show the selected row. */
    private void changed() {
        LoadedExtension was = selected();
        sync();
        if (was != null && rows.contains(was)) select(was);
        showSelected();
    }

    private void sync() {
        syncing = true;
        try {
            List<LoadedExtension> now = loader.items();
            boolean same = now.size() == rows.size();
            if (same) for (int i = 0; i < now.size(); i++) if (now.get(i) != rows.get(i)) { same = false; break; }
            if (!same) {
                model.setRowCount(0);
                rows = now;
                for (LoadedExtension x : rows) model.addRow(values(x));
            } else {
                for (int i = 0; i < rows.size(); i++) {
                    Object[] v = values(rows.get(i));
                    for (int c = 0; c < v.length; c++) if (!Objects.equals(model.getValueAt(i, c), v[c])) model.setValueAt(v[c], i, c);
                }
            }
        } finally { syncing = false; }
        updateTotalImpact();
    }

    private static Object[] values(LoadedExtension x) {
        return new Object[]{ x.loaded, x.type, x.name, x.impact, x.autoReload };
    }

    private void showSelected() {
        details.setRowCount(0);
        output.setText("");
        errors.setText("");
        LoadedExtension x = selected();
        loadedBox.setEnabled(x != null);
        resume.setEnabled(x != null && x.unresponsive && x.module != null);
        loadedBox.setSelected(x != null && x.loaded);
        if (x == null) return;
        details.addRow(new Object[]{"Name", x.name});
        details.addRow(new Object[]{"Type", x.type});
        details.addRow(new Object[]{"File", x.file.getAbsolutePath()});
        details.addRow(new Object[]{"Status", x.status});
        if (!x.note.isEmpty()) details.addRow(new Object[]{"Why", x.note});
        details.addRow(new Object[]{"Loaded", x.loaded ? "Yes" : "No"});
        details.addRow(new Object[]{"System impact", impactLabel(x.impact) + " (" + x.impact + " of 100)"});
        details.addRow(new Object[]{"Auto-reload", x.autoReload ? "Yes" : "No"});
        output.setText(x.output.toString());
        errors.setText(x.errors.toString());
    }
}