DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Strengthening Cybersecurity: The Role of Digital Certificates and PKI in Authentication
  • Building Resilient Identity Systems: Lessons from Securing Billions of Authentication Requests
  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer

Trending

  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • Kullback–Leibler Divergence: Theory, Applications, and Implications
  • 5 Subtle Indicators Your Development Environment Is Under Siege
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  1. DZone
  2. Coding
  3. Languages
  4. Using TLS With Rust (Part 2): Client Authentication

Using TLS With Rust (Part 2): Client Authentication

Learn more about client authentication with Rust.

By 
Oren Eini user avatar
Oren Eini
·
Jan. 22, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
8.9K Views

Join the DZone community and get the full member experience.

Join For Free

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.

TLS Rust (programming language) authentication

Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Strengthening Cybersecurity: The Role of Digital Certificates and PKI in Authentication
  • Building Resilient Identity Systems: Lessons from Securing Billions of Authentication Requests
  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!