Thursday, September 29, 2011

Using SSL with the ServerSocket Class

Using ServerSockets to serve SSLSockets has been problematic at best for anyone wanting to create an application that serves secure TCP sockets. It was recently brought to my attention that even though a critical framework bug was fixed this spring, we still lacked instructions on how to set it up properly.

The instructions here are for Linux and Mac OS X, and we are actively trying to figure out the right configuration for Windows. As soon as we have that information, it will be added to the SSLSocket page in the Documentation Wiki.

The Secure Part of Secure Sockets Layer (SSL)
The first thing you'll need is to get an SSL Certificate. If you'll be testing internally or only connecting to your own apps, a self-signed certificate will do the trick. For simplicity and ease of understanding, open a Terminal window and follow steps 1-4 on this site.

The second thing you'll need to do is to combine the private and public keys (server.key and server.csr) into a single file. Use your favorite text editor to copy the contents of server.key into server.csr and save. The resulting file should look something like this:

…Edited for content...

…Edited for content...

The Hookup
Now that you've got the certificate, you will need to create an app that can listen securely. If you've done any work using ServerSockets with TCPSockets, you know that ServerSocket has an AddSocket event that fires every time the ServerSocket thinks it needs to make more connections available.

Traditionally, you would create a subclass of ServerSocket and then do something like this:

Function AddSocket() As TCPSocket
  Dim ssl As New SSLSocket
  ssl.ConnectionType = ssl.TLSv1
  //If your certificate has a password you'd enter it here
  ssl.CertificatePassword = "" 
  ssl.CertificateFile = getfolderitem("certificatefile.crt")
  ssl.Secure = True
  Return ssl
End Function

Let's say your ServerSocket subclass is called "MyServer". When you call MyServer.Listen (assuming everything else is set up), you're all ready to go!


Travis said...


Now why can't we drop a key/cert file in alongside a standalone web app and do SSL direct? The CGI gateway/app launching overhead can sometimes be significant, and given that I've actually benched a standalone SSL-tunneled web app being faster than Apache/CGI on the same hardware/network. There are some particular cases where this would come in quite handy.

Anyway, I appreciate you clearly showing how this is done. Nice post!

Greg O'Lone said...


File a feature request!

Travis said...

That feature request has been in for more than a year and it is already #7 overall in Feedback. Case 13710.

Thanks for all your work.