feat(app): warn about active SSH clients missing from the whitelist
This commit is contained in:
parent
2b4e32ed52
commit
987ccec905
6 changed files with 163 additions and 0 deletions
|
|
@ -9,6 +9,8 @@
|
|||
|
||||
### Added
|
||||
|
||||
- Anti-lockout: при старте edge предупреждает (`WARN`) о каждом активном SSH-клиенте, которого
|
||||
нет в `whitelist` (разбор `/proc/net/tcp{,6}`, без root).
|
||||
- Startup-диагностика XDP: детект контейнера (lxc/openvz/docker), единая строка окружения
|
||||
для edge и `rampart-cli doctor`, вердикт и `hint:` в ошибках load/attach.
|
||||
- `docs/architecture.md` — текущее устройство системы (процессы, путь трафика,
|
||||
|
|
|
|||
|
|
@ -127,6 +127,20 @@ clang -O2 -g -target bpf -I"/usr/include/$(gcc -print-multiarch)" \
|
|||
# [xdp] enabled = false → systemctl restart rampart
|
||||
```
|
||||
|
||||
Edge при старте пишет строку `XDP environment: …`; ошибка attach содержит `hint:`
|
||||
(см. [troubleshooting](troubleshooting.md#xdp-не-загружается)). Её же показывает
|
||||
`rampart-cli doctor`.
|
||||
|
||||
### Если нода заблокировала администратора
|
||||
|
||||
При старте edge пишет `WARN active SSH client is not in whitelist` — добавьте адрес в
|
||||
`whitelist` до атаки. Если доступ уже потерян, зайдите через консоль провайдера (VNC/KVM):
|
||||
|
||||
```bash
|
||||
ip link set dev eth0 xdp off # снять XDP-программу с интерфейса
|
||||
systemctl stop rampart # или [xdp] enabled = false и рестарт
|
||||
```
|
||||
|
||||
## 5. Клиенты не могут подключиться
|
||||
|
||||
```bash
|
||||
|
|
|
|||
94
src/app/lockout.rs
Normal file
94
src/app/lockout.rs
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
//! Anti-lockout: warn when an administrator's live SSH session is not whitelisted.
|
||||
//!
|
||||
//! A blind ban by IP cuts off SSH together with the attack. At startup the edge reads the
|
||||
//! established TCP connections to the SSH port from procfs (no root, no `ss`) and warns
|
||||
//! about every remote client that is not in the whitelist.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
const TCP_ESTABLISHED: &str = "01";
|
||||
const DEFAULT_SSH_PORT: u16 = 22;
|
||||
|
||||
/// SSH port to inspect: the server port of the current session (`SSH_CONNECTION`) when the
|
||||
/// daemon is started from SSH, otherwise 22.
|
||||
#[must_use]
|
||||
pub fn ssh_port(ssh_connection: Option<&str>) -> u16 {
|
||||
ssh_connection
|
||||
.and_then(|value| value.split_whitespace().nth(3))
|
||||
.and_then(|port| port.parse().ok())
|
||||
.unwrap_or(DEFAULT_SSH_PORT)
|
||||
}
|
||||
|
||||
/// Remote addresses of established connections whose local port is `port`, parsed from
|
||||
/// the contents of `/proc/net/tcp` or `/proc/net/tcp6`.
|
||||
#[must_use]
|
||||
pub fn established_peers(proc_net_tcp: &str, port: u16) -> Vec<IpAddr> {
|
||||
proc_net_tcp
|
||||
.lines()
|
||||
.skip(1)
|
||||
.filter_map(|line| {
|
||||
let mut fields = line.split_whitespace();
|
||||
let local = fields.nth(1)?;
|
||||
let remote = fields.next()?;
|
||||
let state = fields.next()?;
|
||||
let (_, local_port) = local.rsplit_once(':')?;
|
||||
if state != TCP_ESTABLISHED || u16::from_str_radix(local_port, 16).ok()? != port {
|
||||
return None;
|
||||
}
|
||||
parse_proc_addr(remote.rsplit_once(':')?.0)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Decodes a procfs address: one little-endian word for IPv4, four for IPv6.
|
||||
fn parse_proc_addr(hex: &str) -> Option<IpAddr> {
|
||||
match hex.len() {
|
||||
8 => Some(IpAddr::V4(Ipv4Addr::from(
|
||||
u32::from_str_radix(hex, 16).ok()?.swap_bytes(),
|
||||
))),
|
||||
32 => {
|
||||
let mut octets = [0u8; 16];
|
||||
for (index, chunk) in octets.chunks_exact_mut(4).enumerate() {
|
||||
let word = u32::from_str_radix(hex.get(index * 8..index * 8 + 8)?, 16).ok()?;
|
||||
chunk.copy_from_slice(&word.swap_bytes().to_be_bytes());
|
||||
}
|
||||
let addr = Ipv6Addr::from(octets);
|
||||
Some(addr.to_ipv4_mapped().map_or(IpAddr::V6(addr), IpAddr::V4))
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Remote SSH clients that would be exposed to filtering: not loopback, not whitelisted.
|
||||
/// The result is sorted and deduplicated.
|
||||
#[must_use]
|
||||
pub fn unprotected_clients(peers: &[IpAddr], whitelist: &HashSet<IpAddr>) -> Vec<IpAddr> {
|
||||
let mut exposed: Vec<IpAddr> = peers
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|ip| !ip.is_loopback() && !whitelist.contains(ip))
|
||||
.collect();
|
||||
exposed.sort();
|
||||
exposed.dedup();
|
||||
exposed
|
||||
}
|
||||
|
||||
/// Logs a warning for every active SSH client missing from the whitelist.
|
||||
pub fn warn_unlisted_ssh_clients(whitelist: &HashSet<IpAddr>) {
|
||||
let port = ssh_port(std::env::var("SSH_CONNECTION").ok().as_deref());
|
||||
let mut peers = Vec::new();
|
||||
for path in ["/proc/net/tcp", "/proc/net/tcp6"] {
|
||||
if let Ok(table) = std::fs::read_to_string(path) {
|
||||
peers.extend(established_peers(&table, port));
|
||||
}
|
||||
}
|
||||
for ip in unprotected_clients(&peers, whitelist) {
|
||||
tracing::warn!(
|
||||
client = %ip,
|
||||
ssh_port = port,
|
||||
"active SSH client is not in `whitelist`: an XDP/blacklist ban of this address would lock you out; \
|
||||
add it to `whitelist` in config.toml"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
//! Edge daemon wiring: service construction and the main run loop.
|
||||
|
||||
pub mod lockout;
|
||||
pub mod runtime;
|
||||
pub mod services;
|
||||
mod shutdown;
|
||||
|
|
|
|||
|
|
@ -56,6 +56,7 @@ pub async fn run() -> anyhow::Result<RunExit> {
|
|||
);
|
||||
}
|
||||
let whitelist = build_whitelist(&config)?;
|
||||
super::lockout::warn_unlisted_ssh_clients(&whitelist);
|
||||
|
||||
let rate_limiter = Arc::new(RateLimiter::new(
|
||||
config.limits.rate_limit_pps,
|
||||
|
|
|
|||
51
tests/app_lockout.rs
Normal file
51
tests/app_lockout.rs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
use rampart::app::lockout::{established_peers, ssh_port, unprotected_clients};
|
||||
use std::collections::HashSet;
|
||||
use std::net::IpAddr;
|
||||
|
||||
const TCP4: &str = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
|
||||
0: 0100A8C0:0016 0A01A8C0:C350 01 00000000:00000000 02:000A1B2C 00000000 0 0 12345 2 0000000000000000 20 4 30 10 -1
|
||||
1: 0100A8C0:0016 0B01A8C0:C351 06 00000000:00000000 03:00000000 00000000 0 0 0 3 0000000000000000
|
||||
2: 0100A8C0:0050 0C01A8C0:C352 01 00000000:00000000 00:00000000 00000000 0 0 22 1 0000000000000000 20 4 30 10 -1
|
||||
3: 0100007F:0016 0100007F:C353 01 00000000:00000000 00:00000000 00000000 0 0 23 1 0000000000000000 20 4 30 10 -1
|
||||
";
|
||||
|
||||
const TCP6: &str = " sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
|
||||
0: 00000000000000000000000001000000:0016 B80D0120000000000000000001000000:D431 01 00000000:00000000 02:000A1B2C 00000000 0 0 5 2 0000000000000000 20 4 30 10 -1
|
||||
1: 0000000000000000FFFF00000100A8C0:0016 0000000000000000FFFF00000D01A8C0:D432 01 00000000:00000000 00:00000000 00000000 0 0 6 1 0000000000000000 20 4 30 10 -1
|
||||
";
|
||||
|
||||
fn ip(text: &str) -> IpAddr {
|
||||
text.parse().expect("valid test address")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_only_established_connections_to_the_ssh_port() {
|
||||
let peers = established_peers(TCP4, 22);
|
||||
assert_eq!(peers, vec![ip("192.168.1.10"), ip("127.0.0.1")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_ipv6_and_mapped_ipv4_peers() {
|
||||
let peers = established_peers(TCP6, 22);
|
||||
assert_eq!(peers, vec![ip("2001:db8::1"), ip("192.168.1.13")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warns_only_about_non_loopback_clients_missing_from_the_whitelist() {
|
||||
let peers = established_peers(TCP4, 22);
|
||||
assert_eq!(unprotected_clients(&peers, &HashSet::new()), vec![ip("192.168.1.10")]);
|
||||
let whitelist: HashSet<IpAddr> = [ip("192.168.1.10")].into();
|
||||
assert!(unprotected_clients(&peers, &whitelist).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ssh_port_follows_the_current_session() {
|
||||
assert_eq!(ssh_port(Some("10.0.0.5 51000 10.0.0.1 2222")), 2222);
|
||||
assert_eq!(ssh_port(Some("garbage")), 22);
|
||||
assert_eq!(ssh_port(None), 22);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_lines_are_ignored() {
|
||||
assert!(established_peers("header\nnot a table row\n", 22).is_empty());
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue