Skip to content

Instantly share code, notes, and snippets.

@rogerhub
Created March 12, 2013 04:25
Show Gist options
  • Save rogerhub/5140348 to your computer and use it in GitHub Desktop.
Save rogerhub/5140348 to your computer and use it in GitHub Desktop.
AirBears Automatic Login in Java
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.*;
class AirBearsAutoLogin {
// Published URLs that SHOULD not change.
public static String google = "http://www.google.com/generate_204";
public static String airbears = "https://wlan.berkeley.edu/cgi-bin/login/calnet.cgi";
public static String calcas = "auth.berkeley.edu/cas/";
private static String username = "rogerhub";
private static String password = "";
private static ArrayList<String[]> wlancookies = new ArrayList<String[]>();
public static StringBuffer responseText;
public static void main(String[] args) {
System.out.println("===================================");
System.out.println("| AirBears Automatic Login (Java) |");
System.out.println("===================================\n");
// Determine where we're at
HttpURLConnection connection = checkGoogle(); // Requests: Google
System.out.println("It looks like we are currently: " + checkStatus(connection));
if (checkStatus(connection).equals("airbears")) {
System.out.println("The portal redirects us to:\n " + getRedirectTarget(connection));
} else {
System.out.println("There's nothing left to do! I'm exiting now.");
return;
}
System.out.println();
String cookieHeader;
System.out.println("Requesting login using wlan.berkeley.edu. Connecting to:\n " + getRedirectTarget(connection));
openHTTP(getRedirectTarget(connection), "", false, false, false); // Requests: wlan
if ((cookieHeader = getHeader(connection, "Set-Cookie")) != null) {
assimilateCookies(cookieHeader);
}
System.out.println();
// Try Airbears
System.out.println("Requesting automated WLAN Login through CalNet.");
connection = checkAirbears(); // Requests: wlan
// Some sanity checks
String authtarget = getRedirectTarget(connection);
System.out.println("CAS redirects to:\n " + authtarget);
if (authtarget == null || authtarget.toLowerCase().indexOf(calcas) == -1) {
System.out.println("It looks like there's nothing left to do! I'm exiting now.");
return;
}
if ((cookieHeader = getHeader(connection, "Set-Cookie")) != null) {
assimilateCookies(cookieHeader);
}
System.out.println();
connection = openHTTP(authtarget, "", false, false, false); // Requests: auth
System.out.println(getHeader(connection, "Set-Cookie", true));
System.out.println("Cookie parsed was: " + getCookiePart(getHeader(connection, "Set-Cookie")));
String params = "lt=" + encodeParam(getInputValueByName("lt"));
params += "&_eventId=" + encodeParam(getInputValueByName("_eventId"));
params += "&username=" + encodeParam(username);
params += "&password=" + encodeParam(password);
authtarget = "https://auth.berkeley.edu" + getTagAttrByAttr("loginForm", "form", "id", "action");
System.out.println("Parameters prepared! Attempting to open connection to:\n " + authtarget);
connection = openHTTP(authtarget, params, false, false, true);
System.out.println();
try {
int httpresponse = connection.getResponseCode();
if (httpresponse == 200) {
System.out.println("Looks like the authentication failed. Time to quit!");
return;
} else if (httpresponse != 302 && httpresponse != 301) {
System.out.println("Looks like the authentication failed. Time to quit!");
return;
}
} catch (Exception e) {
System.out.println("Looks like the authentication failed. Time to quit!");
return;
}
System.out.println("\n Successful authentication attempt!\n");
System.out.println("Attempting final auth: " + authtarget);
authtarget = getRedirectTarget(connection);
connection = openHTTP(authtarget, "", false, false, false);
if ((cookieHeader = getHeader(connection, "Set-Cookie")) != null) {
assimilateCookies(cookieHeader);
}
System.out.println("Redirected to: " + authtarget);
authtarget = getRedirectTarget(connection);
openHTTP(authtarget, "", false, false, false);
System.out.println();
System.out.println("All done! Have fun on the Internet.");
}
private static HttpURLConnection checkAirbears() {
HttpURLConnection connection = openHTTP(airbears + "?submit=CalNet&url=" + encodeParam(google), "", false, false);
System.out.println("Received response code: " + connection.getHeaderField(0));
return connection;
}
private static HttpURLConnection checkGoogle() {
HttpURLConnection connection = openHTTP(google, "", false, false);
System.out.println("Received response code: " + connection.getHeaderField(0));
return connection;
}
private static void assimilateCookies(String cookieHeader) {
System.out.println("Assimilating cookies from:\n " + cookieHeader);
String[] cookieHeaders = cookieHeader.split("\n");
int i;
for (i = 0; i < cookieHeaders.length; i++) {
if (cookieHeaders[i].trim().equals("")) {
continue;
}
String[] cookieSet = new String[2];
cookieSet[0] = getCookiePart(cookieHeaders[i], "key");
cookieSet[1] = getCookiePart(cookieHeaders[i], "content");
wlancookies.add(cookieSet);
}
}
private static String cookieString() {
String cookies = "";
for (String[] cookieSet : wlancookies) {
if (!cookies.equals("")) {
cookies += "&";
}
cookies += encodeParam(cookieSet[0]) + "=" + encodeParam(cookieSet[1]);
}
return cookies;
}
private static String checkStatus(HttpURLConnection connection) {
try {
int httpresponse = connection.getResponseCode();
if (httpresponse == 204) {
return "connected";
} else if (httpresponse == 302 || httpresponse == 301) {
return "airbears";
} else if (httpresponse == 200) {
return "unknown";
} else {
return "fuckfuck";
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static String getRedirectTarget(HttpURLConnection connection) {
String target;
if ((target = getHeader(connection, "Location")) != null) {
return target;
} else {
return target; // hahaha
}
}
private static String getHeader(HttpURLConnection connection) {
return getHeader(connection, "", true);
}
private static String getHeader(HttpURLConnection connection, String headerKey) {
return getHeader(connection, headerKey, false);
}
private static String getHeader(HttpURLConnection connection, String headerKey, boolean printDebug) {
int i = 1;
String key;
while ((key = connection.getHeaderFieldKey(i)) != null) {
if (printDebug) {
System.out.println("\tGot header -- " + key + ": " + connection.getHeaderField(i));
}
if (key.equalsIgnoreCase(headerKey)) {
return connection.getHeaderField(i);
} else {
i += 1;
}
}
return null;
}
public static String encodeParam(String param) {
try {
return URLEncoder.encode(param, "UTF-8");
} catch (Exception e) {
return "";
}
}
public static String getCookiePart(String cookie) {
return getCookiePart(cookie, "content");
}
public static String getCookiePart(String cookie, String part) {
String[] cookieparts = cookie.split(";");
if (part.equals("content") || part.equals("key")) {
String[] partparts = cookieparts[0].split("=");
if (part.equals("content")) {
return partparts[1].trim();
} else {
return partparts[0].trim();
}
}
int i;
for (i = 1; i < cookieparts.length; i++) {
String[] partparts = cookieparts[i].split("=");
if (partparts[0].trim().equals(part)) {
return partparts[1].trim();
}
}
return null;
}
private static String getInputValueByName(String name) {
return getTagValueByName(name, "input");
}
private static String getTagValueByName(String name, String tagname) {
return getTagValueByAttr(name, tagname, "name");
}
private static String getTagValueByAttr(String name, String tagname, String attr) {
return getTagAttrByAttr(name, tagname, attr, "value");
}
private static String getTagAttrByAttr(String name, String tagname, String attr, String targetattr) {
Matcher m = Pattern.compile("<" + tagname + "[^>]+>").matcher(responseText);
String tag;
while (m.find()) {
tag = m.group();
Matcher name_match = Pattern.compile(attr + "=\"([^\"]+)\"").matcher(tag);
if (name_match.find()) { // Only first result
System.out.println("match!" + name_match.group());
if (name_match.group(1).trim().toLowerCase().equals(name.toLowerCase())) {
Matcher value_match = Pattern.compile(targetattr + "=\"([^\"]+)\"").matcher(tag);
if (value_match.find()) {
return value_match.group(1);
}
}
}
}
return "";
}
public static HttpURLConnection openHTTP(String targetUrl, String urlParameters) {
return openHTTP(targetUrl, urlParameters, true);
}
public static HttpURLConnection openHTTP(String targetUrl, String urlParameters, boolean followRedirect) {
return openHTTP(targetUrl, urlParameters, followRedirect, true);
}
public static HttpURLConnection openHTTP(String targetUrl, String urlParameters, boolean followRedirect, boolean useCache) {
return openHTTP(targetUrl, urlParameters, followRedirect, useCache, false);
}
public static HttpURLConnection openHTTP(String targetUrl, String urlParameters, boolean followRedirect, boolean useCache, boolean usePost) {
URL url;
HttpURLConnection connection = null;
try {
url = new URL(targetUrl); // Reuse, yes I know.
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(usePost ? "POST" : "GET");
if (usePost) {
connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
}
String cookies;
if ((cookies = cookieString()) != "") {
connection.setRequestProperty("Cookie", cookieString());
}
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11");
connection.setInstanceFollowRedirects(followRedirect);
connection.setUseCaches(useCache);
connection.setDoInput(true);
connection.setDoOutput(true);
if (usePost) {
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
}
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
responseText = new StringBuffer();
while ((line = rd.readLine()) != null) {
responseText.append(line);
responseText.append('\n');
}
rd.close();
return connection;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment