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
use std::collections::HashMap;
use std::time::Duration;

use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper_util::rt::TokioIo;
use indexmap::IndexMap;
use reqwest::header::HeaderValue;
use reqwest::{header::HeaderMap, redirect::Policy, Client, Method};
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpStream;
use tokio::time::timeout;

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpResult {
    pub status: u16,
    pub headers: HashMap<String, String>,
    pub body: String,
    pub duration_ms: u64,
    pub url: String,
}

pub struct HttpCheck {
    client: Client,
    follow_redirects: bool,
    tls_insecure: bool,
    timeout: Duration,
}

/// Most redirects followed, as reqwest's `Policy::limited(10)`.
const MAX_REDIRECTS: usize = 10;

impl HttpCheck {
    pub fn new(follow_redirects: bool, tls_insecure: bool, timeout_secs: u64) -> Result<Self> {
        let redirect = if follow_redirects {
            Policy::limited(10)
        } else {
            Policy::none()
        };

        let client = Client::builder()
            .redirect(redirect)
            .timeout(Duration::from_secs(timeout_secs))
            .danger_accept_invalid_certs(tls_insecure)
            .build()
            .map_err(NoctisError::Http)?;

        Ok(Self {
            client,
            follow_redirects,
            tls_insecure,
            timeout: Duration::from_secs(timeout_secs),
        })
    }

    pub async fn run(
        &self,
        method: &str,
        url: &str,
        headers: &IndexMap<String, String>,
        body: Option<&str>,
    ) -> Result<HttpResult> {
        let method = Method::from_bytes(method.as_bytes()).map_err(|_| NoctisError::StepError {
            test: String::new(),
            step: String::new(),
            message: format!("invalid HTTP method: {method}"),
        })?;

        let mut req = self.client.request(method.clone(), url);

        let mut header_map = HeaderMap::new();
        for (k, v) in headers {
            if let (Ok(name), Ok(value)) = (
                reqwest::header::HeaderName::from_bytes(k.as_bytes()),
                reqwest::header::HeaderValue::from_str(v),
            ) {
                header_map.insert(name, value);
            }
        }
        req = req.headers(header_map);

        if let Some(b) = body {
            req = req.body(b.to_string());
        }

        let start = std::time::Instant::now();
        let resp = match req.send().await {
            Ok(r) => r,
            // rustls could not open the connection: an HTTPS server that only
            // speaks TLS 1.0/1.1 or static-RSA key exchange (#2446). Retry the
            // request over the legacy OpenSSL stack. Certificates are never
            // checked there, so only for steps that skip the check anyway.
            Err(e)
                if e.is_connect()
                    && !e.is_timeout()
                    && self.tls_insecure
                    && url.starts_with("https://") =>
            {
                match self.run_legacy(method, url, headers, body).await {
                    Ok(r) => return Ok(r),
                    Err(le) => {
                        tracing::debug!("legacy TLS retry failed: {le}");
                        return Err(NoctisError::Http(e));
                    }
                }
            }
            Err(e) => return Err(NoctisError::Http(e)),
        };

        let status = resp.status().as_u16();
        let url_final = resp.url().to_string();

        let mut resp_headers = HashMap::new();
        for (k, v) in resp.headers() {
            resp_headers.insert(k.to_string(), v.to_str().unwrap_or("<binary>").to_string());
        }

        let body = resp.text().await.map_err(NoctisError::Http)?;
        // Timed after the body read, not when the headers arrive: a target that
        // streams its reply (unbuffered PHP/CGI, chunked) flushes headers before
        // the slow work runs, so time-based proofs need the full response (#1924).
        let duration_ms = start.elapsed().as_millis() as u64;

        Ok(HttpResult {
            status,
            headers: resp_headers,
            body,
            duration_ms,
            url: url_final,
        })
    }
}

impl HttpCheck {
    /// The request over HTTP/1.1 on connections the legacy OpenSSL stack opens
    /// (plain TCP for `http://` redirect targets), following redirects like
    /// reqwest does, the whole exchange bounded by the step timeout.
    async fn run_legacy(
        &self,
        method: Method,
        url: &str,
        headers: &IndexMap<String, String>,
        body: Option<&str>,
    ) -> std::result::Result<HttpResult, String> {
        let start = std::time::Instant::now();
        let exchange = async {
            let mut url = reqwest::Url::parse(url).map_err(|e| e.to_string())?;
            let mut method = method;
            let mut body = body.map(|b| b.to_string());
            let mut headers = headers.clone();
            let mut hops = 0;
            loop {
                let resp = legacy_send(&method, &url, &headers, body.as_deref()).await?;
                let status = resp.status().as_u16();
                let next = match resp.headers().get(hyper::header::LOCATION) {
                    Some(loc)
                        if self.follow_redirects
                            && matches!(status, 301 | 302 | 303 | 307 | 308) =>
                    {
                        loc.to_str().ok().and_then(|l| url.join(l).ok())
                    }
                    _ => None,
                };
                let Some(next) = next else {
                    return Ok::<_, String>((resp, url));
                };
                hops += 1;
                if hops > MAX_REDIRECTS {
                    return Err("too many redirects".to_string());
                }
                // reqwest's rules: 303 becomes GET (HEAD stays HEAD), 301/302
                // turn POST into GET; the body goes with the method change.
                if (status == 303 && method != Method::HEAD)
                    || (matches!(status, 301 | 302) && method == Method::POST)
                {
                    method = Method::GET;
                    body = None;
                    headers.retain(|k, _| {
                        ![
                            "content-type",
                            "content-length",
                            "content-encoding",
                            "transfer-encoding",
                        ]
                        .iter()
                        .any(|h| k.eq_ignore_ascii_case(h))
                    });
                }
                // Credentials stay with the origin that was asked for.
                if next.scheme() != url.scheme()
                    || next.host_str() != url.host_str()
                    || next.port_or_known_default() != url.port_or_known_default()
                {
                    headers.retain(|k, _| {
                        ![
                            "authorization",
                            "cookie",
                            "cookie2",
                            "proxy-authorization",
                            "www-authenticate",
                        ]
                        .iter()
                        .any(|h| k.eq_ignore_ascii_case(h))
                    });
                }
                url = next;
            }
        };
        let (resp, final_url) = timeout(self.timeout, exchange)
            .await
            .map_err(|_| "timed out".to_string())??;

        let status = resp.status().as_u16();
        let mut resp_headers = HashMap::new();
        for (k, v) in resp.headers() {
            resp_headers.insert(k.to_string(), v.to_str().unwrap_or("<binary>").to_string());
        }
        let remaining = self.timeout.saturating_sub(start.elapsed());
        let bytes = timeout(remaining, resp.into_body().collect())
            .await
            .map_err(|_| "timed out reading the body".to_string())?
            .map_err(|e| e.to_string())?
            .to_bytes();
        let duration_ms = start.elapsed().as_millis() as u64;
        Ok(HttpResult {
            status,
            headers: resp_headers,
            body: String::from_utf8_lossy(&bytes).into_owned(),
            duration_ms,
            url: final_url.to_string(),
        })
    }
}

trait LegacyIo: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> LegacyIo for T {}

/// One HTTP/1.1 exchange: connect (legacy TLS for https), send, read headers.
async fn legacy_send(
    method: &Method,
    url: &reqwest::Url,
    headers: &IndexMap<String, String>,
    body: Option<&str>,
) -> std::result::Result<hyper::Response<hyper::body::Incoming>, String> {
    let host = url.host_str().ok_or("URL without host")?;
    let port = url.port_or_known_default().ok_or("URL without port")?;
    // IPv6 literals keep their brackets in host_str(); connect needs them off.
    let bare = host.trim_start_matches('[').trim_end_matches(']');
    let tcp = TcpStream::connect((bare, port))
        .await
        .map_err(|e| format!("connect: {e}"))?;
    let io: Box<dyn LegacyIo> = match url.scheme() {
        "https" => Box::new(super::legacy_tls::legacy_handshake(tcp, bare).await?),
        "http" => Box::new(tcp),
        other => return Err(format!("unsupported scheme {other}")),
    };
    let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(io))
        .await
        .map_err(|e| e.to_string())?;
    tokio::spawn(async move {
        let _ = conn.await;
    });

    let target = match url.query() {
        Some(q) => format!("{}?{q}", url.path()),
        None => url.path().to_string(),
    };
    let mut req = hyper::Request::builder()
        .method(method.as_str())
        .uri(target);
    let h = req.headers_mut().ok_or("bad request")?;
    // reqwest's defaults; a step's own headers replace them.
    let host_value = match url.port() {
        Some(p) => format!("{host}:{p}"),
        None => host.to_string(),
    };
    if let Ok(v) = HeaderValue::from_str(&host_value) {
        h.insert(hyper::header::HOST, v);
    }
    h.insert(hyper::header::ACCEPT, HeaderValue::from_static("*/*"));
    for (k, v) in headers {
        if let (Ok(name), Ok(value)) = (
            reqwest::header::HeaderName::from_bytes(k.as_bytes()),
            HeaderValue::from_str(v),
        ) {
            h.insert(name, value);
        }
    }
    let req = req
        .body(Full::new(Bytes::from(body.unwrap_or("").to_string())))
        .map_err(|e| e.to_string())?;
    sender.send_request(req).await.map_err(|e| e.to_string())
}

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

    /// A reply whose headers and first chunk go out at once and whose last
    /// chunk follows a delay must be timed as a whole (#1924).
    #[tokio::test]
    async fn duration_covers_streamed_body() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 1024];
            let _ = sock.read(&mut buf).await;
            sock.write_all(
                b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n5\r\nhello\r\n",
            )
            .await
            .unwrap();
            sock.flush().await.unwrap();
            tokio::time::sleep(Duration::from_millis(800)).await;
            sock.write_all(b"6\r\n world\r\n0\r\n\r\n").await.unwrap();
            sock.flush().await.unwrap();
        });

        let check = HttpCheck::new(false, true, 10).unwrap();
        let res = check
            .run("GET", &format!("http://{addr}/"), &IndexMap::new(), None)
            .await
            .unwrap();
        assert_eq!(res.status, 200);
        assert_eq!(res.body, "hello world");
        assert!(
            res.duration_ms >= 700,
            "duration_ms {} stops before the delayed body chunk",
            res.duration_ms
        );
    }

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

    /// An HTTPS server rustls cannot handshake with (RSA key exchange only,
    /// or TLS 1.0 only) is still queried, over the legacy stack (#2446).
    #[tokio::test]
    async fn legacy_tls_server_is_queried() {
        for mode in [Mode::RsaKex, Mode::Tls10] {
            let port = spawn(mode).await;
            let check = HttpCheck::new(true, true, 10).unwrap();
            let mut headers = IndexMap::new();
            headers.insert("X-Probe".to_string(), "1".to_string());
            let res = check
                .run(
                    "GET",
                    &format!("https://127.0.0.1:{port}/a?b=c"),
                    &headers,
                    None,
                )
                .await
                .unwrap();
            assert_eq!(res.status, 200);
            assert_eq!(
                res.body,
                format!("legacy-ok GET /a?b=c HTTP/1.1\nhost=127.0.0.1:{port}")
            );
            assert_eq!(res.headers.get("x-legacy").map(String::as_str), Some("yes"));
        }
    }

    #[tokio::test]
    async fn legacy_tls_redirects_are_followed() {
        let port = spawn(Mode::RsaKex).await;
        let check = HttpCheck::new(true, true, 10).unwrap();
        let res = check
            .run(
                "GET",
                &format!("https://127.0.0.1:{port}/redirect"),
                &IndexMap::new(),
                None,
            )
            .await
            .unwrap();
        assert_eq!(res.status, 200);
        assert!(
            res.body.starts_with("legacy-ok GET /final "),
            "{}",
            res.body
        );
        assert_eq!(res.url, format!("https://127.0.0.1:{port}/final"));

        let check = HttpCheck::new(false, true, 10).unwrap();
        let res = check
            .run(
                "GET",
                &format!("https://127.0.0.1:{port}/redirect"),
                &IndexMap::new(),
                None,
            )
            .await
            .unwrap();
        assert_eq!(res.status, 302);
    }

    /// Without `tls_insecure` the step asked for certificate checks, which
    /// the legacy stack does not do: no retry there.
    #[tokio::test]
    async fn legacy_retry_needs_tls_insecure() {
        let port = spawn(Mode::RsaKex).await;
        let check = HttpCheck::new(true, false, 10).unwrap();
        let res = check
            .run(
                "GET",
                &format!("https://127.0.0.1:{port}/"),
                &IndexMap::new(),
                None,
            )
            .await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn legacy_post_carries_the_body() {
        let port = spawn(Mode::RsaKex).await;
        let check = HttpCheck::new(true, true, 10).unwrap();
        let res = check
            .run(
                "POST",
                &format!("https://127.0.0.1:{port}/p"),
                &IndexMap::new(),
                Some("x=1"),
            )
            .await
            .unwrap();
        assert!(res.body.starts_with("legacy-ok POST /p "), "{}", res.body);
    }

    /// Plain HTTP server that answers one request with its raw text as body.
    async fn echo_server() -> u16 {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        tokio::spawn(async move {
            while let Ok((mut sock, _)) = listener.accept().await {
                let mut buf = vec![0u8; 4096];
                let n = sock.read(&mut buf).await.unwrap_or(0);
                let req = String::from_utf8_lossy(&buf[..n]).to_string();
                let reply = format!(
                    "HTTP/1.0 200 OK\r\nContent-Length: {}\r\n\r\n{req}",
                    req.len()
                );
                let _ = sock.write_all(reply.as_bytes()).await;
            }
        });
        port
    }

    /// A legacy-path redirect to another scheme/port drops credentials, and a
    /// 302 turns POST into a body-less GET, as reqwest does.
    #[tokio::test]
    async fn legacy_redirect_to_other_origin_drops_credentials() {
        let port = spawn(Mode::RsaKex).await;
        let plain = echo_server().await;
        let check = HttpCheck::new(true, true, 10).unwrap();
        let mut headers = IndexMap::new();
        headers.insert("Authorization".to_string(), "Basic c2VjcmV0".to_string());
        headers.insert("Cookie".to_string(), "sid=secret".to_string());
        headers.insert("Content-Type".to_string(), "text/plain".to_string());
        headers.insert("X-Keep".to_string(), "1".to_string());
        let res = check
            .run(
                "POST",
                &format!("https://127.0.0.1:{port}/away?to=http://127.0.0.1:{plain}/landed"),
                &headers,
                Some("x=1"),
            )
            .await
            .unwrap();
        let echoed = res.body.to_ascii_lowercase();
        assert!(echoed.starts_with("get /landed http/1.1"), "{echoed}");
        assert!(echoed.contains("x-keep: 1"), "{echoed}");
        for gone in ["authorization", "cookie", "content-type", "x=1"] {
            assert!(!echoed.contains(gone), "{gone} kept: {echoed}");
        }
        assert_eq!(res.url, format!("http://127.0.0.1:{plain}/landed"));
    }
}