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.

15.9 KB
Raw Blame
package opensuite.dashboard;

import opensuite.engine.ScanAuth;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;

/**
 * Where a session check is made. The user selects a request, the request is
 * sent with the scan's session and without it, and both requests and their
 * real responses are shown: the requests, so it can be seen which cookie,
 * token or other header carries the session; the responses, so the user can
 * highlight text that is there only while logged in. Highlighting it puts it
 * in the Logged-in text box; Verify proves it; OK adds the check. The text is then
 * proven on the application before the check can be added: it must be in
 * every response with the session and absent without it.
 *
 * <p>Nothing here decides what a logged-in response looks like. The user says
 * so, by the text, and the application confirms it.
 */
final class SessionCheckDialog {
    private SessionCheckDialog() {}

    /** The most of a response that is put on screen. The whole of it is searched whatever is shown. */
    static final int SHOWN = 400_000;
    /** The colour of a test that failed. A test that passed is in the theme's own green. */
    private static final Color FAILED = new Color(0xC0, 0x39, 0x2B);
    /** The width of the window's contents, in the units of {@link Ui#em}. */
    private static final int WIDE = 860;

    /**
     * @param candidates the requests to choose from
     * @param session    the session's headers, as the scan will send them
     * @param extra      the headers typed in by hand, sent as well
     * @return the proven check to add, or null when the window was closed without one
     */
    static ScanAuth.Check show(Component parent, List<ScanAuth.Check> candidates, List<ScanAuth.Header> session, List<ScanAuth.Header> extra) {
        JDialog dialog = new JDialog(SwingUtilities.getWindowAncestor(parent), "Session check", java.awt.Dialog.ModalityType.APPLICATION_MODAL);
        List<ScanAuth.Header> all = new ArrayList<>(extra);
        all.addAll(session);

        List<String> names = new ArrayList<>();
        for (ScanAuth.Check c : candidates) names.add(c.request.method() + "  " + c.service.url() + c.request.requestTarget());
        DefaultListModel<String> listed = new DefaultListModel<>();
        List<Integer> listedIndex = new ArrayList<>();
        JList<String> list = new JList<>(listed);
        list.setFont(Ui.PLAIN);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setVisibleRowCount(6);
        JTextField search = new JTextField();
        search.setFont(Ui.PLAIN);
        search.setToolTipText("Show only requests whose URL contains this text. Multiple words must all match");
        JLabel count = Ui.label(" ");
        count.setForeground(Theme.MUTED);

        JTextArea with = area(), without = area(), withSent = area(), withoutSent = area();
        JTabbedPane answers = new JTabbedPane();
        answers.setFont(Ui.PLAIN);
        answers.addTab("With the session", pair(withSent, with));
        answers.addTab("Without the session", pair(withoutSent, without));

        JTextField text = Ui.field("", 34);
        JButton verify = Ui.button("Verify", "Send the request " + ScanAuth.TIMES + " times with the session and once without it, and check for the text each time");
        JButton clear = Ui.button("Clear", "Remove the logged-in text and its result, to highlight other text");
        JLabel result = Ui.label("Select a request.");
        result.setForeground(Theme.TEXT);
        JButton add = Ui.button("OK", "Add this request and its logged-in text as a session check. Available once the text has been verified");
        JButton cancel = Ui.button("Cancel");
        // What the result line says, and how: plainly, or as a test that passed or failed.
        java.util.function.BiConsumer<String, Color> say = (words, colour) -> {
            result.setText(words);
            result.setToolTipText(words);
            result.setForeground(colour);
        };
        add.setEnabled(false);

        // What is on screen now, and what was last proven: Add is offered only for a proven pair of request and text.
        ScanAuth.Check[] current = {null}, proven = {null};
        int[] turn = {0};
        ScanAuth.Check[] chosen = {null};

        Runnable unproven = () -> { proven[0] = null; add.setEnabled(false); };

        Runnable fill = () -> {
            listed.clear();
            listedIndex.clear();
            List<String> match = ApplicationLoginPanel.matching(names, search.getText());
            java.util.Set<String> want = new java.util.HashSet<>(match);
            for (int i = 0; i < names.size(); i++) if (want.contains(names.get(i))) { listed.addElement(names.get(i)); listedIndex.add(i); }
            count.setText(listed.size() + " of " + names.size() + " shown");
        };

        Runnable send = () -> {
            int row = list.getSelectedIndex();
            if (row < 0 || row >= listedIndex.size()) return;
            ScanAuth.Check from = candidates.get(listedIndex.get(row));
            ScanAuth.Check c = new ScanAuth.Check(from.service, from.request);
            current[0] = c;
            unproven.run();
            int mine = ++turn[0];
            for (JTextArea t : new JTextArea[] {with, without, withSent, withoutSent}) t.setText("");
            answers.setSelectedIndex(0);
            say.accept("Sending the request with the session and without it...", Theme.TEXT);
            new Thread(() -> {
                ScanAuth.Answer a = ScanAuth.ask(c, all, true), b = ScanAuth.ask(c, all, false);
                SwingUtilities.invokeLater(() -> {
                    if (mine != turn[0]) return;
                    show(withSent, a.sent());
                    show(withoutSent, b.sent());
                    if (a.ok()) show(with, a.shown());
                    if (b.ok()) show(without, b.shown());
                    if (!a.ok()) { say.accept("No response with the session (" + a.error() + ").", Theme.TEXT); return; }
                    String said = "Returned " + a.status() + " with the session and "
                            + (b.ok() ? String.valueOf(b.status()) : "no response") + " without it. "
                            + "Highlight text in the response that shows you are logged in.";
                    say.accept(said, Theme.TEXT);
                });
            }, "session-check-send").start();
        };

        Runnable prove = () -> {
            ScanAuth.Check c = current[0];
            if (c == null) { say.accept("Select a request first.", Theme.TEXT); return; }
            String wanted = text.getText();
            if (wanted.isBlank()) { say.accept("Highlight the logged-in text in the response with the session first.", Theme.TEXT); return; }
            c.text = wanted;
            unproven.run();
            int mine = ++turn[0];
            say.accept("Verifying...", Theme.TEXT);
            verify.setEnabled(false);   // Clear stays: it calls a check off
            new Thread(() -> {
                ScanAuth.Proof p;
                try { p = ScanAuth.measure(c, session, extra); }
                catch (RuntimeException ex) { p = new ScanAuth.Proof(false, false, "Could not be verified: " + ex, null, null); }
                final ScanAuth.Proof got = p;
                SwingUtilities.invokeLater(() -> {
                    verify.setEnabled(true);
                    if (mine != turn[0]) return;
                    say.accept(got.said(), got.ok() ? Theme.OK : FAILED);
                    if (got.with() != null) { show(withSent, got.with().sent()); if (got.with().ok()) show(with, got.with().shown()); }
                    if (got.without() != null) { show(withoutSent, got.without().sent()); if (got.without().ok()) show(without, got.without().shown()); }
                    // A refusal is explained by the response that caused it: bring that one to the front.
                    if (got.misleading()) answers.setSelectedIndex(1);
                    if (got.ok() && wanted.equals(text.getText())) { proven[0] = c; add.setEnabled(true); }
                });
            }, "session-check-prove").start();
        };

        list.addListSelectionListener(e -> { if (!e.getValueIsAdjusting()) send.run(); });
        search.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override public void insertUpdate(javax.swing.event.DocumentEvent e) { fill.run(); }
            @Override public void removeUpdate(javax.swing.event.DocumentEvent e) { fill.run(); }
            @Override public void changedUpdate(javax.swing.event.DocumentEvent e) { fill.run(); }
        });
        search.addActionListener(e -> { if (!listed.isEmpty()) { list.setSelectedIndex(0); list.requestFocusInWindow(); } });
        // Text changed after a test: the result on show no longer speaks for what is in the box.
        Runnable edited = () -> {
            unproven.run();
            if (result.getForeground() != Theme.TEXT) say.accept("The text has changed. Press Verify.", Theme.TEXT);
        };
        text.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override public void insertUpdate(javax.swing.event.DocumentEvent e) { edited.run(); }
            @Override public void removeUpdate(javax.swing.event.DocumentEvent e) { edited.run(); }
            @Override public void changedUpdate(javax.swing.event.DocumentEvent e) { edited.run(); }
        });
        clear.addActionListener(e -> {
            ++turn[0];                      // a check still running is no longer waited for
            text.setText("");
            unproven.run();
            say.accept(current[0] == null ? "Select a request."
                    : "Highlight text in the response that shows you are logged in.", Theme.TEXT);
            text.requestFocusInWindow();
        });
        text.addActionListener(e -> prove.run());
        verify.addActionListener(e -> prove.run());
        // Text highlighted in the response with the session goes straight into the box: by the mouse when it
        // is let go, or by the keys. Verifying is left to the button, so nothing is sent while the user is still choosing.
        Runnable picked = () -> {
            String chosenText = with.getSelectedText();
            if (chosenText == null || chosenText.isBlank() || chosenText.equals(text.getText())) return;
            text.setText(chosenText);
            say.accept("Press Verify to check this text.", Theme.TEXT);
        };
        with.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mouseReleased(java.awt.event.MouseEvent e) { picked.run(); }
        });
        with.addKeyListener(new java.awt.event.KeyAdapter() {
            @Override public void keyReleased(java.awt.event.KeyEvent e) { picked.run(); }
        });
        add.addActionListener(e -> { chosen[0] = proven[0]; dialog.dispose(); });
        cancel.addActionListener(e -> dialog.dispose());

        fill.run();
        JPanel find = new JPanel(new BorderLayout(8, 0));
        find.setOpaque(false);
        find.add(Ui.label("Search:"), BorderLayout.WEST);
        find.add(search, BorderLayout.CENTER);
        find.add(count, BorderLayout.EAST);
        JScrollPane listScroll = Ui.scroll(list);
        listScroll.setPreferredSize(new Dimension(Ui.em(WIDE), Ui.em(104)));
        JPanel top = new JPanel(new BorderLayout(0, 6));
        top.setOpaque(false);
        JTextArea note = Ui.note("Select a request whose response shows that you are logged in, such as an account page or an API call that returns your details. "
                + "It is sent with the scan's session and without it, and both requests and responses are shown below. Highlight text that appears "
                + "only while logged in, then press Verify: the session is treated as valid for as long as the response contains that text.");
        Ui.sizeNote(note, Ui.em(WIDE));
        top.add(note, BorderLayout.NORTH);
        top.add(find, BorderLayout.CENTER);
        top.add(listScroll, BorderLayout.SOUTH);

        answers.setPreferredSize(new Dimension(Ui.em(WIDE), Ui.em(290)));

        // Three rows: the text, what was found of it, and the buttons together, all the same size.
        JButton[] four = {verify, clear, cancel, add};
        int bw = 0, bh = 0;
        for (JButton b : four) { bw = Math.max(bw, b.getPreferredSize().width); bh = Math.max(bh, b.getPreferredSize().height); }
        bw = Math.max(bw, Ui.em(84));
        for (JButton b : four) { b.setPreferredSize(new Dimension(bw, bh)); b.setMinimumSize(new Dimension(bw, bh)); }
        JPanel textRow = new JPanel(new BorderLayout(8, 0));
        textRow.setOpaque(false);
        textRow.add(Ui.label("Logged-in text:"), BorderLayout.WEST);
        textRow.add(text, BorderLayout.CENTER);
        JPanel buttons = new JPanel(new BorderLayout(8, 0));
        buttons.setOpaque(false);
        buttons.add(Ui.row(verify, clear), BorderLayout.WEST);
        buttons.add(Ui.row(cancel, add), BorderLayout.EAST);
        JPanel bottom = new JPanel(new BorderLayout(0, 8));
        bottom.setOpaque(false);
        bottom.add(textRow, BorderLayout.NORTH);
        bottom.add(result, BorderLayout.CENTER);
        bottom.add(buttons, BorderLayout.SOUTH);

        JPanel p = new JPanel(new BorderLayout(0, 8));
        p.setBorder(Ui.pad(12, 12, 12, 12));
        p.add(top, BorderLayout.NORTH);
        p.add(answers, BorderLayout.CENTER);
        p.add(bottom, BorderLayout.SOUTH);
        dialog.setContentPane(p);
        dialog.getRootPane().registerKeyboardAction(e -> dialog.dispose(),
                javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
        dialog.pack();
        dialog.setLocationRelativeTo(SwingUtilities.getWindowAncestor(parent));
        SwingUtilities.invokeLater(search::requestFocusInWindow);
        dialog.setVisible(true);
        return chosen[0];
    }

    /** A request and its response side by side, each under its name. */
    private static JComponent pair(JTextArea request, JTextArea response) {
        javax.swing.JSplitPane split = new javax.swing.JSplitPane(javax.swing.JSplitPane.HORIZONTAL_SPLIT,
                titled("Request", request), titled("Response", response));
        split.setBorder(null);
        split.setDividerSize(6);
        // Placed by proportion each time the pane is given its size. Left to itself the divider of a tab
        // first drawn after its text had loaded was placed from that text, and squeezed the request.
        Ui.balance(split, 0.42);
        return split;
    }

    private static JComponent titled(String title, JTextArea area) {
        JPanel p = new JPanel(new BorderLayout(0, 4));
        p.setOpaque(false);
        p.setBorder(Ui.pad(6, 0, 0, 0));
        p.add(Ui.bold(title), BorderLayout.NORTH);
        p.add(Ui.scroll(area), BorderLayout.CENTER);
        p.setMinimumSize(new Dimension(Ui.em(120), 0));
        return p;
    }

    private static JTextArea area() {
        JTextArea a = new JTextArea();
        a.setEditable(false);
        a.setFont(Ui.MONO);
        a.setLineWrap(true);
        a.setWrapStyleWord(false);
        return a;
    }

    /** Put a response on screen from its start. A very long one is cut for display only. */
    private static void show(JTextArea area, String shown) {
        area.setText(shown.length() > SHOWN
                ? shown.substring(0, SHOWN) + "\n\n[The rest of this response is not displayed. All of it is searched for the text.]" : shown);
        area.setCaretPosition(0);
    }
}