noctis 0.6.0

Open-source black-box vulnerability scanner: readable YAML checks that prove each bug on the live service, QoD-graded findings, REST API.
use std::sync::Arc;
use std::time::Duration;

use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::client::WebPkiServerVerifier;
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{CertificateError, ClientConfig, DigitallySignedStruct, SignatureScheme};
use serde::{Deserialize, Serialize};
use tokio::net::TcpStream;

use super::legacy_tls;
use webpki_roots::TLS_SERVER_ROOTS;
use x509_parser::prelude::*;

use crate::error::{NoctisError, Result};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TlsResult {
    pub connected: bool,
    pub protocol_version: Option<String>,
    pub cipher_suite: Option<String>,
    pub cert_valid: bool,
    pub cert_subject: Option<String>,
    pub cert_issuer: Option<String>,
    pub cert_expiry: Option<String>,
    pub cert_sans: Vec<String>,
    pub duration_ms: u64,
}

pub async fn inspect(host: &str, port: u16, timeout_secs: u64) -> Result<TlsResult> {
    let addr = format!("{host}:{port}");
    let start = std::time::Instant::now();
    let limit = Duration::from_secs(timeout_secs);
    let dial = || async {
        tokio::time::timeout(limit, TcpStream::connect(&addr))
            .await
            .map_err(|_| NoctisError::Tls(format!("connect timeout: {addr}")))?
            .map_err(|e| NoctisError::Tls(format!("connect {addr}: {e}")))
    };
    let stream = dial().await?;

    let verifier = webpki_verifier()?;
    let config = ClientConfig::builder_with_provider(crate::checks::tcp::crypto_provider())
        .with_safe_default_protocol_versions()
        .map_err(|e| NoctisError::Tls(format!("TLS config: {e}")))?
        .dangerous()
        .with_custom_certificate_verifier(verifier.clone())
        .with_no_client_auth();

    // A certificate that fails verification makes the rustls handshake fail
    // too: the legacy retry (no verification) then still reports the session,
    // with `cert_valid: false`. It also reaches servers that only speak
    // TLS 1.0/1.1 or static-RSA key exchange (#2446).
    let tls = legacy_tls::connect(stream, host, Arc::new(config), Some(limit), dial)
        .await
        .map_err(|e| NoctisError::Tls(format!("TLS handshake: {e}")))?;

    let duration_ms = start.elapsed().as_millis() as u64;
    let session = tls.session_info();
    let leaf = session.chain.first().map(Vec::as_slice);
    let cert = cert_info(leaf);
    let cert_valid =
        cert.parsed && (!tls.is_legacy() || chain_verifies(&verifier, &session.chain, host));

    Ok(TlsResult {
        connected: true,
        protocol_version: session.protocol_version,
        cipher_suite: session.cipher_suite,
        cert_valid,
        cert_subject: cert.subject,
        cert_issuer: cert.issuer,
        cert_expiry: cert.expiry,
        cert_sans: cert.sans,
        duration_ms,
    })
}

/// The Mozilla-root (webpki-roots) verifier `tls_check` judges certificates by.
fn webpki_verifier() -> Result<Arc<ScanVerifier>> {
    let mut root_store = rustls::RootCertStore::empty();
    root_store.extend(TLS_SERVER_ROOTS.iter().cloned());
    WebPkiServerVerifier::builder_with_provider(
        Arc::new(root_store),
        crate::checks::tcp::crypto_provider(),
    )
    .build()
    .map(|inner| Arc::new(ScanVerifier { inner }))
    .map_err(|e| NoctisError::Tls(format!("TLS verifier: {e}")))
}

/// The webpki verifier, except that a scan by IP address does not check the
/// certificate's names: targets come from port scans, so a properly issued
/// certificate (DNS names only) would otherwise always look invalid. A name
/// mismatch still counts when the target was given as a host name.
#[derive(Debug)]
struct ScanVerifier {
    inner: Arc<WebPkiServerVerifier>,
}

impl ServerCertVerifier for ScanVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> std::result::Result<ServerCertVerified, rustls::Error> {
        match self.inner.verify_server_cert(
            end_entity,
            intermediates,
            server_name,
            ocsp_response,
            now,
        ) {
            Err(rustls::Error::InvalidCertificate(
                CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
            )) if matches!(server_name, ServerName::IpAddress(_)) => {
                Ok(ServerCertVerified::assertion())
            }
            other => other,
        }
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

/// Verify a chain (leaf first, DER) received over the legacy stack the way
/// the rustls handshake would have.
fn chain_verifies(verifier: &ScanVerifier, chain: &[Vec<u8>], host: &str) -> bool {
    let Some((leaf, rest)) = chain.split_first() else {
        return false;
    };
    let Ok(name) = ServerName::try_from(host.to_string()) else {
        return false;
    };
    let leaf = CertificateDer::from(leaf.as_slice());
    let intermediates: Vec<CertificateDer<'_>> = rest
        .iter()
        .map(|c| CertificateDer::from(c.as_slice()))
        .collect();
    verifier
        .verify_server_cert(&leaf, &intermediates, &name, &[], UnixTime::now())
        .is_ok()
}

/// Leaf certificate fields of an established TLS session.
#[derive(Debug, Default)]
pub(crate) struct CertInfo {
    /// The leaf certificate was present and parsed as X.509.
    pub parsed: bool,
    pub subject: Option<String>,
    pub issuer: Option<String>,
    pub expiry: Option<String>,
    pub sans: Vec<String>,
}

/// Read the peer's leaf certificate (subject, issuer, expiry, SANs), DER.
/// Shared by `tls_check` and `tcp_starttls`.
pub(crate) fn cert_info(leaf: Option<&[u8]>) -> CertInfo {
    let mut info = CertInfo::default();
    let Some(leaf) = leaf else {
        return info;
    };
    let Ok((_, cert)) = X509Certificate::from_der(leaf) else {
        return info;
    };
    info.parsed = true;
    info.subject = Some(cert.subject().to_string());
    info.issuer = Some(cert.issuer().to_string());
    info.expiry = Some(
        cert.validity()
            .not_after
            .to_rfc2822()
            .unwrap_or_else(|_| "unknown".to_string()),
    );
    if let Ok(Some(san_ext)) = cert.subject_alternative_name() {
        for san in &san_ext.value.general_names {
            let s = match san {
                GeneralName::DNSName(n) => n.to_string(),
                GeneralName::IPAddress(b) => {
                    if b.len() == 4 {
                        format!("{}.{}.{}.{}", b[0], b[1], b[2], b[3])
                    } else {
                        format!("{b:?}")
                    }
                }
                other => format!("{other:?}"),
            };
            info.sans.push(s);
        }
    }
    info
}

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

    /// `ClientConfig::builder()` panics here (rustls has both ring and aws-lc-rs,
    /// so there is no process default provider): a TLS handshake attempt must
    /// return a result, not panic.
    #[tokio::test]
    async fn inspect_reaches_the_handshake_without_panicking() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        // Accept then drop: the handshake fails cleanly.
        tokio::spawn(async move {
            let _ = listener.accept().await;
        });
        let res = inspect("127.0.0.1", port, 2).await;
        assert!(
            matches!(res, Err(NoctisError::Tls(ref m)) if m.starts_with("TLS handshake")),
            "{res:?}"
        );
    }

    use crate::checks::legacy_tls::test_server::{spawn, Mode};

    /// `tls_check` reports a TLS 1.0-only server instead of failing, so the
    /// weak-protocol finding can fire (#2446); its self-signed certificate is
    /// reported as not valid.
    #[tokio::test]
    async fn inspect_reports_a_tls10_only_server() {
        let port = spawn(Mode::Tls10).await;
        let r = inspect("127.0.0.1", port, 5).await.unwrap();
        assert!(r.connected);
        assert_eq!(r.protocol_version.as_deref(), Some("TLSv1_0"));
        assert_eq!(
            r.cipher_suite.as_deref(),
            Some("TLS_RSA_WITH_AES_128_CBC_SHA")
        );
        assert!(!r.cert_valid);
        assert_eq!(r.cert_subject.as_deref(), Some("CN=legacy.test"));
    }

    /// A modern server with a self-signed certificate used to fail the
    /// verified handshake outright; it is now reported, `cert_valid: false`.
    #[tokio::test]
    async fn inspect_reports_an_untrusted_certificate() {
        let (port, _) = crate::checks::raw_socket::starttls_test_server::spawn_direct_tls().await;
        let r = inspect("127.0.0.1", port, 5).await.unwrap();
        assert!(r.connected);
        assert!(!r.cert_valid);
        assert_eq!(r.protocol_version.as_deref(), Some("TLSv1_3"));
    }

    /// A CA-issued certificate for `legacy.test` (DNS name only): valid when
    /// the target is scanned by IP address, invalid for another host name.
    #[test]
    fn ip_scan_skips_the_certificate_name_check() {
        use openssl::asn1::Asn1Time;
        use openssl::bn::BigNum;
        use openssl::hash::MessageDigest;
        use openssl::pkey::PKey;
        use openssl::rsa::Rsa;
        use openssl::x509::extension::{BasicConstraints, SubjectAlternativeName};
        use openssl::x509::{X509NameBuilder, X509};

        let cert = |cn: &str, ca: bool, issuer: Option<(&X509, &PKey<openssl::pkey::Private>)>| {
            let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
            let mut name = X509NameBuilder::new().unwrap();
            name.append_entry_by_text("CN", cn).unwrap();
            let name = name.build();
            let mut b = X509::builder().unwrap();
            b.set_version(2).unwrap();
            b.set_serial_number(
                &BigNum::from_u32(if ca { 1 } else { 2 })
                    .unwrap()
                    .to_asn1_integer()
                    .unwrap(),
            )
            .unwrap();
            b.set_subject_name(&name).unwrap();
            b.set_pubkey(&key).unwrap();
            b.set_not_before(&Asn1Time::days_from_now(0).unwrap())
                .unwrap();
            b.set_not_after(&Asn1Time::days_from_now(30).unwrap())
                .unwrap();
            if ca {
                b.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
                    .unwrap();
                b.set_issuer_name(&name).unwrap();
                b.sign(&key, MessageDigest::sha256()).unwrap();
            } else {
                let (ica, ikey) = issuer.unwrap();
                let san = SubjectAlternativeName::new()
                    .dns("legacy.test")
                    .build(&b.x509v3_context(Some(ica), None))
                    .unwrap();
                b.append_extension(san).unwrap();
                b.set_issuer_name(ica.subject_name()).unwrap();
                b.sign(ikey, MessageDigest::sha256()).unwrap();
            }
            (b.build(), key)
        };
        let (ca, ca_key) = cert("noctis test CA", true, None);
        let (leaf, _) = cert("legacy.test", false, Some((&ca, &ca_key)));

        let mut roots = rustls::RootCertStore::empty();
        roots
            .add(CertificateDer::from(ca.to_der().unwrap()))
            .unwrap();
        let inner = WebPkiServerVerifier::builder_with_provider(
            Arc::new(roots),
            crate::checks::tcp::crypto_provider(),
        )
        .build()
        .unwrap();
        let v = ScanVerifier { inner };
        let chain = vec![leaf.to_der().unwrap()];
        assert!(chain_verifies(&v, &chain, "127.0.0.1"));
        assert!(chain_verifies(&v, &chain, "legacy.test"));
        assert!(!chain_verifies(&v, &chain, "other.test"));
        // an untrusted self-signed certificate stays invalid, even by IP
        let (stray, _) = cert("stray", true, None);
        assert!(!chain_verifies(&v, &[stray.to_der().unwrap()], "127.0.0.1"));
    }
}