Search code examples
javasslhttpscertificatejsse

SSLSocket also for unsecure http?


Can I use SSLServerSocket class for both http and https sessions and listen to one port (with autodetection either the client comes with http or https)? Or it is obligatory to open two ports and use SSLServerSocket for https and ServerSocket for http?

Thanks


Solution

  • What you're trying to do is called port unification. It's implemented in Grizzly for example.

    You can't really use an SSLServerSocket directly to listen to both HTTP and HTTPS traffic, since it would start the handshake straight upon reading, but you could have a plain ServerSocket, accept a plain Socket, try to detect when you get an TLS Client hello or an HTTP request by reading the first few bytes, and then convert it to an SSLSocket.

    I can't say I've tried with Sockets, but you'll need something to read ahead the TLS Client Hello and push it back if necessary, possibly using a PushBackInputStream, as suggested by EJP.

    (As far as I'm aware Grizzly uses SSLEngine instead of SSLSocket for this.)

    Note that using port unification is quite unusual. I'm not sure what the overhead for reading ahead is. Using multiple ports instead is usually not a problem (in addition HTTP and HTTPS have different default ports, so you'd have to specify the port in at least one of the two URLs).