From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from mp11.migadu.com ([2001:41d0:2:4a6f::]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits)) by ms5.migadu.com with LMTPS id uFMFElU1BWOsQQEAbAwnHQ (envelope-from ) for ; Tue, 23 Aug 2022 22:15:17 +0200 Received: from aspmx1.migadu.com ([2001:41d0:2:4a6f::]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits)) by mp11.migadu.com with LMTPS id eBALElU1BWOQFAEA9RJhRA (envelope-from ) for ; Tue, 23 Aug 2022 22:15:17 +0200 Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by aspmx1.migadu.com (Postfix) with ESMTPS id CEBB82E23D for ; Tue, 23 Aug 2022 22:15:16 +0200 (CEST) Received: from localhost ([::1]:37122 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1oQaIu-0007bm-15 for larch@yhetil.org; Tue, 23 Aug 2022 16:15:16 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:43046) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1oQaIh-0007ba-BM for guix-patches@gnu.org; Tue, 23 Aug 2022 16:15:03 -0400 Received: from debbugs.gnu.org ([209.51.188.43]:55359) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1oQaIg-0002Z0-OS for guix-patches@gnu.org; Tue, 23 Aug 2022 16:15:03 -0400 Received: from Debian-debbugs by debbugs.gnu.org with local (Exim 4.84_2) (envelope-from ) id 1oQaIg-0007KM-Bf for guix-patches@gnu.org; Tue, 23 Aug 2022 16:15:02 -0400 X-Loop: help-debbugs@gnu.org Subject: [bug#56608] [PATCH v3] gnu: security: Add fail2ban-service-type. Resent-From: muradm Original-Sender: "Debbugs-submit" Resent-CC: guix-patches@gnu.org Resent-Date: Tue, 23 Aug 2022 20:15:02 +0000 Resent-Message-ID: Resent-Sender: help-debbugs@gnu.org X-GNU-PR-Message: followup 56608 X-GNU-PR-Package: guix-patches X-GNU-PR-Keywords: patch To: 56608@debbugs.gnu.org, Maxim Cournoyer Received: via spool by 56608-submit@debbugs.gnu.org id=B56608.166128564828086 (code B ref 56608); Tue, 23 Aug 2022 20:15:02 +0000 Received: (at 56608) by debbugs.gnu.org; 23 Aug 2022 20:14:08 +0000 Received: from localhost ([127.0.0.1]:45108 helo=debbugs.gnu.org) by debbugs.gnu.org with esmtp (Exim 4.84_2) (envelope-from ) id 1oQaHm-0007Iu-Br for submit@debbugs.gnu.org; Tue, 23 Aug 2022 16:14:07 -0400 Received: from nomad-cl1.staging.muradm.net ([139.162.159.157]:41012 helo=nomad-cl1.muradm.net) by debbugs.gnu.org with esmtp (Exim 4.84_2) (envelope-from ) id 1oQaHi-0007IG-PP for 56608@debbugs.gnu.org; Tue, 23 Aug 2022 16:14:04 -0400 Received: from localhost ([127.0.0.1]:37512) by nomad-cl1.muradm.net with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.96) (envelope-from ) id 1oQaGm-0006o3-2r; Tue, 23 Aug 2022 20:13:05 +0000 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=muradm.net; s=mail; h=Content-Transfer-Encoding:Content-Type:MIME-Version:References: In-Reply-To:Message-Id:Date:Subject:To:From:Sender:Reply-To:Cc:Content-ID: Content-Description:Resent-Date:Resent-From:Resent-Sender:Resent-To:Resent-Cc :Resent-Message-ID:List-Id:List-Help:List-Unsubscribe:List-Subscribe: List-Post:List-Owner:List-Archive; bh=aQgQwmD2oKwwdgjkfRaF7Dsx6I7hYHoNHbZ+ZWGJiA4=; b=mU48DXqk/N7BJgepYikPUG9cxo 94IsRODz1ZcpYSXC+aMK6cl8kM8lSYWAmFzP2u/IiLtZGTpDhb6wv929I9AmeL2xl5AlL3z3mWA2y fRZb9qHBxMWIuRGSrcpyXJux8XHOfsC2FMyMLiamnt1FSoSIL2G0lQCgpwtu1sc9Cf2AI98IQ4wVw SRknmR0cGcM4bBlPEnn4oWco8+SL0W5kBc95cpwH512QRcJ9jb6ZKBYtyqDOItksSOR1q+nKE91Bm uqfzeKbHAsBcxL0qse/SbJHOrBTKoeETHId5BH/G5I3pVJmWMHfLHKn3EnvNNfae3Wr2UOzOsr7i+ I/AJGsRGeeGj6JkEG3IR65wHJKCCORn29COlbcaRl63DbnR+r4/y6ala6gfodKm3PWa2qDq6NyTr8 L/BxNwDDL0zQwuulaLz52nOkJRy8wA6QO2wWcpeb/0AyBH6WDHCerOw9+K7fnN1X/6ysQHAy+WmTb 3fR+zkGn1k207v0rojsm8yxc; Received: from muradm by localhost with local (Exim 4.96) (envelope-from ) id 1oQaHb-0006AM-2m; Tue, 23 Aug 2022 23:13:55 +0300 From: muradm Date: Tue, 23 Aug 2022 23:13:55 +0300 Message-Id: <20220823201355.23691-1-mail@muradm.net> X-Mailer: git-send-email 2.37.1 In-Reply-To: <87r116ybj4.fsf@muradm.net> References: <87r116ybj4.fsf@muradm.net> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-BeenThere: debbugs-submit@debbugs.gnu.org X-Mailman-Version: 2.1.18 Precedence: list X-BeenThere: guix-patches@gnu.org List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: guix-patches-bounces+larch=yhetil.org@gnu.org Sender: "Guix-patches" X-Migadu-Flow: FLOW_IN X-Migadu-To: larch@yhetil.org X-Migadu-Country: US ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=yhetil.org; s=key1; t=1661285717; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding:resent-cc: resent-from:resent-sender:resent-message-id:in-reply-to:in-reply-to: references:references:list-id:list-help:list-unsubscribe: list-subscribe:list-post:dkim-signature; bh=lCH7BP7SeaDTJlXY6Le36WQp3OzKKSNeuj2iBPlQDVM=; b=cf84Qtc1vUUJcaVFyCEfQhrdv/r/ehMZ/f3oLRolxwVeWOoVjAxrlr6RXgnjc1O6G1Ysfw I3vBwOL08KLiT7Z3LfrBNaqPF4j76eUcgIdv2Fy2Ad7lwDUmIqJcpDbi4XaOCxXNlRx1N/ gjnRSHVxYhOnbGdkq3y2GAZiyl/tn72zlx7D2/UUQHF1eqUKvp6zrlB4koTDRHDW+Sf1qy rxAK+IxXafoktlvJe+QSLkkLfRil/VqkhiMLVHGW3qXIGUQH9HssKiNYAN5mSN0q/Z4DuD tmM/rsuu4Ns05PjdRAVF8BOovMi2coHzlprs2SysFC7MZWzoiQdhPJJyrKG8eg== ARC-Seal: i=1; s=key1; d=yhetil.org; t=1661285717; a=rsa-sha256; cv=none; b=fkA0tpMcNxfbMXmq4S52N6s7cUxLSMUsHKQ+PgG7o6zAF0ZQrhgdwwHTdrB2hOdc1ZS1l8 9BBob6kU6X4NSyvRJDNTRjm8iPilKqHty+hsXjV6+QOOTWCODbSum0G/0y6yCabAlQ2myP QCQnoQcF9tnuL7Dt/6uO7gz133WEiW3/VAz4x1dpgFkYWmsdHgiSJkpUkCGVB95WRA+hMd EsJYxl3tTYGmDCGRb518b1sBL16Yj/en2OHzVrGIuiOZS/7GWKxbzgLCxS9XH3NjqKzf/M UTT26YSYCq0wKF9TE3NvlUDR5YnRJ2Rimx7M1bo5ye2efRZEWVnFRMofnC5KJA== ARC-Authentication-Results: i=1; aspmx1.migadu.com; dkim=fail ("body hash did not verify") header.d=muradm.net header.s=mail header.b=mU48DXqk; dmarc=none; spf=pass (aspmx1.migadu.com: domain of "guix-patches-bounces+larch=yhetil.org@gnu.org" designates 209.51.188.17 as permitted sender) smtp.mailfrom="guix-patches-bounces+larch=yhetil.org@gnu.org" X-Migadu-Spam-Score: 2.20 Authentication-Results: aspmx1.migadu.com; dkim=fail ("body hash did not verify") header.d=muradm.net header.s=mail header.b=mU48DXqk; dmarc=none; spf=pass (aspmx1.migadu.com: domain of "guix-patches-bounces+larch=yhetil.org@gnu.org" designates 209.51.188.17 as permitted sender) smtp.mailfrom="guix-patches-bounces+larch=yhetil.org@gnu.org" X-Migadu-Queue-Id: CEBB82E23D X-Spam-Score: 2.20 X-Migadu-Scanner: scn1.migadu.com X-TUID: t3ZK0NUnnsA2 * gnu/services/security.scm: New module. * gnu/tests/security.scm: New module. * gnu/local.mk: Add new security module and tests. * doc/guix.text: Add fail2ban-service-type documentation. --- doc/guix.texi | 249 +++++++++++++++++++++++ gnu/local.mk | 3 + gnu/services/security.scm | 401 ++++++++++++++++++++++++++++++++++++++ gnu/tests/security.scm | 227 +++++++++++++++++++++ 4 files changed, 880 insertions(+) create mode 100644 gnu/services/security.scm create mode 100644 gnu/tests/security.scm diff --git a/doc/guix.texi b/doc/guix.texi index 023b48ae35..62a9e76a2c 100644 --- a/doc/guix.texi +++ b/doc/guix.texi @@ -36283,6 +36283,255 @@ Extra command line options for @code{nix-service-type}. @end table @end deftp +@cindex Fail2ban +@subsubheading Fail2ban service + +@uref{http://www.fail2ban.org/, @code{fail2ban}} scans log files +(e.g. @code{/var/log/apache/error_log}) and bans IPs that show the malicious +signs -- too many password failures, seeking for exploits, etc. + +@code{fail2ban} service is provided in @code{(gnu services security)} module. + +This is the type of the service that runs @code{fail2ban} daemon. It can be +used in various ways, which are: + +@itemize + +@item Explicit configuration +users are free to enable @code{fail2ban} configuration without strong +dependency. + +@item On-demand extending configuration +convenience @code{fail2ban-jail-service} function is provided, in order +to extend existing services on-demand. + +@item Permanent extending configuration +service developers may use @code{fail2ban-service-type} in service-type's +extensions. + +@end itemize + +@defvr {Scheme Variable} fail2ban-service-type + +This is the type of the service that runs @code{fail2ban} daemon. It can be +configured explicitly as following: + +@lisp +(append + (list + ;; Here is explicit configuration, this way fail2ban daemon + ;; will start and do its thing for sshd jail. + (service fail2ban-service-type + (fail2ban-configuration + (extra-jails + (list + (fail2ban-jail-configuration + (name "sshd") + (enabled #t)))))) + ;; There is no direct dependency on actual openssh + ;; server configuration, it could be customizaed as needed + ;; or started by different means. + (service openssh-service-type)) + %base-services) +@end lisp +@end defvr + +@deffn {Scheme Procedure} fail2ban-jail-service @var{svc-type} @var{jail} +Return extended @var{svc-type} of @code{} with added +@var{jail} of type @code{fail2ban-jail-configuration} extension +for @code{fail2ban-service-type}. + +For example: + +@lisp +(append + (list + (service + ;; Using convenience function we can extend virtually + ;; any service type with any fail2ban jail. + ;; This way we don't have to explicitly extend services + ;; with fail2ban-service-type. + (fail2ban-jail-service + openssh-service-type + (fail2ban-jail-configuration + (name "sshd") + (enabled #t))) + (openssh-configuration ...)))) +@end lisp +@end deffn + +@deftp {Data Type} fail2ban-configuration +Available @code{fail2ban-configuration} fields are: + +@table @asis +@item @code{fail2ban} (default: @code{fail2ban}) (type: package) +The @code{fail2ban} package to use. It used for both binaries and as +base default configuration that will be extended with +@code{}s. + +@item @code{run-directory} (default: @code{"/var/run/fail2ban"}) (type: string) +State directory for @code{fail2ban} daemon. + +@item @code{jails} (default: @code{()}) (type: list-of-fail2ban-jail-configurations) +Instances of @code{} collected from +extensions. + +@item @code{extra-jails} (default: @code{()}) (type: list-of-fail2ban-jail-configurations) +Instances of @code{} provided by user +explicitly. + +@item @code{extra-content} (type: maybe-string) +Extra raw content to add at the end of the @file{jail.local} file. + +@end table + +@end deftp + + +@deftp {Data Type} fail2ban-jail-configuration +Available @code{fail2ban-jail-configuration} fields are: + +@table @asis +@item @code{name} (type: string) +Required name of this jail configuration. + +@item @code{enabled?} (type: maybe-boolean) +Either @code{#t} or @code{#f} for @samp{true} and @samp{false} +respectively. + +@item @code{backend} (type: maybe-symbol) +Backend to be used to detect changes in the @code{ogpath}. + +@item @code{max-retry} (type: maybe-integer) +Is the number of failures before a host get banned (e.g. +@code{(max-retry 5)}). + +@item @code{max-matches} (type: maybe-integer) +Is the number of matches stored in ticket (resolvable via tag +@code{}) in action. + +@item @code{find-time} (type: maybe-string) +A host is banned if it has generated @code{max-retry} during the last +@code{find-time} seconds (e.g. @code{(find-time "10m")}). + +@item @code{ban-time} (type: maybe-string) +Is the number of seconds that a host is banned (e.g. @code{(ban-time +"10m")}). + +@item @code{ban-time-increment?} (type: maybe-boolean) +Allows to use database for searching of previously banned ip's to +increase a default ban time using special formula. + +@item @code{ban-time-factor} (type: maybe-string) +Is a coefficient to calculate exponent growing of the formula or common +multiplier. + +@item @code{ban-time-formula} (type: maybe-string) +Used by default to calculate next value of ban time. + +@item @code{ban-time-multipliers} (type: maybe-string) +Used to calculate next value of ban time instead of formula. + +@item @code{ban-time-max-time} (type: maybe-string) +Is the max number of seconds using the ban time can reach (doesn't grow +further). + +@item @code{ban-time-rnd-time} (type: maybe-string) +Is the max number of seconds using for mixing with random time to +prevent ``clever'' botnets calculate exact time IP can be unbanned +again. + +@item @code{ban-time-overall-jails?} (type: maybe-boolean) +Either @code{#t} or @code{#f} for @samp{true} and @samp{false} +respectively. @itemize @bullet @item @code{true} - specifies the search +of IP in the database will be executed cross over all jails @item +@code{false} - only current jail of the ban IP will be searched @end +itemize + +@item @code{ignore-command} (type: maybe-string) +External command that will take an tagged arguments to ignore. Note: +while provided, currently unimplemented in the context of @code{guix}. + +@item @code{ignore-self?} (type: maybe-boolean) +Specifies whether the local resp. own IP addresses should be ignored. + +@item @code{ignore-ip} (default: @code{()}) (type: list-of-strings) +Can be a list of IP addresses, CIDR masks or DNS hosts. @code{fail2ban} +will not ban a host which matches an address in this list. + +@item @code{ignore-cache} (type: maybe-fail2ban-ignore-cache-configuration) +Provide cache parameters for ignore failure check. + +@item @code{filter} (type: maybe-fail2ban-jail-filter-configuration) +Defines the filter to use by the jail, using +@code{}. By default jails have +names matching their filter name. + +@item @code{log-time-zone} (type: maybe-string) +Force the time zone for log lines that don't have one. + +@item @code{log-encoding} (type: maybe-symbol) +Specifies the encoding of the log files handled by the jail. Possible +values: @code{'ascii}, @code{'utf-8}, @code{'auto}. + +@item @code{log-path} (default: @code{()}) (type: list-of-strings) +File name(s) of the log files to be monitored. + +@item @code{action} (default: @code{()}) (type: list-of-fail2ban-jail-actions) +List of @code{}. + +@item @code{extra-content} (type: maybe-string) +Extra content for the jail configuration. + +@end table + +@end deftp + +@deftp {Data Type} fail2ban-ignore-cache-configuration +Available @code{fail2ban-ignore-cache-configuration} fields are: + +@table @asis +@item @code{key} (type: string) +Cache key. + +@item @code{max-count} (type: integer) +Cache size. + +@item @code{max-time} (type: integer) +Cache time. + +@end table + +@end deftp + +@deftp {Data Type} fail2ban-jail-action-configuration +Available @code{fail2ban-jail-action-configuration} fields are: + +@table @asis +@item @code{name} (type: string) +Action name. + +@item @code{arguments} (default: @code{()}) (type: list-of-arguments) +Action arguments. + +@end table + +@end deftp + +@deftp {Data Type} fail2ban-jail-filter-configuration +Available @code{fail2ban-jail-filter-configuration} fields are: + +@table @asis +@item @code{name} (type: string) +Filter to use. + +@item @code{mode} (type: maybe-string) +Mode for filter. + +@end table + +@end deftp + @node Setuid Programs @section Setuid Programs diff --git a/gnu/local.mk b/gnu/local.mk index 26dfb6afe2..31569033bc 100644 --- a/gnu/local.mk +++ b/gnu/local.mk @@ -51,6 +51,7 @@ # Copyright © 2022 Remco van 't Veer # Copyright © 2022 Artyom V. Poptsov # Copyright © 2022 John Kehayias +# Copyright © 2022 muradm # # This file is part of GNU Guix. # @@ -672,6 +673,7 @@ GNU_SYSTEM_MODULES = \ %D%/services/nfs.scm \ %D%/services/pam-mount.scm \ %D%/services/science.scm \ + %D%/services/security.scm \ %D%/services/security-token.scm \ %D%/services/shepherd.scm \ %D%/services/sound.scm \ @@ -756,6 +758,7 @@ GNU_SYSTEM_MODULES = \ %D%/tests/package-management.scm \ %D%/tests/reconfigure.scm \ %D%/tests/rsync.scm \ + %D%/tests/security.scm \ %D%/tests/security-token.scm \ %D%/tests/singularity.scm \ %D%/tests/ssh.scm \ diff --git a/gnu/services/security.scm b/gnu/services/security.scm new file mode 100644 index 0000000000..58c785fb6c --- /dev/null +++ b/gnu/services/security.scm @@ -0,0 +1,401 @@ +;;; GNU Guix --- Functional package management for GNU +;;; Copyright © 2022 muradm +;;; +;;; This file is part of GNU Guix. +;;; +;;; GNU Guix is free software; you can redistribute it and/or modify it +;;; under the terms of the GNU General Public License as published by +;;; the Free Software Foundation; either version 3 of the License, or (at +;;; your option) any later version. +;;; +;;; GNU Guix is distributed in the hope that it will be useful, but +;;; WITHOUT ANY WARRANTY; without even the implied warranty of +;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;;; GNU General Public License for more details. +;;; +;;; You should have received a copy of the GNU General Public License +;;; along with GNU Guix. If not, see . + +(define-module (gnu services security) + #:use-module (gnu packages admin) + #:use-module (gnu services) + #:use-module (gnu services configuration) + #:use-module (gnu services shepherd) + #:use-module (guix gexp) + #:use-module (guix packages) + #:use-module (guix records) + #:use-module (guix ui) + #:use-module (ice-9 format) + #:use-module (ice-9 match) + #:use-module (srfi srfi-1) + #:export (fail2ban-configuration + fail2ban-configuration-fields + fail2ban-jail-configuration + fail2ban-jail-configuration-fields + + fail2ban-ignore-cache-configuration + fail2ban-ignore-cache-configuration-fields + fail2ban-jail-action-configuration + fail2ban-jail-action-configuration-fields + fail2ban-jail-filter-configuration + fail2ban-jail-filter-configuration-fields + + fail2ban-service-type + fail2ban-jail-service)) + +(define-configuration/no-serialization fail2ban-ignore-cache-configuration + (key string "Cache key.") + (max-count integer "Cache size.") + (max-time integer "Cache time.")) + +(define serialize-fail2ban-ignore-cache-configuration + (match-lambda + (($ _ key max-count max-time) + (format #f "key=\"~a\", max-count=~d, max-time=~d" + key max-count max-time)))) + +(define-maybe/no-serialization string) + +(define-configuration/no-serialization fail2ban-jail-filter-configuration + (name string "Filter to use.") + (mode maybe-string "Mode for filter.")) + +(define serialize-fail2ban-jail-filter-configuration + (match-lambda + (($ _ name mode) + (format #f "~a~@[[mode=~a]~]" name (and (not (eq? 'unset mode)) mode))))) + +(define (argument? a) + (and (pair? a) + (string? (car a)) + (or (string? (cdr a)) + (list-of-strings? (cdr a))))) + +(define list-of-arguments? (list-of argument?)) + +(define-configuration/no-serialization fail2ban-jail-action-configuration + (name string "Action name.") + (arguments (list-of-arguments '()) "Action arguments.")) + +(define list-of-fail2ban-jail-actions? + (list-of fail2ban-jail-action-configuration?)) + +(define (serialize-fail2ban-jail-action-configuration-arguments args) + (let* ((multi-value + (lambda (v) + (format #f "~a" (string-join v ",")))) + (any-value + (lambda (v) + (if (list? v) (string-append "\"" (multi-value v) "\"") v))) + (key-value + (lambda (e) + (format #f "~a=~a" (car e) (any-value (cdr e)))))) + (format #f "~a" (string-join (map key-value args) ",")))) + +(define serialize-fail2ban-jail-action-configuration + (match-lambda + (($ _ name arguments) + (format + #f "~a~a" + name + (if (null? arguments) "" + (format + #f "[~a]" + (serialize-fail2ban-jail-action-configuration-arguments + arguments))))))) + +(define fail2ban-backend->string + (match-lambda + ('auto "auto") + ('pyinotify "pyinotify") + ('gamin "gamin") + ('polling "polling") + ('systemd "systemd") + (unknown + (leave + (G_ "fail2ban: '~a' is not a supported backend~%") unknown)))) + +(define fail2ban-log-encoding->string + (match-lambda + ('auto "auto") + ('utf-8 "utf-8") + ('ascii "ascii") + (unknown + (leave + (G_ "fail2ban: '~a' is not a supported log encoding~%") unknown)))) + +(define (fail2ban-jail-configuration-serialize-field-name name) + (cond ((symbol? name) + (fail2ban-jail-configuration-serialize-field-name + (symbol->string name))) + ((string-suffix? "?" name) + (fail2ban-jail-configuration-serialize-field-name + (string-drop-right name 1))) + ((string-prefix? "ban-time-" name) + (fail2ban-jail-configuration-serialize-field-name + (string-append "bantime." (substring name 9)))) + ((string-contains name "-") + (fail2ban-jail-configuration-serialize-field-name + (string-filter (lambda (c) (equal? c #\-)) name))) + (#t name))) + +(define (fail2ban-jail-configuration-serialize-string field-name value) + #~(string-append + #$(fail2ban-jail-configuration-serialize-field-name field-name) + " = " #$value "\n")) + +(define (fail2ban-jail-configuration-serialize-integer field-name value) + (fail2ban-jail-configuration-serialize-string + field-name (number->string value))) + +(define (fail2ban-jail-configuration-serialize-boolean field-name value) + (fail2ban-jail-configuration-serialize-string + field-name (if value "true" "false"))) + +(define (fail2ban-jail-configuration-serialize-backend field-name value) + (if (eq? 'unset value) "" + (fail2ban-jail-configuration-serialize-string + field-name (fail2ban-backend->string value)))) + +(define (fail2ban-jail-configuration-serialize-fail2ban-ignore-cache-configuration field-name value) + (fail2ban-jail-configuration-serialize-string + field-name (serialize-fail2ban-ignore-cache-configuration value))) + +(define (fail2ban-jail-configuration-serialize-fail2ban-jail-filter-configuration field-name value) + (fail2ban-jail-configuration-serialize-string + field-name (serialize-fail2ban-jail-filter-configuration value))) + +(define (fail2ban-jail-configuration-serialize-log-encoding field-name value) + (if (eq? 'unset value) "" + (fail2ban-jail-configuration-serialize-string + field-name (fail2ban-log-encoding->string value)))) + +(define (fail2ban-jail-configuration-serialize-list-of-strings field-name value) + (if (null? value) "" + (fail2ban-jail-configuration-serialize-string + field-name (string-join value " ")))) + +(define (fail2ban-jail-configuration-serialize-list-of-fail2ban-jail-actions field-name value) + (if (null? value) "" + (fail2ban-jail-configuration-serialize-string + field-name (string-join + (map serialize-fail2ban-jail-action-configuration value) "\n")))) + +(define (fail2ban-jail-configuration-serialize-symbol field-name value) + (fail2ban-jail-configuration-serialize-string field-name (symbol->string value))) + +(define (fail2ban-jail-configuration-serialize-extra-content field-name value) + (if (eq? 'unset value) "" (string-append "\n" value "\n"))) + +(define-maybe integer (prefix fail2ban-jail-configuration-)) +(define-maybe string (prefix fail2ban-jail-configuration-)) +(define-maybe boolean (prefix fail2ban-jail-configuration-)) +(define-maybe symbol (prefix fail2ban-jail-configuration-)) +(define-maybe fail2ban-ignore-cache-configuration (prefix fail2ban-jail-configuration-)) +(define-maybe fail2ban-jail-filter-configuration (prefix fail2ban-jail-configuration-)) + +(define-configuration fail2ban-jail-configuration + (name + string + "Required name of this jail configuration.") + (enabled? + maybe-boolean + "Either @code{#t} or @code{#f} for @samp{true} and +@samp{false} respectively.") + (backend + maybe-symbol + "Backend to be used to detect changes in the @code{ogpath}." + fail2ban-jail-configuration-serialize-backend) + (max-retry + maybe-integer + "Is the number of failures before a host get banned +(e.g. @code{(max-retry 5)}).") + (max-matches + maybe-integer + "Is the number of matches stored in ticket (resolvable via +tag @code{}) in action.") + (find-time + maybe-string + "A host is banned if it has generated @code{max-retry} during the last +@code{find-time} seconds (e.g. @code{(find-time \"10m\")}).") + (ban-time + maybe-string + "Is the number of seconds that a host is banned +(e.g. @code{(ban-time \"10m\")}).") + (ban-time-increment? + maybe-boolean + "Allows to use database for searching of previously banned +ip's to increase a default ban time using special formula.") + (ban-time-factor + maybe-string + "Is a coefficient to calculate exponent growing of the +formula or common multiplier.") + (ban-time-formula + maybe-string + "Used by default to calculate next value of ban time.") + (ban-time-multipliers + maybe-string + "Used to calculate next value of ban time instead of formula.") + (ban-time-max-time + maybe-string + "Is the max number of seconds using the ban time can reach +(doesn't grow further).") + (ban-time-rnd-time + maybe-string + "Is the max number of seconds using for mixing with random time +to prevent ``clever'' botnets calculate exact time IP can be unbanned again.") + (ban-time-overall-jails? + maybe-boolean + "Either @code{#t} or @code{#f} for @samp{true} and @samp{false} respectively. +@itemize +@item @code{true} - specifies the search of IP in the database will be executed cross over all jails +@item @code{false} - only current jail of the ban IP will be searched +@end itemize") + (ignore-command + maybe-string + "External command that will take an tagged arguments to ignore. +Note: while provided, currently unimplemented in the context of @code{guix}.") + (ignore-self? + maybe-boolean + "Specifies whether the local resp. own IP addresses should be ignored.") + (ignore-ip + (list-of-strings '()) + "Can be a list of IP addresses, CIDR masks or DNS hosts. @code{fail2ban} +will not ban a host which matches an address in this list.") + (ignore-cache + maybe-fail2ban-ignore-cache-configuration + "Provide cache parameters for ignore failure check.") + (filter + maybe-fail2ban-jail-filter-configuration + "Defines the filter to use by the jail, using +@code{}. +By default jails have names matching their filter name.") + (log-time-zone + maybe-string + "Force the time zone for log lines that don't have one.") + (log-encoding + maybe-symbol + "Specifies the encoding of the log files handled by the jail. +Possible values: @code{'ascii}, @code{'utf-8}, @code{'auto}." + fail2ban-jail-configuration-serialize-log-encoding) + (log-path + (list-of-strings '()) + "File name(s) of the log files to be monitored.") + (action + (list-of-fail2ban-jail-actions '()) + "List of @code{}.") + (extra-content + maybe-string + "Extra content for the jail configuration." + fail2ban-jail-configuration-serialize-extra-content) + (prefix fail2ban-jail-configuration-)) + +(define list-of-fail2ban-jail-configurations? + (list-of fail2ban-jail-configuration?)) + +(define (serialize-fail2ban-jail-configuration config) + #~(string-append + #$(format #f "[~a]\n" (fail2ban-jail-configuration-name config)) + #$(serialize-configuration + config fail2ban-jail-configuration-fields))) + +(define-configuration/no-serialization fail2ban-configuration + (fail2ban + (package fail2ban) + "The @code{fail2ban} package to use. It used for both binaries and +as base default configuration that will be extended with +@code{}s.") + (run-directory + (string "/var/run/fail2ban") + "State directory for @code{fail2ban} daemon.") + (jails + (list-of-fail2ban-jail-configurations '()) + "Instances of @code{} collected from +extensions.") + (extra-jails + (list-of-fail2ban-jail-configurations '()) + "Instances of @code{} provided by user +explicitly.") + (extra-content + maybe-string + "Extra raw content to add at the end of the @file{jail.local} file.")) + +(define (serialize-fail2ban-configuration config) + (let* ((jails (fail2ban-configuration-jails config)) + (extra-jails (fail2ban-configuration-extra-jails config)) + (extra-content (fail2ban-configuration-extra-content config))) + (interpose + (append (map serialize-fail2ban-jail-configuration + (append jails extra-jails)) + (list (if (eq? 'unset extra-content) "" extra-content)))))) + +(define (make-fail2ban-configuration-package config) + (let* ((fail2ban (fail2ban-configuration-fail2ban config)) + (jail-local (apply mixed-text-file "jail.local" + (serialize-fail2ban-configuration config)))) + (computed-file + "fail2ban-configuration" + (with-imported-modules '((guix build utils)) + #~(begin + (use-modules (guix build utils)) + (let ((out (ungexp output))) + (mkdir-p (string-append out "/etc/fail2ban")) + (copy-recursively + (string-append #$fail2ban "/etc/fail2ban") + (string-append out "/etc/fail2ban")) + (symlink + #$jail-local + (string-append out "/etc/fail2ban/jail.local")))))))) + +(define (fail2ban-shepherd-service config) + (match-record config + (fail2ban run-directory) + (let* ((fail2ban-server (file-append fail2ban "/bin/fail2ban-server")) + (pid-file (in-vicinity run-directory "fail2ban.pid")) + (socket-file (in-vicinity run-directory "fail2ban.sock")) + (config-dir (make-fail2ban-configuration-package config)) + (config-dir (file-append config-dir "/etc/fail2ban")) + (fail2ban-action + (lambda args + #~(lambda _ + (invoke #$fail2ban-server + "-c" #$config-dir + "-p" #$pid-file + "-s" #$socket-file + "-b" + #$@args))))) + + ;; TODO: Add 'reload' action. + (list (shepherd-service + (provision '(fail2ban)) + (documentation "Run the fail2ban daemon.") + (requirement '(user-processes)) + (modules `((ice-9 match) + ,@%default-modules)) + (start (fail2ban-action "start")) + (stop (fail2ban-action "stop"))))))) + +(define fail2ban-service-type + (service-type (name 'fail2ban) + (extensions + (list (service-extension shepherd-root-service-type + fail2ban-shepherd-service))) + (compose concatenate) + (extend (lambda (config jails) + (fail2ban-configuration + (inherit config) + (jails + (append + (fail2ban-configuration-jails config) + jails))))) + (default-value (fail2ban-configuration)) + (description "Run the fail2ban server."))) + +(define (fail2ban-jail-service svc-type jail) + (service-type + (inherit svc-type) + (extensions + (append + (service-type-extensions svc-type) + (list (service-extension fail2ban-service-type + (lambda _ (list jail)))))))) diff --git a/gnu/tests/security.scm b/gnu/tests/security.scm new file mode 100644 index 0000000000..1e6d939b12 --- /dev/null +++ b/gnu/tests/security.scm @@ -0,0 +1,227 @@ +;;; GNU Guix --- Functional package management for GNU +;;; Copyright © 2022 muradm +;;; +;;; This file is part of GNU Guix. +;;; +;;; GNU Guix is free software; you can redistribute it and/or modify it +;;; under the terms of the GNU General Public License as published by +;;; the Free Software Foundation; either version 3 of the License, or (at +;;; your option) any later version. +;;; +;;; GNU Guix is distributed in the hope that it will be useful, but +;;; WITHOUT ANY WARRANTY; without even the implied warranty of +;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;;; GNU General Public License for more details. +;;; +;;; You should have received a copy of the GNU General Public License +;;; along with GNU Guix. If not, see . + +(define-module (gnu tests security) + #:use-module (guix gexp) + #:use-module (gnu packages admin) + #:use-module (gnu services) + #:use-module (gnu services security) + #:use-module (gnu services ssh) + #:use-module (gnu system) + #:use-module (gnu system vm) + #:use-module (gnu tests) + #:export (%test-fail2ban-basic + %test-fail2ban-extension + %test-fail2ban-simple)) + + +;;; +;;; fail2ban tests +;;; + +(define-syntax-rule (fail2ban-test test-name test-os tests-more ...) + (lambda () + (define os + (marionette-operating-system + test-os + #:imported-modules '((gnu services herd)))) + + (define vm + (virtual-machine + (operating-system os) + (port-forwardings '()))) + + (define test + (with-imported-modules '((gnu build marionette) + (guix build utils)) + #~(begin + (use-modules (srfi srfi-64) + (gnu build marionette)) + + (define marionette (make-marionette (list #$vm))) + + (test-runner-current (system-test-runner #$output)) + (test-begin test-name) + + (test-assert "fail2ban running" + (marionette-eval + '(begin + (use-modules (gnu services herd)) + (start-service 'fail2ban)) + marionette)) + + (test-assert "fail2ban socket ready" + (wait-for-unix-socket + "/var/run/fail2ban/fail2ban.sock" marionette)) + + (test-assert "fail2ban running after restart" + (marionette-eval + '(begin + (use-modules (gnu services herd)) + (restart-service 'fail2ban)) + marionette)) + + (test-assert "fail2ban socket ready after restart" + (wait-for-unix-socket + "/var/run/fail2ban/fail2ban.sock" marionette)) + + (test-assert "fail2ban pid ready" + (marionette-eval + '(file-exists? "/var/run/fail2ban/fail2ban.pid") + marionette)) + + (test-assert "fail2ban log file" + (marionette-eval + '(file-exists? "/var/log/fail2ban.log") + marionette)) + + tests-more ... + + (test-end)))) + + (gexp->derivation test-name test))) + +(define run-fail2ban-basic-test + (fail2ban-test + "fail2ban-basic-test" + + (simple-operating-system + (service fail2ban-service-type)))) + +(define %test-fail2ban-basic + (system-test + (name "fail2ban-basic") + (description "Test basic fail2ban running capability.") + (value (run-fail2ban-basic-test)))) + +(define %fail2ban-server-cmd + (program-file + "fail2ban-server-cmd" + #~(begin + (let ((cmd #$(file-append fail2ban "/bin/fail2ban-server"))) + (apply execl cmd cmd `("-p" "/var/run/fail2ban/fail2ban.pid" + "-s" "/var/run/fail2ban/fail2ban.sock" + ,@(cdr (program-arguments)))))))) + +(define run-fail2ban-simple-test + (fail2ban-test + "fail2ban-basic-test" + + (simple-operating-system + (service + fail2ban-service-type + (fail2ban-configuration + (jails + (list + (fail2ban-jail-configuration (name "sshd") (enabled? #t))))))) + + (test-equal "fail2ban sshd jail running status output" + '("Status for the jail: sshd" + "|- Filter" + "| |- Currently failed:\t0" + "| |- Total failed:\t0" + "| `- File list:\t/var/log/secure" + "`- Actions" + " |- Currently banned:\t0" + " |- Total banned:\t0" + " `- Banned IP list:\t" + "") + (marionette-eval + '(begin + (use-modules (ice-9 rdelim) (ice-9 popen) (rnrs io ports)) + (let ((call-command + (lambda (cmd) + (let* ((err-cons (pipe)) + (port (with-error-to-port (cdr err-cons) + (lambda () (open-input-pipe cmd)))) + (_ (setvbuf (car err-cons) 'block + (* 1024 1024 16))) + (result (read-delimited "" port))) + (close-port (cdr err-cons)) + (values result (read-delimited "" (car err-cons))))))) + (string-split + (call-command + (string-join (list #$%fail2ban-server-cmd "status" "sshd") " ")) + #\newline))) + marionette)) + + (test-equal "fail2ban sshd jail running exit code" + 0 + (marionette-eval + '(status:exit-val (system* #$%fail2ban-server-cmd "status" "sshd")) + marionette)))) + +(define %test-fail2ban-simple + (system-test + (name "fail2ban-simple") + (description "Test simple fail2ban running capability.") + (value (run-fail2ban-simple-test)))) + +(define run-fail2ban-extension-test + (fail2ban-test + "fail2ban-extension-test" + + (simple-operating-system + (service + (fail2ban-jail-service + openssh-service-type + (fail2ban-jail-configuration + (name "sshd") (enabled? #t))) + (openssh-configuration))) + + (test-equal "fail2ban sshd jail running status output" + '("Status for the jail: sshd" + "|- Filter" + "| |- Currently failed:\t0" + "| |- Total failed:\t0" + "| `- File list:\t/var/log/secure" + "`- Actions" + " |- Currently banned:\t0" + " |- Total banned:\t0" + " `- Banned IP list:\t" + "") + (marionette-eval + '(begin + (use-modules (ice-9 rdelim) (ice-9 popen) (rnrs io ports)) + (let ((call-command + (lambda (cmd) + (let* ((err-cons (pipe)) + (port (with-error-to-port (cdr err-cons) + (lambda () (open-input-pipe cmd)))) + (_ (setvbuf (car err-cons) 'block + (* 1024 1024 16))) + (result (read-delimited "" port))) + (close-port (cdr err-cons)) + (values result (read-delimited "" (car err-cons))))))) + (string-split + (call-command + (string-join (list #$%fail2ban-server-cmd "status" "sshd") " ")) + #\newline))) + marionette)) + + (test-equal "fail2ban sshd jail running exit code" + 0 + (marionette-eval + '(status:exit-val (system* #$%fail2ban-server-cmd "status" "sshd")) + marionette)))) + +(define %test-fail2ban-extension + (system-test + (name "fail2ban-extension") + (description "Test extension fail2ban running capability.") + (value (run-fail2ban-extension-test)))) -- 2.37.1