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.

20.4 KB
Raw Blame
package opensuite.report;

import opensuite.core.Issue;
import opensuite.core.LogEntry;
import opensuite.ui.Advisory;

import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Component;
import java.io.File;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Writes findings and traffic to disk: an HTML or XML issue report, and logged
 * traffic as CSV or HAR 1.2. Output is files only (no PDF), as agreed.
 */
public final class Export {

    /** Open the report wizard on {@code issues}; the file it suggests is named {@code baseName}. */
    public static void reportDialog(Component parent, List<Issue> issues, String baseName) {
        if (issues == null || issues.isEmpty()) {
            JOptionPane.showMessageDialog(parent, "There are no findings to export.",
                    "export report", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        java.awt.Window w = parent == null ? null : parent instanceof java.awt.Window pw ? pw : javax.swing.SwingUtilities.getWindowAncestor(parent);
        new ReportWizard(w instanceof java.awt.Frame f ? f : null, issues, baseName).setVisible(true);
    }

    private Export() {}

    // ---------------- issue report ----------------

    public static String issuesHtml(List<Issue> issues) {
        int high = 0, med = 0, low = 0, info = 0;
        for (Issue i : issues) switch (i.severity()) {
            case HIGH -> high++; case MEDIUM -> med++; case LOW -> low++; default -> info++;
        }
        StringBuilder b = new StringBuilder();
        b.append("<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">\n");
        b.append("<title>Open Suite report</title>\n<style>\n");
        b.append("body{font-family:system-ui,Segoe UI,Helvetica,Arial,sans-serif;margin:32px;color:#1c2733;}\n");
        b.append("h1{color:#DB612F;} h2{margin:0 0 4px;} .meta{color:#667;} hr{border:0;border-top:1px solid #dde3ea;margin:24px 0;}\n");
        b.append(".sev{display:inline-block;padding:1px 8px;border-radius:10px;color:#fff;font-size:12px;font-weight:600;}\n");
        b.append(".High{background:#E0474C;}.Medium{background:#7E57C2;}.Low{background:#4477CC;}.Information{background:#888;}\n");
        b.append("pre{background:#f5f7fa;border:1px solid #dde3ea;padding:10px;overflow:auto;white-space:pre-wrap;word-break:break-all;}\n");
        b.append("</style></head><body>\n");
        b.append("<h1>Open Suite findings</h1>\n");
        b.append("<p class=\"meta\">Generated ").append(Advisory.esc(Instant.now().toString()))
                .append(" &middot; ").append(issues.size()).append(" findings &middot; ")
                .append("High ").append(high).append(", Medium ").append(med)
                .append(", Low ").append(low).append(", Information ").append(info).append("</p>\n");
        // Findings at several sites are given site by site, with the list of sites first.
        java.util.Map<String, List<Issue>> bySite = bySite(issues);
        boolean grouped = bySite.size() > 1;
        if (grouped) {
            b.append("<h2>Sites</h2>\n<table style=\"border-collapse:collapse\">\n<tr><th align=\"left\">Site</th><th>High</th><th>Medium</th><th>Low</th><th>Information</th></tr>\n");
            int n = 0;
            for (java.util.Map.Entry<String, List<Issue>> en : bySite.entrySet()) {
                int h = 0, m = 0, l = 0, f = 0;
                for (Issue i : en.getValue()) switch (i.severity()) {
                    case HIGH -> h++; case MEDIUM -> m++; case LOW -> l++; default -> f++;
                }
                b.append("<tr><td style=\"padding:2px 24px 2px 0\"><a href=\"#site").append(++n).append("\">").append(Advisory.esc(en.getKey())).append("</a></td>")
                        .append("<td align=\"center\">").append(h).append("</td><td align=\"center\">").append(m)
                        .append("</td><td align=\"center\">").append(l).append("</td><td align=\"center\">").append(f).append("</td></tr>\n");
            }
            b.append("</table>\n");
        }
        List<Issue> ordered = new java.util.ArrayList<>();
        for (List<Issue> g : bySite.values()) ordered.addAll(g);
        String siteNow = null;
        int siteNo = 0;
        for (Issue i : ordered) {
            String site = siteOf(i);
            if (grouped && !site.equals(siteNow)) {
                siteNow = site;
                b.append("<hr>\n<h1 id=\"site").append(++siteNo).append("\">").append(Advisory.esc(site)).append("</h1>\n");
            }
            b.append("<hr>\n<h2>").append(Advisory.esc(i.title())).append("</h2>\n");
            b.append("<p><span class=\"sev ").append(i.severity().label()).append("\">")
                    .append(i.severity().label()).append("</span> &middot; confidence ")
                    .append(Advisory.esc(i.confidence().label())).append("</p>\n");
            b.append("<p class=\"meta\">").append(Advisory.esc(i.host())).append(Advisory.esc(i.path()));
            if (i.param() != null && !i.param().isEmpty()) b.append(" &middot; parameter ").append(Advisory.esc(i.param()));
            b.append("</p>\n");
            if (i.locationCount() > 1) {
                b.append("<p><b>Affected locations (").append(i.locationCount()).append("):</b></p>\n<ul>\n");
                for (String loc : i.locations()) b.append("<li>").append(Advisory.esc(i.host())).append(Advisory.esc(loc)).append("</li>\n");
                b.append("</ul>\n");
            }
            section(b, "Issue detail", i.detail());
            section(b, "Background", i.background());
            section(b, "Remediation", i.remediation());
            section(b, "Evidence", i.evidence());
            if (i.cwe() > 0) b.append("<p class=\"meta\">CWE-").append(i.cwe()).append("</p>\n");
            if (i.request() != null) pre(b, "Request", i.request().raw());
            if (i.response() != null) pre(b, "Response", i.response().raw());
        }
        b.append("</body></html>\n");
        return b.toString();
    }

    /** The site a finding is at, as a report names it: its address without a path. */
    static String siteOf(Issue i) {
        return i.service() != null ? i.service().url() : i.host() == null ? "" : i.host();
    }

    /** The findings site by site, sites in the order they first appear and findings in the order given. */
    static java.util.Map<String, List<Issue>> bySite(List<Issue> issues) {
        java.util.Map<String, List<Issue>> out = new java.util.LinkedHashMap<>();
        for (Issue i : issues) out.computeIfAbsent(siteOf(i), k -> new java.util.ArrayList<>()).add(i);
        return out;
    }

    private static void section(StringBuilder b, String title, String body) {
        if (body == null || body.isBlank()) return;
        b.append("<p><b>").append(title).append(":</b> ").append(Advisory.esc(body)).append("</p>\n");
    }

    private static void pre(StringBuilder b, String title, byte[] raw) {
        String s = new String(raw, StandardCharsets.ISO_8859_1);
        if (s.length() > 4000) s = s.substring(0, 4000) + "\n... (truncated)";
        b.append("<p><b>").append(title).append("</b></p>\n<pre>").append(Advisory.esc(s)).append("</pre>\n");
    }

    public static String issuesXml(List<Issue> issues) {
        StringBuilder b = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<issues>\n");
        for (Issue i : issues) {
            b.append("  <issue>\n");
            el(b, "title", i.title());
            el(b, "severity", i.severity().label());
            el(b, "confidence", i.confidence().label());
            el(b, "host", i.host());
            el(b, "path", i.path());
            el(b, "parameter", i.param());
            if (i.locationCount() > 1) {
                b.append("    <locations>\n");
                for (String loc : i.locations()) el(b, "location", loc);
                b.append("    </locations>\n");
            }
            el(b, "cwe", i.cwe() > 0 ? String.valueOf(i.cwe()) : "");
            el(b, "detail", i.detail());
            el(b, "background", i.background());
            el(b, "remediation", i.remediation());
            el(b, "evidence", i.evidence());
            b.append("  </issue>\n");
        }
        return b.append("</issues>\n").toString();
    }

    private static void el(StringBuilder b, String tag, String value) {
        b.append("    <").append(tag).append('>').append(xml(value)).append("</").append(tag).append(">\n");
    }

    private static String xml(String s) {
        if (s == null) return "";
        return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
    }

    // ---------------- traffic ----------------

    public static String trafficCsv(List<LogEntry> entries) {
        StringBuilder b = new StringBuilder("number,time,tool,method,url,status,length,mime,duration_ms,remote_ip\n");
        for (LogEntry e : entries) {
            b.append(e.number()).append(',')
             .append(csv(String.valueOf(e.time()))).append(',')
             .append(csv(e.tool())).append(',')
             .append(csv(e.request() == null ? "" : e.request().method())).append(',')
             .append(csv(e.url())).append(',')
             .append(e.status()).append(',')
             .append(e.responseLen()).append(',')
             .append(csv(e.mimeType())).append(',')
             .append(e.durationMillis()).append(',')
             .append(csv(e.remoteIp())).append('\n');
        }
        return b.toString();
    }

    private static String csv(String s) {
        if (s == null) s = "";
        if (s.contains(",") || s.contains("\"") || s.contains("\n")) return '"' + s.replace("\"", "\"\"") + '"';
        return s;
    }

    public static String trafficHar(List<LogEntry> entries) {
        StringBuilder b = new StringBuilder();
        b.append("{\"log\":{\"version\":\"1.2\",\"creator\":{\"name\":\"Open Suite\",\"version\":\"1\"},\"entries\":[");
        boolean first = true;
        for (LogEntry e : entries) {
            if (!first) b.append(',');
            first = false;
            b.append("\n{\"startedDateTime\":\"").append(js(Instant.ofEpochMilli(e.time().getTime()).toString()))
             .append("\",\"time\":").append(e.durationMillis()).append(',');
            harMessage(b, "request", e.request(), e.url());
            b.append(',');
            harMessage(b, "response", e.response(), null);
            b.append(",\"cache\":{},\"timings\":{\"send\":0,\"wait\":").append(e.durationMillis()).append(",\"receive\":0}}");
        }
        b.append("\n]}}\n");
        return b.toString();
    }

    private static void harMessage(StringBuilder b, String key, opensuite.core.HttpMessage m, String url) {
        b.append('"').append(key).append("\":{");
        if (m == null) {
            if ("request".equals(key)) b.append("\"method\":\"\",\"url\":\"").append(js(url == null ? "" : url))
                    .append("\",\"httpVersion\":\"HTTP/1.1\",\"headers\":[],\"queryString\":[],\"cookies\":[],\"headersSize\":-1,\"bodySize\":0");
            else b.append("\"status\":0,\"statusText\":\"\",\"httpVersion\":\"HTTP/1.1\",\"headers\":[],\"cookies\":[],"
                    + "\"content\":{\"size\":0,\"mimeType\":\"\",\"text\":\"\"},\"redirectURL\":\"\",\"headersSize\":-1,\"bodySize\":0");
            b.append('}');
            return;
        }
        // headers
        StringBuilder hdr = new StringBuilder("[");
        boolean f = true;
        for (String line : m.headerLines()) {
            int c = line.indexOf(':');
            if (c < 0) continue;
            if (!f) hdr.append(',');
            f = false;
            hdr.append("{\"name\":\"").append(js(line.substring(0, c).trim()))
               .append("\",\"value\":\"").append(js(line.substring(c + 1).trim())).append("\"}");
        }
        hdr.append(']');
        String body = m.bodyText();
        if ("request".equals(key)) {
            b.append("\"method\":\"").append(js(m.method())).append("\",\"url\":\"").append(js(url == null ? "" : url))
             .append("\",\"httpVersion\":\"HTTP/1.1\",\"headers\":").append(hdr)
             .append(",\"queryString\":[],\"cookies\":[],\"headersSize\":-1,\"bodySize\":").append(body.length());
            if (!body.isEmpty()) {
                b.append(",\"postData\":{\"mimeType\":\"").append(js(m.contentType()))
                 .append("\",\"text\":\"").append(js(body)).append("\"}");
            }
        } else {
            b.append("\"status\":").append(m.statusCode()).append(",\"statusText\":\"").append(js(m.statusText()))
             .append("\",\"httpVersion\":\"HTTP/1.1\",\"headers\":").append(hdr).append(",\"cookies\":[],")
             .append("\"content\":{\"size\":").append(body.length()).append(",\"mimeType\":\"").append(js(m.contentType()))
             .append("\",\"text\":\"").append(js(body)).append("\"},\"redirectURL\":\"\",\"headersSize\":-1,\"bodySize\":")
             .append(body.length());
        }
        b.append('}');
    }

    private static String js(String s) {
        if (s == null) return "";
        StringBuilder b = new StringBuilder(s.length() + 8);
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '"' -> b.append("\\\"");
                case '\\' -> b.append("\\\\");
                case '\n' -> b.append("\\n");
                case '\r' -> b.append("\\r");
                case '\t' -> b.append("\\t");
                default -> { if (c < 0x20) b.append(String.format("\\u%04x", (int) c)); else b.append(c); }
            }
        }
        return b.toString();
    }

    // ---------------- save helper ----------------

    // ---- saved items (request/response records, plain or base64) --------------

    private static final String ITEMS_DOCTYPE =
            "<!DOCTYPE items [\n"
          + "<!ELEMENT items (item*)>\n"
          + "<!ATTLIST items exportTool CDATA \"\">\n"
          + "<!ATTLIST items exportVersion CDATA \"\">\n"
          + "<!ATTLIST items exportTime CDATA \"\">\n"
          + "<!ELEMENT item (time, url, host, port, protocol, method, path, extension, request, status, responselength, mimetype, response, comment)>\n"
          + "<!ELEMENT time (#PCDATA)>\n"
          + "<!ELEMENT url (#PCDATA)>\n"
          + "<!ELEMENT host (#PCDATA)>\n"
          + "<!ATTLIST host ip CDATA \"\">\n"
          + "<!ELEMENT port (#PCDATA)>\n"
          + "<!ELEMENT protocol (#PCDATA)>\n"
          + "<!ELEMENT method (#PCDATA)>\n"
          + "<!ELEMENT path (#PCDATA)>\n"
          + "<!ELEMENT extension (#PCDATA)>\n"
          + "<!ELEMENT request (#PCDATA)>\n"
          + "<!ATTLIST request base64 (true|false) \"false\">\n"
          + "<!ELEMENT status (#PCDATA)>\n"
          + "<!ELEMENT responselength (#PCDATA)>\n"
          + "<!ELEMENT mimetype (#PCDATA)>\n"
          + "<!ELEMENT response (#PCDATA)>\n"
          + "<!ATTLIST response base64 (true|false) \"false\">\n"
          + "<!ELEMENT comment (#PCDATA)>\n"
          + "]>\n";

    /** The selected entries as an item XML, requests and responses plain or base64-encoded. */
    public static String itemsXml(List<opensuite.core.LogEntry> entries, boolean base64) {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
        StringBuilder b = new StringBuilder();
        b.append("<?xml version=\"1.1\"?>\n");
        b.append("<!-- NOTE: Any NULL bytes in requests and responses are preserved within this output, even "
                + "though this strictly breaks the XML syntax. If your XML parser rejects the NULL bytes then you "
                + "will need to remove or replace these bytes before parsing. Alternatively, you can use the option "
                + "to base64-encode requests and responses. -->\n");
        b.append(ITEMS_DOCTYPE);
        b.append("<items exportTool=\"Open Suite\" exportVersion=\"").append(Advisory.esc(opensuite.ui.Main.VERSION))
         .append("\" exportTime=\"").append(fmt.format(new Date())).append("\">\n");
        for (opensuite.core.LogEntry e : entries) {
            opensuite.core.HttpService svc = e.service();
            byte[] req  = e.request() == null ? new byte[0] : e.request().raw();
            byte[] resp = e.response() == null ? new byte[0] : e.response().raw();
            String ext = e.fileExtension();
            b.append("  <item>\n");
            plain(b, "time", fmt.format(e.time()));
            cdata(b, "url", e.url());
            b.append("    <host ip=\"").append(Advisory.esc(e.remoteIp())).append("\">")
             .append(Advisory.esc(svc == null ? "" : svc.host())).append("</host>\n");
            plain(b, "port", String.valueOf(svc == null ? 0 : svc.port()));
            plain(b, "protocol", svc != null && svc.secure() ? "https" : "http");
            cdata(b, "method", e.method());
            cdata(b, "path", e.requestPath());
            plain(b, "extension", ext == null || ext.isEmpty() ? "null" : ext);
            bodyEl(b, "request", req, base64);
            plain(b, "status", e.status() == 0 ? "" : String.valueOf(e.status()));
            plain(b, "responselength", String.valueOf(e.responseLen()));
            plain(b, "mimetype", e.mimeType());
            bodyEl(b, "response", resp, base64);
            cdata(b, "comment", e.notes());
            b.append("  </item>\n");
        }
        return b.append("</items>\n").toString();
    }

    private static void plain(StringBuilder b, String tag, String v) {
        b.append("    <").append(tag).append('>').append(Advisory.esc(v == null ? "" : v)).append("</").append(tag).append(">\n");
    }

    private static void cdata(StringBuilder b, String tag, String v) {
        b.append("    <").append(tag).append("><![CDATA[").append(cdataSafe(v)).append("]]></").append(tag).append(">\n");
    }

    private static void bodyEl(StringBuilder b, String tag, byte[] raw, boolean base64) {
        b.append("    <").append(tag).append(" base64=\"").append(base64).append("\"><![CDATA[");
        if (base64) b.append(Base64.getEncoder().encodeToString(raw));
        else b.append(cdataSafe(new String(raw, StandardCharsets.ISO_8859_1)));
        b.append("]]></").append(tag).append(">\n");
    }

    /** Make text safe inside a CDATA section by splitting any "]]>" sequence. */
    private static String cdataSafe(String s) {
        return s == null ? "" : s.replace("]]>", "]]]]><![CDATA[>");
    }

    /** Save items to a file chosen in a dialog, with an option to base64-encode. */
    public static void saveItemsDialog(Component parent, List<opensuite.core.LogEntry> entries) {
        if (entries == null || entries.isEmpty()) {
            JOptionPane.showMessageDialog(parent, "There are no items to save.", "Save items", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("save items");
        fc.setSelectedFile(new File("items.xml"));
        JCheckBox b64 = new JCheckBox("Base64-encode requests and responses");
        JPanel acc = new JPanel(new BorderLayout());
        acc.add(b64, BorderLayout.NORTH);
        fc.setAccessory(acc);
        if (fc.showSaveDialog(parent) != JFileChooser.APPROVE_OPTION) return;
        File f = fc.getSelectedFile();
        try (PrintWriter w = new PrintWriter(f, StandardCharsets.UTF_8)) {
            w.print(itemsXml(entries, b64.isSelected()));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(parent, "Save failed: " + e.getMessage(), "Save items", JOptionPane.ERROR_MESSAGE);
            return;
        }
        JOptionPane.showMessageDialog(parent, "Save successful: " + f.getAbsolutePath(),
                "Save items", JOptionPane.INFORMATION_MESSAGE);
    }

    public static void save(Component parent, String suggestedName, String content) {
        JFileChooser fc = new opensuite.ui.FileChooser();
        fc.setDialogTitle("export");
        fc.setSelectedFile(new java.io.File(suggestedName));
        if (fc.showSaveDialog(parent) != JFileChooser.APPROVE_OPTION) return;
        try (PrintWriter w = new PrintWriter(fc.getSelectedFile(), StandardCharsets.UTF_8)) {
            w.print(content);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(parent, "Export failed: " + e.getMessage(),
                    "export", JOptionPane.ERROR_MESSAGE);
        }
    }
}