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.
Java application-securityappsecbug-bountyburp-alternativeburp-suitedasthttp-proxyinfosecintercepting-proxyjavaowaspowasp-zappenetration-testingpentestingsecuritysecurity-toolsvulnerability-scannerweb-application-securityweb-security
package opensuite.engine;
import opensuite.core.Bytes;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.Settings;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Logs in with a username and a password by having the scan engine fill in
* the login page in a browser without a window, the way a person would. That
* copes with logins a plain request cannot do: fields found on the page
* itself, forms spread over several pages, tokens set by script.
*
* <p>The engine says a login ran to its end whether or not the application
* accepted it, so its word is not taken. What the browser sent after the login
* is read back and the cookies and tokens it carried become the scanner's
* headers. Whether those make a valid session is not judged here: that is
* for the session check, by the text the user marked. The pages the browser
* fetched after logging in are handed back to be offered for that check.
*/
public final class EngineLogin {
private EngineLogin() {}
static final String CONTEXT = "Open Suite login";
/**
* The login add-on's own passive checks. They report on how a login works,
* not on a weakness of the target, so they are switched off when the
* engine starts.
*/
static final String OWN_CHECKS = "10111,10112,10113";
/**
* What a login gave: the session's headers, and the requests the browser
* made with them, to offer for a session check. {@code ok} says only that
* a session was received.
*/
public record Result(boolean ok, List<ScanAuth.Header> headers, List<ScanAuth.Check> checks, String detail) {
static Result failed(String why) { return new Result(false, List.of(), List.of(), why); }
}
/** One request the browser made while logging in, and how it was answered. */
record Seen(HttpService service, HttpMessage request, int status, String body) {}
public static Result login(ZapApi api, Settings settings, Collection<String> sites, String loginUrl,
String username, String password) {
// Said at once: without a browser the engine would only wait until it gave up.
if (opensuite.proxy.EmbeddedBrowser.findBinary() == null || opensuite.proxy.EmbeddedBrowser.findDriver() == null)
return Result.failed("no browser is installed for the scan login. Open the browser once from the toolbar "
+ "to download it, or use the browser's session instead");
boolean noSandbox = settings != null && settings.getBool(opensuite.proxy.BrowserFlags.NO_SANDBOX, false);
if (!noSandbox && !opensuite.proxy.EmbeddedBrowser.sandboxWorks())
return Result.failed("the browser sandbox is not available on this system, so the login page cannot be opened. "
+ "Enable \"Allow Open Suite's browser to run without a sandbox\" under Settings > Tools > Browser, "
+ "or use the browser's session instead");
Set<String> all = new LinkedHashSet<>(sites);
HttpService page = loginUrl == null ? null : HttpService.parse(loginUrl);
if (page == null) return Result.failed("\"" + loginUrl + "\" is not a URL that a browser can open");
all.add(page.url());
List<Seen> seen = new ArrayList<>();
try {
if (!api.canBrowserLogin()) return Result.failed("this scan engine does not support browser-based login");
api.setBrowserSandboxOff(noSandbox);
try { api.removeContext(CONTEXT); } catch (Exception ignore) { /* none yet */ }
String ctx = api.newContext(CONTEXT);
for (String site : all) api.includeInContext(CONTEXT, SessionGuard.regex(site) + "(/.*)?");
api.setBrowserLogin(ctx, loginUrl);
String user = api.newUser(ctx, username, password);
java.util.Map<String, Integer> before = new java.util.LinkedHashMap<>();
for (String site : all) before.put(site, Math.max(0, api.messageCount(site)));
api.authenticateAsUser(ctx, user);
if (api.lastLogin(ctx, user) == 0)
return Result.failed("the browser could not be started to open the login page");
// A crawl or an audit may be running against the same site: only what the
// login's own browser sent is read.
for (String site : all) {
int from = before.get(site);
for (int batch = 0; batch < 10; batch++) {
List<ZapApi.Recorded> got = api.messagesAfter(site, from, 500);
for (ZapApi.Recorded r : got) {
if (!ZapApi.LOGIN_TRAFFIC.equals(r.type())) continue;
Seen s = seen(r);
if (s != null) seen.add(s);
}
if (got.size() < 500) break;
from += got.size();
}
}
try { api.removeContext(CONTEXT); } catch (Exception ignore) { }
} catch (Exception e) {
return Result.failed("the scan engine could not run the login (" + e.getMessage() + ")");
}
return judge(seen, username);
}
/** Work out from what the browser did whether the login was accepted, and what the session is. */
static Result judge(List<Seen> seen, String username) {
if (seen.isEmpty()) return Result.failed("the browser opened the login page but no request was sent");
// Only what came after the password was sent belongs to the session.
int sent = -1;
for (int i = 0; i < seen.size(); i++) {
Seen s = seen.get(i);
if (!"GET".equals(s.request().method()) && s.request().body().length > 0) sent = i;
}
if (sent < 0) return Result.failed("no username and password fields were found on the login page");
List<Seen> after = seen.subList(sent, seen.size());
List<ScanAuth.Header> headers = ScanAuth.captureFrom(after.subList(Math.min(1, after.size()), after.size()));
String last = "";
for (Seen s : after) if (s.status() == 200 && s.body() != null && s.body().contains("<")) last = s.body();
boolean formBack = LoginFlow.asksForPassword(last);
if (headers.isEmpty())
return Result.failed(formBack ? "the login form was displayed again, so the username or password was not accepted"
: "the login produced no session cookie or token");
List<ScanAuth.Check> candidates = new ArrayList<>(ScanAuth.candidatesFrom(after, 40));
// Offered first: a page that names the user, the likeliest to have text worth marking.
candidates.sort((a, b) -> Boolean.compare(names(b, after, username), names(a, after, username)));
return new Result(true, headers, candidates, "a session was received");
}
private static boolean names(ScanAuth.Check c, List<Seen> seen, String username) {
if (username == null || username.isEmpty()) return false;
for (Seen s : seen)
if (s.request().requestTarget().equals(c.request.requestTarget()) && s.service().url().equals(c.service.url()))
return s.body() != null && s.body().contains(username);
return false;
}
/** An exchange as the engine records it, as a request to a service; null when it cannot be read. */
static Seen seen(ZapApi.Recorded r) {
try {
String head = r.requestHeader();
int eol = head.indexOf("\r\n");
String[] first = head.substring(0, eol).split(" ");
if (first.length < 3 || !first[1].startsWith("http")) return null;
HttpService svc = HttpService.parse(first[1]);
if (svc == null) return null;
java.net.URI u = java.net.URI.create(first[1]);
String target = (u.getRawPath() == null || u.getRawPath().isEmpty() ? "/" : u.getRawPath())
+ (u.getRawQuery() == null ? "" : "?" + u.getRawQuery());
String raw = first[0] + " " + target + " " + first[2] + head.substring(eol);
if (!raw.endsWith("\r\n\r\n")) raw = raw.stripTrailing() + "\r\n\r\n";
HttpMessage req = new HttpMessage(Bytes.bytes(raw + (r.requestBody() == null ? "" : r.requestBody())));
int status = 0;
String[] st = r.responseHeader() == null ? new String[0] : r.responseHeader().split(" ", 3);
if (st.length >= 2) try { status = Integer.parseInt(st[1].trim()); } catch (NumberFormatException ignore) { }
return new Seen(svc, req, status, r.responseBody());
} catch (RuntimeException e) {
return null;
}
}
}