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
//! Generic TCP dialogue: connect, read the greeting, then send a feed-supplied
//! exchange and capture the reply. Two modes:
//!
//! - text: a sequence of `commands`, each terminated by `line_ending` (FTP,
//!   SMTP, Telnet, POP3, IMAP and similar line protocols).
//! - binary: a single raw `send_hex` frame sent verbatim, with the reply
//!   captured as both lossy text and hex (length-prefixed binary protocols
//!   such as MongoDB's wire protocol).
//!
//! No protocol specifics live in the engine — the feed drives the exchange.

use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::time::timeout;

use super::tcp::insecure_client_config;
use crate::error::{NoctisError, Result};

/// Idle gap that marks the end of one reply (line protocols keep the socket open).
/// The first byte of a reply may take up to the step's `timeout_secs`.
const READ_IDLE_MS: u64 = 500;
/// Hard cap on bytes accumulated for a single reply.
const MAX_REPLY_BYTES: usize = 64 * 1024;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DialogueResult {
    pub connected: bool,
    pub banner: Option<String>,
    pub responses: Vec<String>,
    pub transcript: String,
    /// All received bytes (banner + replies) as lowercase hex, when any arrived.
    /// Lets feeds match binary replies that are not valid UTF-8.
    pub response_hex: Option<String>,
    pub duration_ms: u64,
}

/// Lossy-decode received bytes to a trimmed string (how text protocols are matched).
fn to_text(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes).trim_end().to_string()
}

/// Read one reply: wait up to `first_wait` for the first byte, then read until
/// no more bytes arrive for `READ_IDLE_MS`, EOF, or the byte cap.
async fn read_reply<S: AsyncReadExt + Unpin>(
    stream: &mut S,
    first_wait: Duration,
) -> Option<Vec<u8>> {
    let mut acc = Vec::new();
    let mut chunk = [0u8; 4096];
    loop {
        let wait = if acc.is_empty() {
            first_wait
        } else {
            Duration::from_millis(READ_IDLE_MS)
        };
        match timeout(wait, stream.read(&mut chunk)).await {
            Ok(Ok(0)) => break, // EOF
            Ok(Ok(n)) => {
                acc.extend_from_slice(&chunk[..n]);
                if acc.len() >= MAX_REPLY_BYTES {
                    break;
                }
            }
            Ok(Err(_)) => break, // read error
            Err(_) => break,     // no first byte in time, or idle gap → reply complete
        }
    }
    if acc.is_empty() {
        None
    } else {
        Some(acc)
    }
}

/// Raw bytes received from one exchange: the optional banner plus one entry per reply.
struct Exchange {
    banner: Option<Vec<u8>>,
    replies: Vec<Vec<u8>>,
}

async fn converse<S: AsyncReadExt + AsyncWriteExt + Unpin>(
    stream: &mut S,
    read_banner: bool,
    commands: &[String],
    line_ending: &str,
    send_hex: Option<&[u8]>,
    first_wait: Duration,
) -> Exchange {
    let banner = if read_banner {
        read_reply(stream, first_wait).await
    } else {
        None
    };
    let mut replies = Vec::new();
    if let Some(frame) = send_hex {
        // Binary mode: one raw frame, one reply.
        if stream.write_all(frame).await.is_ok() {
            replies.push(read_reply(stream, first_wait).await.unwrap_or_default());
        }
    } else {
        for cmd in commands {
            let line = format!("{cmd}{line_ending}");
            if stream.write_all(line.as_bytes()).await.is_err() {
                break;
            }
            replies.push(read_reply(stream, first_wait).await.unwrap_or_default());
        }
    }
    Exchange { banner, replies }
}

#[allow(clippy::too_many_arguments)]
pub async fn run(
    host: &str,
    port: u16,
    use_tls: bool,
    read_banner: bool,
    commands: Vec<String>,
    line_ending: String,
    send_hex: Option<Vec<u8>>,
    timeout_secs: u64,
) -> Result<DialogueResult> {
    let addr = format!("{host}:{port}");
    let start = std::time::Instant::now();

    let tcp = match timeout(Duration::from_secs(timeout_secs), TcpStream::connect(&addr)).await {
        Ok(Ok(s)) => s,
        Ok(Err(e)) => return Err(NoctisError::Tcp(format!("connect {addr}: {e}"))),
        Err(_) => {
            return Ok(DialogueResult {
                connected: false,
                banner: None,
                responses: Vec::new(),
                transcript: String::new(),
                response_hex: None,
                duration_ms: start.elapsed().as_millis() as u64,
            })
        }
    };

    let send_hex = send_hex.as_deref();
    let first_wait = super::raw_socket::first_byte_wait(timeout_secs);
    let ex = if use_tls {
        // rustls first, then the legacy OpenSSL stack on a new connection (#2446).
        let limit = Duration::from_secs(timeout_secs);
        let reconnect = || async {
            timeout(limit, TcpStream::connect(&addr))
                .await
                .map_err(|_| NoctisError::Tcp(format!("connect timeout: {addr}")))?
                .map_err(|e| NoctisError::Tcp(format!("connect {addr}: {e}")))
        };
        let config = Arc::new(insecure_client_config()?);
        let mut stream = super::legacy_tls::connect(tcp, host, config, Some(limit), reconnect)
            .await
            .map_err(|e| NoctisError::Tcp(format!("TLS handshake {addr}: {e}")))?;
        converse(
            &mut stream,
            read_banner,
            &commands,
            &line_ending,
            send_hex,
            first_wait,
        )
        .await
    } else {
        let mut stream = tcp;
        converse(
            &mut stream,
            read_banner,
            &commands,
            &line_ending,
            send_hex,
            first_wait,
        )
        .await
    };

    // Text views (lossy) for line protocols and ASCII markers inside binary replies.
    let banner = ex.banner.as_deref().map(to_text);
    let responses: Vec<String> = ex.replies.iter().map(|b| to_text(b)).collect();
    let mut transcript_parts: Vec<&str> = Vec::new();
    if let Some(b) = &banner {
        transcript_parts.push(b);
    }
    for r in &responses {
        transcript_parts.push(r);
    }
    let transcript = transcript_parts.join("\n");

    // Hex view (all raw bytes, banner then replies) for binary protocols.
    let mut raw: Vec<u8> = Vec::new();
    if let Some(b) = &ex.banner {
        raw.extend_from_slice(b);
    }
    for r in &ex.replies {
        raw.extend_from_slice(r);
    }
    let response_hex = if raw.is_empty() {
        None
    } else {
        Some(raw.iter().map(|b| format!("{b:02x}")).collect())
    };

    Ok(DialogueResult {
        connected: true,
        banner,
        responses,
        transcript,
        response_hex,
        duration_ms: start.elapsed().as_millis() as u64,
    })
}

#[cfg(test)]
mod tests {
    /// `tcp_dialogue` over TLS reaches a TLS 1.0-only server (#2446).
    #[tokio::test]
    async fn tls_dialogue_falls_back_to_legacy_stack() {
        use crate::checks::legacy_tls::test_server::{spawn, Mode};
        let port = spawn(Mode::Tls10).await;
        let r = run(
            "127.0.0.1",
            port,
            true,
            false,
            vec!["PING".to_string()],
            "\n".to_string(),
            None,
            5,
        )
        .await
        .unwrap();
        assert!(r.connected);
        assert_eq!(r.responses, vec!["PONG-LEGACY".to_string()]);
    }

    use super::*;
    use tokio::io::AsyncWriteExt;
    use tokio::net::TcpListener;

    /// A scripted server: sends a greeting, then echoes "<n>: <cmd>" per line received.
    async fn scripted_server() -> std::net::SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            if let Ok((mut sock, _)) = listener.accept().await {
                let _ = sock.write_all(b"220 ready\r\n").await;
                let mut buf = [0u8; 1024];
                let mut n = 0u32;
                loop {
                    match sock.read(&mut buf).await {
                        Ok(0) | Err(_) => break,
                        Ok(len) => {
                            n += 1;
                            let line = String::from_utf8_lossy(&buf[..len]);
                            let reply = format!("{n}: {}\r\n", line.trim());
                            if sock.write_all(reply.as_bytes()).await.is_err() {
                                break;
                            }
                        }
                    }
                }
            }
        });
        addr
    }

    #[tokio::test]
    async fn banner_and_command_replies() {
        let addr = scripted_server().await;
        let r = run(
            &addr.ip().to_string(),
            addr.port(),
            false,
            true,
            vec!["EHLO x".into(), "QUIT".into()],
            "\r\n".into(),
            None,
            5,
        )
        .await
        .unwrap();

        assert!(r.connected);
        assert_eq!(r.banner.as_deref(), Some("220 ready"));
        assert_eq!(r.responses.len(), 2);
        assert_eq!(r.responses[0], "1: EHLO x");
        assert_eq!(r.responses[1], "2: QUIT");
        assert!(r.transcript.contains("220 ready"));
        assert!(r.transcript.contains("1: EHLO x"));
    }

    #[tokio::test]
    async fn skip_banner() {
        let addr = scripted_server().await;
        // Not reading the banner: the greeting stays buffered and is consumed as the
        // first command's "reply" — so responses[0] contains the greeting.
        let r = run(
            &addr.ip().to_string(),
            addr.port(),
            false,
            false,
            vec!["NOOP".into()],
            "\r\n".into(),
            None,
            5,
        )
        .await
        .unwrap();
        assert!(r.banner.is_none());
        assert_eq!(r.responses.len(), 1);
        assert!(r.responses[0].contains("220 ready"));
    }

    /// A server that replies to one binary frame with binary bytes (0x00 .. marker).
    async fn binary_server() -> std::net::SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            if let Ok((mut sock, _)) = listener.accept().await {
                let mut buf = [0u8; 1024];
                if let Ok(n) = sock.read(&mut buf).await {
                    if n > 0 {
                        // reply: a NUL, a non-UTF8 byte, then an ASCII marker
                        let _ = sock.write_all(&[0x00, 0xff]).await;
                        let _ = sock.write_all(b"databases").await;
                    }
                }
            }
        });
        addr
    }

    #[tokio::test]
    async fn binary_frame_sends_and_captures_hex() {
        let addr = binary_server().await;
        let r = run(
            &addr.ip().to_string(),
            addr.port(),
            false,
            false,
            Vec::new(),
            "\r\n".into(),
            Some(vec![0xde, 0xad, 0xbe, 0xef]),
            5,
        )
        .await
        .unwrap();

        assert!(r.connected);
        let hex = r.response_hex.expect("response_hex present");
        // 0x00 0xff then "databases" (646174616261736573)
        assert!(hex.starts_with("00ff"));
        assert!(hex.contains("646174616261736573"));
        // ASCII marker survives in the lossy transcript too
        assert!(r.transcript.contains("databases"));
    }

    /// Greets at once, then answers each line only after `delay_ms` (#1417).
    async fn slow_reply_server(delay_ms: u64) -> std::net::SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            while let Ok((mut sock, _)) = listener.accept().await {
                let _ = sock.write_all(b"220 ready\r\n").await;
                let mut buf = [0u8; 1024];
                while let Ok(n) = sock.read(&mut buf).await {
                    if n == 0 {
                        break;
                    }
                    tokio::time::sleep(Duration::from_millis(delay_ms)).await;
                    if sock.write_all(b"250 slow ok\r\n").await.is_err() {
                        break;
                    }
                }
            }
        });
        addr
    }

    #[tokio::test]
    async fn slow_first_reply_byte_is_awaited() {
        let addr = slow_reply_server(1200).await;
        for send_hex in [None, Some(vec![0x01, 0x02])] {
            let r = run(
                &addr.ip().to_string(),
                addr.port(),
                false,
                true,
                vec!["NOOP".into()],
                "\r\n".into(),
                send_hex,
                3,
            )
            .await
            .unwrap();
            assert!(r.transcript.contains("250 slow ok"), "{r:?}");
        }
    }
}