Skip to content
ImagineWorld

Security

node_idnode-book_network-programming-with-rust_chapter-08-security
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleSecurity
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Security is often looked at as an afterthought in systems design. That is evident in common protocols; security related RFCs has historically been proposed after the main protocol. Notice that any communication over a public medium (like the internet) is vulnerable to man-in-the-middle attacks. An adversary might hijack the communication by carefully inspecting input packets from both sides. In light of that, some security related questions are reasonable: When a client connects to a server, how does it verify that the server is the one it claims to be? How do they decide on a shared secret key to use for encryption? In this chapter, we will see how these questions are commonly addressed.

We will cover the following topics:

  • Securing web-based applications using certificates
  • Key exchange using the Diffie-Hellman method

In a previous chapter, we studied HTTP. We noted how important it has been in making our lives easier. However, HTTP is vulnerable to a range of attacks that might result in leaking the payload. Thus, it was necessary to add some form of security between parties using HTTP to communicate. RFC 2818 proposed HTTPS (HTTP Secure) as a version of HTTP that uses a secure streaming protocol underneath. Initially, this was Secure Socket Layer (SSL), and later evolved into Transport Layer Security (TLS).

The basic scheme of things goes like this:

  • The Client and Server establish a TCP connection.
  • The Client and Server agree upon a cipher and hash function to use throughout the connection. For this, the client sends a list of ciphers and hash functions. The Server picks one from that list and lets the Client know.
  • The Server sends a certificate to the Client. The Client validates this against a list of certificate authorities that it has locally.
  • Both agree on a session key to be used to encrypt data during the connection.
  • At this point, a regular HTTP session can begin.

The following image illustrates the steps for this:

Client-server communication over SSL

One of the most important steps here is verifying the server’s identity. This answers a fundamental question: W hen the client talks to a server, how does it know the server is actually the server it wanted? In practice, this is achieved using certificates. A certificate is a document that is signed by a certificate authority, a trusted provider who is legally allowed to vouch for others. A client has a list of trusted CAs, and if the CA which issued a given certificate is on that list, a client can trust the server that presents that certificate. In practice, there are often a chain of certificates issued as a chain of trust relationships, going back to a root CA.

In recent years, search engines put a heavy emphasis on having HTTPS on websites, often ranking them higher in that case. However, issuing a certificate for a website has traditionally been a tedious process. A website owner will have to log in to a CA’s website and provide some form of identification. Issuing the certificate often took a few hours and was very costly for small business owners. In 2015, Let’s Encrypt launched as a non-profit CA with the goal of providing free, short-lived certificates to all websites on the internet. They automate the validation process by issuing a challenge to the server administrator. This typically involves either placing a given file in a known location on the website or creating a DNS record with a given content. Once letsencrypt has validated the server, it issues a certificate valid for 90 days. Thus, the certificate needs to be renewed periodically.

More recently, letsencrypt standardized the challenge response protocol as JSON over HTTPS and named it ACME. Here is how this works:

  • The local client generates a private-public keypair and contacts the letsencrypt server with the Public key.
  • The server creates an account for the given key and registers it.
  • Based on challenge preferences, the Client will present a list of challenges that can be fulfilled and ask the server to validate the domain. Currently, two challenges are supported: an HTTP based challenge where a file is placed on a known location and the server will read it to validate, or a DNS based challenge where the operator has to create a TXT record on the domain with a given content.
  • The server generates the challenge and sends it back.
  • At this point, the client will poll the server for confirmation.
  • When the server returns an OK, the client can proceed to generating a certificate signing request (CSR) for the server and send it across.
  • The server then generates a certificate and sends it back.

The following diagram illustrates individual steps in the ACME protocol:

ACME protocol operation

Currently, there is one crate that allows access to letsencrypt using Rust. The CLI tool called acme-client can interact with the API to obtain or revoke a certificate or run validations of ownership. The binary is backed by a crate called acme-client that enables programmatic interaction with the API. Let’s see how this can be used to secure an HTTP server running on Rocket. Remember, for this to work, letsencrypt will need to reach the server. Thus, this needs to be publicly accessible over the internet.

The first step is to install the CLI tool using Cargo:

$ cargo install acme-client

For our example, we will run our rocket blog over TLS. While Rocket does support TLS out of the box, it is not enabled by default. We will need to change the Cargo.toml file to add TLS as a feature flag. It should look like this:

[package]
authors = ["Foo <[email protected]>"]
name = "rocket-blog"
version = "0.1.0"
[dependencies]
rocket = { version="0.3.5", features = ["tls"] }
rocket_codegen = "0.3.5"
rocket_contrib = "0.3.5"
diesel = { version = "0.16.0", features = ["sqlite"] }
diesel_codegen = { version = "0.16.0", features = ["sqlite"] }
dotenv = "0.10.1"
serde = "1.0.21"
serde_json = "1.0.6"
serde_derive = "1.0.21"
lazy_static = "0.2.11"
r2d2 = "0.7.4"
r2d2-diesel = "0.16.0"

We will also run Rocket on the public interface. For this, we will place a config file called Rocket.toml in the root of the repository. This is how it looks; everything else is left at the defaults:

$ cat Rocket.toml
[global]
address = "0.0.0.0"

Like we did before, we can run our server using Cargo:

$ DATABASE_URL=./db.sql cargo run

Letsencrypt also requires all servers to have a domain name. Thus, we will need to create a record for our server in a DNS provider. In our example, that DNS name is my.domain.io, which we will use in subsequent steps. Once that record has propagated everywhere, we can move on to the next step: generating certificates. Here is how we will do that using the CLI:

$ acme-client -vvvvv sign --dns -D my.domain.io -P /var/www -o domain.crt
INFO:acme_client: Registering account
DEBUG:acme_client: User successfully registered
INFO:acme_client: Sending identifier authorization request for foo.datasine.com
Please create a TXT record for _acme-challenge.my.domain.io: MFfatN9I3UFQk2WP_f1uRWi4rLnr4qMVaI
Press enter to continue
INFO:acme_client: Triggering dns-01 validation
DEBUG:acme_client: Status is pending, trying again...
INFO:acme_client: Signing certificate
DEBUG:acme_client: Certificate successfully signed

We will have to use the DNS based validation here since we will not be able to serve back challenges. The CLI asked us to create a TXT record with a given name and content. Once we create the record, we will need to wait for some time so that it can propagate before we move forward. It is a good idea to check if the record is updated using dig before moving forward. Here is how the output of dig should look:

$ dig _acme-challenge.my.domain.io TXT
; <<>> DiG 9.9.7-P3 <<>> _acme-challenge.my.domain.io TXT
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 49153
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 8192
;; QUESTION SECTION:
;_acme-challenge.my.domain.io. IN TXT
;; ANSWER SECTION:
_acme-challenge.my.domain.io. 60 IN TXT "MFfatN9I3UFQk2WP_f1uRWi4rLnr4qMVaI"
;; Query time: 213 msec
;; SERVER: 192.168.0.1#53(192.168.0.1)
;; WHEN: Fri Jan 05 18:04:01 GMT 2018
;; MSG SIZE rcvd: 117

When the output from dig says that we have the correct TXT record, we can move ahead with installing the certificate. letsencrypt will then query the TXT record and run domain validation. When everything looks fine, we will get a new certificate named domain.crt. Let’s inspect the certificate to make sure everything looks okay. The subject should match our domain name and the issuer should always be Let’s Encrypt, as shown in the following code snippet:

$ openssl x509 -in domain.crt -subject -issuer -noout
subject= /CN=my.domain.io
issuer= /C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3

Now we are ready to use this certificate in our Rocket application. We will need to place it at a location where the running Rocket has permission to read it. Now, if we restart Rocket and use curl to access the endpoint over HTTPS, it should work exactly like last time:

$ curl -sS -D - https://my.domain.io:8000/posts
HTTP/1.1 200 OK
Content-Type: application/json
Server: Rocket
Content-Length: 992
Date: Fri, 05 Jan 2018 18:37:58 GMT
[{"id":1,"title":"test","body":"test body","pinned":true},{"id":2,"title":"Hello Rust!","body":"Rust is awesome!!","pinned":true},{"id":3,"title":"Testing this","body":"Try to write something","pinned":true},{"id":4,"title":"Testing this","body":"Try to write something","pinned":true},{"id":5,"title":"Testing this","body":"Try to write something","pinned":true},{"id":6,"title":"Testing this","body":"Try to write something","pinned":true},{"id":7,"title":"Testing this","body":"Try to write something","pinned":true},{"id":8,"title":"Testing this","body":"Try to write something","pinned":true},{"id":9,"title":"Testing this","body":"Try to write something","pinned":true},{"id":10,"title":"Testing this","body":"Try to write something","pinned":true},{"id":11,"title":"Testing this","body":"Try to write something","pinned":true},{"id":12,"title":"Testing this","body":"Try to write something","pinned":true},{"id":13,"title":"Testing this","body":"Try to write something","pinned":true}]

As of the time of writing, Let’s Encrypt has a limit of five certificates for a given domain per week. For testing, it is possible to reach that limit pretty quickly. If that happens, the client will just say Acme server error*.*

Let’s write a simple client for our server here using rustls. We set up the project using Cargo:

$ cargo new --bin rustls-client

We then add rustls to our project as a dependency:

[package]
name = "rustls-client"
version = "0.1.0"
authors = ["Foo <[email protected]>"]
[dependencies]
rustls = "0.12.0"
webpki = "0.18.0-alpha"
webpki-roots = "0.14.0"

Here is how the client looks; note that the webpki crate does DNS resolution, which is then used by rustls:

ch8/rustls-client/src/main.rs
use std::sync::Arc;
use std::net::TcpStream;
use std::io::{Read, Write};
extern crate rustls;
extern crate webpki;
extern crate webpki_roots;
fn main() {
let mut tls = rustls::ClientConfig::new();
tls.root_store.add_server_trust_anchors
(&webpki_roots::TLS_SERVER_ROOTS);
let name = webpki::DNSNameRef::try_from_ascii_str("my.domain.io")
.expect("Could not resolve name");
let mut sess = rustls::ClientSession::new(&Arc::new(tls), name);
let mut conn = TcpStream::connect("my.domain.io:8000").unwrap();
let mut stream = rustls::Stream::new(&mut sess, &mut conn);
stream.write(concat!("GET /posts HTTP/1.1\r\n",
"Connection: close\r\n",
"\r\n")
.as_bytes())
.expect("Could not write request");
let mut plaintext = Vec::new();
stream.read_to_end(&mut plaintext).expect("Could not read");
println!("{}", String::from_utf8(plaintext)
.expect("Could not print output"));
}

Here, we are connecting to our server and running the same HTTP request. We import all three required crates. The first step is to initialize a TLS session and add the root certificates to it. We then resolve our given server to a DNS name reference and establish a TLS session with it. Having set this up, we can set up a TCP session by using connect. Finally, a rustls Stream is a combination of the SSL session and the TCP session. Once all those are working, we can write HTTP queries by hand. Here we are running a GET on the /posts endpoint. Later, we read the response and print it out. The output should be exactly the same as using the other clients:

HTTP/1.1 200 OK
Content-Type: application/json
Server: Rocket
Content-Length: 992
Date: Fri, 05 Jan 2018 18:37:58 GMT
[{"id":1,"title":"test","body":"test body","pinned":true},{"id":2,"title":"Hello Rust!","body":"Rust is awesome!!","pinned":true},{"id":3,"title":"Testing this","body":"Try to write something","pinned":true},{"id":4,"title":"Testing this","body":"Try to write something","pinned":true},{"id":5,"title":"Testing this","body":"Try to write something","pinned":true},{"id":6,"title":"Testing this","body":"Try to write something","pinned":true},{"id":7,"title":"Testing this","body":"Try to write something","pinned":true},{"id":8,"title":"Testing this","body":"Try to write something","pinned":true},{"id":9,"title":"Testing this","body":"Try to write something","pinned":true},{"id":10,"title":"Testing this","body":"Try to write something","pinned":true},{"id":11,"title":"Testing this","body":"Try to write something","pinned":true},{"id":12,"title":"Testing this","body":"Try to write something","pinned":true},{"id":13,"title":"Testing this","body":"Try to write something","pinned":true}]

The OpenSSL library and CLI is a complete set of tools to work with SSL (and TLS) objects. It is an open source project and is widely used by companies all around. As one would expect, Rust has bindings for using as a library in Rust projects. In this discussion, we will take a closer look at the certificates we saw in the last section.

These are commonly defined by a standard called X.509 (defined in RFC 5280) and have the following fields:

  • Version number: Almost always set to 2, corresponding to version 3 (since the first version is 0). According to the standard, this field can be omitted and should be assumed to be version 1 (value set to 0).
  • Serial number: A 20 octet identifier that is unique for the CA which signed this certificate.
  • Signature: A unique ID that identifies the algorithm used to sign this certificate. This is usually a string defined in subsequent RFCs, an example being sha1WithRSAEncryption.
  • Issuer name: Identifies the CA that signed the certificate. This must have at least one Distinguished name (DN) composed of a number of components, including a Common Name (CN), State (ST), Country (C), and so on.
  • Validity: Defines when the certificate should be valid. This has two sub-fields; notBefore denotes when this starts to be valid and notAfter denotes when it expires.
  • Subject name: Identifies the entity this certificate certifies. For a root certificate, this will be the same as the issuer. This has the same format as the issuer name and should at least have a DN.
  • Subject public key info: Information about the subject’s encrypted public key. This has two sub-fields; the first one is an ID for the encryption algorithm (as in the signature field), and the second is a bit stream that has the encrypted public key.
  • Issuer unique ID: An optional field that can be used to uniquely identify the issuer.
  • Subject unique ID: An optional field that can be used to identify the subject.
  • Extensions: This field is only applicable if the version is set to 3. Denotes a number of optional fields that can be used to attach additional information to certificates.
  • Certificate signature algorithm: Algorithm used to sign this certificate; must be the same as the one used in the signature attribute previously.
  • Certificate signature value: A bit string that has the actual signature for verification.

In the following example, we will use rust-openssl to generate and inspect a certificate from scratch. Installing the library, however, can be a little complicated. Since it is a wrapper around libopenssl, it needs to link against the native library. Thus, the library has to be installed. The crate’s documentation has instructions to get this set up. The project setup is routine:

$ cargo new --bin openssl-example

Here is the Cargo.toml file:

[package]
name = "openssl-example"
version = "0.1.0"
authors = ["Foo <[email protected]>"]
[dependencies]
openssl = { git = "https://github.com/sfackler/rust-openssl" }

Also, for this example, we will use the master branch of the repository, since we need a few features that are not released yet. For that, we will need to specify the repository link, as shown previously. Here is the main file:

ch8/openssl-example/src/main.rs
extern crate openssl;
use std::env;
use std::fs::File;
use std::io::Write;
use openssl::x509::{X509, X509Name};
use openssl::nid::Nid;
use openssl::pkey::{PKey, Private};
use openssl::rsa::Rsa;
use openssl::error::ErrorStack;
use openssl::asn1::Asn1Time;
use openssl::bn::{BigNum, MsbOption};
use openssl::hash::MessageDigest;
fn create_cert() -> Result<(X509, PKey<Private>), ErrorStack> {
let mut cert_builder = X509::builder()?;
cert_builder.set_version(2)?;
let serial_number = {
let mut serial = BigNum::new()?;
serial.rand(160, MsbOption::MAYBE_ZERO, false)?;
serial.to_asn1_integer()?
};
cert_builder.set_serial_number(&serial_number)?;
let mut name = X509Name::builder()?;
name.append_entry_by_text("C", "UK")?;
name.append_entry_by_text("CN", "Our common name")?;
let cert_name = name.build();
cert_builder.set_issuer_name(&cert_name)?;
let not_before = Asn1Time::days_from_now(0)?;
cert_builder.set_not_before(&not_before)?;
let not_after = Asn1Time::days_from_now(365)?;
cert_builder.set_not_after(&not_after)?;
cert_builder.set_subject_name(&cert_name)?;
let private_key = PKey::from_rsa(Rsa::generate(3072)?)?;
cert_builder.set_pubkey(&private_key)?;
cert_builder.sign(&private_key, MessageDigest::sha512())?;
let cert = cert_builder.build();
Ok((cert, private_key))
}
fn main() {
if let Some(arg) = env::args().nth(1) {
let (cert, _key) = create_cert().expect("could not create
cert");
let cert_data = cert.to_pem().expect("could not convert cert
to pem");
let mut cert_file = File::create(arg)
.expect("could not create cert file");
cert_file
.write_all(&cert_data)
.expect("failed to write cert");
let subject = cert.subject_name();
let cn = subject
.entries_by_nid(Nid::COMMONNAME)
.next()
.expect("failed to get subject");
println!("{}",String::from_utf8(cn.data()
.as_slice().to_vec()).unwrap()
);
} else {
eprintln!("Expected at least one argument");
std::process::exit(1);
}
}

Here, we take in a filename as a command-line parameter to write the certificate to. Certificate creation is offloaded to a helper function called create_cert that returns either a tuple having the generated certificate and private key or a list of errors as a Result.

The first step is to initialize a certificate builder object that we will add on to, and finally, build our certificate. We use the set_version method to set the version to 3 (numerically set to 2). Now we need to generate a serial number and set it. We generate that by randomly sampling 160 bits (20 octets of 8 bits each). We use the set_serial_number method to set the serial number. The next step is to generate a name by using a name builder. The append_entry_by_text method is then used to add a country name and a common name to our name builder. We use set_issuer_name to append the name object to the certificate. We set the expiry date to 365 days after the current date and use set_not_before and set_not_after to set those two. The subject name is set to the same name object using set_subject_name. Finally, we need to generate a private key, which we generate using the Rsa module, and we set the private key on the certificate. Now, the certificate needs to be signed with the private key using SHA512. Once done, we can use the build method to create the certificate. At the end of the function, we return the certificate and private key to the caller.

In our main function, we call the helper function. For our example, we will ignore the key, but a real application does need to save it for verification later. We convert the certificate object to PEM encoding and write it to a file on the disk. The next step is reading the subject name programmatically. For this, we use the subject_name method on the certificate object and print it out as a string. This should match the subject name we set earlier.

Here is how we can run this using Cargo. Note that this creates a certificate named bar.crt in the current directory:

$ cargo run bar.crt
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running \`target/debug/openssl-example bar.crt\`
Our common name
$ ls -la bar.crt
-rw-r--r--+ 1 Abhishek staff 1399 19 Feb 22:02 bar.crt

A common problem in implementing Tokio based protocols is around securing them. Luckily, the Tokio ecosystem has tokio-tls for this. Let’s look at an example of using this to secure our hyper example from a previous chapter. Here is our setup:

$ cargo new --bin tokio-tls-example

The Cargo manifest should look like this:

[package]
name = "tokio-tls-example"
version = "0.1.0"
authors = ["Foo <[email protected]>"]
[dependencies]
hyper = "0.11.7"
futures = "0.1.17"
net2 = "0.2.31"
tokio-core = "0.1.10"
num_cpus = "1.0"
native-tls = "*"
tokio-service = "*"
tokio-proto = "*"
tokio-tls = { version = "0.1", features = ["tokio-proto"] }

We will need to use the tokio-proto feature on tokio-tls to enable integration with tokio-proto. The next step is to generate a self-signed certificate for our server. tokio-tls uses the native-tls library underneath, and that does not support constructing acceptors from X509 certificates at the time of this writing. Thus, we will need to use PKCS12 certificates. The command shown ahead generates a self signed certificate, valid for 365 days, in PEM format. This will ask for a pass-phrase for the certificate. In our case, we used foobar. Please ensure that this command is run in the tokio-tls-example directory so that our code can read the certificate:

$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

The following command converts the given certificate to PKCS12 format. This should generate a file called cert.pfx in the current directory, which we will use in the code:

$ openssl pkcs12 -export -out cert.pfx -inkey key.pem -in cert.pem

Here is our main file, with some changes for enabling SSL:

ch8/tokio-tls-example/src/main.rs
extern crate futures;
extern crate hyper;
extern crate native_tls;
extern crate tokio_proto;
extern crate tokio_service;
extern crate tokio_tls;
use std::io;
use std::{thread, time};
use futures::future::{ok, Future};
use hyper::server::Http;
use hyper::header::ContentLength;
use hyper::{Request, Response, StatusCode};
use native_tls::{Pkcs12, TlsAcceptor};
use tokio_proto::TcpServer;
use tokio_service::Service;
use tokio_tls::proto;
fn heavy_work() -> String {
let duration = time::Duration::from_millis(100);
thread::sleep(duration);
"done".to_string()
}
struct SlowMo;
impl Service for SlowMo {
type Request = Request;
type Response = Response;
type Error = io::Error;
type Future = Box<Future<Item = Response, Error = io::Error>>;
fn call(&self, req: Request) -> Self::Future {
let b = heavy_work().into_bytes();
println!("Request: {:?}", req);
Box::new(ok(Response::new()
.with_status(StatusCode::Ok)
.with_header(ContentLength(b.len() as u64))
.with_body(b)))
}
}
fn main() {
let raw_cert = include_bytes!("../cert.pfx");
let cert = Pkcs12::from_der(raw_cert, "foobar").unwrap();
let acceptor = TlsAcceptor::builder(cert).unwrap().build().unwrap();
let proto = proto::Server::new(Http::new(), acceptor);
let addr = "0.0.0.0:9999".parse().unwrap();
let srv = TcpServer::new(proto, addr);
println!("Listening on {}", addr);
srv.serve(|| Ok(SlowMo));
}

The major changes here are that in the main function, we use the include_bytes macro to read the certificate as raw bytes. We then construct a Pkcs12 object using from_der by passing the certificate bytes and the pass-phrase that we used while creating the certificate. The next step is to create a TlsAcceptor object using the given Pkcs12 certificate object. We will then need to wrap the acceptor object and the hyper protocol object into a Server. This is passed to the TcpServer constructor, which we then start.

Here is what a session looks like from a client’s perspective:

$ curl -k https://localhost:9999
done

Here is what the server prints; this originates from the println! macro in the call function:

$ cargo run
Compiling rustls-example v0.1.0 (file:///src/ch8/rustls-example)
Finished dev [unoptimized + debuginfo] target(s) in 3.14 secs
Running \`target/debug/rustls-example\`
Listening on 0.0.0.0:9999
Request: Request { method: Get, uri: "/", version: Http11, remote_addr: None, headers: {"Host": "localhost:9999", "User-Agent": "curl/7.57.0", "Accept": "*/*"} }
^C

Interestingly, the openssl command-line tool has a TCP client that can be used to test SSL connections as well. Here is how to use it to test our server:

$ openssl s_client -connect 127.0.0.1:9999
CONNECTED(00000003)
depth=0 C = UK, ST = Scotland, O = Internet Widgits Pty Ltd
verify error:num=18:self signed certificate
verify return:1
depth=0 C = UK, ST = Scotland, O = Internet Widgits Pty Ltd
verify return:1
---
Certificate chain
0 s:/C=UK/ST=Scotland/O=Internet Widgits Pty Ltd
i:/C=UK/ST=Scotland/O=Internet Widgits Pty Ltd
---
Server certificate
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
subject=/C=UK/ST=Scotland/O=Internet Widgits Pty Ltd
issuer=/C=UK/ST=Scotland/O=Internet Widgits Pty Ltd
---
No client certificate CA names sent
Peer signing digest: SHA256
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 2128 bytes and written 433 bytes
---
New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 4096 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
Protocol : TLSv1.2
Cipher : ECDHE-RSA-AES256-GCM-SHA384
Session-ID: 9FAB89D29DB02891EF52C825AC23E3A658FDCE228A1A7E4FD97652AC3A5E24F3
Session-ID-ctx:
Master-Key: 940EF0C4FA1A929133C2D273739C8042FAF1BD5057E793ED1D7A0F0187F0236EF9E43D236DF8C17D663D7B77F1B4CEDD
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
Start Time: 1515350045
Timeout : 300 (sec)
Verify return code: 18 (self signed certificate)
---
GET / HTTP/1.1
host: foobar
HTTP/1.1 200 OK
Content-Length: 4
Date: Sun, 07 Jan 2018 18:34:52 GMT
done

This tool negotiates an SSL session and dumps the server certificate as shown previously (we have replaced the actual certificate for brevity). Notice that it correctly detects that the given server is using a self-signed certificate. Finally, it starts a TCP session. Since this is bare TCP, we will need to hand craft our HTTP requests. If we use a simple GET request on /, we get back a response of 200 OK, and the string is done. On the other side, this is what the server prints:

$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running \`target/debug/tokio-tls-example\`
Listening on 0.0.0.0:9999
Request: Request { method: Get, uri: "/", version: Http11, remote_addr: None, headers: {"Host": "foobar"} }

Notice that this prints the Host header, set to the string foobar, as we wrote on the client side.

A commonly used crate for cryptography is called ring. This crate supports a number of lower-level crypto primitives, like random number generation, key exchanges, and so on. In this section, we will take key exchange as an example and see how this crate can be used in client-server applications.

A common problem in communication is that of encrypting information so that a third-party cannot decipher it. In a private key system, both the client and the server will need to agree on a key to use for this to work. Now, this key cannot be transmitted in plain text over an insecure connection. The Diffie-Hellman key exchange method defines a mechanism where two parties talking over a secure link can negotiate a key that is shared between them, but has not been transmitted over the connection. This method has a number of implementations on many platforms, including the crate in question.

The following diagram shows how the protocol works:

Diffie-Hellman key exchange in action

Initially, the server will be listening for incoming clients. When a client connects, this is the sequence of events:

  1. A TCP session is first set up.
  2. Both the server and the client generate private and public keys.
  3. The client then sends its public key to the server.
  4. The server responds by sending the public key that it generated.
  5. At this point, both of the parties can generate the shared secret key using their private keys and the public key that they received.
  6. Further communication can be encrypted using the shared secret key.

We will create an empty library project for this example. We will then create an example directory and place the two files shown later in there. Project setup will go like this:

$ cargo new key-exchange

Also, here is what Cargo.toml should look like:

[package]
name = "key-exchange"
version = "0.1.0"
authors = ["Foo <[email protected]>"]
[dependencies]
ring = "0.12.1"
untrusted = "0.5.1"

Let’s look at the client first. This is heavily borrowed from the simple TCP servers we wrote in the second chapter. This is completely synchronous and blocking:

ch8/key-exchange/examples/client.rs
extern crate ring;
extern crate untrusted;
use std::net::TcpStream;
use std::io::{BufRead, BufReader, Write};
use ring::{agreement, rand};
use untrusted::Input;
fn main() {
let mut stream = TcpStream::connect("127.0.0.1:8888")
.expect("Could not connect to server");
let rng = rand::SystemRandom::new();
// Generate the client's private key
let client_private_key =
agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng)
.expect("Failed to generate key");
let mut client_public_key = [0u8; agreement::PUBLIC_KEY_MAX_LEN];
let client_public_key = &mut
client_public_key[..client_private_key.public_key_len()];
// Generate the client's public key
client_private_key.compute_public_key
(client_public_key).expect("Failed to
generate key");
// Send client's public key to server
stream.write(client_public_key)
.expect("Failed to write to server");
let mut buffer: Vec<u8> = Vec::new();
let mut reader = BufReader::new(&stream);
// Read server's public key
reader.read_until(b'\n', &mut buffer)
.expect("Could not read into buffer");
let peer_public_key = Input::from(&buffer);
println!("Received: {:?}", peer_public_key);
// Generate shared secret key
let res = agreement::agree_ephemeral
(client_private_key, &agreement::X25519,
peer_public_key,
ring::error::Unspecified,
|key_material| {
let mut key = Vec::new();
key.extend_from_slice(key_material);
Ok(key)
});
println!("{:?}", res.unwrap());
}

We of course need the ring crate as an external dependency. The other crate, called untrusted, is a helper for taking in data from untrusted sources to ring as input. We then initialize ring’s random number generator; this will be used to generate keys later. We then generate a private key for the client using the generate method. The client’s public key is generated based on the private key using compute_public_key. At this point, the client is ready to send the public key to the server. It writes the key as a byte stream to the connection created earlier. Ideally, the server should send out its public key at this point, which the client needs to read off the same connection. This is done by the read_until call that places the data received in the buffer. The incoming data is then passed through the untrusted crate so that ring can consume it. Finally, the client-side key is generated using agree_ephemeral, which takes in the two keys collected (the client’s private key and the server’s public key), an error value, and a closure to be used on the generated byte stream. In the closure, we collect all the data in a vector and return it. The last step is to print that vector.

The server is similar and looks like the following code snippet:

ch8/key-exchange/src/examples/server.rs
extern crate ring;
extern crate untrusted;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::{Read, Write};
use ring::{agreement, rand};
use untrusted::Input;
use ring::error::Unspecified;
fn handle_client(mut stream: TcpStream) -> Result<(), Unspecified> {
let rng = rand::SystemRandom::new();
// Generate server's private key
let server_private_key =
agreement::EphemeralPrivateKey::generate
(&agreement::X25519, &rng)?;
let mut server_public_key = [0u8; agreement::PUBLIC_KEY_MAX_LEN];
let server_public_key = &mut
server_public_key[..server_private_key.public_key_len()];
// Generate server's public key
server_private_key.compute_public_key(server_public_key)?;
let mut peer_public_key_buf = [0u8; 32];
// Read client's public key
stream.read(&mut peer_public_key_buf).expect("Failed to read");
let peer_public_key = Input::from(&peer_public_key_buf);
println!("Received: {:?}", peer_public_key);
// Send server's public key
stream.write(&server_public_key)
.expect("Failed to send server public key");
// Generate shared secret key
let res = agreement::agree_ephemeral(server_private_key,
&agreement::X25519,
peer_public_key,
ring::error::Unspecified,
|key_material| {
let mut key = Vec::new();
key.extend_from_slice(key_material);
Ok(key)
});
println!("{:?}", res.unwrap());
Ok(())
}
fn main() {
let listener = TcpListener::bind("0.0.0.0:8888").expect("Could not bind");
for stream in listener.incoming() {
match stream {
Err(e) => { eprintln!("failed: {}", e) }
Ok(stream) => {
thread::spawn(move || {
handle_client(stream)
.unwrap_or_else(|error| eprintln!(
"{:?}", error));
});
}
}
}
}

Like we did last time, we handle each client in a new thread. The semantics in the handle_client function is similar to that of the client; we start with generating a private and a public key. The next step is to read the public key that the client sent, followed by sending the public key of the server. Once settled, we can then use agree_ephemeral to generate the shared secret key, which should match the one generated on the client side.

Here is a sample run on the server side:

$ cargo run --example server
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running \`target/debug/examples/server\`
Received: Input { value: Slice { bytes: [60, 110, 82, 192, 131, 173, 255, 92, 134, 0, 185, 186, 87, 178, 51, 71, 136, 201, 15, 179, 204, 137, 125, 32, 87, 94, 227, 209, 47, 243, 75, 73] } }
Generated: [184, 9, 123, 15, 139, 191, 170, 9, 133, 143, 81, 45, 254, 15, 234, 12, 223, 57, 131, 145, 127, 231, 93, 101, 92, 251, 163, 179, 219, 24, 81, 111]

And here is one on the client side:

$ cargo run --example client
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running \`target/debug/examples/client\`
Received: Input { value: Slice { bytes: [83, 44, 93, 28, 132, 238, 70, 152, 163, 73, 185, 146, 142, 5, 172, 255, 219, 52, 51, 151, 99, 134, 35, 98, 154, 192, 210, 137, 141, 167, 60, 67] } }
Generated: [184, 9, 123, 15, 139, 191, 170, 9, 133, 143, 81, 45, 254, 15, 234, 12, 223, 57, 131, 145, 127, 231, 93, 101, 92, 251, 163, 179, 219, 24, 81, 111]

Note that the generated key is the same for both the server and the client, which is what we expect.

At the time of writing, the ring crate does not work on the latest nightly. To make it work, run these in the project directory:
rustupcomponentaddrustfmt−preview−−toolchainnightly−2017−12−21∗∗∗∗ rustup component add rustfmt-preview --toolchain nightly-2017-12-21** ** rustup override set nightly-2017-12-21

In this chapter, we took a quick look at securing communication over public networks. We started with an overview of certificates and how they are used for identifying servers on the web. We looked at using letsencrypt and openssl in Rust. We then moved on to securing Tokio applications using the same techniques. Finally, we took a quick look at doing key exchanges using the DH method.

The following section is the appendix; there, we will look at some extra crates and techniques that are becoming popular in the community.