ergon-tune 0.1.45

Start-up and housekeeping checks of a host's low-latency settings (CPU isolation, NIC interrupts, transparent hugepages, the Aeron directory, NUMA, scheduling policy, SMT siblings, a CPU quota and its throttling, how CLOCK_REALTIME is kept and the kernel's clock source, background noise on the hot CPUs (unbound workqueues, compaction, other processes' tasks, kernel instrumentation, KSM, steal), a hot thread's page faults, the IRQ CPUs' idle depth and TCP autocorking, and with `nic` the NIC's moderation, deferral, VF and ring): pure functions returning findings, with no threads or statics, and one audited unsafe call (a read-only adjtimex)
Documentation
//! T27: the ports an application listens on must not overlap the kernel's
//! ephemeral port range (`net.ipv4.ip_local_port_range`) unless the overlap
//! is reserved (`net.ipv4.ip_local_reserved_ports`).
//!
//! Both sysctls are read in this process's network namespace, so this is the
//! namespace the process runs in (a pod's own, or the node's under
//! `hostNetwork`).

use std::ops::RangeInclusive;

use crate::finding::{Finding, Severity};
use crate::host::{Host, ReadError};

const PORT_RANGE: &str = "/proc/sys/net/ipv4/ip_local_port_range";
const RESERVED: &str = "/proc/sys/net/ipv4/ip_local_reserved_ports";

const T27_EVIDENCE: &str = "Linux's outgoing-connection port selection (an ephemeral \
     port from ip_local_port_range, minus the ip_local_reserved_ports) and \
     Documentation/networking/ip-sysctl.rst (ip_local_port_range, ip_local_reserved_ports); \
     not measured here";

/// Reads `net.ipv4.ip_local_port_range`: the range of ports the kernel hands
/// to outgoing connections, both ends included.
///
/// # Errors
/// The file cannot be read, or is not two port numbers in order (a
/// [`ReadError::Malformed`]); never a guessed default.
pub fn ip_local_port_range(host: &Host) -> Result<RangeInclusive<u16>, ReadError> {
    let text = host.read_line(PORT_RANGE)?;
    let mut nums = text.split_whitespace();
    let (Some(lo), Some(hi), None) = (nums.next(), nums.next(), nums.next()) else {
        return Err(malformed(PORT_RANGE, "not a `lo hi` port pair"));
    };
    let lo = lo
        .parse::<u16>()
        .map_err(|_| malformed(PORT_RANGE, "not a number"))?;
    let hi = hi
        .parse::<u16>()
        .map_err(|_| malformed(PORT_RANGE, "not a number"))?;
    if lo > hi {
        return Err(malformed(PORT_RANGE, "ends before it starts"));
    }
    Ok(lo..=hi)
}

/// Reads `net.ipv4.ip_local_reserved_ports`: the ports the kernel will not
/// hand to an outgoing connection, as the sorted, merged ranges of the
/// comma-separated list (single ports and `lo-hi` ranges).
///
/// # Errors
/// The file cannot be read, or an entry is not a port or an increasing
/// `lo-hi` range (a [`ReadError::Malformed`]) — an empty entry included. A
/// lone empty list means no reserved ports and is ok. Never a guessed
/// default.
pub fn ip_local_reserved_ports(host: &Host) -> Result<Vec<RangeInclusive<u16>>, ReadError> {
    let text = host.read_line(RESERVED)?;
    if text.is_empty() {
        return Ok(Vec::new());
    }
    let mut out = Vec::new();
    for entry in text.split(',') {
        let entry = entry.trim();
        if entry.is_empty() {
            return Err(malformed(RESERVED, "an empty entry"));
        }
        let range = if let Some((lo, hi)) = entry.split_once('-') {
            let lo = lo
                .parse::<u16>()
                .map_err(|_| malformed(RESERVED, "not a number"))?;
            let hi = hi
                .parse::<u16>()
                .map_err(|_| malformed(RESERVED, "not a number"))?;
            if lo > hi {
                return Err(malformed(RESERVED, "ends before it starts"));
            }
            lo..=hi
        } else {
            let p = entry
                .parse::<u16>()
                .map_err(|_| malformed(RESERVED, "not a number"))?;
            p..=p
        };
        out.push(range);
    }
    Ok(merge(out))
}

fn malformed(path: &str, detail: &'static str) -> ReadError {
    ReadError::Malformed {
        path: path.to_owned(),
        detail,
    }
}

/// The part of `a` that is also in `b`, or none when they do not overlap.
fn overlap(a: &RangeInclusive<u16>, b: &RangeInclusive<u16>) -> Option<RangeInclusive<u16>> {
    let lo = (*a.start()).max(*b.start());
    let hi = (*a.end()).min(*b.end());
    (lo <= hi).then_some(lo..=hi)
}

/// `ranges` with every port of `r` removed: each range that `r` only partly
/// covers is split around it.
fn subtract(ranges: &[RangeInclusive<u16>], r: &RangeInclusive<u16>) -> Vec<RangeInclusive<u16>> {
    let mut out = Vec::new();
    for g in ranges {
        let (glo, ghi) = (*g.start(), *g.end());
        let (rlo, rhi) = (*r.start(), *r.end());
        if rhi < glo || rlo > ghi {
            out.push(g.clone());
            continue;
        }
        if glo < rlo {
            out.push(glo..=(rlo - 1));
        }
        if ghi > rhi {
            out.push((rhi + 1)..=ghi);
        }
    }
    out
}

/// The ports of `listen` that are inside `ephemeral` and outside every
/// reserved range: the ports an outgoing connection could steal.
fn unreserved(
    ephemeral: &RangeInclusive<u16>,
    reserved: &[RangeInclusive<u16>],
    listen: &RangeInclusive<u16>,
) -> Vec<RangeInclusive<u16>> {
    let Some(o) = overlap(ephemeral, listen) else {
        return Vec::new();
    };
    let mut gaps = vec![o];
    for r in reserved {
        gaps = subtract(&gaps, r);
    }
    gaps
}

/// Sorts `ranges` and merges the ones that touch, so the output is a disjoint
/// list in port order.
fn merge(ranges: Vec<RangeInclusive<u16>>) -> Vec<RangeInclusive<u16>> {
    let mut ranges = ranges;
    if ranges.is_empty() {
        return ranges;
    }
    ranges.sort_by_key(|r| *r.start());
    let mut out: Vec<RangeInclusive<u16>> = Vec::new();
    for r in ranges {
        if let Some(last) = out.last_mut()
            && *r.start() <= last.end().saturating_add(1)
        {
            *last = (*last.start())..=(*last.end()).max(*r.end());
            continue;
        }
        out.push(r);
    }
    out
}

/// One range as a name: `60000` for a single port, `60000-60999` otherwise.
fn range_name(r: &RangeInclusive<u16>) -> String {
    let (lo, hi) = (*r.start(), *r.end());
    if lo == hi {
        lo.to_string()
    } else {
        format!("{lo}-{hi}")
    }
}

/// The names of `ranges`, comma-separated.
fn range_list(ranges: &[RangeInclusive<u16>]) -> String {
    ranges.iter().map(range_name).collect::<Vec<_>>().join(",")
}

/// The `ip_local_reserved_ports` value that reserves the unreserved gaps on
/// top of what is already reserved, as one comma-separated list.
fn reserved_line(reserved: &[RangeInclusive<u16>], gaps: &[RangeInclusive<u16>]) -> String {
    let mut all = reserved.to_vec();
    all.extend(gaps.iter().cloned());
    range_list(&merge(all))
}

/// T27: no port an application listens on is one the kernel can hand to an
/// outgoing connection.
///
/// `listen` is the port range(s) the application is configured to listen on,
/// both ends included. A listen range that overlaps
/// `net.ipv4.ip_local_port_range` but is not covered by
/// `net.ipv4.ip_local_reserved_ports` warns, naming the unreserved overlap
/// and the exact `sysctl` fix. No overlap, or an overlap that is fully
/// reserved, is ok. A listen range that ends before it starts is malformed
/// caller input and reports unknown, never ok. The sysctls are per network
/// namespace, so this is the namespace the process runs in.
#[must_use]
pub fn t27_ephemeral_overlap(host: &Host, listen: &[RangeInclusive<u16>]) -> Finding {
    let id = "T27";
    let sev = Severity::Warn;
    if listen.is_empty() {
        return Finding::ok(
            id,
            sev,
            T27_EVIDENCE,
            "no listen port range given: nothing to check".to_owned(),
        );
    }
    for l in listen {
        if l.start() > l.end() {
            return Finding::unknown(
                id,
                sev,
                T27_EVIDENCE,
                "cannot check the listen port ranges: one ends before it starts".to_owned(),
                range_name(l),
            );
        }
    }
    let ephemeral = match ip_local_port_range(host) {
        Ok(e) => e,
        Err(e) => {
            return Finding::unknown(
                id,
                sev,
                T27_EVIDENCE,
                "cannot tell the kernel's ephemeral port range".to_owned(),
                e,
            );
        }
    };
    let reserved = match ip_local_reserved_ports(host) {
        Ok(r) => r,
        Err(e) => {
            return Finding::unknown(
                id,
                sev,
                T27_EVIDENCE,
                "cannot tell the reserved ports".to_owned(),
                e,
            );
        }
    };
    let any_overlap = listen.iter().any(|l| overlap(&ephemeral, l).is_some());
    let overlapping: Vec<RangeInclusive<u16>> = listen
        .iter()
        .filter(|l| overlap(&ephemeral, l).is_some())
        .cloned()
        .collect();
    let mut gaps: Vec<RangeInclusive<u16>> = Vec::new();
    for l in listen {
        gaps.extend(unreserved(&ephemeral, &reserved, l));
    }
    let gaps = merge(gaps);
    if gaps.is_empty() {
        if !any_overlap {
            return Finding::ok(
                id,
                sev,
                T27_EVIDENCE,
                format!(
                    "listen ports {} do not overlap net.ipv4.ip_local_port_range {}: the kernel \
                     cannot hand a listen port to an outgoing connection",
                    range_list(listen),
                    range_name(&ephemeral)
                ),
            );
        }
        return Finding::ok(
            id,
            sev,
            T27_EVIDENCE,
            format!(
                "the overlap between listen ports {} and net.ipv4.ip_local_port_range {} is \
                 fully reserved (net.ipv4.ip_local_reserved_ports {}): the kernel will not hand \
                 it out",
                range_list(listen),
                range_name(&ephemeral),
                range_list(&reserved)
            ),
        );
    }
    let ephem = range_name(&ephemeral);
    Finding::found(
        id,
        sev,
        T27_EVIDENCE,
        format!(
            "listen ports {} overlap net.ipv4.ip_local_port_range {ephem}; the unreserved part \
             {} can be handed to an outgoing connection, so the listening app fails with \
             \"Address already in use\". Fix: move the listen range below the ephemeral range \
             (net.ipv4.ip_local_port_range {ephem}), or reserve it: `sysctl -w \
             net.ipv4.ip_local_reserved_ports=\"{}\"`",
            range_list(&overlapping),
            range_list(&gaps),
            reserved_line(&reserved, &gaps)
        ),
    )
}