-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Verify hostname after handshake
Marcel Prestel edited this page May 10, 2020
·
2 revisions
Android proposes to verify the hostname of any connection.
See also: https://developer.android.com/training/articles/security-ssl.html#CommonHostnameProbs
The following code is an example how to verify a hostname, in this example echo.websocket.org. The code is based on the example provided here.
WebSocketClient client = null;
try {
client = new WebSocketClient(new URI("wss://echo.websocket.org")) {
@Override
public void onOpen(ServerHandshake handshakedata) {
Log.i("Client", "Open");
}
@Override
public void onMessage(String message) {
Log.i("Client", "Message: " + message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
Log.i("Client", "Close: " + reason + " Code: " + code + " Remote: " + remote);
}
@Override
public void onError(Exception ex) {
Log.e("Client", "Error: " + ex.getMessage());
}
};
client.connectBlocking();
//Verify
HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
SSLSocket socket = (SSLSocket) client.getSocket();
SSLSession s = socket.getSession();
if (!hv.verify("echo.websocket.org", s)) {
Log.e("Client", "Expected echo.websocket.org, found " + s.getPeerPrincipal());
throw new SSLHandshakeException("Expected websocket.org, found " + s.getPeerPrincipal());
} else {
Log.i("Client", "Success");
}
} catch (SSLHandshakeException e) {
client.close();
} catch (Exception e) {
e.printStackTrace();
}