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

import opensuite.core.Classifications;
import opensuite.core.HttpMessage;
import opensuite.core.Issue;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * The issue report: a summary table of severity against confidence, a bar
 * chart, a table of contents, then every issue with what was chosen of its
 * background, remediation, references, classifications, and its requests and
 * responses with the relevant part marked. One self-contained HTML file.
 */
public final class Report {
    private Report() {}

    public enum Messages { NONE, EXTRACT, FULL }
    public enum Organise { BY_TYPE, BY_SEVERITY, BY_SITE }

    /** Everything the report wizard lets the user choose. */
    public static final class Options {
        public boolean html = true;
        public boolean base64 = true;
        public boolean background = true, remediation = true, references = true, detail = true, classifications = true;
        public Messages requests = Messages.EXTRACT, responses = Messages.EXTRACT;
        public int requestLimit = 0, responseLimit = 0;    // 0: no limit
        public java.util.Set<String> types = null;          // null: every type
        public boolean falsePositives = false;
        public String title = "Open Suite Scanner Report";
        public Organise organise = Organise.BY_TYPE;
        public int contentsLevels = 2;
        public boolean summaryTable = true, summaryChart = true;
    }

    /** The issues the options let through, most serious first. */
    public static List<Issue> chosen(List<Issue> issues, Options o) {
        List<Issue> out = new ArrayList<>();
        for (Issue i : issues) {
            if (i.falsePositive() && !o.falsePositives) continue;
            if (o.types != null && !o.types.contains(i.title())) continue;
            out.add(i);
        }
        out.sort(java.util.Comparator.comparingInt(Report::order).thenComparing(Issue::title));
        return out;
    }

    private static int order(Issue i) { return i.falsePositive() ? 99 : i.severity().ordinal() * 3 + i.confidence().ordinal(); }

    private static final String[] SEV = {"High", "Medium", "Low", "Information", "False positive"};
    private static final String[] SEV_COLOUR = {"#D51F3D", "#FF6633", "#26649D", "#B0AFAF", "#C9CDD2"};
    private static final String[] CONF = {"Certain", "Firm", "Tentative"};

    private static int sevIndex(Issue i) { return i.falsePositive() ? 4 : i.severity().ordinal(); }

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

    private static String siteOf(Issue i) { return i.service() != null ? i.service().url() : i.host() == null ? "" : i.host(); }

    /** The top-level heading an issue goes under, by the chosen organisation. */
    private static String groupOf(Issue i, Options o) {
        return switch (o.organise) {
            case BY_TYPE -> i.title();
            case BY_SEVERITY -> SEV[sevIndex(i)];
            case BY_SITE -> siteOf(i);
        };
    }

    private static String entryTitle(Issue i, Options o) {
        String where = siteOf(i) + i.path() + (i.param() == null || i.param().isBlank() ? "" : " [" + i.param() + "]");
        return o.organise == Organise.BY_TYPE ? where : i.title() + (o.organise == Organise.BY_SITE ? " " + i.path() : " " + where);
    }

    /** The Open Suite mark, drawn in the page itself so the report stays one file. */
    private static final String LOGO = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"20 80 360 240\" width=\"54\" height=\"36\" aria-hidden=\"true\">"
            + "<defs><g id=\"osc\" transform=\"translate(0 2.5)\"><circle cx=\"92\" cy=\"248\" r=\"62\"/><circle cx=\"142\" cy=\"190\" r=\"58\"/>"
            + "<circle cx=\"211\" cy=\"180\" r=\"95\"/><circle cx=\"300\" cy=\"241\" r=\"69\"/><rect x=\"92\" y=\"200\" width=\"208\" height=\"110\"/></g>"
            + "<clipPath id=\"osl\"><rect x=\"0\" y=\"0\" width=\"140\" height=\"400\"/></clipPath>"
            + "<clipPath id=\"osr\"><rect x=\"152\" y=\"0\" width=\"248\" height=\"400\"/></clipPath></defs>"
            + "<use href=\"#osc\" fill=\"#414143\" clip-path=\"url(#osl)\"/><use href=\"#osc\" fill=\"#EC673A\" clip-path=\"url(#osr)\"/></svg>";

    public static String html(List<Issue> all, Options o) {
        List<Issue> issues = chosen(all, o);
        Map<String, List<Issue>> groups = new LinkedHashMap<>();
        for (Issue i : issues) groups.computeIfAbsent(groupOf(i, o), k -> new ArrayList<>()).add(i);

        StringBuilder b = new StringBuilder(64 * 1024);
        b.append("<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">\n<title>").append(esc(o.title)).append("</title>\n<style>\n")
         .append("body{font:14px/1.5 system-ui,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#1c2733;margin:0;background:#fff}\n")
         .append(".page{max-width:1100px;margin:0 auto;padding:10px 40px 60px}\n")
         .append(".top{text-align:center;padding:34px 0 22px;border-bottom:2px solid #EC673A}\n")
         .append(".brand{display:inline-flex;align-items:center;gap:10px;font-size:30px;font-weight:700;letter-spacing:-.5px;color:#414143}.brand span{color:#EC673A}\n")
         .append(".top h1{margin:14px 0 0;font-size:24px;color:#414143}.top p{margin:6px 0 0;color:#5b6877}\n")
         .append("table.m,table.chart{margin:14px auto}\n")
         .append("h1.s{font-size:22px;margin:34px 0 10px;padding-bottom:6px;border-bottom:1px solid #dde3ea;color:#414143}\n")
         .append("h2{font-size:19px;margin:30px 0 8px}h3{font-size:16px;margin:24px 0 6px}h4{font-size:14px;margin:18px 0 6px;color:#0B0B1E}\n")
         .append("table.m{border-collapse:collapse}table.m th,table.m td{padding:6px 14px;text-align:center;border:1px solid #dde3ea}table.m th{background:#f3f5f8;font-weight:600}\n")
         .append("table.m td.l,table.m th.l{text-align:left}\n")
         .append(".b{display:inline-block;min-width:34px;padding:2px 8px;border-radius:3px;color:#fff;font-weight:600}\n")
         .append(".bar{height:18px;border-radius:2px;display:inline-block;vertical-align:middle}.chart td{padding:4px 10px 4px 0}\n")
         .append("table.k{border-collapse:collapse}table.k td{padding:3px 18px 3px 0;vertical-align:top}table.k td:first-child{color:#5b6877}\n")
         .append("ul.toc{list-style:none;padding-left:0}ul.toc ul{list-style:none;padding-left:22px}ul.toc a{color:#1c2733;text-decoration:none}ul.toc a:hover{text-decoration:underline}\n")
         .append("pre{background:#f6f8fa;border:1px solid #dde3ea;padding:10px;overflow:auto;white-space:pre-wrap;word-break:break-all;font:12px/1.45 ui-monospace,Menlo,Consolas,monospace}\n")
         .append("mark{background:#FFD9A8;color:inherit;padding:1px 0}.snip{color:#8a94a0}.rule{border-top:1px solid #dde3ea;margin:30px 0 0}\n")
         .append(".nav{font-size:12px;float:right}.nav a{color:#EC673A;margin-left:10px}a{color:#D2562A}\n")
         .append("</style></head><body>\n")
         .append("<div class=\"page\">\n<div class=\"top\"><div class=\"brand\">").append(LOGO).append("<div>Open <span>Suite</span></div></div><h1>")
         .append(esc(o.title)).append("</h1><p>Generated ")
         .append(esc(new java.text.SimpleDateFormat("d MMMM yyyy, HH:mm").format(new java.util.Date())))
         .append(" &middot; ").append(issues.size()).append(issues.size() == 1 ? " issue" : " issues").append("</p></div>\n");

        int[][] grid = new int[SEV.length][CONF.length];
        for (Issue i : issues) grid[sevIndex(i)][i.confidence().ordinal()]++;
        int rows = o.falsePositives ? SEV.length : SEV.length - 1;

        if (o.summaryTable || o.summaryChart) b.append("<h1 class=\"s\">Summary</h1>\n");
        if (o.summaryTable) {
            b.append("<p>The table below shows the numbers of issues identified in different categories. Issues are classified ")
             .append("according to severity as High, Medium, Low or Information. This reflects the likely impact of each issue for a ")
             .append("typical organisation. Issues are also classified according to confidence as Certain, Firm or Tentative. This ")
             .append("reflects how reliable the technique was that identified the issue.</p>\n")
             .append("<table class=\"m\"><tr><th></th><th></th><th colspan=\"3\">Confidence</th><th></th></tr>\n")
             .append("<tr><th></th><th></th><th>Certain</th><th>Firm</th><th>Tentative</th><th>Total</th></tr>\n");
            for (int s = 0; s < rows; s++) {
                b.append("<tr>");
                if (s == 0) b.append("<th rowspan=\"").append(rows).append("\">Severity</th>");
                b.append("<th class=\"l\">").append(SEV[s]).append("</th>");
                int total = 0;
                for (int c = 0; c < CONF.length; c++) {
                    total += grid[s][c];
                    b.append("<td><span class=\"b\" style=\"background:").append(SEV_COLOUR[s]).append(";opacity:").append(c == 0 ? "1" : c == 1 ? ".8" : ".6")
                     .append("\">").append(grid[s][c]).append("</span></td>");
                }
                b.append("<td><b>").append(total).append("</b></td></tr>\n");
            }
            b.append("</table>\n");
        }
        if (o.summaryChart) {
            int max = 1;
            int[] totals = new int[SEV.length];
            for (int s = 0; s < rows; s++) { for (int c = 0; c < CONF.length; c++) totals[s] += grid[s][c]; max = Math.max(max, totals[s]); }
            b.append("<p>The chart below shows the aggregated numbers of issues identified in each category. Solid colour bars ")
             .append("represent issues with a confidence level of Certain, and the bars fade as the confidence level falls.</p>\n<table class=\"chart\">\n");
            for (int s = 0; s < rows; s++) {
                b.append("<tr><td>").append(SEV[s]).append("</td><td>");
                for (int c = 0; c < CONF.length; c++) {
                    int w = (int) Math.round(600.0 * grid[s][c] / max);
                    if (w > 0) b.append("<span class=\"bar\" title=\"").append(CONF[c]).append(": ").append(grid[s][c]).append("\" style=\"width:").append(w)
                            .append("px;background:").append(SEV_COLOUR[s]).append(";opacity:").append(c == 0 ? "1" : c == 1 ? ".7" : ".45").append("\"></span>");
                }
                b.append(" ").append(totals[s]).append("</td></tr>\n");
            }
            b.append("</table>\n");
        }

        if (o.contentsLevels > 0) {
            b.append("<h1 class=\"s\">Contents</h1>\n<ul class=\"toc\">\n");
            int g = 0;
            for (Map.Entry<String, List<Issue>> en : groups.entrySet()) {
                g++;
                b.append("<li><a href=\"#g").append(g).append("\">").append(g).append(". ").append(esc(en.getKey())).append("</a>");
                if (o.contentsLevels > 1 && (en.getValue().size() > 1 || o.organise != Organise.BY_TYPE)) {
                    b.append("<ul>");
                    int n = 0;
                    for (Issue i : en.getValue()) {
                        n++;
                        b.append("<li><a href=\"#g").append(g).append("i").append(n).append("\">").append(g).append('.').append(n).append(". ")
                         .append(esc(entryTitle(i, o))).append("</a></li>");
                    }
                    b.append("</ul>");
                }
                b.append("</li>\n");
            }
            b.append("</ul>\n");
        }

        int g = 0;
        for (Map.Entry<String, List<Issue>> en : groups.entrySet()) {
            g++;
            List<Issue> list = en.getValue();
            b.append("<div class=\"rule\"></div>\n<h2 id=\"g").append(g).append("\">").append(g).append(". ").append(esc(en.getKey())).append("</h2>\n");
            boolean byType = o.organise == Organise.BY_TYPE;
            if (byType) {
                if (list.size() > 1) b.append("<p>There are ").append(list.size()).append(" instances of this issue.</p>\n");
                common(b, list.get(0), o);
            }
            int n = 0;
            for (Issue i : list) {
                n++;
                b.append("<h3 id=\"g").append(g).append("i").append(n).append("\"><span class=\"nav\">")
                 .append(n > 1 ? "<a href=\"#g" + g + "i" + (n - 1) + "\">Previous</a>" : "")
                 .append(n < list.size() ? "<a href=\"#g" + g + "i" + (n + 1) + "\">Next</a>" : "")
                 .append("</span>").append(g).append('.').append(n).append(". ").append(esc(entryTitle(i, o))).append("</h3>\n");
                b.append("<h4>Summary</h4>\n<table class=\"k\">")
                 .append("<tr><td>Severity:</td><td><b style=\"color:").append(SEV_COLOUR[sevIndex(i)]).append("\">").append(SEV[sevIndex(i)]).append("</b></td></tr>")
                 .append("<tr><td>Confidence:</td><td><b>").append(i.confidence().label()).append("</b></td></tr>")
                 .append("<tr><td>Host:</td><td><b>").append(esc(siteOf(i))).append("</b></td></tr>")
                 .append("<tr><td>Path:</td><td><b>").append(esc(i.path())).append("</b></td></tr>");
                if (i.param() != null && !i.param().isBlank()) b.append("<tr><td>Parameter:</td><td><b>").append(esc(i.param())).append("</b></td></tr>");
                b.append("</table>\n");
                if (i.locationCount() > 1) {
                    b.append("<h4>Affected locations (").append(i.locationCount()).append(")</h4>\n<ul>");
                    for (String loc : i.locations()) b.append("<li>").append(esc(siteOf(i))).append(esc(loc)).append("</li>");
                    b.append("</ul>\n");
                }
                if (o.detail) text(b, "Issue detail", i.detail());
                if (!byType) common(b, i, o);
                message(b, "Request", i.request(), o.requests, o.requestLimit, i.attack().isEmpty() ? i.evidence() : i.attack());
                message(b, "Response", i.response(), o.responses, o.responseLimit, i.evidence());
            }
        }
        b.append("<div class=\"rule\"></div>\n<p style=\"color:#8a94a0;font-size:12px\">Report generated by Open Suite.</p>\n</div></body></html>\n");
        return b.toString();
    }

    /** What is the same for every instance of a type: background, remediation, references, classifications. */
    private static void common(StringBuilder b, Issue i, Options o) {
        if (o.background) text(b, "Issue background", i.background());
        if (o.remediation) text(b, "Issue remediation", i.remediation());
        if (o.references) {
            List<String> refs = Classifications.references(i);
            if (!refs.isEmpty()) {
                b.append("<h4>References</h4>\n<ul>");
                for (String r : refs) b.append("<li>").append(link(r, r)).append("</li>");
                b.append("</ul>\n");
            }
        }
        if (o.classifications) {
            List<Classifications.Entry> cs = Classifications.of(i);
            if (!cs.isEmpty()) {
                b.append("<h4>Vulnerability classifications</h4>\n<ul>");
                for (Classifications.Entry c : cs) b.append("<li>").append(link(c.label(), c.link())).append("</li>");
                b.append("</ul>\n");
            }
        }
    }

    private static String link(String text, String to) {
        if (to == null || !(to.startsWith("http://") || to.startsWith("https://"))) return esc(text);
        return "<a href=\"" + esc(to) + "\">" + esc(text) + "</a>";
    }

    private static void text(StringBuilder b, String title, String body) {
        if (body == null || body.isBlank()) return;
        b.append("<h4>").append(title).append("</h4>\n");
        for (String para : body.trim().split("\\R\\s*\\R")) b.append("<p>").append(esc(para.trim()).replace("\n", "<br>")).append("</p>\n");
    }

    private static void message(StringBuilder b, String title, HttpMessage m, Messages how, int limit, String mark) {
        if (m == null || how == Messages.NONE) return;
        String s = new String(m.raw(), StandardCharsets.ISO_8859_1);
        if (s.isEmpty()) return;
        b.append("<h4>").append(title).append("</h4>\n<pre>").append(how == Messages.FULL ? full(s, mark, limit) : extract(s, mark, limit)).append("</pre>\n");
    }

    private static final String SNIP = "<span class=\"snip\">\n...[SNIP]...\n</span>";

    /** The whole message, cut at the limit, with the relevant part marked. */
    static String full(String s, String mark, int limit) {
        boolean cut = limit > 0 && s.length() > limit;
        if (cut) s = s.substring(0, limit);
        return marked(s, mark) + (cut ? SNIP : "");
    }

    /**
     * The relevant extract: the headers, then only the part of the body around
     * what the finding points at. With nothing to point at, the start of the body.
     */
    static String extract(String s, String mark, int limit) {
        int headEnd = s.indexOf("\r\n\r\n");
        String head = headEnd < 0 ? s : s.substring(0, headEnd + 4);
        String body = headEnd < 0 ? "" : s.substring(headEnd + 4);
        StringBuilder out = new StringBuilder(marked(head, mark));
        int budget = limit > 0 ? Math.max(0, limit - head.length()) : Integer.MAX_VALUE;
        if (body.isEmpty() || budget == 0) return out.toString();
        int at = mark == null || mark.isEmpty() ? -1 : body.indexOf(mark);
        final int around = 240;
        if (at < 0) {
            int take = Math.min(Math.min(body.length(), 600), budget);
            out.append(esc(body.substring(0, take)));
            if (take < body.length()) out.append(SNIP);
            return out.toString();
        }
        int from = Math.max(0, at - around), to = Math.min(body.length(), at + mark.length() + around);
        if (to - from > budget) to = Math.max(at + Math.min(mark.length(), budget), from + budget);
        to = Math.min(to, body.length());
        if (from > 0) out.append(SNIP);
        out.append(marked(body.substring(from, to), mark));
        if (to < body.length()) out.append(SNIP);
        return out.toString();
    }

    /** Escaped text with every occurrence of {@code mark} wrapped as the relevant part. */
    static String marked(String s, String mark) {
        if (mark == null || mark.isBlank()) return esc(s);
        StringBuilder out = new StringBuilder(s.length() + 64);
        int from = 0;
        while (true) {
            int at = s.indexOf(mark, from);
            if (at < 0) break;
            out.append(esc(s.substring(from, at))).append("<mark>").append(esc(mark)).append("</mark>");
            from = at + mark.length();
        }
        return out.append(esc(s.substring(from))).toString();
    }

    /** Issue data as XML, with requests and responses, Base64-encoded when asked. */
    public static String xml(List<Issue> all, Options o) {
        StringBuilder b = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<issues exportTime=\"")
                .append(esc(java.time.Instant.now().toString())).append("\">\n");
        for (Issue i : chosen(all, o)) {
            b.append("  <issue>\n");
            el(b, "name", i.title());
            el(b, "host", siteOf(i));
            el(b, "path", i.path());
            el(b, "parameter", i.param());
            el(b, "severity", SEV[sevIndex(i)]);
            el(b, "confidence", i.confidence().label());
            if (i.locationCount() > 1) {
                b.append("    <locations>\n");
                for (String loc : i.locations()) b.append("  ").append(tag("location", loc));
                b.append("    </locations>\n");
            }
            if (o.background) el(b, "issueBackground", i.background());
            if (o.remediation) el(b, "remediationBackground", i.remediation());
            if (o.detail) el(b, "issueDetail", i.detail());
            if (o.references) el(b, "references", String.join("\n", Classifications.references(i)));
            if (o.classifications) {
                StringBuilder c = new StringBuilder();
                for (Classifications.Entry e : Classifications.of(i)) c.append(e.label()).append('\n');
                el(b, "vulnerabilityClassifications", c.toString().trim());
            }
            el(b, "evidence", i.evidence());
            if (o.requests != Messages.NONE && i.request() != null || o.responses != Messages.NONE && i.response() != null) {
                b.append("    <requestresponse>\n");
                if (o.requests != Messages.NONE && i.request() != null) raw(b, "request", i.request().raw(), o.requestLimit, o.base64);
                if (o.responses != Messages.NONE && i.response() != null) raw(b, "response", i.response().raw(), o.responseLimit, o.base64);
                b.append("    </requestresponse>\n");
            }
            b.append("  </issue>\n");
        }
        return b.append("</issues>\n").toString();
    }

    private static void raw(StringBuilder b, String tag, byte[] bytes, int limit, boolean base64) {
        if (limit > 0 && bytes.length > limit) bytes = java.util.Arrays.copyOf(bytes, limit);
        b.append("      <").append(tag).append(" base64=\"").append(base64).append("\">")
         .append(base64 ? java.util.Base64.getEncoder().encodeToString(bytes) : esc(new String(bytes, StandardCharsets.ISO_8859_1)))
         .append("</").append(tag).append(">\n");
    }

    private static void el(StringBuilder b, String tag, String value) { if (value != null && !value.isBlank()) b.append(tag(tag, value)); }
    private static String tag(String tag, String value) { return "    <" + tag + ">" + esc(value) + "</" + tag + ">\n"; }
}