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.

13.1 KB
Raw Blame
package opensuite.core;

import opensuite.testkit.Expect;
import opensuite.testkit.Harness;

import java.net.InetAddress;

/** Settings > Network as the HTTP client applies it. */
public final class NetworkConfigTest {

    public void run() {
        Harness.suite("network settings");

        Harness.test("a hostname override gives the address and keeps the name", () -> {
            String rows = "true\tapp.test\t10.1.2.3\nfalse\toff.test\t10.9.9.9\ntrue\tbad.test\tnot-an-ip.example\n";
            Expect.isTrue("10.1.2.3".equals(NetworkConfig.override(rows, "APP.test")), "matched whatever the case");
            Expect.isTrue(NetworkConfig.override(rows, "off.test") == null, "a disabled row is ignored");
            Expect.isTrue(NetworkConfig.override(rows, "bad.test") == null, "only a literal address is taken");
            Expect.isTrue(NetworkConfig.override(rows, "other.test") == null, "no row, no override");
            Settings s = new Settings();
            try {
                s.set(NetworkConfig.DNS_OVERRIDES, rows);
                NetworkConfig.bind(s);
                InetAddress a = unchecked(() -> NetworkConfig.resolve("app.test"));
                Expect.isTrue("10.1.2.3".equals(a.getHostAddress()) && "app.test".equals(a.getHostName()), a.toString());
            } finally { s.remove(NetworkConfig.DNS_OVERRIDES); NetworkConfig.bind(null); }
        });

        Harness.test("the preferred address family comes first when there is one", () -> {
            InetAddress v4 = unchecked(() -> InetAddress.getByName("192.0.2.1")), v6 = unchecked(() -> InetAddress.getByName("2001:db8::1"));
            InetAddress[] both = { v6, v4 };
            Expect.isTrue(NetworkConfig.prefer(both, "ipv4") == v4, "IPv4 preferred");
            Expect.isTrue(NetworkConfig.prefer(both, "ipv6") == v6, "IPv6 preferred");
            Expect.isTrue(NetworkConfig.prefer(both, "system") == v6, "the system's order otherwise");
            Expect.isTrue(NetworkConfig.prefer(new InetAddress[]{ v6 }, "ipv4") == v6, "none of the family: the first there is");
        });

        Harness.test("the SOCKS proxy is used unless switched off or the host bypasses it", () -> {
            Settings s = new Settings();
            try {
                NetworkConfig.bind(s);
                s.set(NetworkConfig.SOCKS_HOST, "127.0.0.1");
                s.set(NetworkConfig.SOCKS_PORT, "9050");
                Expect.isTrue(NetworkConfig.socksFor("a.test") == null, "off");
                s.setBool(NetworkConfig.SOCKS_ON, true);
                UpstreamProxy p = NetworkConfig.socksFor("a.test");
                Expect.isTrue(p != null && p.type == UpstreamProxy.Type.SOCKS && p.port == 9050, "on");
                s.set(NetworkConfig.SOCKS_BYPASS, "*.internal.test\nlocalhost\n");
                Expect.isTrue(NetworkConfig.socksFor("db.internal.test") == null && NetworkConfig.socksFor("localhost") == null, "bypassed");
                Expect.isTrue(NetworkConfig.socksFor("a.test") != null, "others still go through it");
                Expect.isTrue(NetworkConfig.socksLogin("127.0.0.1") == null, "no login without a username");
                s.set(NetworkConfig.SOCKS_USER, "u");
                s.set(NetworkConfig.SOCKS_PASSWORD, "p");
                Expect.isTrue(NetworkConfig.socksLogin("127.0.0.1") != null && NetworkConfig.socksLogin("elsewhere.test") == null,
                        "the login goes to the configured proxy only");
            } finally {
                for (String k : new String[]{ NetworkConfig.SOCKS_HOST, NetworkConfig.SOCKS_PORT, NetworkConfig.SOCKS_ON, NetworkConfig.SOCKS_BYPASS,
                        NetworkConfig.SOCKS_USER, NetworkConfig.SOCKS_PASSWORD }) s.remove(k);
                NetworkConfig.bind(null);
            }
        });

        Harness.test("custom protocols and ciphers are the chosen ones that the runtime supports", () -> {
            String[] supported = { "SSLv2Hello", "TLSv1.2", "TLSv1.3", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" };
            String[] all = NetworkConfig.usable(supported, null);
            Expect.isTrue(all.length == 2 && NetworkConfig.has(all, "TLSv1.2") && NetworkConfig.has(all, "TLSv1.3"), "all usable ones");
            String[] one = NetworkConfig.usable(supported, "TLSv1.3, TLSv9");
            Expect.isTrue(one.length == 1 && one[0].equals("TLSv1.3"), "only what is both chosen and supported");
        });

        Harness.test("a client certificate row is picked by host, first match first", () -> {
            String rows = "true\t*.corp.test\tPKCS12\ta\ts\ti\t\tRSA\t/x/one.p12\tpw\n"
                        + "false\t*\tPKCS12\ta\ts\ti\t\tRSA\t/x/off.p12\tpw\n"
                        + "true\t\tPKCS12\ta\ts\ti\t\tRSA\t/x/any.p12\tpw\n";
            Expect.isTrue("/x/one.p12".equals(NetworkConfig.clientRow(rows, "app.corp.test")[8]), "the host's own row");
            Expect.isTrue("/x/any.p12".equals(NetworkConfig.clientRow(rows, "other.test")[8]), "a row with no host serves every host");
            Expect.isTrue(NetworkConfig.clientRow("", "other.test") == null, "no rows");
        });

        Harness.test("a redirect is followed only if its kind is allowed", () -> {
            Settings s = new Settings();
            String[] keys = { "http.redirect.3xx", "http.redirect.anyLocation", "http.redirect.refreshHeader", "http.redirect.metaRefresh", "http.redirect.javascript" };
            HttpMessage found = response("HTTP/1.1 302 Found\r\nLocation: /next", "");
            HttpMessage created = response("HTTP/1.1 201 Created\r\nLocation: /made", "");
            HttpMessage header = response("HTTP/1.1 200 OK\r\nRefresh: 0; url=/by-header", "");
            HttpMessage meta = response("HTTP/1.1 200 OK\r\nContent-Type: text/html", "<html><head><meta http-equiv=\"refresh\" content=\"0;URL='/by-meta?a=1&amp;b=2'\"></head></html>");
            HttpMessage script = response("HTTP/1.1 200 OK\r\nContent-Type: text/html", "<script>window.location.href = '/by-script';</script>");
            HttpMessage json = response("HTTP/1.1 200 OK\r\nContent-Type: application/json", "{\"x\":\"location = '/not-a-page'\"}");
            try {
                NetworkConfig.bind(s);
                Expect.isTrue("/next".equals(NetworkConfig.redirectTarget(found)), "3xx with Location, on by default");
                Expect.isTrue(NetworkConfig.redirectTarget(created) == null, "any status with Location, off by default");
                Expect.isTrue("/by-header".equals(NetworkConfig.redirectTarget(header)), "Refresh header, on by default");
                Expect.isTrue("/by-meta?a=1&b=2".equals(NetworkConfig.redirectTarget(meta)), "meta refresh, on by default: " + NetworkConfig.redirectTarget(meta));
                Expect.isTrue(NetworkConfig.redirectTarget(script) == null, "JavaScript-driven, off by default");
                s.setBool("http.redirect.javascript", true);
                s.setBool("http.redirect.anyLocation", true);
                Expect.isTrue("/by-script".equals(NetworkConfig.redirectTarget(script)), "JavaScript-driven once allowed");
                Expect.isTrue(NetworkConfig.redirectTarget(json) == null, "but only in a page");
                Expect.isTrue("/made".equals(NetworkConfig.redirectTarget(created)), "any status once allowed");
                s.setBool("http.redirect.3xx", false);
                s.setBool("http.redirect.anyLocation", false);
                s.setBool("http.redirect.refreshHeader", false);
                s.setBool("http.redirect.metaRefresh", false);
                Expect.isTrue(NetworkConfig.redirectTarget(found) == null && NetworkConfig.redirectTarget(header) == null
                        && NetworkConfig.redirectTarget(meta) == null, "each kind can be switched off");
            } finally { for (String k : keys) s.remove(k); NetworkConfig.bind(null); }
        });

        Harness.test("a 100 Continue is passed over for the response that follows it", () -> {
            try (java.net.ServerSocket server = new java.net.ServerSocket(0, 1, java.net.InetAddress.getLoopbackAddress())) {
                Thread t = new Thread(() -> {
                    try (java.net.Socket c = server.accept()) {
                        c.getInputStream().read(new byte[2048]);
                        c.getOutputStream().write("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok".getBytes());
                        c.getOutputStream().flush();
                    } catch (Exception ignored) { }
                });
                t.setDaemon(true);
                t.start();
                HttpMessage req = new HttpMessage("POST / HTTP/1.1\r\nHost: x\r\nExpect: 100-continue\r\nContent-Length: 1\r\n\r\na".getBytes());
                HttpClient.Result r = new HttpClient().send(new HttpService("127.0.0.1", server.getLocalPort(), false), req, new HttpClient.Options());
                Expect.isTrue(r.ok() && r.response.statusCode() == 200, "the real response: " + r.error);
                Expect.isTrue(r.interim != null && new String(r.interim).startsWith("HTTP/1.1 100"), "and the interim one is kept beside it");
            } catch (java.io.IOException e) { throw new IllegalStateException(e); }
        });

        Harness.test("verification is off unless asked for, and then uses a checking context", () -> {
            Settings s = new Settings();
            try {
                NetworkConfig.bind(s);
                Expect.isTrue(!NetworkConfig.verifies() && !NetworkConfig.special("a.test"), "off by default, as the reference");
                javax.net.ssl.SSLContext open = unchecked(() -> NetworkConfig.context("a.test"));
                s.setBool(NetworkConfig.TLS_VERIFY, true);
                javax.net.ssl.SSLContext checking = unchecked(() -> NetworkConfig.context("a.test"));
                Expect.isTrue(NetworkConfig.verifies() && NetworkConfig.special("a.test") && checking != open, "a context of its own when verifying");
            } finally { s.remove(NetworkConfig.TLS_VERIFY); NetworkConfig.bind(null); }
        });

        Harness.test("a streaming response loses its chunk sizes unless asked to keep them", () -> {
            String wire = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n3\r\nabc\r\n0\r\n\r\n";
            Settings s = new Settings();
            NetworkConfig.bind(s);
            try {
                byte[] stripped = unchecked(() -> HttpClient.readResponse(new java.io.ByteArrayInputStream(wire.getBytes(java.nio.charset.StandardCharsets.ISO_8859_1)), "GET", null, -1, new boolean[2], true));
                HttpMessage plain = new HttpMessage(stripped);
                Expect.equal(plain.bodyText(), "helloabc", "sizes gone");
                Expect.isNull(plain.header("Transfer-Encoding"), "no longer chunked");
                s.setBool("http.streaming.stripChunked", false);
                byte[] kept = unchecked(() -> HttpClient.readResponse(new java.io.ByteArrayInputStream(wire.getBytes(java.nio.charset.StandardCharsets.ISO_8859_1)), "GET", null, -1, new boolean[2], true));
                HttpMessage framed = new HttpMessage(kept);
                Expect.equal(framed.bodyText(), "5\r\nhello\r\n3\r\nabc\r\n0\r\n\r\n", "as the server sent it");
                Expect.equal(framed.header("Transfer-Encoding"), "chunked", "still chunked");
            } finally {
                NetworkConfig.bind(new Settings());
            }
        });

        Harness.test("a new request starts on HTTP/2 only when asked, over TLS, to a server that speaks it", () -> {
            Expect.equal(NetworkConfig.defaultMode(true, true, true), HttpMode.HTTP_2, "all three");
            Expect.equal(NetworkConfig.defaultMode(false, true, true), HttpMode.HTTP_1, "setting off");
            Expect.equal(NetworkConfig.defaultMode(true, false, true), HttpMode.HTTP_1, "plain HTTP");
            Expect.equal(NetworkConfig.defaultMode(true, true, false), HttpMode.HTTP_1, "server is HTTP/1 only");
        });

        Harness.test("the server is asked once and the answer kept", () -> {
            int[] asked = { 0 };
            NetworkConfig.setHttp2Probe(svc -> { asked[0]++; return svc.host().equals("h2.test"); });
            try {
                HttpService two = new HttpService("h2.test", 443, true), one = new HttpService("h1.test", 443, true);
                Expect.isTrue(NetworkConfig.speaksHttp2(two) && NetworkConfig.speaksHttp2(two), "speaks it");
                Expect.isFalse(NetworkConfig.speaksHttp2(one), "does not");
                Expect.equal(asked[0], 2, "one handshake a server");
                Expect.isFalse(NetworkConfig.speaksHttp2(new HttpService("h2.test", 80, false)), "plain HTTP is never asked");
                Expect.equal(asked[0], 2, "still two");
            } finally {
                NetworkConfig.setHttp2Probe(null);
            }
        });
    }

    private static HttpMessage response(String head, String body) {
        return new HttpMessage((head + "\r\nContent-Length: " + body.length() + "\r\n\r\n" + body).getBytes(java.nio.charset.StandardCharsets.ISO_8859_1));
    }

    private interface Throwing<T> { T get() throws Exception; }

    private static <T> T unchecked(Throwing<T> t) {
        try { return t.get(); } catch (Exception e) { throw new IllegalStateException(e); }
    }
}