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.

11.9 KB
Raw Blame
package opensuite.proxy;

import opensuite.core.HttpMessage;
import opensuite.core.Settings;
import opensuite.core.SuiteContext;
import opensuite.testkit.Expect;
import opensuite.testkit.Harness;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.zip.GZIPOutputStream;

/** Settings > Tools > Proxy: the miscellaneous options, the response modification rules and the default rules. */
public final class ProxyOptionsTest {

    private static ProxyServer server() {
        try {
            java.nio.file.Path dir = Files.createTempDirectory("ot-proxy-options");
            // Removed with everything in it when the test run ends.
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                try (java.util.stream.Stream<java.nio.file.Path> all = Files.walk(dir)) {
                    all.sorted(java.util.Comparator.reverseOrder()).forEach(x -> x.toFile().delete());
                } catch (Exception ignored) { }
            }));
            return new ProxyServer(new SuiteContext(), dir);
        }
        catch (Exception e) { throw new RuntimeException(e); }
    }

    private static HttpMessage html(String headers, String body) {
        return new HttpMessage(("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n" + headers + "Content-Length: " + body.length() + "\r\n\r\n" + body)
                .getBytes(StandardCharsets.ISO_8859_1));
    }

    public void run() {
        Harness.suite("proxy options");

        Harness.test("a listener whose port is taken at start moves to the next free port", () -> {
            try (java.net.ServerSocket held = new java.net.ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1"))) {
                ProxyServer server = server();
                server.listeners().clear();
                ProxyListener l = new ProxyListener(held.getLocalPort());
                server.listeners().add(l);
                server.startAll();
                try {
                    Expect.isTrue(l.running, "the listener is running");
                    Expect.isTrue(l.port > held.getLocalPort() && l.port <= held.getLocalPort() + 50, "on a port just above the taken one, was " + l.port);
                } finally { server.stopAll(); }
            } catch (java.io.IOException e) { throw new RuntimeException(e); }
        });

        Harness.test("a listener whose port is free at start keeps it", () -> {
            int port;
            try (java.net.ServerSocket probe = new java.net.ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1"))) { port = probe.getLocalPort(); }
            catch (java.io.IOException e) { throw new RuntimeException(e); }
            ProxyServer server = server();
            server.listeners().clear();
            ProxyListener l = new ProxyListener(port);
            server.listeners().add(l);
            server.startAll();
            try { Expect.isTrue(l.running && l.port == port, "kept port " + port + ", was " + l.port); }
            finally { server.stopAll(); }
        });

        Harness.test("a kept-alive proxy connection goes on as Connection: keep-alive", () -> {
            HttpMessage m = new HttpMessage(("GET http://example.test/ HTTP/1.1\r\nHost: example.test\r\n"
                    + "Proxy-Connection: Keep-Alive\r\nProxy-Authorization: Basic eDp5\r\nAccept: */*\r\n\r\n")
                    .getBytes(StandardCharsets.ISO_8859_1));
            ProxyServer.stripProxyHeaders(m);
            Expect.isTrue(m.header("Proxy-Connection") == null, "Proxy-Connection removed");
            Expect.isTrue(m.header("Proxy-Authorization") == null, "Proxy-Authorization removed");
            Expect.isTrue("keep-alive".equals(m.header("Connection")), "Connection: keep-alive added");

            HttpMessage own = new HttpMessage(("GET / HTTP/1.1\r\nHost: example.test\r\n"
                    + "Proxy-Connection: Keep-Alive\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.ISO_8859_1));
            ProxyServer.stripProxyHeaders(own);
            Expect.isTrue("close".equals(own.header("Connection")), "the client's own Connection header is left alone");

            HttpMessage none = new HttpMessage("GET / HTTP/1.1\r\nHost: example.test\r\n\r\n".getBytes(StandardCharsets.ISO_8859_1));
            ProxyServer.stripProxyHeaders(none);
            Expect.isTrue(none.header("Connection") == null, "nothing added when the client did not ask");
        });

        Harness.test("encodings the suite cannot unpack are taken out of Accept-Encoding", () -> {
            Expect.equal(ProxyServer.supportedEncodings("gzip, deflate, br, zstd"), "gzip, deflate", "br and zstd removed");
            Expect.equal(ProxyServer.supportedEncodings("br"), "", "nothing left");
            Expect.equal(ProxyServer.supportedEncodings("gzip;q=0.8, identity"), "gzip;q=0.8, identity", "weights kept");
        });

        Harness.test("a gzip request body is unpacked and its headers put right", () -> {
            ByteArrayOutputStream packed = new ByteArrayOutputStream();
            try (GZIPOutputStream z = new GZIPOutputStream(packed)) { z.write("a=1&b=2".getBytes(StandardCharsets.UTF_8)); }
            catch (java.io.IOException e) { throw new java.io.UncheckedIOException(e); }
            byte[] head = ("POST /x HTTP/1.1\r\nHost: h\r\nContent-Encoding: gzip\r\nContent-Length: " + packed.size() + "\r\n\r\n").getBytes(StandardCharsets.ISO_8859_1);
            byte[] raw = new byte[head.length + packed.size()];
            System.arraycopy(head, 0, raw, 0, head.length);
            System.arraycopy(packed.toByteArray(), 0, raw, head.length, packed.size());
            HttpMessage request = new HttpMessage(raw);
            ProxyServer.unpackRequestBody(request);
            Expect.equal(new String(request.body(), StandardCharsets.UTF_8), "a=1&b=2", "body");
            Expect.isNull(request.header("Content-Encoding"), "encoding header gone");
            Expect.equal(request.header("Content-Length"), "7", "length");
        });

        Harness.test("a body that is not what it claims is left alone", () -> {
            HttpMessage request = new HttpMessage("POST /x HTTP/1.1\r\nHost: h\r\nContent-Encoding: gzip\r\nContent-Length: 5\r\n\r\nplain".getBytes(StandardCharsets.ISO_8859_1));
            ProxyServer.unpackRequestBody(request);
            Expect.equal(new String(request.body(), StandardCharsets.UTF_8), "plain", "body");
            Expect.equal(request.header("Content-Encoding"), "gzip", "header kept");
        });

        Harness.test("the secure flag comes off every cookie and nothing else changes", () -> {
            ProxyServer server = server();
            server.removeSecureFlag = true;
            HttpMessage response = html("Set-Cookie: a=1; Path=/; Secure; HttpOnly\r\nSet-Cookie: b=2; secure\r\nSet-Cookie: c=secure\r\n", "<p>hi</p>");
            server.applyResponseModification(response);
            Expect.equal(String.join("|", response.headers("Set-Cookie")), "a=1; Path=/; HttpOnly|b=2|c=secure", "cookies");
            Expect.equal(response.bodyText(), "<p>hi</p>", "body");
        });

        Harness.test("HTTPS links become HTTP links", () -> {
            ProxyServer server = server();
            server.httpsLinksToHttp = true;
            HttpMessage response = html("", "<a href=\"https://x.test/a\">https://x.test</a><form action='https://x.test/f'>");
            server.applyResponseModification(response);
            Expect.equal(response.bodyText(), "<a href=\"http://x.test/a\">https://x.test</a><form action='http://x.test/f'>", "body");
            Expect.equal(response.header("Content-Length"), String.valueOf(response.body().length), "length follows");
        });

        Harness.test("unhidden fields are marked only when highlighting is on", () -> {
            ProxyServer server = server();
            server.unhideHiddenFields = true;
            HttpMessage plain = html("", "<input type=\"hidden\" name=\"t\">");
            server.applyResponseModification(plain);
            Expect.equal(plain.bodyText(), "<input type=\"text\" name=\"t\">", "plain");
            server.highlightUnhidden = true;
            HttpMessage marked = html("", "<input type=\"hidden\" name=\"t\">");
            server.applyResponseModification(marked);
            Expect.isTrue(marked.bodyText().contains("type=\"text\" style=\"border:"), "marked: " + marked.bodyText());
        });

        Harness.test("the default rules are the reference's, in its order", () -> {
            ProxyServer server = server();
            Expect.equal(server.requestRules.size(), 4, "request rules");
            ProxyRule method = server.requestRules.get(2);
            Expect.equal(method.matchItem + "/" + method.relationship + "/" + method.condition + "/" + method.enabled,
                    "HTTP method/does not match/(get|post)/false", "third request rule");
            Expect.equal(server.responseRules.size(), 5, "response rules");
            Expect.equal(server.responseRules.get(2).relationship, "was intercepted", "third response rule");
        });

        Harness.test("interception at startup follows the setting", () -> {
            Settings s = new Settings();
            Expect.isFalse(ProxyTool.interceptAtStartup(s), "off by default");
            s.set(ProxyTool.INTERCEPT_STARTUP, "always");
            Expect.isTrue(ProxyTool.interceptAtStartup(s), "always");
            s.set(ProxyTool.INTERCEPT_STARTUP, "restore");
            Expect.isFalse(ProxyTool.interceptAtStartup(s), "restore, last off");
            s.setBool(ProxyTool.INTERCEPT_LAST, true);
            Expect.isTrue(ProxyTool.interceptAtStartup(s), "restore, last on");
        });

        Harness.test("WebSocket messages are held by direction and by scope", () -> {
            boolean c2s = WebSocketConnection.interceptClientToServer, s2c = WebSocketConnection.interceptServerToClient,
                    scoped = WebSocketConnection.interceptInScopeOnly;
            java.util.function.Predicate<String> before = WebSocketConnection.inScope;
            try {
                WebSocketConnection.interceptClientToServer = false;
                WebSocketConnection.interceptServerToClient = true;
                WebSocketConnection.interceptInScopeOnly = false;
                Expect.isFalse(WebSocketConnection.holds(true, "a.test"), "client to server off");
                Expect.isTrue(WebSocketConnection.holds(false, "a.test"), "server to client on");
                WebSocketConnection.interceptInScopeOnly = true;
                WebSocketConnection.inScope = "a.test"::equals;
                Expect.isTrue(WebSocketConnection.holds(false, "a.test"), "in scope");
                Expect.isFalse(WebSocketConnection.holds(false, "b.test"), "out of scope");
            } finally {
                WebSocketConnection.interceptClientToServer = c2s;
                WebSocketConnection.interceptServerToClient = s2c;
                WebSocketConnection.interceptInScopeOnly = scoped;
                WebSocketConnection.inScope = before;
            }
        });

        Harness.test("a listener whose port is taken reports that it did not start, and starts once moved", () -> {
            try (java.net.ServerSocket taken = new java.net.ServerSocket(0, 5, java.net.InetAddress.getLoopbackAddress())) {
                ProxyServer server = server();
                ProxyListener l = new ProxyListener();
                l.port = taken.getLocalPort();
                Expect.isTrue(!server.start(l), "start says no when the port is in use");
                Expect.isTrue(!l.running, "and the listener is not marked running");
                int free;
                try (java.net.ServerSocket probe = new java.net.ServerSocket(0)) { free = probe.getLocalPort(); }
                l.port = free;
                Expect.isTrue(server.start(l), "it starts on a free port");
                Expect.isTrue(l.running, "and is then running");
                server.stop(l);
            } catch (java.io.IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}