9 Comments

Background

imageAs discussed before, Windows Phone Mango brought the socket support to Windows Phone app developers. Unfortunately  the platform doesn’t provide secure sockets (SSL socket) out of the box. Many applications nowadays require SSL socket and for example many IRC servers only allow secure socket connections.

Solution

Fortunately it is possible to get the SSL Socket support to Windows Phone with the help of an excellent OSS library “Bouncy Castle”. Bouncy Castle isn’t officially available for the Windows Phone but it’s possible to modify the code so that required parts for the SSL Socket support are available.

I have modified the code and packaged it with the SocketEx –library I blogged about a little while ago. Here’s an example of how to open a SSL Socket using the SocketEx:

        private SecureTcpClient CreateConnection()
        {
            var connection = new SecureTcpClient(serverAddress, serverPort);

            return connection;
        }

The SecureTcpClient inherits from the TcpClient so you should be able to just replace the TcpClient where needed.

Advanced usage

The SecureTcpClient works as wrapper around the TcpClient and Bouncy Castle. If more control is needed, you can create a normal connection through TcpClient and then “elevate” it to secure:

            var connection = new TcpClient("server", 443);

            var handler = new TlsProtocolHandler(connection.GetStream());
            handler.Connect(new LegacyTlsClient(new AlwaysValidVerifyer()));

This way it’s possible to for example to add some validation to the certificate the server sends. Other option is to provide the TlsClient to the SecureSockectConnection:

            var tlsClient = new LegacyTlsClient(new AlwaysValidVerifyer());
            var connection = new SecureTcpClient(serverAddress, serverPort, tlsClient);

Supported protocols

SecureTcpClient supports the TLS 1.0 (“SSL 3.1”) protocol. The following cipher suits are supported:

TLS_DHE_RSA_WITH_AES_256_CBC_SHA
TLS_DHE_RSA_WITH_AES_128_CBC_SHA
TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA
TLS_RSA_WITH_AES_256_CBC_SHA
TLS_RSA_WITH_AES_128_CBC_SHA
TLS_RSA_WITH_3DES_EDE_CBC_SHA

The client supports the simple TLS handshake where the server but not the client is authenticated. With some work it should be possible to get the SSL 3.0 support to Bouncy Castle, but TLS should be enough in most of the situations.

Sample and source code

The source code for SocketEx is available from GitHub. It comes with two examples: One for TcpClient and one for SecureTcpClient.

NuGet

SocketEx.SecureTcpClient is also available from NuGet as a package SocketEx.SSL.