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.

14.6 KB
Raw Blame
package opensuite.engine;

import opensuite.core.Bytes;
import opensuite.core.HttpClient;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.LogEntry;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Finding where an application's login is, so a scan that logs in by itself
 * knows which page to open.
 *
 * <p>It is found in one of two ways. If the user has already logged in through
 * the proxy, the request that carried the password is in the history and the
 * page it was sent from is the login page. Otherwise the pages at the target
 * are looked at for a form with a password field. The logging in itself is
 * done by {@link EngineLogin}.
 */
public final class LoginFlow {
    private LoginFlow() {}

    static final String USER = "\u00abOSUSER\u00bb", PASS = "\u00abOSPASS\u00bb";

    /** A login request with marks where the username and the password go. */
    public static final class Template {
        public HttpService service;
        /** The page the form is on, fetched before each login; null when there is none. */
        public String pagePath;
        /** The request, its body holding the marks. */
        public HttpMessage request;
        public boolean json;
        public boolean fromHistory;

        /** The address of the page to log in at. */
        public String pageUrl() {
            return service.url() + (pagePath == null || pagePath.isEmpty() ? request.path() : pagePath);
        }

        public String describe() {
            return pageUrl() + (fromHistory ? " (login observed in the proxy history)" : " (login form detected at the target)");
        }
    }

    // ------------------------------------------------------- learning a login

    /**
     * The login the user performed through the proxy: the newest request to
     * one of the sites whose body carries the password.
     */
    public static Template fromHistory(List<LogEntry> history, Collection<String> sites, String user, String pass) {
        if (pass == null || pass.isEmpty()) return null;
        int looked = 0;
        for (int i = history.size() - 1; i >= 0 && looked < 3000; i--) {
            LogEntry e = history.get(i);
            if (!"proxy".equals(e.tool()) || e.service() == null || !sites.contains(e.service().url())) continue;
            looked++;
            try {
                if ("GET".equals(e.method()) || e.requestBodyBytes() <= 0) continue;
                HttpMessage req = e.request();
                if (req == null) continue;
                String body = req.bodyText();
                String ct = String.valueOf(req.header("Content-Type")).toLowerCase(Locale.ROOT);
                boolean json = ct.contains("json");
                String encPass = json ? jsonString(pass) : form(pass);
                if (!body.contains(encPass)) continue;
                String marked = body.replace(encPass, PASS);
                String encUser = json ? jsonString(user) : form(user);
                if (!user.isEmpty()) marked = marked.replace(encUser, USER);
                Template t = new Template();
                t.service = e.service();
                t.json = json;
                t.fromHistory = true;
                HttpMessage tmpl = req.copy();
                tmpl.removeHeader("Cookie");
                tmpl.setBody(Bytes.bytes(marked));
                t.request = tmpl;
                String ref = req.header("Referer");
                if (ref != null) {
                    HttpService rs = HttpService.parse(ref);
                    if (rs != null && rs.equals(e.service())) t.pagePath = pathOf(ref);
                }
                return t;
            } catch (RuntimeException ignored) { /* an unreadable entry is not the login */ }
        }
        return null;
    }

    private static final Pattern LOGIN_LINK = Pattern.compile("(?i)log-?_?in|sign-?_?in|auth|account|session/new");

    /**
     * Find a login form at the target: on the page given, or on one of the few
     * pages it links to whose address looks like a login. Null when none is found.
     */
    public static Template detect(HttpService svc, String path) {
        List<String> queue = new ArrayList<>(List.of(path == null || path.isEmpty() ? "/" : path));
        java.util.Set<String> tried = new java.util.HashSet<>();
        for (int n = 0; n < queue.size() && n < 8; n++) {
            String p = queue.get(n);
            if (!tried.add(p)) continue;
            Fetched f = get(svc, p, new LinkedHashMap<>(), 3);
            if (f == null) continue;
            Template t = formIn(svc, f.path, f.body);
            if (t != null) return t;
            if (n == 0) {
                Matcher m = Pattern.compile("(?i)<a\\b[^>]*\\bhref\\s*=\\s*[\"']([^\"'#]+)").matcher(f.body);
                while (m.find()) {
                    String href = unescape(m.group(1));
                    if (!LOGIN_LINK.matcher(href).find()) continue;
                    String r = resolve(svc, f.path, href);
                    if (r != null && !queue.contains(r)) queue.add(r);
                }
                for (String guess : List.of("/login", "/signin", "/users/sign_in", "/account/login"))
                    if (!queue.contains(guess)) queue.add(guess);
            }
        }
        return null;
    }

    /** The first form on the page with a password field, as a login request. */
    static Template formIn(HttpService svc, String pagePath, String html) {
        Matcher fm = Pattern.compile("(?is)<form\\b([^>]*)>(.*?)</form>").matcher(html);
        while (fm.find()) {
            Map<String, String> fa = attrs(fm.group(1));
            String inner = fm.group(2);
            List<Map<String, String>> inputs = new ArrayList<>();
            Matcher im = Pattern.compile("(?is)<(input|button|select|textarea)\\b([^>]*)>").matcher(inner);
            boolean hasPassword = false;
            while (im.find()) {
                Map<String, String> a = attrs(im.group(2));
                a.put("\u0000tag", im.group(1).toLowerCase(Locale.ROOT));
                if ("password".equalsIgnoreCase(a.get("type"))) hasPassword = true;
                inputs.add(a);
            }
            if (!hasPassword) continue;
            // The username is the text field just before the password.
            String userField = null, last = null;
            for (Map<String, String> a : inputs) {
                String type = a.getOrDefault("type", "text").toLowerCase(Locale.ROOT), name = a.get("name");
                if (name == null || !"input".equals(a.get("\u0000tag"))) continue;
                if (type.equals("password")) { userField = last; break; }
                if (type.equals("text") || type.equals("email") || type.equals("tel")) last = name;
            }
            StringBuilder body = new StringBuilder();
            boolean submitted = false;
            for (Map<String, String> a : inputs) {
                String name = a.get("name");
                if (name == null || name.isEmpty()) continue;
                String tag = a.get("\u0000tag"), type = a.getOrDefault("type", tag.equals("button") ? "submit" : "text").toLowerCase(Locale.ROOT);
                String value;
                if (type.equals("password")) value = PASS;
                else if (name.equals(userField)) value = USER;
                else if (type.equals("submit") || type.equals("image")) { if (submitted) continue; submitted = true; value = form(a.getOrDefault("value", "")); }
                else if (type.equals("checkbox") || type.equals("radio")) { if (!a.containsKey("checked")) continue; value = form(a.getOrDefault("value", "on")); }
                else if (type.equals("reset") || type.equals("button") || type.equals("file")) continue;
                else value = form(a.getOrDefault("value", ""));
                if (body.length() > 0) body.append('&');
                body.append(form(name)).append('=').append(value);
            }
            String action = fa.getOrDefault("action", "");
            String target = action.isEmpty() ? pagePath : resolve(svc, pagePath, unescape(action));
            if (target == null) continue;   // posts to another site: not a login we can replay
            boolean get = "get".equalsIgnoreCase(fa.get("method"));
            String host = svc.host() + (svc.defaultPort() ? "" : ":" + svc.port());
            String raw = get
                    ? "GET " + target + (target.contains("?") ? "&" : "?") + body + " HTTP/1.1\r\nHost: " + host + "\r\n"
                      + "Referer: " + svc.url() + pagePath + "\r\n\r\n"
                    : "POST " + target + " HTTP/1.1\r\nHost: " + host + "\r\n"
                      + "Content-Type: application/x-www-form-urlencoded\r\n"
                      + "Origin: " + svc.url() + "\r\nReferer: " + svc.url() + pagePath + "\r\n"
                      + "Content-Length: 0\r\n\r\n" + body;
            Template t = new Template();
            t.service = svc;
            t.pagePath = pagePath;
            t.request = new HttpMessage(Bytes.bytes(raw));
            if (!get) t.request.updateContentLength();
            return t;
        }
        return null;
    }

    // ------------------------------------------------------------ logging in

    /** Whether a page has a password field on it. */
    static boolean asksForPassword(String html) {
        return html != null && Pattern.compile("(?is)<input\\b[^>]*\\btype\\s*=\\s*[\"']?password").matcher(html).find();
    }

    private record Fetched(String path, String body, int status) {}

    /** Fetch a page, keeping its cookies and following redirects within the site. */
    private static Fetched get(HttpService svc, String path, Map<String, String> jar, int redirects) {
        String at = path;
        for (int hop = 0; hop <= redirects; hop++) {
            String host = svc.host() + (svc.defaultPort() ? "" : ":" + svc.port());
            StringBuilder raw = new StringBuilder("GET ").append(at).append(" HTTP/1.1\r\nHost: ").append(host)
                    .append("\r\nAccept: text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8\r\n")
                    .append("User-Agent: Mozilla/5.0 (X11; Linux x86_64) OpenSuite\r\n");
            if (!jar.isEmpty()) raw.append("Cookie: ").append(ScanAuth.cookieHeader(jar)).append("\r\n");
            raw.append("\r\n");
            HttpClient.Options opt = new HttpClient.Options();
            opt.followRedirects = false;
            HttpClient.Result r = new HttpClient().send(svc, new HttpMessage(Bytes.bytes(raw.toString())), opt);
            if (!r.ok()) return null;
            learn(r.response, jar);
            int st = r.response.statusCode();
            String loc = r.response.header("Location");
            if (st >= 300 && st < 400 && loc != null) {
                String next = resolve(svc, pathOnly(at), loc);
                if (next == null) return new Fetched(at, "", st);
                at = next;
                continue;
            }
            return new Fetched(at, r.response.bodyText(), st);
        }
        return new Fetched(at, "", 0);
    }

    /** Take the cookies a response sets into the jar; one set to nothing or expired is dropped. */
    static void learn(HttpMessage response, Map<String, String> jar) {
        for (String sc : response.headers("Set-Cookie")) {
            String first = sc.split(";", 2)[0].trim();
            int eq = first.indexOf('=');
            if (eq <= 0) continue;
            String name = first.substring(0, eq).trim(), value = first.substring(eq + 1).trim();
            String rest = sc.toLowerCase(Locale.ROOT);
            boolean gone = value.isEmpty() || rest.contains("max-age=0") || rest.contains("expires=thu, 01 jan 1970");
            if (gone) jar.remove(name); else jar.put(name, value);
        }
    }

    /** A link's target as a path on this service, or null when it leaves the site. */
    static String resolve(HttpService svc, String fromPath, String href) {
        try {
            java.net.URI base = java.net.URI.create(svc.url() + (fromPath == null || fromPath.isEmpty() ? "/" : pathOnly(fromPath)));
            java.net.URI u = base.resolve(href.trim().replace(" ", "%20"));
            HttpService to = HttpService.parse(u.toString());
            if (to == null || !to.equals(svc)) return null;
            String p = u.getRawPath() == null || u.getRawPath().isEmpty() ? "/" : u.getRawPath();
            return u.getRawQuery() == null ? p : p + "?" + u.getRawQuery();
        } catch (RuntimeException e) {
            return null;
        }
    }

    private static String pathOf(String url) {
        try {
            java.net.URI u = java.net.URI.create(url);
            String p = u.getRawPath() == null || u.getRawPath().isEmpty() ? "/" : u.getRawPath();
            return u.getRawQuery() == null ? p : p + "?" + u.getRawQuery();
        } catch (RuntimeException e) { return "/"; }
    }

    private static String pathOnly(String pathAndQuery) {
        int q = pathAndQuery.indexOf('?');
        return q < 0 ? pathAndQuery : pathAndQuery.substring(0, q);
    }

    /** The attributes of a tag, names in lower case; one without a value maps to "". */
    static Map<String, String> attrs(String tagBody) {
        Map<String, String> out = new LinkedHashMap<>();
        Matcher m = Pattern.compile("([A-Za-z_:][-A-Za-z0-9_:.]*)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'>]+)))?").matcher(tagBody);
        while (m.find()) {
            String v = m.group(2) != null ? m.group(2) : m.group(3) != null ? m.group(3) : m.group(4) != null ? m.group(4) : "";
            out.putIfAbsent(m.group(1).toLowerCase(Locale.ROOT), unescape(v));
        }
        return out;
    }

    private static String unescape(String s) {
        return s.replace("&amp;", "&").replace("&quot;", "\"").replace("&#39;", "'").replace("&lt;", "<").replace("&gt;", ">");
    }

    static String form(String s) { return URLEncoder.encode(s == null ? "" : s, StandardCharsets.UTF_8); }

    /** The text as it stands inside a JSON string, without the quotes. */
    static String jsonString(String s) {
        StringBuilder sb = new StringBuilder();
        for (char c : (s == null ? "" : s).toCharArray()) {
            switch (c) {
                case '"' -> sb.append("\\\"");
                case '\\' -> sb.append("\\\\");
                case '\n' -> sb.append("\\n");
                case '\r' -> sb.append("\\r");
                case '\t' -> sb.append("\\t");
                default -> sb.append(c);
            }
        }
        return sb.toString();
    }
}