encore-postgres-rustls 0.1.0

TLS support for tokio-postgres via rustls
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! TLS support for `tokio-postgres` via `rustls`.
//!
//! The counterpart of `postgres-native-tls`: [`MakeTlsConnector`] wraps a
//! [`rustls::ClientConfig`], and the streams it makes report the
//! `tls-server-end-point` channel binding, so SCRAM-SHA-256-PLUS works as it
//! does over native-tls.
#![warn(rust_2018_idioms, clippy::all, missing_docs)]

use std::convert::Infallible;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use rustls::pki_types::ServerName;
use tokio::io::{AsyncRead, AsyncWrite, BufReader, ReadBuf};
use tokio_postgres::tls;
#[cfg(feature = "runtime")]
use tokio_postgres::tls::MakeTlsConnect;
use tokio_postgres::tls::{ChannelBinding, TlsConnect};

/// A `MakeTlsConnect` implementation using `rustls`.
///
/// Requires the `runtime` Cargo feature (enabled by default).
#[cfg(feature = "runtime")]
#[derive(Clone)]
pub struct MakeTlsConnector(Arc<rustls::ClientConfig>);

#[cfg(feature = "runtime")]
impl MakeTlsConnector {
    /// Creates a new connector from a client configuration.
    pub fn new(config: Arc<rustls::ClientConfig>) -> MakeTlsConnector {
        MakeTlsConnector(config)
    }
}

#[cfg(feature = "runtime")]
impl<S> MakeTlsConnect<S> for MakeTlsConnector
where
    S: AsyncRead + AsyncWrite + Unpin + 'static + Send,
{
    type Stream = TlsStream<S>;
    type TlsConnect = TlsConnector;
    type Error = Infallible;

    fn make_tls_connect(&mut self, domain: &str) -> Result<TlsConnector, Self::Error> {
        Ok(TlsConnector::new(self.0.clone(), domain))
    }
}

/// A `TlsConnect` implementation using `rustls`.
pub struct TlsConnector {
    connector: tokio_rustls::TlsConnector,
    // Read as a server name only in `connect`: tokio-postgres makes a
    // connector before it knows whether TLS is used, with an empty domain for
    // a Unix socket, and that must not fail a plain-text connection.
    domain: String,
}

impl TlsConnector {
    /// Creates a new connector configured to connect to the specified domain,
    /// which may also be an IP address. One that is not a valid server name
    /// fails the handshake, not this.
    pub fn new(config: Arc<rustls::ClientConfig>, domain: &str) -> TlsConnector {
        TlsConnector {
            connector: tokio_rustls::TlsConnector::from(config),
            domain: domain.to_string(),
        }
    }
}

impl<S> TlsConnect<S> for TlsConnector
where
    S: AsyncRead + AsyncWrite + Unpin + 'static + Send,
{
    type Stream = TlsStream<S>;
    type Error = io::Error;
    #[allow(clippy::type_complexity)]
    type Future = Pin<Box<dyn Future<Output = Result<TlsStream<S>, io::Error>> + Send>>;

    fn connect(self, stream: S) -> Self::Future {
        let stream = BufReader::with_capacity(8192, stream);
        Box::pin(async move {
            let domain = server_name(&self.domain)?;
            let stream = self.connector.connect(domain, stream).await?;
            Ok(TlsStream(stream))
        })
    }
}

/// The name the server's certificate is verified against, and sent as SNI.
fn server_name(domain: &str) -> io::Result<ServerName<'static>> {
    if domain.is_empty() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "no host name to verify the server's TLS certificate against",
        ));
    }
    match ServerName::try_from(domain) {
        Ok(name) => Ok(name.to_owned()),
        Err(_) => Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("{:?} is not a valid host name for TLS", domain),
        )),
    }
}

/// The stream returned by `TlsConnector`.
pub struct TlsStream<S>(tokio_rustls::client::TlsStream<BufReader<S>>);

impl<S> AsyncRead for TlsStream<S>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.0).poll_read(cx, buf)
    }
}

impl<S> AsyncWrite for TlsStream<S>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.0).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.0).poll_flush(cx)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.0).poll_shutdown(cx)
    }
}

impl<S> tls::TlsStream for TlsStream<S>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    fn channel_binding(&self) -> ChannelBinding {
        let (_, session) = self.0.get_ref();
        match session.peer_certificates().and_then(|certs| certs.first()) {
            Some(cert) => match tls_server_end_point(cert) {
                Some(hash) => ChannelBinding::tls_server_end_point(hash),
                None => ChannelBinding::none(),
            },
            None => ChannelBinding::none(),
        }
    }
}

/// The `tls-server-end-point` channel binding of a DER certificate (RFC 5929
/// §4.1): its hash under the hash function of its signature algorithm, with
/// MD5 and SHA-1 replaced by SHA-256. For RSASSA-PSS that is the hash its
/// parameters name, as PostgreSQL's server takes it. `None` for algorithms
/// the RFC leaves undefined (e.g. Ed25519), hashes `ring` lacks, or a
/// certificate that does not parse, as native-tls does; the connection then
/// authenticates without the binding.
fn tls_server_end_point(cert: &[u8]) -> Option<Vec<u8>> {
    let (oid, parameters) = signature_algorithm(cert)?;
    let hash = match oid {
        RSA_PSS => pss_hash(parameters)?,
        oid => oid,
    };
    let algorithm = match hash {
        // md5WithRSAEncryption, sha1WithRSAEncryption, ecdsa-with-SHA1, and
        // SHA-1 itself, the RSASSA-PSS default.
        RSA_MD5 | RSA_SHA1 | ECDSA_SHA1 | SHA1 => &ring::digest::SHA256,
        RSA_SHA256 | ECDSA_SHA256 | SHA256 => &ring::digest::SHA256,
        RSA_SHA384 | ECDSA_SHA384 | SHA384 => &ring::digest::SHA384,
        RSA_SHA512 | ECDSA_SHA512 | SHA512 => &ring::digest::SHA512,
        _ => return None,
    };
    Some(ring::digest::digest(algorithm, cert).as_ref().to_vec())
}

// The DER contents of the signature algorithm OIDs above.
const RSA_MD5: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x04];
const RSA_SHA1: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05];
const RSA_PSS: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0a];
const RSA_SHA256: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b];
const RSA_SHA384: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0c];
const RSA_SHA512: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0d];
const ECDSA_SHA1: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x01];
const ECDSA_SHA256: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02];
const ECDSA_SHA384: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03];
const ECDSA_SHA512: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x04];

// The DER contents of the hash OIDs an RSASSA-PSS signature can name.
const SHA1: &[u8] = &[0x2b, 0x0e, 0x03, 0x02, 0x1a];
const SHA256: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01];
const SHA384: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02];
const SHA512: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03];

const SEQUENCE: u8 = 0x30;
const OID: u8 = 0x06;

/// A DER certificate's outer `signatureAlgorithm`, as `(the algorithm's OID,
/// the DER of its parameters)`: `Certificate ::= SEQUENCE { tbsCertificate,
/// signatureAlgorithm AlgorithmIdentifier, signatureValue }`,
/// `AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER,
/// parameters ANY OPTIONAL }`. The parameters are empty when absent.
fn signature_algorithm(cert: &[u8]) -> Option<(&[u8], &[u8])> {
    let (certificate, _) = der_element(cert, SEQUENCE)?;
    let (_tbs, rest) = der_element(certificate, SEQUENCE)?;
    let (algorithm_identifier, _) = der_element(rest, SEQUENCE)?;
    der_element(algorithm_identifier, OID)
}

/// The OID of the hash RSASSA-PSS parameters name (RFC 4055 §3.1):
/// `RSASSA-PSS-params ::= SEQUENCE { hashAlgorithm [0] HashAlgorithm DEFAULT
/// sha1, ... }`, `HashAlgorithm ::= AlgorithmIdentifier`. The parameters
/// must be present in a signature's algorithm identifier, so `None` if they
/// are not.
fn pss_hash(parameters: &[u8]) -> Option<&[u8]> {
    const HASH_ALGORITHM: u8 = 0xa0; // [0], explicit, so constructed.
    let (params, _) = der_element(parameters, SEQUENCE)?;
    if params.first() != Some(&HASH_ALGORITHM) {
        return Some(SHA1);
    }
    let (hash_algorithm, _) = der_element(params, HASH_ALGORITHM)?;
    let (algorithm_identifier, _) = der_element(hash_algorithm, SEQUENCE)?;
    let (oid, _) = der_element(algorithm_identifier, OID)?;
    Some(oid)
}

/// Splits one DER element with the given tag off the front of `input`:
/// `(its contents, what follows it)`.
fn der_element(input: &[u8], tag: u8) -> Option<(&[u8], &[u8])> {
    let (&actual, input) = input.split_first()?;
    if actual != tag {
        return None;
    }
    let (&first, mut input) = input.split_first()?;
    let len = if first < 0x80 {
        usize::from(first)
    } else {
        // Long form: the low bits count the length's bytes.
        let count = usize::from(first & 0x7f);
        if count == 0 || count > std::mem::size_of::<usize>() || input.len() < count {
            return None;
        }
        let (bytes, rest) = input.split_at(count);
        input = rest;
        bytes
            .iter()
            .fold(0usize, |len, &b| (len << 8) | usize::from(b))
    };
    if input.len() < len {
        return None;
    }
    Some(input.split_at(len))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cert(alg: &'static rcgen::SignatureAlgorithm) -> Vec<u8> {
        let key = rcgen::KeyPair::generate_for(alg).unwrap();
        let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).unwrap();
        params.self_signed(&key).unwrap().der().to_vec()
    }

    #[test]
    fn hashes_with_the_signature_algorithm_hash() {
        let p256 = cert(&rcgen::PKCS_ECDSA_P256_SHA256);
        assert_eq!(signature_algorithm(&p256).unwrap().0, ECDSA_SHA256);
        assert_eq!(
            tls_server_end_point(&p256).unwrap(),
            ring::digest::digest(&ring::digest::SHA256, &p256).as_ref()
        );

        let p384 = cert(&rcgen::PKCS_ECDSA_P384_SHA384);
        assert_eq!(signature_algorithm(&p384).unwrap().0, ECDSA_SHA384);
        assert_eq!(
            tls_server_end_point(&p384).unwrap(),
            ring::digest::digest(&ring::digest::SHA384, &p384).as_ref()
        );
    }

    /// Made by OpenSSL 3: `openssl req -x509 -key <an RSA-PSS key> -sha384
    /// -sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:48`.
    const RSA_PSS_SHA384_CERT: &[u8] = include_bytes!("../testdata/rsa_pss_sha384.der");

    #[test]
    fn hashes_rsa_pss_with_the_hash_its_parameters_name() {
        let (oid, parameters) = signature_algorithm(RSA_PSS_SHA384_CERT).unwrap();
        assert_eq!(oid, RSA_PSS);
        assert_eq!(pss_hash(parameters), Some(SHA384));
        assert_eq!(
            tls_server_end_point(RSA_PSS_SHA384_CERT).unwrap(),
            ring::digest::digest(&ring::digest::SHA384, RSA_PSS_SHA384_CERT).as_ref()
        );
    }

    /// A DER element: `tag`, a short-form length, `contents`.
    fn der(tag: u8, contents: &[u8]) -> Vec<u8> {
        assert!(contents.len() < 0x80);
        [&[tag, contents.len() as u8][..], contents].concat()
    }

    /// The outline of a certificate signed under RSASSA-PSS with the given
    /// DER parameters: all `tls_server_end_point` reads of one.
    fn pss_cert(parameters: &[u8]) -> Vec<u8> {
        let algorithm = der(SEQUENCE, &[der(OID, RSA_PSS), parameters.to_vec()].concat());
        let signature = der(0x03, &[0x00]);
        der(
            SEQUENCE,
            &[der(SEQUENCE, &[]), algorithm, signature].concat(),
        )
    }

    /// RSASSA-PSS parameters naming `hash`, with a NULL parameter as
    /// OpenSSL writes it.
    fn pss_parameters(hash: &[u8]) -> Vec<u8> {
        let hash_algorithm = der(SEQUENCE, &[der(OID, hash), der(0x05, &[])].concat());
        der(SEQUENCE, &der(0xa0, &hash_algorithm))
    }

    #[test]
    fn hashes_rsa_pss_by_its_parameters() {
        for (hash, algorithm) in [
            (SHA1, &ring::digest::SHA256),
            (SHA256, &ring::digest::SHA256),
            (SHA384, &ring::digest::SHA384),
            (SHA512, &ring::digest::SHA512),
        ] {
            let cert = pss_cert(&pss_parameters(hash));
            assert_eq!(
                tls_server_end_point(&cert).unwrap(),
                ring::digest::digest(algorithm, &cert).as_ref()
            );
        }

        // No hashAlgorithm: SHA-1, the default, so SHA-256.
        let cert = pss_cert(&der(SEQUENCE, &[]));
        assert_eq!(
            tls_server_end_point(&cert).unwrap(),
            ring::digest::digest(&ring::digest::SHA256, &cert).as_ref()
        );
    }

    #[test]
    fn has_no_binding_for_rsa_pss_without_a_known_hash() {
        // SHA-224, which ring lacks.
        let sha224 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04];
        assert_eq!(
            tls_server_end_point(&pss_cert(&pss_parameters(&sha224))),
            None
        );
        // No parameters, which a signature's algorithm must have.
        assert_eq!(tls_server_end_point(&pss_cert(&[])), None);
        // A truncated hashAlgorithm.
        assert_eq!(
            tls_server_end_point(&pss_cert(&der(SEQUENCE, &[0xa0, 0x05]))),
            None
        );
    }

    #[test]
    fn has_no_binding_for_ed25519() {
        let ed25519 = cert(&rcgen::PKCS_ED25519);
        assert!(signature_algorithm(&ed25519).is_some());
        assert_eq!(tls_server_end_point(&ed25519), None);
    }

    fn connector(domain: &str) -> TlsConnector {
        let provider = Arc::new(rustls::crypto::ring::default_provider());
        let config = rustls::ClientConfig::builder_with_provider(provider)
            .with_safe_default_protocol_versions()
            .unwrap()
            .with_root_certificates(rustls::RootCertStore::empty())
            .with_no_client_auth();
        let mut make = MakeTlsConnector::new(Arc::new(config));
        MakeTlsConnect::<tokio::io::DuplexStream>::make_tls_connect(&mut make, domain).unwrap()
    }

    async fn handshake_error(domain: &str) -> String {
        let (client, _server) = tokio::io::duplex(1024);
        match connector(domain).connect(client).await {
            Ok(_) => panic!("expected the handshake to fail"),
            Err(err) => {
                assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
                err.to_string()
            }
        }
    }

    /// tokio-postgres makes a connector for a Unix socket too, with no host
    /// name, before it knows whether TLS is used.
    #[tokio::test]
    async fn an_empty_domain_fails_only_the_handshake() {
        let err = handshake_error("").await;
        assert!(err.contains("no host name"), "{err}");
    }

    #[tokio::test]
    async fn an_invalid_domain_fails_only_the_handshake() {
        let err = handshake_error("not a host").await;
        assert!(
            err.contains("\"not a host\" is not a valid host name"),
            "{err}"
        );
    }

    #[test]
    fn rejects_malformed_certificates() {
        let p256 = cert(&rcgen::PKCS_ECDSA_P256_SHA256);
        for len in [0, 1, 2, 10, p256.len() / 2] {
            assert_eq!(tls_server_end_point(&p256[..len]), None);
        }
        assert_eq!(
            tls_server_end_point(&[0x30, 0x84, 0xff, 0xff, 0xff, 0xff]),
            None
        );
    }
}