GSSCredential.ACCEPT_ONLY);
while (true) {
logger.debug("Waiting for incoming connection on port {} ...",
localPort);
GSSContext context = manager.createContext(serverCreds);
Socket socket = ss.accept();
try {
DataInputStream inStream = new DataInputStream(socket
.getInputStream());
DataOutputStream outStream = new DataOutputStream(socket
.getOutputStream());
logger.debug("Got connection from client @ {}", socket
.getInetAddress());
// Read SOCKS5 greeting packet
byte ver = (byte) inStream.read();
if (ver != 0x05) {
throw new IllegalStateException(
"Wrong socks version received - " + ver);
}
byte nbAuthMethods = (byte) inStream.read();
byte[] methods = new byte[nbAuthMethods];
inStream.readFully(methods);
boolean found = false;
for (byte b : methods) {
if (b == SocksProxyConstants.GSSAPI_AUTH) {
found = true;
break;
}
}
if (!found) {
throw new IllegalStateException(
"Client does not support GSSAPI authentication");
}
// Send selected mechanism message
outStream.write(SELECT_GSSAPI_AUTH_MSG);
outStream.flush();
// Do the context establishment loop
byte[] token = null;
while (!context.isEstablished()) {
byte authVersion = (byte) inStream.read();
if (authVersion != 0x01) {
throw new IllegalStateException(
"Wrong socks GSSAPI auth version received: "
+ authVersion);
}
byte mtyp = (byte) inStream.read();
if (mtyp != 0x01) {
throw new IllegalArgumentException(
"Message type should be equal to 1.");
}
int len = inStream.readShort();
token = new byte[len];
inStream.readFully(token);
logger.debug(" Received Token[{}] = {}", len,
ByteUtilities.asHex(token));
token = context.acceptSecContext(token, 0, token.length);
// Send a token to the peer if one was generated by acceptSecContext
if (token != null) {
logger.debug(" Sending Token[{}] = {}", token.length,
ByteUtilities.asHex(token));
outStream.writeByte(authVersion);
outStream.writeByte(mtyp);
outStream.writeShort(token.length);
outStream.write(token);
outStream.flush();
}
}
logger.debug("Context Established !");
logger.debug("Client is {}", context.getSrcName());
logger.debug("Server is {}", context.getTargName());
/*
* If mutual authentication did not take place, then
* only the client was authenticated to the
* server. Otherwise, both client and server were
* authenticated to each other.
*/
if (context.getMutualAuthState()) {
logger.debug("Mutual authentication took place !");
}
// We can now abort the process after a short time as auth is OK
// and finally block will close session
Thread.sleep(500);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
context.dispose();
socket.close();
}
}
}