Using secure sockets and servers

In this recipe, we describe the steps to make your web server encrypt its communication with clients using Secure Sockets Layer (SSL) on the HTTPS protocol.

Getting ready

Dart uses SSL/TSL security; it relies on X.509 certificates to validate servers and (optionally) clients. The server provides a certificate that will verify itself as a trusted server to the client. When the client accepts the certificate, symmetric session keys will be exchanged and used to encrypt the communications between the server and the client. So, in order for your server to provide a secured connection, it has to have a security certificate installed, provided by a Certificate Authority (CA).

Dart uses a Network Security Services (NSS) database to store the server's private key and certificate. For our example, we will use the test certificate database in the subfolder pkcert, which is also provided as an illustration in the tutorial at https://www.dartlang.org/docs/tutorials/httpserver/.

You can set up an NSS key database yourself to create certificates for test purposes. James Locum provides a detailed description on how to do this at http://jamesslocum.com/post/70003236123.

How to do it...

The program secure_server.dart shows us the code needed to start a secure server; perform the following steps to use secure sockets and service:

  1. Import the dart:io package as follows:
    import 'dart:io';
    
    InternetAddress HOST = InternetAddress.LOOPBACK_IP_V6;
    const int PORT = 8080;
    
    main() {
  2. Read the certificate using the following code:
      var testcertDb = Platform.script.resolve('pkcert').toFilePath();
      SecureSocket.initialize(database: testcertDb, password: 'dartdart'),
  3. Start the HTTP server with the certificate using the following code:
      HttpServer.bindSecure(HOST, PORT, certificateName: 'localhost_cert').then((server) {
        print('Secure Server listening'),
        server.listen((HttpRequest req) {
          print('Request for ${req.uri.path}'),
          var resp = req.response;
          resp.write("Don't worry: I encrypt your messages!");
          resp.close();
        });
      });
    } 
  4. If we now use the URL https://localhost:8080 in a browser, we first get a screen warning us that this connection is not trusted (because it is only a test certificate). If we continue, we see the response of the server in the browser's screen as shown in the following screenshot:
    How to do it...

    A secure socket connection

The following is the code for a secure command-line client (secure_client.dart):

import 'dart:io';

InternetAddress HOST = InternetAddress.LOOPBACK_IP_V6;
const int PORT = 4777;
SecureSocket socket;

void main() {
  SecureSocket.connect(HOST, PORT, onBadCertificate: (X509Certificate c) {
  print("Certificate WARNING: ${c.issuer}:${c.subject}");
  return true;
  }).then(handleSecureSocket);
}

handleSecureSocket(SecureSocket ss) {
  // send to server:
  ss.write("From client: can you encrypt me server?");
  // read from server:
  ss.listen((List data) {
  String msg = new String.fromCharCodes(data).trim();
  print(msg);
  });
}

The client console gives the following output:

Certificate WARNING: CN=myauthority:CN=localhost

How it works...

In step 1, we read the certificate. The first line with Platform.script finds the path to the folder pkcert, where the certificate database is located. Then we call the initialize method on the class SecureSocket, providing the certificate. In step 2, the secure server is started by binding to a host and port and providing the name of the certificate. Step 3 shows us a browser connecting to the secure server.

In step 4, we see how a command-line client can connect to the secure server by calling SecureSocket.connect(). This needs an onBadCertificate callback, which must return a Boolean value that indicates whether to accept or reject a bad certificate. The test certificate will trigger this callback, so we need to return true in order to use this certificate. With respect to the write and listen methods of SecureSocket, let's write to and read from the secure server.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset