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.

10.0 KB
Raw Blame
package opensuite.core;

import java.util.ArrayList;
import java.util.List;

/**
 * Switches a request body between URL-encoded and multipart form encoding,
 * for the editor's "Change body encoding" action. Many applications accept
 * either, and a filter that inspects one form often misses the other.
 */
public final class BodyEncoding {
    private BodyEncoding() {}

    private static final String FORM = "application/x-www-form-urlencoded";

    /** True when the request's body is multipart form data. */
    public static boolean isMultipart(HttpMessage req) {
        String ct = req.header("Content-Type");
        return ct != null && ct.toLowerCase().startsWith("multipart/form-data");
    }

    /**
     * Convert the body to the other encoding in place, updating Content-Type
     * and Content-Length. A request with no body is left alone. Returns true
     * when the message changed.
     */
    public static boolean toggle(HttpMessage req, String boundary) {
        if (req == null || !req.isRequest() || req.body().length == 0) return false;
        if (isMultipart(req)) {
            List<String[]> fields = parseMultipart(req.bodyText(), boundaryOf(req.header("Content-Type")));
            if (fields == null) return false;
            StringBuilder sb = new StringBuilder();
            for (String[] f : fields) {
                if (sb.length() > 0) sb.append('&');
                sb.append(encode(f[0])).append('=').append(encode(f[1]));
            }
            req.setBody(Bytes.bytes(sb.toString()));
            req.setHeader("Content-Type", FORM);
        } else {
            StringBuilder sb = new StringBuilder();
            for (String pair : req.bodyText().split("&")) {
                if (pair.isEmpty()) continue;
                int eq = pair.indexOf('=');
                String name = decode(eq < 0 ? pair : pair.substring(0, eq));
                String value = eq < 0 ? "" : decode(pair.substring(eq + 1));
                sb.append("--").append(boundary).append("\r\n")
                  .append("Content-Disposition: form-data; name=\"").append(name.replace("\"", "%22")).append("\"\r\n\r\n")
                  .append(value).append("\r\n");
            }
            sb.append("--").append(boundary).append("--\r\n");
            req.setBody(Bytes.bytes(sb.toString()));
            req.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
        }
        req.updateContentLength();
        return true;
    }

    /** What a request body can be converted to. */
    public enum Kind { FORM, MULTIPART, JSON }

    /** The encoding the body is in now, read from its Content-Type; a form when it says nothing else. */
    public static Kind kindOf(HttpMessage req) {
        if (isMultipart(req)) return Kind.MULTIPART;
        String ct = req == null ? null : req.header("Content-Type");
        return ct != null && ct.toLowerCase(java.util.Locale.ROOT).contains("json") ? Kind.JSON : Kind.FORM;
    }

    /**
     * Convert the body to {@code target} in place, updating Content-Type and
     * Content-Length. The body is read as names and values in the encoding it
     * has now and written again in the other. A request with no body, one
     * already in that encoding, or one whose body cannot be read is left
     * alone. Returns true when the message changed.
     */
    public static boolean convert(HttpMessage req, Kind target, String boundary) {
        if (req == null || !req.isRequest() || req.body().length == 0 || target == null) return false;
        Kind from = kindOf(req);
        if (from == target) return false;
        List<String[]> fields;
        switch (from) {
            case MULTIPART -> fields = parseMultipart(req.bodyText(), boundaryOf(req.header("Content-Type")));
            case JSON -> fields = parseJson(req.bodyText());
            default -> {
                fields = new ArrayList<>();
                for (String pair : req.bodyText().split("&")) {
                    if (pair.isEmpty()) continue;
                    int eq = pair.indexOf('=');
                    fields.add(new String[]{decode(eq < 0 ? pair : pair.substring(0, eq)), eq < 0 ? "" : decode(pair.substring(eq + 1))});
                }
            }
        }
        if (fields == null) return false;
        StringBuilder sb = new StringBuilder();
        switch (target) {
            case FORM -> {
                for (String[] f : fields) {
                    if (sb.length() > 0) sb.append('&');
                    sb.append(encode(f[0])).append('=').append(encode(f[1]));
                }
                req.setHeader("Content-Type", FORM);
            }
            case MULTIPART -> {
                for (String[] f : fields) {
                    sb.append("--").append(boundary).append("\r\n")
                      .append("Content-Disposition: form-data; name=\"").append(f[0].replace("\"", "%22")).append("\"\r\n\r\n")
                      .append(f[1]).append("\r\n");
                }
                sb.append("--").append(boundary).append("--\r\n");
                req.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
            }
            case JSON -> {
                sb.append('{');
                for (int i = 0; i < fields.size(); i++) {
                    if (i > 0) sb.append(',');
                    sb.append('"').append(opensuite.spider.Cdp.jsonEscape(fields.get(i)[0])).append("\":\"")
                      .append(opensuite.spider.Cdp.jsonEscape(fields.get(i)[1])).append('"');
                }
                sb.append('}');
                req.setHeader("Content-Type", "application/json");
            }
        }
        req.setBody(Bytes.bytes(sb.toString()));
        req.updateContentLength();
        return true;
    }

    /** The top-level names and values of a JSON object, or null when the body is not one. */
    static List<String[]> parseJson(String body) {
        try {
            opensuite.spider.Cdp.JsonValue v = opensuite.spider.Cdp.JsonValue.parse(body);
            if (v == null || !v.isObject()) return null;
            List<String[]> out = new ArrayList<>();
            for (String k : v.keys()) {
                String value = v.get(k).asString();
                out.add(new String[]{k, value == null ? "" : value});
            }
            return out;
        } catch (RuntimeException e) {
            return null;
        }
    }

    /** A boundary unlikely to occur in a form value. */
    public static String newBoundary() {
        return "----OpenSuiteFormBoundary" + Long.toHexString(System.nanoTime());
    }

    static String boundaryOf(String contentType) {
        if (contentType == null) return null;
        int i = contentType.toLowerCase().indexOf("boundary=");
        if (i < 0) return null;
        String b = contentType.substring(i + 9).trim();
        int semi = b.indexOf(';');
        if (semi >= 0) b = b.substring(0, semi).trim();
        if (b.length() >= 2 && b.startsWith("\"") && b.endsWith("\"")) b = b.substring(1, b.length() - 1);
        return b.isEmpty() ? null : b;
    }

    /** Name and value of each part, or null when the body cannot be read as multipart. */
    static List<String[]> parseMultipart(String body, String boundary) {
        if (boundary == null) return null;
        List<String[]> out = new ArrayList<>();
        String delim = "--" + boundary;
        int at = body.indexOf(delim);
        if (at < 0) return null;
        while (true) {
            int start = at + delim.length();
            if (body.startsWith("--", start)) break;               // closing delimiter
            int next = body.indexOf(delim, start);
            if (next < 0) break;
            String part = body.substring(start, next);
            if (part.startsWith("\r\n")) part = part.substring(2);
            else if (part.startsWith("\n")) part = part.substring(1);
            int gap = part.indexOf("\r\n\r\n");
            int skip = 4;
            if (gap < 0) { gap = part.indexOf("\n\n"); skip = 2; }
            if (gap >= 0) {
                String head = part.substring(0, gap);
                String value = part.substring(gap + skip);
                if (value.endsWith("\r\n")) value = value.substring(0, value.length() - 2);
                else if (value.endsWith("\n")) value = value.substring(0, value.length() - 1);
                String name = attribute(head, "name");
                if (name != null) out.add(new String[]{name, value});
            }
            at = next;
        }
        return out;
    }

    private static String attribute(String head, String attr) {
        String lower = head.toLowerCase();
        int i = 0;
        String key = attr + "=\"";
        while ((i = lower.indexOf(key, i)) >= 0) {
            // "name=" must not be the tail of "filename=".
            if (i == 0 || !Character.isLetterOrDigit(lower.charAt(i - 1))) {
                int end = head.indexOf('"', i + key.length());
                return end < 0 ? null : head.substring(i + key.length(), end);
            }
            i += key.length();
        }
        return null;
    }

    private static String encode(String s) {
        StringBuilder sb = new StringBuilder();
        for (byte b : Bytes.bytes(s)) {
            int c = b & 0xff;
            if (Character.isLetterOrDigit(c) && c < 128 || c == '-' || c == '_' || c == '.' || c == '~') sb.append((char) c);
            else if (c == ' ') sb.append('+');
            else sb.append('%').append(String.format("%02X", c));
        }
        return sb.toString();
    }

    private static String decode(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '+') sb.append(' ');
            else if (c == '%' && i + 2 < s.length() + 0 && isHex(s.charAt(i + 1)) && isHex(s.charAt(i + 2))) {
                sb.append((char) Integer.parseInt(s.substring(i + 1, i + 3), 16));
                i += 2;
            } else sb.append(c);
        }
        return sb.toString();
    }

    private static boolean isHex(char c) {
        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
    }
}