nixos-vps/modules/crowdsec.nix

149 lines
3.7 KiB
Nix

# CrowdSec Module
# Provides: Collaborative intrusion detection and prevention
#
# Usage:
# myModules.crowdsec = {
# enable = true;
# enableBouncer = true; # Block attackers at firewall level
# };
{
config,
lib,
pkgs,
...
}:
let
cfg = config.myModules.crowdsec;
credentialsFile = "/var/lib/crowdsec/state/lapi_credentials.yaml";
in
{
options.myModules.crowdsec = {
enable = lib.mkEnableOption "CrowdSec security engine";
enableBouncer = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Enable firewall bouncer to block malicious IPs";
};
whitelistIPs = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "1.2.3.4" "10.0.0.0/8" ];
description = "IP addresses or CIDR ranges to whitelist";
};
banDuration = lib.mkOption {
type = lib.types.str;
default = "4h";
description = "Default ban duration for malicious IPs";
};
};
config = lib.mkIf cfg.enable {
services.crowdsec = {
enable = true;
autoUpdateService = true;
# Enable Local API server
settings = {
general.api.server = {
enable = true;
listen_uri = "127.0.0.1:8080";
};
lapi.credentialsFile = credentialsFile;
};
# Log acquisitions
localConfig.acquisitions = [
# SSH logs
{
source = "journalctl";
journalctl_filter = [ "_SYSTEMD_UNIT=sshd.service" ];
labels = {
type = "syslog";
};
}
# Nginx access logs
{
source = "journalctl";
journalctl_filter = [ "_SYSTEMD_UNIT=nginx.service" ];
labels = {
type = "nginx";
};
}
];
# Whitelist parser for trusted IPs
localConfig.parsers.s02Enrich = lib.mkIf (cfg.whitelistIPs != [ ]) [
{
name = "nixos/whitelist";
description = "Whitelist trusted IPs";
whitelist = {
reason = "Trusted IPs";
ip = lib.filter (ip: !(lib.hasInfix "/" ip)) cfg.whitelistIPs;
cidr = lib.filter (lib.hasInfix "/") cfg.whitelistIPs;
};
}
];
# Remediation profiles
localConfig.profiles = [
{
name = "block_non_de";
filters = [ "Alert.Remediation == true && Alert.GetScope() == 'Ip' && Alert.Enriched.IsoCode != 'DE' && Alert.Enriched.IsoCode != ''" ];
decisions = [
{
type = "ban";
duration = "24h";
}
];
on_success = "break";
}
{
name = "default_ip_remediation";
filters = [ "Alert.Remediation == true && Alert.GetScope() == 'Ip'" ];
decisions = [
{
type = "ban";
duration = cfg.banDuration;
}
];
on_success = "break";
}
];
# Hub collections for common attack patterns
hub = {
parsers = [
"crowdsecurity/geoip-enrich"
];
collections = [
"crowdsecurity/linux"
"crowdsecurity/nginx"
"crowdsecurity/sshd"
];
};
};
# Firewall bouncer - blocks malicious IPs at firewall level
services.crowdsec-firewall-bouncer = lib.mkIf cfg.enableBouncer {
enable = true;
registerBouncer.enable = true;
registerBouncer.bouncerName = "firewall-bouncer";
};
# Ensure credentials directory exists
systemd.tmpfiles.settings."10-crowdsec-lapi" = {
"/var/lib/crowdsec/state" = {
d = {
user = "crowdsec";
group = "crowdsec";
mode = "0750";
};
};
};
};
}