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.

17.3 KB
Raw Blame
package opensuite.core;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Platform authentication (Settings > Network > Connections): when a
 * server answers 401 and credentials are configured for its host, the request
 * is sent again with them, as Basic, Digest or NTLMv2.
 */
public final class PlatformAuth {

    public static final String ON = "auth.platform", ROWS = "auth.platform.rows", PROMPT = "auth.prompt";

    /** One set of credentials. */
    public record Login(String type, String user, String password, String domain, String workstation) {}

    /** Asks the owner for credentials for a host; returns null when they decline. */
    public interface Prompter { Login ask(String host, String schemes); }

    private static volatile Settings settings;
    private static volatile Prompter prompter;
    /** What the owner typed when prompted, kept for the session only. */
    private static final Map<String, Login> PROMPTED = new ConcurrentHashMap<>();
    private static final Map<String, Boolean> DECLINED = new ConcurrentHashMap<>();

    private PlatformAuth() { }

    public static void bind(Settings s) { settings = s; PROMPTED.clear(); DECLINED.clear(); }
    public static void setPrompter(Prompter p) { prompter = p; }

    /** The credentials configured for a host, or null. Rows are: enabled, host, type, username, password, domain, domain hostname. */
    static Login loginFor(String rows, String host) {
        for (String line : rows.split("\n")) {
            String[] c = line.split("\t", -1);
            if (c.length < 5 || "false".equals(c[0]) || c[3].isEmpty()) continue;
            if (!NetworkConfig.hostMatches(c[1], host)) continue;
            return new Login(c[2].trim(), c[3], c[4], c.length > 5 ? c[5].trim() : "", c.length > 6 ? c[6].trim() : "");
        }
        return null;
    }

    /** The schemes a 401 offers, lower case, in the order given. */
    static List<String> offered(HttpMessage response) {
        List<String> out = new java.util.ArrayList<>();
        for (String h : response.headers("WWW-Authenticate")) {
            String scheme = h.trim().split("\\s+", 2)[0].toLowerCase(Locale.ROOT);
            if (!scheme.isEmpty() && !out.contains(scheme)) out.add(scheme);
        }
        return out;
    }

    /** The scheme to answer with: the one the credentials name if the server offers it, else the strongest offered. */
    static String choose(String wanted, List<String> offered) {
        String w = wanted == null ? "" : wanted.toLowerCase(Locale.ROOT);
        if (w.startsWith("ntlm") && offered.contains("ntlm")) return "ntlm";
        if (w.startsWith("digest") && offered.contains("digest")) return "digest";
        if (w.startsWith("basic") && offered.contains("basic")) return "basic";
        for (String s : new String[]{ "ntlm", "digest", "basic" }) if (offered.contains(s)) return s;
        return null;
    }

    /**
     * Answer a 401. {@code sender} sends one request and returns its result;
     * for NTLM it must keep the connection between the two sends.
     */
    static HttpClient.Result answer(HttpService svc, HttpMessage request, HttpClient.Result first,
                                    java.util.function.Function<HttpMessage, HttpClient.Result> sender) {
        Settings s = settings;
        if (s == null || !s.getBool(ON, true) || first == null || !first.ok() || first.response.statusCode() != 401) return first;
        // A request that already carries credentials of its own is the tester's business.
        if (request.header("Authorization") != null) return first;
        List<String> offered = offered(first.response);
        if (offered.isEmpty()) return first;
        Login login = loginFor(s.get(ROWS, ""), svc.host());
        if (login == null) login = PROMPTED.get(svc.host());
        if (login == null && s.getBool(PROMPT, false)) login = prompt(svc.host(), offered);
        if (login == null) return first;
        String scheme = choose(login.type(), offered);
        if (scheme == null) return first;
        try {
            HttpClient.Result r = switch (scheme) {
                case "basic" -> sender.apply(with(request, "Basic " + Base64.getEncoder().encodeToString(
                        (login.user() + ":" + login.password()).getBytes(StandardCharsets.UTF_8))));
                case "digest" -> {
                    String challenge = null;
                    for (String h : first.response.headers("WWW-Authenticate")) if (h.trim().toLowerCase(Locale.ROOT).startsWith("digest")) challenge = h.trim().substring(6);
                    yield sender.apply(with(request, digest(challenge, request.method(), request.requestTarget(), login.user(), login.password(),
                            hex(random(8)), 1, request.body())));
                }
                default -> ntlm(request, login, sender);
            };
            if (r != null && r.ok() && r.response.statusCode() == 401 && PROMPTED.remove(svc.host()) != null) {
                // What was typed did not work; ask again next time rather than repeat it.
                DECLINED.remove(svc.host());
            }
            return r == null ? first : r;
        } catch (Exception e) {
            Debug.error("platform authentication to " + svc.host() + " failed", e);
            return first;
        }
    }

    private static Login prompt(String host, List<String> offered) {
        Prompter p = prompter;
        if (p == null || DECLINED.containsKey(host)) return null;
        synchronized (PROMPTED) {
            Login known = PROMPTED.get(host);
            if (known != null) return known;
            if (DECLINED.containsKey(host)) return null;
            Login typed = p.ask(host, String.join(", ", offered));
            if (typed == null) { DECLINED.put(host, true); return null; }
            PROMPTED.put(host, typed);
            return typed;
        }
    }

    private static HttpMessage with(HttpMessage request, String authorization) {
        HttpMessage m = request.copy();
        m.setHeader("Authorization", authorization);
        return m;
    }

    // ---- Digest (RFC 7616, and the older RFC 2617 form) ----

    static String digest(String challenge, String method, String uri, String user, String password, String cnonce, int count, byte[] body) throws Exception {
        Map<String, String> c = params(challenge);
        String realm = c.getOrDefault("realm", ""), nonce = c.getOrDefault("nonce", ""), opaque = c.get("opaque");
        String algorithm = c.getOrDefault("algorithm", "MD5");
        String hash = algorithm.toUpperCase(Locale.ROOT).startsWith("SHA-256") ? "SHA-256" : "MD5";
        boolean session = algorithm.toLowerCase(Locale.ROOT).endsWith("-sess");
        String qop = null;
        if (c.containsKey("qop")) {
            for (String q : c.get("qop").split(",")) if (q.trim().equalsIgnoreCase("auth")) qop = "auth";
            if (qop == null) for (String q : c.get("qop").split(",")) if (q.trim().equalsIgnoreCase("auth-int")) qop = "auth-int";
        }
        String nc = String.format("%08x", count);
        String ha1 = h(hash, user + ":" + realm + ":" + password);
        if (session) ha1 = h(hash, ha1 + ":" + nonce + ":" + cnonce);
        String ha2 = "auth-int".equals(qop) ? h(hash, method + ":" + uri + ":" + hex(MessageDigest.getInstance(hash).digest(body == null ? new byte[0] : body)))
                : h(hash, method + ":" + uri);
        String response = qop == null ? h(hash, ha1 + ":" + nonce + ":" + ha2) : h(hash, ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2);
        StringBuilder sb = new StringBuilder("Digest username=\"").append(quote(user)).append("\", realm=\"").append(quote(realm))
                .append("\", nonce=\"").append(quote(nonce)).append("\", uri=\"").append(quote(uri)).append("\", response=\"").append(response).append('"');
        if (c.containsKey("algorithm")) sb.append(", algorithm=").append(algorithm);
        if (opaque != null) sb.append(", opaque=\"").append(quote(opaque)).append('"');
        if (qop != null) sb.append(", qop=").append(qop).append(", nc=").append(nc).append(", cnonce=\"").append(cnonce).append('"');
        return sb.toString();
    }

    private static final Pattern PARAM = Pattern.compile("([A-Za-z0-9_-]+)\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|([^,\\s]+))");

    static Map<String, String> params(String challenge) {
        Map<String, String> out = new LinkedHashMap<>();
        if (challenge == null) return out;
        Matcher m = PARAM.matcher(challenge);
        while (m.find()) out.put(m.group(1).toLowerCase(Locale.ROOT), m.group(2) != null ? m.group(2).replace("\\\"", "\"") : m.group(3));
        return out;
    }

    private static String quote(String s) { return s.replace("\\", "\\\\").replace("\"", "\\\""); }

    private static String h(String algorithm, String text) throws Exception {
        return hex(MessageDigest.getInstance(algorithm).digest(text.getBytes(StandardCharsets.UTF_8)));
    }

    static String hex(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (byte x : b) sb.append(String.format("%02x", x));
        return sb.toString();
    }

    private static byte[] random(int n) {
        byte[] b = new byte[n];
        new SecureRandom().nextBytes(b);
        return b;
    }

    // ---- NTLMv2 (MS-NLMP) ----

    private static final byte[] SIGNATURE = { 'N', 'T', 'L', 'M', 'S', 'S', 'P', 0 };
    /** Unicode, request target, NTLM, always sign, extended session security. */
    private static final int FLAGS = 0x00088205;

    private static HttpClient.Result ntlm(HttpMessage request, Login login, java.util.function.Function<HttpMessage, HttpClient.Result> sender) throws Exception {
        // The handshake belongs to one connection, so both sends ask to keep it.
        HttpMessage negotiate = with(request, "NTLM " + Base64.getEncoder().encodeToString(type1()));
        negotiate.setHeader("Connection", "keep-alive");
        HttpClient.Result challenge = sender.apply(negotiate);
        if (challenge == null || !challenge.ok() || challenge.response.statusCode() != 401) return challenge;
        byte[] type2 = null;
        for (String h : challenge.response.headers("WWW-Authenticate")) {
            String v = h.trim();
            if (v.length() > 5 && v.regionMatches(true, 0, "NTLM ", 0, 5)) type2 = Base64.getDecoder().decode(v.substring(5).trim());
        }
        if (type2 == null) return challenge;
        HttpMessage authenticate = with(request, "NTLM " + Base64.getEncoder().encodeToString(
                type3(type2, login.user(), login.password(), login.domain(), login.workstation(), random(8), System.currentTimeMillis())));
        authenticate.setHeader("Connection", "keep-alive");
        return sender.apply(authenticate);
    }

    static byte[] type1() {
        ByteBuffer b = ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN);
        b.put(SIGNATURE).putInt(1).putInt(FLAGS | 0x2);
        b.putShort((short) 0).putShort((short) 0).putInt(32);   // domain: none
        b.putShort((short) 0).putShort((short) 0).putInt(32);   // workstation: none
        return b.array();
    }

    static byte[] type3(byte[] type2, String user, String password, String domain, String workstation, byte[] clientNonce, long nowMillis) throws Exception {
        ByteBuffer in = ByteBuffer.wrap(type2).order(ByteOrder.LITTLE_ENDIAN);
        if (type2.length < 32 || in.getInt(8) != 2) throw new IllegalArgumentException("not an NTLM challenge");
        byte[] serverChallenge = java.util.Arrays.copyOfRange(type2, 24, 32);
        byte[] targetInfo = new byte[0];
        if (type2.length >= 48) {
            int len = in.getShort(40) & 0xFFFF, off = in.getInt(44);
            if (len > 0 && off >= 0 && off + len <= type2.length) targetInfo = java.util.Arrays.copyOfRange(type2, off, off + len);
        }
        // The server's own clock, when it sends it, is the time to answer with.
        byte[] time = avPair(targetInfo, 7);
        if (time == null || time.length != 8) {
            long filetime = (nowMillis + 11644473600000L) * 10000L;
            time = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(filetime).array();
        }
        byte[] v2 = ntlmv2Hash(user, password, domain);
        ByteArrayOutputStream blob = new ByteArrayOutputStream();
        blob.write(new byte[]{ 1, 1, 0, 0, 0, 0, 0, 0 });
        blob.write(time);
        blob.write(clientNonce);
        blob.write(new byte[4]);
        blob.write(targetInfo);
        blob.write(new byte[4]);
        byte[] proof = hmacMd5(v2, concat(serverChallenge, blob.toByteArray()));
        byte[] nt = concat(proof, blob.toByteArray());
        byte[] lm = concat(hmacMd5(v2, concat(serverChallenge, clientNonce)), clientNonce);

        byte[] d = utf16(domain == null ? "" : domain), u = utf16(user), w = utf16(workstation == null ? "" : workstation);
        int offset = 64;
        ByteBuffer out = ByteBuffer.allocate(offset + lm.length + nt.length + d.length + u.length + w.length).order(ByteOrder.LITTLE_ENDIAN);
        out.put(SIGNATURE).putInt(3);
        int at = offset;
        at = field(out, lm.length, at);
        at = field(out, nt.length, at);
        at = field(out, d.length, at);
        at = field(out, u.length, at);
        at = field(out, w.length, at);
        field(out, 0, at);            // no session key
        out.putInt(FLAGS);
        out.put(lm).put(nt).put(d).put(u).put(w);
        return out.array();
    }

    private static int field(ByteBuffer out, int length, int offset) {
        out.putShort((short) length).putShort((short) length).putInt(offset);
        return offset + length;
    }

    private static byte[] avPair(byte[] info, int wanted) {
        ByteBuffer b = ByteBuffer.wrap(info).order(ByteOrder.LITTLE_ENDIAN);
        while (b.remaining() >= 4) {
            int id = b.getShort() & 0xFFFF, len = b.getShort() & 0xFFFF;
            if (id == 0 || len > b.remaining()) return null;
            byte[] v = new byte[len];
            b.get(v);
            if (id == wanted) return v;
        }
        return null;
    }

    /** NTOWFv2: HMAC-MD5 of the upper-cased user and the domain, keyed with the MD4 of the password. */
    static byte[] ntlmv2Hash(String user, String password, String domain) throws Exception {
        return hmacMd5(md4(utf16(password)), utf16(user.toUpperCase(Locale.ROOT) + (domain == null ? "" : domain)));
    }

    private static byte[] utf16(String s) { return s.getBytes(StandardCharsets.UTF_16LE); }

    private static byte[] concat(byte[] a, byte[] b) {
        byte[] out = java.util.Arrays.copyOf(a, a.length + b.length);
        System.arraycopy(b, 0, out, a.length, b.length);
        return out;
    }

    private static byte[] hmacMd5(byte[] key, byte[] data) throws Exception {
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(new SecretKeySpec(key, "HmacMD5"));
        return mac.doFinal(data);
    }

    /** MD4 (RFC 1320); the runtime no longer offers it, and NTLM is built on it. */
    static byte[] md4(byte[] message) {
        int length = message.length;
        int padded = ((length + 8) / 64 + 1) * 64;
        byte[] m = java.util.Arrays.copyOf(message, padded);
        m[length] = (byte) 0x80;
        ByteBuffer.wrap(m, padded - 8, 8).order(ByteOrder.LITTLE_ENDIAN).putLong((long) length * 8);
        int a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476;
        int[] x = new int[16];
        ByteBuffer words = ByteBuffer.wrap(m).order(ByteOrder.LITTLE_ENDIAN);
        for (int block = 0; block < padded / 64; block++) {
            for (int i = 0; i < 16; i++) x[i] = words.getInt();
            int aa = a, bb = b, cc = c, dd = d;
            for (int i = 0; i < 16; i += 4) {
                a = Integer.rotateLeft(a + ((b & c) | (~b & d)) + x[i], 3);
                d = Integer.rotateLeft(d + ((a & b) | (~a & c)) + x[i + 1], 7);
                c = Integer.rotateLeft(c + ((d & a) | (~d & b)) + x[i + 2], 11);
                b = Integer.rotateLeft(b + ((c & d) | (~c & a)) + x[i + 3], 19);
            }
            for (int i = 0; i < 4; i++) {
                a = Integer.rotateLeft(a + ((b & c) | (b & d) | (c & d)) + x[i] + 0x5a827999, 3);
                d = Integer.rotateLeft(d + ((a & b) | (a & c) | (b & c)) + x[i + 4] + 0x5a827999, 5);
                c = Integer.rotateLeft(c + ((d & a) | (d & b) | (a & b)) + x[i + 8] + 0x5a827999, 9);
                b = Integer.rotateLeft(b + ((c & d) | (c & a) | (d & a)) + x[i + 12] + 0x5a827999, 13);
            }
            for (int i : new int[]{ 0, 2, 1, 3 }) {
                a = Integer.rotateLeft(a + (b ^ c ^ d) + x[i] + 0x6ed9eba1, 3);
                d = Integer.rotateLeft(d + (a ^ b ^ c) + x[i + 8] + 0x6ed9eba1, 9);
                c = Integer.rotateLeft(c + (d ^ a ^ b) + x[i + 4] + 0x6ed9eba1, 11);
                b = Integer.rotateLeft(b + (c ^ d ^ a) + x[i + 12] + 0x6ed9eba1, 15);
            }
            a += aa; b += bb; c += cc; d += dd;
        }
        return ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN).putInt(a).putInt(b).putInt(c).putInt(d).array();
    }
}