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.
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Legacy TLS fallback for the client handshakes noctis makes (#2446).
//!
//! rustls never implemented static-RSA key exchange and refuses TLS 1.0/1.1,
//! CBC-only suite lists and servers without the secure-renegotiation
//! extension. Those are exactly the EOL appliances and old daemons many feeds
//! target: against them every TLS connection failed and the feed silently
//! reported nothing. rustls stays the first choice; when its handshake fails,
//! the connection is opened again and the handshake retried with OpenSSL
//! (already linked through libssh2-sys) at security level 0: TLS 1.0+, every
//! cipher OpenSSL was built with, RSA key exchange, legacy renegotiation.
//! Certificates are never verified on this path.

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

use openssl::ssl::{Ssl, SslConnector, SslMethod, SslOptions, SslVerifyMode};
use rustls::pki_types::ServerName;
use rustls::ClientConfig;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::TcpStream;
use tokio::time::timeout;
use tokio_openssl::SslStream;
use tokio_rustls::TlsConnector;

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

/// `SSL_OP_LEGACY_SERVER_CONNECT`: connect to servers that lack the RFC 5746
/// renegotiation extension. OpenSSL 3 no longer sets it by default, and the
/// `openssl` crate exposes no named flag for it.
const SSL_OP_LEGACY_SERVER_CONNECT: u64 = 0x4;

/// The OpenSSL client used when rustls cannot complete a handshake.
fn legacy_ssl(host: &str) -> std::result::Result<Ssl, openssl::error::ErrorStack> {
    let mut b = SslConnector::builder(SslMethod::tls_client())?;
    b.set_verify(SslVerifyMode::NONE);
    // Level 0 is what allows TLS 1.0/1.1, SHA-1 signatures and short keys on
    // OpenSSL 3; the cipher string resets the builder's restricted default.
    b.set_security_level(0);
    b.set_cipher_list("ALL:COMPLEMENTOFALL:@SECLEVEL=0")?;
    b.set_min_proto_version(None)?;
    b.set_options(SslOptions::from_bits_retain(
        SSL_OP_LEGACY_SERVER_CONNECT as _,
    ));
    let mut cfg = b.build().configure()?;
    cfg.set_verify_hostname(false);
    // SNI is sent for host names only (`into_ssl` skips IP literals).
    cfg.into_ssl(host)
}

/// TLS client handshake with OpenSSL on `tcp` (no certificate check).
pub(crate) async fn legacy_handshake(
    tcp: TcpStream,
    host: &str,
) -> std::result::Result<SslStream<TcpStream>, String> {
    let ssl = legacy_ssl(host).map_err(|e| format!("OpenSSL setup: {e}"))?;
    let mut stream = SslStream::new(ssl, tcp).map_err(|e| format!("OpenSSL setup: {e}"))?;
    Pin::new(&mut stream)
        .connect()
        .await
        .map_err(|e| e.to_string())?;
    Ok(stream)
}

/// A client TLS connection, from whichever stack completed the handshake.
pub enum ClientTls {
    Rustls(Box<tokio_rustls::client::TlsStream<TcpStream>>),
    Legacy(SslStream<TcpStream>),
}

/// Negotiated parameters of a [`ClientTls`] session, in the same forms for
/// both stacks: `protocol_version` as rustls prints it (`TLSv1_2`),
/// `cipher_suite` as the IANA name (`TLS_RSA_WITH_AES_128_GCM_SHA256`).
#[derive(Debug, Default)]
pub(crate) struct SessionInfo {
    pub protocol_version: Option<String>,
    pub cipher_suite: Option<String>,
    /// Peer certificate chain, leaf first, DER.
    pub chain: Vec<Vec<u8>>,
}

/// OpenSSL's `SSL_get_version` string in the rustls `Debug` form, so feeds
/// match one spelling whichever stack connected.
fn protocol_name(openssl: &str) -> String {
    match openssl {
        "TLSv1" => "TLSv1_0".to_string(),
        "TLSv1.1" => "TLSv1_1".to_string(),
        "TLSv1.2" => "TLSv1_2".to_string(),
        "TLSv1.3" => "TLSv1_3".to_string(),
        other => other.replace('.', "_"),
    }
}

impl ClientTls {
    pub fn is_legacy(&self) -> bool {
        matches!(self, ClientTls::Legacy(_))
    }

    pub fn tcp(&self) -> &TcpStream {
        match self {
            ClientTls::Rustls(s) => s.get_ref().0,
            ClientTls::Legacy(s) => s.get_ref(),
        }
    }

    pub(crate) fn session_info(&self) -> SessionInfo {
        match self {
            ClientTls::Rustls(s) => {
                let c = s.get_ref().1;
                SessionInfo {
                    protocol_version: c.protocol_version().map(|v| format!("{v:?}")),
                    cipher_suite: c.negotiated_cipher_suite().map(|cs| format!("{cs:?}")),
                    chain: c
                        .peer_certificates()
                        .map(|cs| cs.iter().map(|c| c.as_ref().to_vec()).collect())
                        .unwrap_or_default(),
                }
            }
            ClientTls::Legacy(s) => {
                let ssl = s.ssl();
                let chain = match ssl.peer_cert_chain() {
                    Some(st) => st.iter().filter_map(|c| c.to_der().ok()).collect(),
                    None => ssl
                        .peer_certificate()
                        .and_then(|c| c.to_der().ok())
                        .into_iter()
                        .collect(),
                };
                SessionInfo {
                    protocol_version: Some(protocol_name(ssl.version_str())),
                    cipher_suite: ssl
                        .current_cipher()
                        .map(|c| c.standard_name().unwrap_or(c.name()).to_string()),
                    chain,
                }
            }
        }
    }
}

/// Client TLS handshake on `tcp` with the rustls `config`; when rustls cannot
/// complete it, a fresh connection from `reconnect` is handshaken with OpenSSL
/// instead (the failed attempt leaves the first socket unusable). Each
/// handshake is bounded by `handshake_timeout` when given.
pub(crate) async fn connect<F, Fut>(
    tcp: TcpStream,
    host: &str,
    config: Arc<ClientConfig>,
    handshake_timeout: Option<Duration>,
    reconnect: F,
) -> Result<ClientTls>
where
    F: FnOnce() -> Fut,
    Fut: Future<Output = Result<TcpStream>>,
{
    let server_name = ServerName::try_from(host.to_string())
        .map_err(|e| NoctisError::Tcp(format!("invalid host for TLS SNI: {e}")))?;
    let rustls_err = match bounded(
        handshake_timeout,
        TlsConnector::from(config).connect(server_name, tcp),
    )
    .await
    {
        Ok(Ok(s)) => return Ok(ClientTls::Rustls(Box::new(s))),
        Ok(Err(e)) => e.to_string(),
        // A peer that never answers will not answer OpenSSL either.
        Err(()) => return Err(NoctisError::Tcp("TLS handshake timed out".to_string())),
    };

    let tcp = reconnect().await.map_err(|e| {
        NoctisError::Tcp(format!(
            "{rustls_err} (legacy TLS retry: reconnect failed: {e})"
        ))
    })?;
    match bounded(handshake_timeout, legacy_handshake(tcp, host)).await {
        Ok(Ok(s)) => {
            let info = ClientTls::Legacy(s);
            let si = info.session_info();
            tracing::debug!(
                host,
                rustls_error = %rustls_err,
                protocol = si.protocol_version.as_deref().unwrap_or("?"),
                cipher = si.cipher_suite.as_deref().unwrap_or("?"),
                "TLS: connected with the legacy OpenSSL stack"
            );
            Ok(info)
        }
        Ok(Err(e)) => Err(NoctisError::Tcp(format!(
            "{rustls_err} (legacy TLS retry: {e})"
        ))),
        Err(()) => Err(NoctisError::Tcp(format!(
            "{rustls_err} (legacy TLS retry: timed out)"
        ))),
    }
}

async fn bounded<T>(
    limit: Option<Duration>,
    fut: impl Future<Output = T>,
) -> std::result::Result<T, ()> {
    match limit {
        Some(d) => timeout(d, fut).await.map_err(|_| ()),
        None => Ok(fut.await),
    }
}

impl AsyncRead for ClientTls {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        match self.get_mut() {
            ClientTls::Rustls(s) => Pin::new(s).poll_read(cx, buf),
            ClientTls::Legacy(s) => Pin::new(s).poll_read(cx, buf),
        }
    }
}

impl AsyncWrite for ClientTls {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        match self.get_mut() {
            ClientTls::Rustls(s) => Pin::new(s).poll_write(cx, buf),
            ClientTls::Legacy(s) => Pin::new(s).poll_write(cx, buf),
        }
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        match self.get_mut() {
            ClientTls::Rustls(s) => Pin::new(s).poll_flush(cx),
            ClientTls::Legacy(s) => Pin::new(s).poll_flush(cx),
        }
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        match self.get_mut() {
            ClientTls::Rustls(s) => Pin::new(s).poll_shutdown(cx),
            ClientTls::Legacy(s) => Pin::new(s).poll_shutdown(cx),
        }
    }
}

/// Test-only TLS server that rustls cannot talk to: OpenSSL with one static-RSA
/// suite (`AES128-GCM-SHA256`, TLS 1.2) or TLS 1.0 only (`AES128-SHA`), and a
/// fresh self-signed RSA certificate (CN `legacy.test`). It echoes `PING` as
/// `PONG-LEGACY`, answers anything starting with an HTTP method with a fixed
/// HTTP/1.0 reply (body `legacy-ok <request line>`), and closes. `/redirect`
/// answers 302 to `/final`, `/away?to=<url>` 302 to that URL.
#[cfg(test)]
pub(crate) mod test_server {
    use openssl::asn1::Asn1Time;
    use openssl::bn::BigNum;
    use openssl::hash::MessageDigest;
    use openssl::pkey::PKey;
    use openssl::rsa::Rsa;
    use openssl::ssl::{SslAcceptor, SslMethod, SslVersion};
    use openssl::x509::{X509NameBuilder, X509};
    use std::pin::Pin;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;
    use tokio_openssl::SslStream;

    #[derive(Clone, Copy, PartialEq, Eq)]
    pub(crate) enum Mode {
        /// TLS 1.2, `AES128-GCM-SHA256` (RSA key exchange) only.
        RsaKex,
        /// TLS 1.0 only, `AES128-SHA`.
        Tls10,
    }

    fn acceptor(mode: Mode) -> SslAcceptor {
        let rsa = Rsa::generate(2048).unwrap();
        let key = PKey::from_rsa(rsa).unwrap();
        let mut name = X509NameBuilder::new().unwrap();
        name.append_entry_by_text("CN", "legacy.test").unwrap();
        let name = name.build();
        let mut cert = X509::builder().unwrap();
        cert.set_version(2).unwrap();
        cert.set_serial_number(&BigNum::from_u32(1).unwrap().to_asn1_integer().unwrap())
            .unwrap();
        cert.set_subject_name(&name).unwrap();
        cert.set_issuer_name(&name).unwrap();
        cert.set_pubkey(&key).unwrap();
        cert.set_not_before(&Asn1Time::days_from_now(0).unwrap())
            .unwrap();
        cert.set_not_after(&Asn1Time::days_from_now(30).unwrap())
            .unwrap();
        cert.sign(&key, MessageDigest::sha256()).unwrap();
        let cert = cert.build();

        let mut b = SslAcceptor::mozilla_intermediate(SslMethod::tls_server()).unwrap();
        b.set_private_key(&key).unwrap();
        b.set_certificate(&cert).unwrap();
        b.set_security_level(0);
        match mode {
            Mode::RsaKex => {
                b.set_min_proto_version(Some(SslVersion::TLS1_2)).unwrap();
                b.set_max_proto_version(Some(SslVersion::TLS1_2)).unwrap();
                b.set_cipher_list("AES128-GCM-SHA256:@SECLEVEL=0").unwrap();
            }
            Mode::Tls10 => {
                b.set_min_proto_version(Some(SslVersion::TLS1)).unwrap();
                b.set_max_proto_version(Some(SslVersion::TLS1)).unwrap();
                b.set_cipher_list("AES128-SHA:@SECLEVEL=0").unwrap();
            }
        }
        b.build()
    }

    /// Bind on 127.0.0.1 and serve every connection; returns the port.
    pub(crate) async fn spawn(mode: Mode) -> u16 {
        let acceptor = acceptor(mode);
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        tokio::spawn(async move {
            loop {
                let Ok((sock, _)) = listener.accept().await else {
                    return;
                };
                let ssl = openssl::ssl::Ssl::new(acceptor.context()).unwrap();
                tokio::spawn(async move {
                    let mut s = SslStream::new(ssl, sock).unwrap();
                    if Pin::new(&mut s).accept().await.is_err() {
                        return; // rustls attempt: handshake refused
                    }
                    let mut buf = vec![0u8; 4096];
                    let mut got = Vec::new();
                    loop {
                        let n = match s.read(&mut buf).await {
                            Ok(0) | Err(_) => return,
                            Ok(n) => n,
                        };
                        got.extend_from_slice(&buf[..n]);
                        if got.starts_with(b"PING") {
                            let _ = s.write_all(b"PONG-LEGACY\n").await;
                            got.clear();
                            continue;
                        }
                        if got.windows(4).any(|w| w == b"\r\n\r\n") {
                            let text = String::from_utf8_lossy(&got).to_string();
                            let line = text.lines().next().unwrap_or("").to_string();
                            // `/away?to=<url>` redirects (302) to that absolute URL.
                            if let Some(rest) = line
                                .strip_prefix("POST /away?to=")
                                .or_else(|| line.strip_prefix("GET /away?to="))
                            {
                                let to = rest.split(' ').next().unwrap_or("");
                                let reply = format!(
                                    "HTTP/1.0 302 Found\r\nLocation: {to}\r\nContent-Length: 0\r\n\r\n"
                                );
                                let _ = s.write_all(reply.as_bytes()).await;
                                let _ = s.shutdown().await;
                                return;
                            }
                            let body = if line.starts_with("GET /redirect ") {
                                let _ = s
                                    .write_all(
                                        b"HTTP/1.0 302 Found\r\nLocation: /final\r\nContent-Length: 0\r\n\r\n",
                                    )
                                    .await;
                                let _ = s.shutdown().await;
                                return;
                            } else {
                                format!("legacy-ok {line}\nhost={}", host_header(&text))
                            };
                            let reply = format!(
                                "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nX-Legacy: yes\r\nContent-Length: {}\r\n\r\n{body}",
                                body.len()
                            );
                            let _ = s.write_all(reply.as_bytes()).await;
                            let _ = s.shutdown().await;
                            return;
                        }
                    }
                });
            }
        });
        port
    }

    fn host_header(req: &str) -> String {
        req.lines()
            .find_map(|l| {
                let (k, v) = l.split_once(':')?;
                k.eq_ignore_ascii_case("host").then(|| v.trim().to_string())
            })
            .unwrap_or_default()
    }
}

#[cfg(test)]
mod tests {
    use super::test_server::{spawn, Mode};
    use super::*;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    async fn dial(port: u16) -> Result<ClientTls> {
        let addr = format!("127.0.0.1:{port}");
        let tcp = TcpStream::connect(&addr).await.unwrap();
        let cfg = Arc::new(crate::checks::tcp::insecure_client_config().unwrap());
        connect(
            tcp,
            "127.0.0.1",
            cfg,
            Some(Duration::from_secs(5)),
            || async move {
                TcpStream::connect(&addr)
                    .await
                    .map_err(|e| NoctisError::Tcp(e.to_string()))
            },
        )
        .await
    }

    #[test]
    fn protocol_names_follow_the_rustls_spelling() {
        assert_eq!(protocol_name("TLSv1"), "TLSv1_0");
        assert_eq!(protocol_name("TLSv1.1"), "TLSv1_1");
        assert_eq!(protocol_name("TLSv1.2"), "TLSv1_2");
        assert_eq!(protocol_name("TLSv1.3"), "TLSv1_3");
        assert_eq!(protocol_name("SSLv3"), "SSLv3");
    }

    async fn ping(mode: Mode) -> SessionInfo {
        let port = spawn(mode).await;
        let mut s = dial(port).await.expect("legacy fallback connects");
        assert!(s.is_legacy(), "rustls cannot negotiate with this server");
        s.write_all(b"PING\n").await.unwrap();
        let mut buf = [0u8; 32];
        let n = s.read(&mut buf).await.unwrap();
        assert_eq!(&buf[..n], b"PONG-LEGACY\n");
        s.session_info()
    }

    #[tokio::test]
    async fn rsa_key_exchange_only_server_is_reached() {
        let si = ping(Mode::RsaKex).await;
        assert_eq!(si.protocol_version.as_deref(), Some("TLSv1_2"));
        assert_eq!(
            si.cipher_suite.as_deref(),
            Some("TLS_RSA_WITH_AES_128_GCM_SHA256")
        );
        assert!(!si.chain.is_empty(), "peer certificate is captured");
    }

    #[tokio::test]
    async fn tls_1_0_only_server_is_reached() {
        let si = ping(Mode::Tls10).await;
        assert_eq!(si.protocol_version.as_deref(), Some("TLSv1_0"));
        assert_eq!(
            si.cipher_suite.as_deref(),
            Some("TLS_RSA_WITH_AES_128_CBC_SHA")
        );
    }

    /// A modern server still goes through rustls.
    #[tokio::test]
    async fn modern_server_stays_on_rustls() {
        let (port, _) = crate::checks::raw_socket::starttls_test_server::spawn_direct_tls().await;
        let s = dial(port).await.unwrap();
        assert!(!s.is_legacy());
    }

    #[tokio::test]
    async fn non_tls_peer_reports_both_failures() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        tokio::spawn(async move {
            while let Ok((mut s, _)) = listener.accept().await {
                let _ = s.write_all(b"220 plain text\r\n").await;
            }
        });
        let err = dial(port).await.err().expect("no TLS peer");
        let msg = err.to_string();
        assert!(msg.contains("legacy TLS retry"), "{msg}");
    }
}