Using TLS With Rust (Part 2): Client Authentication

The task that I have for now is to add client authentication via X509 client certificate. That is both obvious and non-obvious, unfortunately. I’ll get to that, but before I do so, I want to go back to the previous post and discuss this piece of code:

fn new(cert_path: &str, key_path: &str, listen_uri: &str) -> Result<Server, ConnectionError> {

    fn open_cert_file<F,T>(file: &str, method: F) -> Result<Vec<T>, ConnectionError> 
        where F : Fn(&mut io::BufRead) -> Result<Vec<T>, ()> {
        let certfile = fs::File::open(file)?;
        let mut reader = io::BufReader::new(certfile);
        match method(&mut reader) {
            Err(_) => return Err(ConnectionError::failed_cert(file)),
            Ok(certs) => match certs.len() {
                0 => return Err(ConnectionError::failed_cert(file)),
                _ => Ok(certs)
            }
        }
    }

    let mut config = rustls::ServerConfig::new(rustls::NoClientAuth::new());

    let certs = open_cert_file(cert_path, rustls::internal::pemfile::certs)?;
    let key = open_cert_file(key_path, rustls::internal::pemfile::rsa_private_keys)
                .or_else(|_| open_cert_file(key_path, rustls::internal::pemfile::pkcs8_private_keys))
                .and_then(|keys| match keys.get(0){
                    None => Err(ConnectionError::failed_cert(key_path)),
                    Some(key) => Ok(key.clone())
                })?;

    config.set_single_cert(certs, key)?;

    let listener = TcpListener::bind(listen_uri)?;

    Ok(Server { tls_config: Arc::new(config), tcp_listener: listener })
}


I’ll admit that I’m enjoying exploring Rust features, so I don’t know how idiomatic this code is, but it is certainly dense. This basically does the setup for a TCP listener and setting up of the TLS details so we can accept a connection.

Rust allows us to define local functions (inside a parent function); this is mostly just a way to define a private function since the nested function has no access to the parent scope. The open_cert_file function is just a way to avoid code duplication, but it is an interesting one. It is a generic function that accepts an open-ended function of its own. Basically, it will open a file, read it, and then pass it to the function it was provided. There is some error handling, but that is pretty much it.

The next fun part happens when we want to read the certs and key file. The certs file is easy, it can only ever appear in a single format, but the key may be either PKCS8 or RSA Private Key. And unlike the certs where we expect to get a collection, we need to get just a single value. To handle that, we have:

image

First, we try to open and read the file as an RSA Private Key; if that isn’t successful, we’ll attempt to read it as a PKCS8 file. If either of those attempts was successful, we’ll try to get the first key, clone it, and return.  However, if there was an error in any part of the process, we abort the whole thing (and exit the function with an error).

From my review of Rust code, it looks like this isn’t non-idiomatic code, although I’m not sure I would call it idiomatic at this point. The problem with this code is that it is pretty fun to write, when you read it is obvious what is going on, but it is really hard to actually debug this. There is too much going on in too little space and it is not easy to follow in a debugger.

The rest of the code is boring, so I’m going to skip that and start talking about why client authentication is going to be interesting. Here is the core of the problem:

image

In order to simplify my life, I’m using the rustls’ Stream to handle transparent encryption and decryption. This is similar to how I would do it when using C#, for example. However, the stream interface doesn’t have any way for me to handle this explicitly. Luckily, I was able to dive into the code, and I think that, given the architecture present, I can invoke the handshake manually on the ServerSession and then hand off the session as is to the stream.

What I actually had to do was to set up client authentication here:

image

And then, I needed to manually complete the handshake first:

image

And this is when I run into a problem; when trying to connect via my a client certificate, I got the following error:

image

I’m assuming that this is because rustls is actually verifying the certificate against PKI, which is not something that I want. I don’t like to use PKI for this; instead, I want to register the allowed certificates thumbprints, but first, I need to figure out how to make rustls accept any kind of client certificate. I’m afraid that this means that I have to break out the debugger again and dive into the code to figure out where we are being rejected and why.

After a short travel in the code, I got to something that looks promising:

image

This looks like something that I should be able to control to see if I like or dislike the certificate. Going inside it, it looks like I was right:

image

I think that I should be able to write an implementation of this that would do the validation without checking for the issuer. However, it looks like my plan run into a snag, see:

image

I’m not sure that I’m a good person to talk about the details of X509 certificate validation. In this case, I think that I could have done enough to validate that the cert is valid enough for my needs, but it seems like there isn’t a way to actually provide another implementation of the ClientCertVerifier because the entire package is private. I guess that this is as far as I can use rustls; I’m going to move to the OpenSSL binding, which I’m more familiar with, and see how that works for me.

Okay, I tried using the rust OpenSSL bindings, and here is what I got:

image

So, this is some sort of link error, and I could spend half a day to try to resolve it, or just give up on this for now. Looking around, it looks like there is also something called native-tls for Rust, so I might take a peek at it tomorrow.

 

 

 

 

Top