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.

16.3 KB
Raw Blame
package opensuite.core;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The REST API of Settings > Suite > REST API: other tools start scans,
 * follow their progress and read issues and traffic over HTTP.
 *
 * Paths are {@code /v0.1/...}, or {@code /<api key>/v0.1/...} when keys are
 * required. The service only ever listens on the address in the service URL,
 * which is the loopback address unless changed, and it has no access beyond
 * what the endpoints below give.
 *
 * <pre>
 * GET  /v0.1/                                   this list of endpoints
 * GET  /v0.1/knowledge_base/issue_definitions   every kind of issue reported so far
 * POST /v0.1/scan                               {"urls": ["http://..."], "audit": true}; 201 with the task id in Location
 * GET  /v0.1/scan/{task id}                     the scan's status, counts and the issues found on its hosts
 * GET  /v0.1/issues                             every issue in the project
 * GET  /v0.1/history?limit=N                    the newest N requests of the history (100 unless given)
 * </pre>
 */
public final class RestApi {

    public static final String RUNNING = "rest.running", URL = "rest.url", NO_KEY = "rest.noKey", KEYS = "rest.keys";
    public static final String DEFAULT_URL = "http://127.0.0.1:1337";

    private final SuiteContext ctx;
    private volatile ServerSocket server;
    private volatile String boundTo = "";
    private volatile String problem = "";

    /** The scans started here: task id to the URLs asked for and the first task number that belongs to it. */
    private record Started(List<String> urls, int afterTask, long at) {}
    private final Map<Integer, Started> scans = new ConcurrentHashMap<>();
    private final AtomicInteger nextScan = new AtomicInteger(1);

    public RestApi(SuiteContext ctx) {
        this.ctx = ctx;
        ctx.settings().addListener(key -> { if (key != null && (key.equals(RUNNING) || key.equals(URL))) sync(); });
    }

    /** Why the service is not running although asked to, or empty. */
    public String problem() { return problem; }
    public boolean running() { return server != null; }

    /** Start, stop or move the service so that it is as the settings say. */
    public synchronized void sync() {
        boolean want = ctx.settings().getBool(RUNNING, false);
        String url = ctx.settings().get(URL, DEFAULT_URL);
        if (server != null && (!want || !url.equals(boundTo))) {
            try { server.close(); } catch (IOException ignored) { }
            server = null;
        }
        problem = "";
        if (!want || server != null) return;
        try {
            URI u = URI.create(url.trim());
            int port = u.getPort() < 0 ? 1337 : u.getPort();
            ServerSocket s = new ServerSocket(port, 50, InetAddress.getByName(u.getHost() == null ? "127.0.0.1" : u.getHost()));
            server = s;
            boundTo = url;
            Thread t = new Thread(() -> accept(s), "rest-api");
            t.setDaemon(true);
            t.start();
            ctx.alert("rest api", "listening on " + url);
        } catch (Exception e) {
            problem = String.valueOf(e.getMessage());
            ctx.alert("rest api", "could not listen on " + url + ": " + e.getMessage());
        }
    }

    /** The port the service is listening on, or -1; a service URL with port 0 gets one from the system. */
    public int port() { ServerSocket s = server; return s == null ? -1 : s.getLocalPort(); }

    private void accept(ServerSocket s) {
        while (!s.isClosed()) {
            try {
                Socket c = s.accept();
                Thread t = new Thread(() -> serve(c), "rest-api-request");
                t.setDaemon(true);
                t.start();
            } catch (IOException e) {
                return;
            }
        }
    }

    private void serve(Socket c) {
        try (c) {
            c.setSoTimeout(15_000);
            InputStream in = c.getInputStream();
            ByteArrayOutputStream head = new ByteArrayOutputStream();
            int b, state = 0;
            while (state < 4 && (b = in.read()) >= 0) {
                head.write(b);
                state = (b == '\r' && (state == 0 || state == 2)) || (b == '\n' && (state == 1 || state == 3)) ? state + 1 : (b == '\r' ? 1 : 0);
                if (head.size() > 64 * 1024) break;
            }
            HttpMessage req = new HttpMessage(head.toByteArray());
            int length = 0;
            try { length = Integer.parseInt(String.valueOf(req.header("Content-Length")).trim()); } catch (NumberFormatException ignored) { }
            length = Math.max(0, Math.min(length, 1024 * 1024));
            byte[] body = in.readNBytes(length);
            String[] answer = handle(req.method(), req.requestTarget(), new String(body, StandardCharsets.UTF_8));
            byte[] out = answer[1].getBytes(StandardCharsets.UTF_8);
            StringBuilder h = new StringBuilder("HTTP/1.1 ").append(answer[0]).append("\r\n")
                    .append("Content-Type: application/json; charset=utf-8\r\n")
                    .append("Content-Length: ").append(out.length).append("\r\n")
                    .append("X-Content-Type-Options: nosniff\r\n")
                    .append("Connection: close\r\n");
            if (answer.length > 2) h.append("Location: ").append(answer[2]).append("\r\n");
            OutputStream os = c.getOutputStream();
            os.write(h.append("\r\n").toString().getBytes(StandardCharsets.ISO_8859_1));
            os.write(out);
            os.flush();
        } catch (Exception e) {
            Debug.error("rest api request failed", e);
        }
    }

    /** One request: the status line's code and text, the JSON body, and for a new scan its Location. */
    String[] handle(String method, String target, String body) {
        String path = target == null ? "/" : target;
        String query = "";
        int q = path.indexOf('?');
        if (q >= 0) { query = path.substring(q + 1); path = path.substring(0, q); }
        List<String> parts = new ArrayList<>();
        for (String p : path.split("/")) if (!p.isEmpty()) parts.add(p);

        boolean open = ctx.settings().getBool(NO_KEY, false);
        if (!parts.isEmpty() && !parts.get(0).equals("v0.1")) {
            if (!open && !validKey(parts.get(0))) return error("401 Unauthorized", "The API key is not valid.");
            parts.remove(0);
        } else if (!open) {
            return error("401 Unauthorized", "An API key is required: /<api key>/v0.1/...");
        }
        if (parts.isEmpty() || !parts.get(0).equals("v0.1")) return error("404 Not Found", "Unknown path. The API is under /v0.1/.");
        parts.remove(0);
        String what = String.join("/", parts);
        boolean get = "GET".equalsIgnoreCase(method), post = "POST".equalsIgnoreCase(method);

        if (what.isEmpty()) {
            if (!get) return error("405 Method Not Allowed", "Use GET.");
            return ok("{\"version\":\"0.1\",\"endpoints\":["
                    + "{\"method\":\"GET\",\"path\":\"/v0.1/knowledge_base/issue_definitions\"},"
                    + "{\"method\":\"POST\",\"path\":\"/v0.1/scan\"},"
                    + "{\"method\":\"GET\",\"path\":\"/v0.1/scan/{task_id}\"},"
                    + "{\"method\":\"GET\",\"path\":\"/v0.1/issues\"},"
                    + "{\"method\":\"GET\",\"path\":\"/v0.1/history\"}]}");
        }
        if (what.equals("knowledge_base/issue_definitions")) {
            if (!get) return error("405 Method Not Allowed", "Use GET.");
            Map<String, Issue> kinds = new LinkedHashMap<>();
            for (Issue i : ctx.issues()) kinds.putIfAbsent(i.title(), i);
            StringBuilder sb = new StringBuilder("[");
            for (Issue i : kinds.values()) {
                if (sb.length() > 1) sb.append(',');
                sb.append("{\"name\":").append(str(i.title())).append(",\"issue_type_id\":").append(i.moduleId())
                  .append(",\"description\":").append(str(i.background())).append(",\"remediation\":").append(str(i.remediation()))
                  .append(",\"references\":").append(str(i.references())).append('}');
            }
            return ok(sb.append(']').toString());
        }
        if (what.equals("issues")) {
            if (!get) return error("405 Method Not Allowed", "Use GET.");
            return ok(issues(ctx.issues()));
        }
        if (what.equals("history")) {
            if (!get) return error("405 Method Not Allowed", "Use GET.");
            int limit = 100;
            Matcher m = Pattern.compile("(?:^|&)limit=(\\d{1,6})").matcher(query);
            if (m.find()) limit = Integer.parseInt(m.group(1));
            List<LogEntry> all = ctx.store().all();
            StringBuilder sb = new StringBuilder("[");
            for (int i = Math.max(0, all.size() - limit); i < all.size(); i++) {
                LogEntry e = all.get(i);
                if (sb.length() > 1) sb.append(',');
                HttpMessage rq = e.request(), rp = e.response();
                sb.append("{\"tool\":").append(str(e.tool())).append(",\"url\":").append(str(e.service().url() + (rq == null ? "" : rq.requestTarget())))
                  .append(",\"method\":").append(str(rq == null ? "" : rq.method()))
                  .append(",\"status\":").append(rp == null ? 0 : rp.statusCode())
                  .append(",\"length\":").append(rp == null ? 0 : rp.length())
                  .append(",\"time\":").append(e.time() == null ? 0 : e.time().getTime()).append('}');
            }
            return ok(sb.append(']').toString());
        }
        if (what.equals("scan")) {
            if (!post) return error("405 Method Not Allowed", "Use POST.");
            if (!ctx.canScan()) return error("503 Service Unavailable", "The scanner is not ready yet.");
            List<String> urls = new ArrayList<>();
            Matcher list = Pattern.compile("\"urls\"\\s*:\\s*\\[(.*?)\\]", Pattern.DOTALL).matcher(body);
            if (list.find()) {
                Matcher one = Pattern.compile("\"((?:[^\"\\\\]|\\\\.)*)\"").matcher(list.group(1));
                while (one.find()) urls.add(one.group(1).replace("\\/", "/"));
            }
            if (urls.isEmpty()) return error("400 Bad Request", "Specify the URLs to scan: {\"urls\": [\"http://example.test/\"]}");
            for (String u : urls) {
                String l = u.toLowerCase(Locale.ROOT);
                if (!(l.startsWith("http://") || l.startsWith("https://"))) return error("400 Bad Request", "Not an http or https URL: " + u);
            }
            boolean audit = !Pattern.compile("\"audit\"\\s*:\\s*false").matcher(body).find();
            int after = 0;
            for (ScanTask t : ctx.tasks()) after = Math.max(after, t.number);
            int id = nextScan.getAndIncrement();
            scans.put(id, new Started(urls, after, System.currentTimeMillis()));
            for (String u : urls) ctx.launchScan(u, audit);
            return new String[] { "201 Created", "{\"task_id\":" + id + "}", String.valueOf(id) };
        }
        if (parts.size() == 2 && parts.get(0).equals("scan")) {
            if (!get) return error("405 Method Not Allowed", "Use GET.");
            Started st;
            try { st = scans.get(Integer.parseInt(parts.get(1))); } catch (NumberFormatException e) { st = null; }
            if (st == null) return error("404 Not Found", "No scan matches that task ID.");
            int requests = 0, total = 0, done = 0;
            boolean any = false, running = false, paused = false;
            for (ScanTask t : ctx.tasks()) {
                // A scan is one task: a crawl while it crawls, an audit once it goes on to audit.
                if (t.number <= st.afterTask() || t.type() == ScanTask.Type.LIVE_PASSIVE) continue;
                any = true;
                requests += t.requests(); total += t.itemsTotal(); done += t.itemsDone();
                running |= t.state() == ScanTask.State.RUNNING;
                paused |= t.state() == ScanTask.State.PAUSED;
            }
            String status = !any ? "initializing" : running ? "running" : paused ? "paused" : "succeeded";
            List<Issue> found = new ArrayList<>();
            for (Issue i : ctx.issues()) {
                if (i.time() < st.at()) continue;
                for (String u : st.urls()) {
                    try { if (URI.create(u).getHost().equalsIgnoreCase(i.host())) { found.add(i); break; } } catch (Exception ignored) { }
                }
            }
            return ok("{\"task_id\":" + parts.get(1) + ",\"scan_status\":" + str(status)
                    + ",\"scan_metrics\":{\"audit_requests_made\":" + requests + ",\"audit_queue_items_completed\":" + done
                    + ",\"audit_queue_items_waiting\":" + Math.max(0, total - done) + ",\"issue_events\":" + found.size() + "}"
                    + ",\"issue_events\":" + issues(found) + "}");
        }
        return error("404 Not Found", "Unknown path. GET /v0.1/ lists the endpoints.");
    }

    private static String issues(List<Issue> list) {
        StringBuilder sb = new StringBuilder("[");
        for (Issue i : list) {
            if (sb.length() > 1) sb.append(',');
            sb.append("{\"name\":").append(str(i.title())).append(",\"severity\":").append(str(i.severity().label().toLowerCase(Locale.ROOT)))
              .append(",\"confidence\":").append(str(i.confidence().label().toLowerCase(Locale.ROOT)))
              .append(",\"origin\":").append(str(i.service() == null ? "" : i.service().url())).append(",\"path\":").append(str(i.path()))
              .append(",\"parameter\":").append(str(i.param())).append(",\"description\":").append(str(i.detail()))
              .append(",\"evidence\":").append(str(i.evidence())).append('}');
        }
        return sb.append(']').toString();
    }

    private static String[] ok(String json) { return new String[] { "200 OK", json }; }
    private static String[] error(String status, String message) { return new String[] { status, "{\"error\":" + str(message) + "}" }; }

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

    // ---- keys ----

    /** A new API key: 32 random characters. Only its hash is kept. */
    public static String newKey() {
        byte[] raw = new byte[24];
        new java.security.SecureRandom().nextBytes(raw);
        return java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(raw);
    }

    public static String hash(String key) {
        try {
            byte[] d = MessageDigest.getInstance("SHA-256").digest(key.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte x : d) sb.append(String.format("%02x", x));
            return sb.toString();
        } catch (Exception e) { throw new IllegalStateException(e); }
    }

    /** Rows of the key table are: enabled, name, created, hash of the key. */
    private boolean validKey(String key) {
        byte[] want = hash(key).getBytes(StandardCharsets.UTF_8);
        boolean valid = false;
        for (String line : ctx.settings().get(KEYS, "").split("\n")) {
            String[] cells = line.split("\t", -1);
            if (cells.length < 4 || "false".equals(cells[0])) continue;
            // Compared in constant time, and every row is compared, so timing tells nothing about a key.
            valid |= MessageDigest.isEqual(want, cells[3].getBytes(StandardCharsets.UTF_8));
        }
        return valid;
    }
}