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.1 KB
Raw Blame
package opensuite.report;

import opensuite.core.Issue;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * The report wizard: format, details to include, requests and responses,
 * issue types, file and structure, then a progress page that says the report
 * is complete and how large it is.
 */
public final class ReportWizard extends JDialog {
    private static final int PAGES = 6;
    private final CardLayout cards = new CardLayout();
    private final JPanel content = new JPanel(cards);
    private final JButton back = Ui.button("Back"), next = Ui.primaryButton("Next", null), cancel = Ui.button("Cancel");
    private int step;
    private final List<Issue> issues;
    private final String baseName;

    // Format
    private final JRadioButton asHtml = Ui.radio("Generate report (HTML)", true);
    private final JRadioButton asXml = Ui.radio("Export issue data (XML)", false);
    private final JCheckBox base64 = Ui.check("Base64-encode requests and responses", true);
    // Details
    private final JCheckBox background = Ui.check("Issue background", true), remediation = Ui.check("Remediation background", true),
            references = Ui.check("References", true), detail = Ui.check("Issue detail (where applicable)", true),
            remediationDetail = Ui.check("Remediation detail (where applicable)", true),
            classifications = Ui.check("Vulnerability classifications (where applicable)", true);
    // Messages
    private final MessageChoice requests = new MessageChoice("requests"), responses = new MessageChoice("responses");
    // Types
    private final List<String> typeNames = new ArrayList<>();
    private final List<Integer> typeCounts = new ArrayList<>();
    private final List<Boolean> typeOn = new ArrayList<>();
    private final JCheckBox falsePositives = Ui.check("Include false positives", false);
    // File and structure
    private final JTextField file = Ui.field(""), title = Ui.field("Open Suite Scanner Report");
    private final JComboBox<String> organise = new JComboBox<>(new String[]{"By type", "By severity", "By URL"});
    private final JComboBox<String> levels = new JComboBox<>(new String[]{"1", "2", "None"});
    private final JCheckBox summaryTable = Ui.check("Summary table", true), summaryChart = Ui.check("Summary bar chart", true);
    // Progress
    private final JProgressBar bar = new JProgressBar(0, 100);
    private final JLabel done = Ui.label(" ");

    /** One of the two "how much of the message" choices. */
    private static final class MessageChoice {
        final JRadioButton none, extract = Ui.radio("Include relevant extract", true), full = Ui.radio("Include full", false);
        final JCheckBox limit = Ui.check("Limit to", false);
        final JSpinner bytes = new JSpinner(new SpinnerNumberModel(5000, 100, 10_000_000, 500));
        MessageChoice(String what) {
            none = Ui.radio("Do not include " + what, false);
            ButtonGroup g = new ButtonGroup(); g.add(none); g.add(extract); g.add(full);
            bytes.setFont(Ui.PLAIN);
        }
        JComponent panel(String heading) {
            JPanel lim = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
            lim.setOpaque(false);
            lim.add(limit); lim.add(bytes); lim.add(Ui.label("bytes"));
            JLabel h = Ui.label(heading);
            h.setFont(Ui.BOLD);
            return stack(h, none, extract, full, lim);
        }
        Report.Messages how() { return none.isSelected() ? Report.Messages.NONE : full.isSelected() ? Report.Messages.FULL : Report.Messages.EXTRACT; }
        int cap() { return limit.isSelected() ? (Integer) bytes.getValue() : 0; }
    }

    public ReportWizard(Frame owner, List<Issue> issues, String baseName) {
        super(owner, "Report issues", true);
        this.issues = issues;
        // Stamped with the time, so a later report never writes over an earlier one.
        this.baseName = baseName + "-" + new java.text.SimpleDateFormat("yyyyMMdd-HHmmss").format(new java.util.Date());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        Map<String, Integer> counts = new LinkedHashMap<>();
        List<Issue> sorted = new ArrayList<>(issues);
        sorted.sort(java.util.Comparator.comparingInt(Issue::rank));
        for (Issue i : sorted) counts.merge(i.title(), 1, Integer::sum);
        for (Map.Entry<String, Integer> e : counts.entrySet()) { typeNames.add(e.getKey()); typeCounts.add(e.getValue()); typeOn.add(true); }

        ButtonGroup fmt = new ButtonGroup(); fmt.add(asHtml); fmt.add(asXml);
        base64.setBorder(Ui.pad(0, 24, 0, 0));
        base64.setEnabled(false);
        asXml.addItemListener(e -> base64.setEnabled(asXml.isSelected()));
        content.add(page("Select the report format", "Choose a readable report, or the issue data for another tool to read.",
                stack(asHtml, asXml, base64)), "0");
        content.add(page("Select the types of details to include", "Each kind of detail is included for the issues that have it.",
                stack(background, remediation, references, detail, remediationDetail, classifications)), "1");
        JPanel two = new JPanel(new GridLayout(1, 2, 30, 0));
        two.setOpaque(false);
        two.add(requests.panel("HTTP requests"));
        two.add(responses.panel("HTTP responses"));
        content.add(page("Select how HTTP messages should be shown", "A relevant extract is the headers and the part of the body the issue points at.", two), "2");
        content.add(page("Select the issue types to include", "Untick a type to leave every issue of that type out.", typesPanel()), "3");
        content.add(page("Select the file and the structure", "Choose where the report is saved and how it is laid out.", structurePanel()), "4");
        bar.setStringPainted(true);
        content.add(page("Generating report", "The report is written to the file you chose.", stack(bar, Box.createVerticalStrut(8), done)), "5");

        cancel.addActionListener(e -> dispose());
        back.addActionListener(e -> go(step - 1));
        next.addActionListener(e -> onNext());
        Ui.sameSize(cancel, back, next);
        JPanel bar2 = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 10));
        bar2.setBackground(Theme.BG);
        bar2.setBorder(Ui.pad(0, 0, 0, 14));
        bar2.add(cancel); bar2.add(back); bar2.add(next);
        setLayout(new BorderLayout());
        add(content, BorderLayout.CENTER);
        add(bar2, BorderLayout.SOUTH);
        go(0);
        setSize(720, 500);
        setLocationRelativeTo(owner);
    }

    private JComponent typesPanel() {
        AbstractTableModel m = new AbstractTableModel() {
            @Override public int getRowCount() { return typeNames.size(); }
            @Override public int getColumnCount() { return 3; }
            @Override public String getColumnName(int c) { return c == 0 ? "" : c == 1 ? "Issue type" : "Count"; }
            @Override public Class<?> getColumnClass(int c) { return c == 0 ? Boolean.class : c == 2 ? Integer.class : String.class; }
            @Override public boolean isCellEditable(int r, int c) { return c == 0; }
            @Override public Object getValueAt(int r, int c) { return c == 0 ? typeOn.get(r) : c == 1 ? typeNames.get(r) : typeCounts.get(r); }
            @Override public void setValueAt(Object v, int r, int c) { typeOn.set(r, Boolean.TRUE.equals(v)); fireTableCellUpdated(r, c); }
        };
        JTable t = new JTable(m);
        t.setFont(Ui.PLAIN);
        t.getTableHeader().setFont(Ui.PLAIN);
        t.setRowHeight(22);
        t.setShowGrid(false);
        t.getColumnModel().getColumn(0).setMaxWidth(36);
        t.getColumnModel().getColumn(2).setMaxWidth(70);
        JButton all = Ui.button("Select all"), none = Ui.button("Select none");
        all.addActionListener(e -> { for (int i = 0; i < typeOn.size(); i++) typeOn.set(i, true); m.fireTableDataChanged(); });
        none.addActionListener(e -> { for (int i = 0; i < typeOn.size(); i++) typeOn.set(i, false); m.fireTableDataChanged(); });
        JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
        buttons.setOpaque(false);
        buttons.add(all); buttons.add(none); buttons.add(Box.createHorizontalStrut(14)); buttons.add(falsePositives);
        falsePositives.setOpaque(false);
        JPanel p = new JPanel(new BorderLayout(0, 8));
        p.setOpaque(false);
        p.add(Ui.scroll(t), BorderLayout.CENTER);
        p.add(buttons, BorderLayout.SOUTH);
        return p;
    }

    private JComponent structurePanel() {
        JButton choose = Ui.button("Select file...");
        choose.addActionListener(e -> {
            JFileChooser fc = new opensuite.ui.FileChooser();
            fc.setSelectedFile(new File(file.getText().isBlank() ? baseName + (asHtml.isSelected() ? ".html" : ".xml") : file.getText()));
            if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) file.setText(fc.getSelectedFile().getAbsolutePath());
        });
        organise.setFont(Ui.PLAIN);
        levels.setFont(Ui.PLAIN);
        levels.setSelectedIndex(1);
        JPanel g = new JPanel(new GridBagLayout());
        g.setOpaque(false);
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(5, 0, 5, 10); c.anchor = GridBagConstraints.WEST;
        Object[][] rows = {{"File:", file, choose}, {"Report title:", title, null}, {"Issue organisation:", organise, null},
                {"Table of contents levels:", levels, null}};
        int y = 0;
        for (Object[] r : rows) {
            c.gridy = y++; c.gridx = 0; c.weightx = 0; c.fill = GridBagConstraints.NONE;
            g.add(Ui.label((String) r[0]), c);
            c.gridx = 1; c.weightx = r[1] instanceof JTextField ? 1 : 0; c.fill = r[1] instanceof JTextField ? GridBagConstraints.HORIZONTAL : GridBagConstraints.NONE;
            g.add((Component) r[1], c);
            if (r[2] != null) { c.gridx = 2; c.weightx = 0; c.fill = GridBagConstraints.NONE; g.add((Component) r[2], c); }
        }
        c.gridy = y++; c.gridx = 1; g.add(summaryTable, c);
        c.gridy = y; g.add(summaryChart, c);
        summaryTable.setOpaque(false); summaryChart.setOpaque(false);
        JPanel p = new JPanel(new BorderLayout());
        p.setOpaque(false);
        p.add(g, BorderLayout.NORTH);
        return p;
    }

    Report.Options options() {
        Report.Options o = new Report.Options();
        o.html = asHtml.isSelected();
        o.base64 = base64.isSelected();
        o.background = background.isSelected();
        // "Remediation detail" is advice written for one finding. No check here produces any, so
        // the box adds nothing on its own: it does not stand in for the general remediation text.
        o.remediation = remediation.isSelected();
        o.references = references.isSelected();
        o.detail = detail.isSelected();
        o.classifications = classifications.isSelected();
        o.requests = requests.how(); o.requestLimit = requests.cap();
        o.responses = responses.how(); o.responseLimit = responses.cap();
        o.types = new java.util.HashSet<>();
        for (int i = 0; i < typeNames.size(); i++) if (typeOn.get(i)) o.types.add(typeNames.get(i));
        o.falsePositives = falsePositives.isSelected();
        o.title = title.getText().isBlank() ? "Open Suite Scanner Report" : title.getText().trim();
        o.organise = Report.Organise.values()[organise.getSelectedIndex()];
        o.contentsLevels = levels.getSelectedIndex() == 2 ? 0 : levels.getSelectedIndex() + 1;
        o.summaryTable = summaryTable.isSelected();
        o.summaryChart = summaryChart.isSelected();
        return o;
    }

    private void onNext() {
        if (step == PAGES - 1) { dispose(); return; }
        if (step == PAGES - 2) {
            if (file.getText().isBlank()) {
                JOptionPane.showMessageDialog(this, "Select a file for the report.", "Report issues", JOptionPane.WARNING_MESSAGE);
                return;
            }
            go(step + 1);
            generate();
            return;
        }
        go(step + 1);
    }

    private void generate() {
        final Report.Options o = options();
        final File target = new File(file.getText().trim());
        back.setEnabled(false); next.setEnabled(false);
        bar.setIndeterminate(true);
        bar.setString("Generating");
        new SwingWorker<Long, Void>() {
            @Override protected Long doInBackground() throws Exception {
                String out = o.html ? Report.html(issues, o) : Report.xml(issues, o);
                byte[] bytes = out.getBytes(StandardCharsets.UTF_8);
                java.nio.file.Files.write(target.toPath(), bytes);
                return (long) bytes.length;
            }
            @Override protected void done() {
                bar.setIndeterminate(false);
                try {
                    long size = get();
                    bar.setValue(100);
                    bar.setString("Report completed");
                    done.setText("Report completed: " + String.format("%,d", size) + " bytes written to " + target.getName());
                    cancel.setVisible(false);
                    next.setText("Close");
                } catch (Exception e) {
                    bar.setValue(0);
                    bar.setString("Failed");
                    Throwable c = e.getCause() == null ? e : e.getCause();
                    done.setText("The report could not be written: " + c.getMessage());
                    back.setEnabled(true);
                }
                next.setEnabled(true);
            }
        }.execute();
    }

    private void go(int i) {
        step = Math.max(0, Math.min(PAGES - 1, i));
        cards.show(content, String.valueOf(step));
        back.setEnabled(step > 0 && step < PAGES - 1);
        next.setText(step == PAGES - 1 ? "Close" : "Next");
        if (step == PAGES - 2 && file.getText().isBlank()) {
            file.setText(new File(System.getProperty("user.home"), baseName + (asHtml.isSelected() ? ".html" : ".xml")).getAbsolutePath());
        }
    }

    private static JPanel stack(Component... parts) {
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
        p.setOpaque(false);
        for (Component c : parts) {
            if (c instanceof JComponent j) { j.setAlignmentX(Component.LEFT_ALIGNMENT); j.setOpaque(false); }
            p.add(c);
            p.add(Box.createVerticalStrut(6));
        }
        return p;
    }

    private static JComponent page(String heading, String text, JComponent body) {
        JPanel p = new JPanel(new BorderLayout(0, 14));
        p.setBackground(Theme.BG);
        p.setBorder(Ui.pad(18, 22, 10, 22));
        JPanel head = new JPanel(new BorderLayout(0, 6));
        head.setOpaque(false);
        head.add(Ui.heading(heading), BorderLayout.NORTH);
        JTextArea note = Ui.note(text);
        note.setOpaque(false);
        head.add(note, BorderLayout.CENTER);
        p.add(head, BorderLayout.NORTH);
        p.add(body, BorderLayout.CENTER);
        return p;
    }
}