Compare commits

...
745 Commits
Author SHA1 Message Date
sebres 095aeda840 Merge branch '0.11' 2021-12-02 18:56:19 +01:00
sebres 3fb02527a4 Merge branch '0.10' into 0.11 2021-12-02 18:52:13 +01:00
sebres 25a61ce632 Merge branch 'gh-actions--test-systemd' into 0.10 + several revisions cherry-picked from 0.11/master 2021-12-02 18:48:59 +01:00
sebres 21d94ff178 amend to fix gh-3098: no option --disable-2to3 anymore 2021-12-02 18:44:24 +01:00
sebres 196c55e931 fix gh-3098: build fails with error in fail2ban setup command: use_2to3 is invalid (setuptools 58+) 2021-12-02 18:44:22 +01:00
sebres 0fa76ef75a gh-actions: temporary ignore tests of systemd backend for python >= v.3.10 (otherwise it fails with "PY_SSIZE_T_CLEAN macro must be defined for '#' formats") 2021-12-02 18:33:10 +01:00
sebres a147a8b0e1 gh-actions: coverage for systemd backend (to monitor journals in test-suite in GHA-env we need to use 0 as default flags, because otherwise it cannot be found using SYSTEM_ONLY(4)) 2021-12-02 18:33:08 +01:00
sebres 1bcb62e31c gh-actions: python releases upgrade + debug/test systemd backend availability in GHA 2021-12-02 18:33:05 +01:00
sebres a57643404c mytime.seconds2str: small amend with speed-up, code simplification and few tests 2021-11-04 14:34:04 +01:00
sebres 80805cabfc Merge branch '0.11' 2021-11-03 16:01:00 +01:00
sebres 4fe4ac8dde amend to merge: replace timedelta string representation with new function seconds2str 2021-11-03 15:58:57 +01:00
sebres 0b3ad780fe Merge branch '0.10' into 0.11 2021-11-03 15:48:21 +01:00
sebres ebf5784b8c Merge branch 'fix-gh-2882' into 0.10
closes gh-2882
2021-11-03 15:47:45 +01:00
sebres 3b02098817 several backends optimizations (in file and journal filters):
- don't need to wait if we still had log-entries from last iteration (which got interrupted for servicing)
- rewritten update log/journal position, it is more stable and faster now (fewer DB access and surely up-to-date at end)
2021-11-03 15:41:50 +01:00
sebres 96661f25ab filtersystemd.py: fixes wrong time point of "in operation" mode
todo: need more tests to cover any step of switch to inOperationMode (all branches)
2021-11-03 15:41:40 +01:00
sebres 7678f59827 better format of time delta (using seconds2str); increase stability for systemd test-cases 2021-11-03 12:57:57 +01:00
sebres 4b54a07d71 Revert "action.d/firewallcmd-*.conf (multiport only): fixed port range selector, replacing : with -;"
This reverts the incompatibility #3047 introduced by commit a038fd5dfe (#2821).
2021-11-01 11:45:40 +01:00
Sergey G. Brester e74baae666 Merge pull request #3135 from sylvestre/patch-2
Add the Debian path to roundcube error logs
2021-10-25 12:11:42 +02:00
Sergey G. Brester cb042dda7d Merge pull request #3133 from sylvestre/master
Fix typo found by lintian (Debian static analyzer)
2021-10-25 12:10:28 +02:00
Sylvestre Ledru 3245b8018b Add the Debian path to roundcube error logs 2021-10-23 17:38:20 +02:00
Sylvestre Ledru 1cd3118da3 Fix typo found by lintian (Debian static analyzer) 2021-10-23 17:06:13 +02:00
Sergey G. Brester 98c7dd04a4 Merge pull request #3037 from floppym/bug794931
tests: improve detection of readable systemd journal
2021-10-22 15:34:47 +02:00
Mike Gilbert d91d949e95 tests: improve detection of readable systemd journal
Look for system.journal in journal sub-directory.
Add -readable to the find command.

Bug: https://bugs.gentoo.org/794931
2021-10-19 11:08:04 -04:00
Viktor Szépe 1e8ce20b32 Display ChangeLog as a Markdown document 2021-10-17 19:53:10 +02:00
Sergey G. Brester 8e3a26bdeb Merge pull request #3117 from fail2ban/gh-3116
filter.d/lighttpd-auth.conf: adjust to the current source code, avoid catch-all's, etc
2021-10-01 15:09:09 +02:00
Sergey G. Brester ba839af8ad filter.d/lighttpd-auth.conf: adjusted to the current source code + avoiding catch-all's, etc (gh-3116) 2021-10-01 15:03:24 +02:00
Sergey G. Brester f8f59dd31a added test cases covering different messages adjusted to new log-format (gh-3116) 2021-10-01 14:58:25 +02:00
Sergey G. Brester 5ee482bc9a Merge pull request #3053 from db48x/fix-grammar-of-timestamp-warnings
Improve grammar and readability of timestamp warnings
2021-09-21 16:16:52 +02:00
Sergey G. Brester d086317cc8 Update filter.py 2021-09-21 16:05:53 +02:00
Sergey G. Brester 17eed32e03 Update filtertestcase.py 2021-09-21 16:00:37 +02:00
sebres 621d8cae17 restore backwards compatibility for date None 2021-09-20 02:20:22 +02:00
sebres ec043cd202 simplifying logic and shortening messages (delta in minutes; removed clock synchronization, because it is rarely an issue on fail2ban side, e. g. for remote logs only, etc) 2021-09-19 21:58:42 +02:00
Daniel Brooks d7afcde2e1 add a warning message for dates in the future
and a test that checks which message was output for which time deltas.
2021-09-19 19:39:52 +02:00
Daniel Brooks 1929e7a76b include more specific information in the warning 2021-09-19 19:39:49 +02:00
Daniel Brooks 320a3dcdd5 remove old warnings from filtertestcase.py
assertLogged only checks that at least one listed message is found, so
it isn’t necessary to repeat them in the test.
2021-09-19 19:39:45 +02:00
Daniel Brooks a98cc08b31 Updated the warning messages created when fail2ban sees unexpected timestamps
to improve their grammar and to remove jargon.

Partially fixes #2822
2021-09-19 19:39:41 +02:00
sebres 5093ff8956 Merge branch '0.11' into master 2021-09-19 18:54:23 +02:00
sebres d6b884f3b7 amend to fix gh-3098: no option --disable-2to3 anymore 2021-09-19 18:52:34 +02:00
sebres 5ac303df8a fix gh-3098: build fails with error in fail2ban setup command: use_2to3 is invalid (setuptools 58+) 2021-09-19 18:49:18 +02:00
sebres 8d45deca86 Merge branch '0.10' into 0.11 2021-09-19 18:42:23 +02:00
sebres 974ba688d4 Merge branch 'patch-3098' into 0.10 2021-09-19 18:41:24 +02:00
Sergey G. Brester 7f22c4873a remove 2to3 in setup (should be called outside before setup) 2021-09-19 18:36:02 +02:00
Sergey G. Brester 1414a44b8e Update main.yml
CI: try to install dependencies via apt, add build test
2021-09-19 18:24:36 +02:00
sebres ad1f9dc4d0 Merge branch '0.11' 2021-09-08 20:12:48 +02:00
sebres 64217fe018 Merge branch '0.10' into 0.11 2021-09-08 20:09:48 +02:00
sebres c0f9348db5 Merge branch 'sebres/gh-3097--fix-unh-except' into 0.10;
closes #3097
2021-09-08 20:08:30 +02:00
sebres d709ec8179 GH actions: use newest python version for 3.10 (3.10.0-rc.2) 2021-09-08 20:00:41 +02:00
sebres ba282b794c pyinotify: amend to 1e4a14fb25: one fix more for sporadic runtime error "dictionary changed size during iteration" (watched files) 2021-09-08 19:56:02 +02:00
sebres e323c148e1 backend systemd: fixes error "local variable 'line' referenced before assignment", introduced in 55d7d9e214f72bbe4f39a2d17aa004d80bfc7299;
don't update database too often (every 10 ticks or ~ 10 seconds in production);
closes gh-3097
2021-09-08 19:44:49 +02:00
sebres 1e4a14fb25 pyinotify: fixes sporadic runtime error "dictionary changed size during iteration" (if something outside changes the pending dict during _checkPending evaluation) - simply deserialize to a list for iteration, without any lock, because unneeded here due to small and mostly empty dictionary (logrotate, etc), not to mention that pending check is normally called once per minute;
don't call process file inside of server thread calling of addLogPath (always retard it as pending event);
ensure to wake-up as soon as possible to process pending events (e. g. if file gets added).
2021-09-08 19:17:44 +02:00
sebres 2f99d5accb test coverage for unhandled exception in run of several filter (gh-3097) 2021-09-08 18:22:31 +02:00
Sergey G. Brester cb667edf17 Merge pull request #3087 from alexporto2200/patch-3
README: added dependencies to setuptools or distutils (if installing from source)
2021-08-17 16:49:40 +02:00
Sergey G. Brester ade79635b2 distutils/setuptools only required if installing from source 2021-08-17 16:41:20 +02:00
Alex Porto dos Santos 39fe0bdce6 Update Readme
Add python3-setuptools or python-setuptools for dependencies. On some distributions this doesn't come by default, it would be nice to let users know about this in the documentation.
2021-08-17 10:39:04 -03:00
sebres 10cd815525 merge 0.11 to 1.0 (GHSA-m985-3f3v-cwmm) 2021-07-07 12:06:06 +02:00
sebres c03fe6682c merge 0.10 to 0.11 (GHSA-m985-3f3v-cwmm) 2021-07-07 12:04:46 +02:00
sebres e3f2fcfab4 merge point (GHSA-m985-3f3v-cwmm 0.9/0.10) 2021-07-07 11:50:49 +02:00
sebres 2ed414ed09 fixed possible RCE vulnerability, unset escape variable (default tilde) stops consider "~" char after new-line as composing escape sequence
closes GHSA-m985-3f3v-cwmm for 0.9
2021-07-07 11:46:28 +02:00
sebres 410a6ce5c8 fixed possible RCE vulnerability, unset escape variable (default tilde) stops consider "~" char after new-line as composing escape sequence 2021-06-21 17:12:53 +02:00
sebres 579c6a94af filter.d/postfix.conf: mode ddos (and aggressive) extended to consider abusive handling of clients hitting command limit (gh-3040) 2021-06-10 15:23:24 +02:00
sebres 43f2923fbd filter.d/postfix.conf: matches rejects with "undeliverable address" (sender/recipient verification, gh-3039) additionally to "Unknown user";
both are configurable now via extended parameter and can be disabled using `exre-user=` supplied in filter parameters
2021-06-10 15:06:54 +02:00
Sergey G. Brester bbfff18280 action.d/ufw.conf: amend to #3018: parameter kill-mode extended with conntrack 2021-06-03 12:02:08 +02:00
sebres c7a86b4616 action.d/firewallcmd-ipset.conf: amend to #2620:
- combines actions `firewallcmd-ipset` and `firewallcmd-ipset-native` (parameter `ipsettype=firewalld`);
- IPv6-capability for firewalld ipset;
- no internal timeout handling by default;
- no permanent rules yet
2021-05-29 22:59:55 +02:00
Sergey G. Brester 2a508da5a0 Merge pull request #2620 from mspolitaev/master
Using native firewalld ipset implementation
2021-05-29 21:30:55 +02:00
sebres 38535b0cca Merge branch '0.11' into master 2021-05-29 21:25:24 +02:00
sebres d2f5c7de09 Merge branch '0.10' into 0.11 2021-05-29 21:24:11 +02:00
sebres 92f90038fa filter.d/dovecot.conf: extended to match prefix like conn unix:auth-worker (uid=143): auth-worker<13247>: (authenticate from external service like exim), gh-2553 2021-05-29 21:12:34 +02:00
sebres 8b984a0135 filter.d\exim-common.conf: pid-prefix extended to match mx1 exim[...]: (gh-2553) 2021-05-29 20:47:56 +02:00
sebres 6be1a5a0b1 filter.d/dovecot.conf: fixed "Authentication failure" regex, matches "Password mismatch" in title case (gh-2880) 2021-05-29 20:25:28 +02:00
sebres 8afea37494 filter.d/sendmail-auth.conf: covering several "authentication failure" messages, sendmail 8.16.1 (gh-2757) 2021-05-29 20:09:57 +02:00
sebres c5f1598a21 filter.d/postfix.conf: extended to cover new vectors:
- reject: BDAT/DATA from (gh-2927)
- (since regex is more precise now) token selector changed to `[A-Z]{4}`, e. g. no matter what a command is supplied now (RCPT, EHLO, VRFY, DATA, BDAT or something else)
- matches "Command rejected" and "Data command rejected" now
2021-05-29 19:48:24 +02:00
sebres ae3e9b9149 filter.d/postfix.conf: extended to cover 2 new vectors:
- RCPT from unknown, 504 5.5.2, need fully-qualified hostname, gh-2995
- 550 5.7.25 Client host rejected, gh-2996
review combining several regex to single one
2021-05-29 19:21:27 +02:00
sebres 87f717e0e0 filter.d/sendmail-reject.conf: fix reverse DNS for ... (gh-3012) 2021-05-29 18:45:59 +02:00
Sergey G. Brester 3d52fe3e4e Merge pull request #2679 from mikaku/updated-to-latest-jail.conf
Add new jail (and filter) Monitorix
2021-05-27 12:17:16 +02:00
sebres 0a05dbdbfc Merge branch '0.11' into master 2021-05-25 23:19:25 +02:00
sebres 3312b8cb95 Merge branch '0.10' into 0.11 2021-05-25 23:18:33 +02:00
sebres 1627d4f573 filter.d/sendmail-auth.conf: user not found, closes gh-3030 2021-05-25 23:16:29 +02:00
Sergey G. Brester f07e0f7ade Merge pull request #2984 from j-marz/zoneminder_filter_update
Zoneminder filter update
2021-05-21 13:03:33 +02:00
Sergey G. Brester ec4e0dd65b padding with space, prefregex, regex review (simplifying, capture user name, consider possible space char in user name) 2021-05-21 13:00:24 +02:00
j-marz 2367ad115c fixed typo in comment 2021-05-20 09:15:45 +10:00
Ioannis Cherouvim 5e3de882af docs: Typo. (#3025) 2021-05-12 13:18:46 +02:00
Sergey G. Brester 3f9cf27853 filter.d/apache-fakegooglebot.conf: better, more precise regex and datepattern (closes possible weakness like #3013) 2021-05-11 13:47:48 +02:00
usernamepi 4f8427178a Missing comment "#" (#3022)
Missed this ... but the logs showed it.
2021-05-07 18:23:40 +02:00
sebres 6ac2156907 Merge branch '0.11' into master 2021-05-07 01:48:36 +02:00
sebres 3e1aa03037 Merge branch '0.10' into 0.11 2021-05-07 01:46:46 +02:00
sebres ef5c826c74 fixes search for the best datepattern (gh-3020) - e. g. if line is too short, boundaries check for previously known unprecise pattern may fail on incomplete lines (logging break-off, no flush, etc) 2021-05-07 01:18:54 +02:00
sebres 2918849f9e fixes precise year pattern %ExY - accept years 20xx up to current century (using almost the same pattern in tests and production now) 2021-05-07 01:10:26 +02:00
usernamepi 88f779ed24 ufw.conf, amend to #3018 - add missing option for comment (#3019) 2021-05-06 23:23:39 +02:00
Sergey G. Brester 5a8f1bceb8 Merge pull request #3018 from usernamepi/master
Update ufw.conf: several fixes and enhancements
2021-05-06 22:20:39 +02:00
Sergey G. Brester 2958ad8636 Update ChangeLog 2021-05-06 22:19:38 +02:00
Sergey G. Brester 8f6a8df3a4 added new options kill-mode and kill, which makes the drop of all connections optional 2021-05-06 21:47:06 +02:00
Sergey G. Brester 5debaa4cac option "add", can be set to "insert <num>" instead of prepend (customization or backwards compat) 2021-05-06 20:23:58 +02:00
usernamepi e4e7a83cff Update ufw.conf
Prerequisites:
* The ss command is available, kernel is compiled with option CONFIG_INET_DIAG_DESTROY.
* Ufw version is => 0.36 (released in 2018)

* Now using "prepend" instead of "insert" to be able to handle IPv6 addresses correctly. The current action will fail for IPv6 addresses.
* Now application names containing a space should handled correctly, solves https://github.com/fail2ban/fail2ban/pull/1532
* Now closing IPv4 and IPv6 connections (if any) from the ip that is being banned. The current action will leave them open.
   Using ss to accomplish this. For this to work the kernel needs to be compiled with the CONFIG_INET_DIAG_DESTROY option.
   My system apparently is compiled that way.
2021-05-06 13:44:36 +02:00
sebres 71ce548117 Merge branch '0.11' 2021-04-27 14:05:53 +02:00
sebres b5b615731e Merge branch '0.10' into 0.11 2021-04-27 14:03:49 +02:00
sebres 319cfefac2 fix travis build (unsupported pythons and pypy versions), update 3.10 in GH actions 2021-04-27 13:41:57 +02:00
sebres d3f5d2d52b documentation (interpolation tags) 2021-04-21 11:50:07 +02:00
sebres f0214b3d36 filter.d/sendmail-reject.conf: fixed regex to consider "Connection rate limit exceeded" with different combination of arguments 2021-04-20 18:13:40 +02:00
Sergey G. Brester ab0847e2d5 more precise anchored RE (also combining all 3 REs in a single regex) 2021-04-14 13:06:58 +02:00
Jordi Sanfeliu b6fac90b5a Update monitorix 2021-04-14 11:46:23 +02:00
Jordi Sanfeliu 63b3f39adc Rename monitorix-httpd to monitorix 2021-04-14 11:30:48 +02:00
Jordi Sanfeliu 8b741129a5 Create monitorix-httpd 2021-04-14 11:26:52 +02:00
Jordi Sanfeliu 7d173b7ce0 Merge branch 'master' into updated-to-latest-jail.conf 2021-04-13 20:24:08 +02:00
sebres 6893d5a8b7 Merge remote-tracking branch 'remotes/gh-upstream/0.11' into master 2021-04-11 19:05:02 +02:00
Sergey G. Brester d74dd9321b Merge pull request #2565 from caronc/0.11
Add Apprise Support (50+ Notifications)
2021-04-04 00:24:21 +02:00
Sergey G. Brester b2f6a3a658 remove unneeded substitution
it is enough to add `apprise` to action
2021-04-04 00:21:59 +02:00
Sergey G. Brester ff09c52927 Merge pull request #2881 from stepodev/master
`filter.d/nginx-http-auth.conf` - extended with parameter mode, so additionally to `auth` (or `normal`)  mode `fallback` (or combined as `aggressive`) can find SSL errors while SSL handshaking
2021-04-04 00:07:03 +02:00
Sergey G. Brester dda70d60c0 Merge branch 'master' into master 2021-04-04 00:04:08 +02:00
Sergey G. Brester c5d43d7573 Update ChangeLog 2021-04-04 00:00:59 +02:00
Michele Mondelli 7579072e3b docs: fix typos 2021-04-03 23:49:23 +02:00
Sergey G. Brester 4eba9f2a4b Merge pull request #2950 from sunweaver/pr/scanlogd-filter
Add support for filtering out detected port scans via scanlogd.
2021-04-03 23:36:14 +02:00
Sergey G. Brester 2d51240b3e correction for default log interpolation and added allports banaction 2021-04-03 23:33:49 +02:00
Sergey G. Brester 977dfe4bd7 small amend: sport after saddr is optional
format of message: saddr[:sport] to daddr [and others,] ports port[, port...], ..., flags[, TOS TOS][, TTL TTL] @HH:MM:SS
2021-04-03 23:29:16 +02:00
Sergey G. Brester 14edeed310 fixed regex (don't need to match whole line, e. g. every port etc) 2021-04-03 23:24:55 +02:00
Sergey G. Brester 0c4d356d11 added test log-file 2021-04-03 23:10:51 +02:00
Sergey G. Brester 080dd12288 Merge pull request #2965 from oukb/patch-1
nsd.conf: fix for the current log format
2021-04-03 21:02:03 +02:00
Sergey G. Brester a838deba7f restore anchor (e. g. catch all in the middle), dot is optional now, RE rewritten a bit more precise 2021-04-03 21:00:14 +02:00
Sergey G. Brester 1215cb28ac Update nsd 2021-04-03 20:58:26 +02:00
sebres d445b5671d Merge pull request #2642 from rolschewsky/mssql (and amend from sebres/mssql) 2021-04-03 20:28:18 +02:00
sebres 7f38b80d35 precise regex (left anchor and fewer catch-all's); fixed tests (added failJSON and more tests for some corner-cases around new RE) 2021-04-03 20:16:47 +02:00
Rüdiger Olschewsky 9eaa2322b0 Filter and Defaults for Microsoft SQL Server 2021-04-03 19:30:29 +02:00
Markus Felten 5aa20c30d8 fix: add journalmatch to nginx filters 2021-04-03 19:20:50 +02:00
j-marz 5d8f500471 updated formatting to pass tests 2021-03-29 08:36:53 +11:00
j-marz 2686811593 Updated zoneminder filter
Support new log format, ERR instead of WAR. Add detection of non-existent user login attempts
2021-03-28 21:19:10 +11:00
sebres 80a33b1dee Merge branch '0.11' 2021-03-25 12:14:11 +01:00
sebres b259e81911 test-suite: skip testFQDN if no network 2021-03-25 12:13:46 +01:00
sebres d8e450cf12 Merge branch 'fix-readline-multibyte' 2021-03-25 12:13:18 +01:00
sebres 4b17dddc23 update ChangeLog 2021-03-25 12:07:34 +01:00
sebres ccf4f3a07d amend with common log-file iterator in fail2ban-regex and test-suite (in sample regex factory also) 2021-03-25 12:07:31 +01:00
sebres 9659033523 fail2ban-regex: reimplemented log-file iterator - uses FileContainer facilities now instead of direct read from file and decode;
fail2banregextestcase.py extended to cover proper line-ending handling by interim NL char as part of multi-byte encodings (utf-16be, utf-16le)
2021-03-25 12:07:29 +01:00
sebres cbac7c176a readline fixed to consider interim new-line character as part of code point in multi-byte logs (e. g. unicode: utf-16be, utf-16le);
suppress warning "Error decoding line" for incomplete line (produced by not fully read multi-byte new-line character at end of data);
added test coverage for such logs
2021-03-25 12:07:26 +01:00
sebres 6cf4669dee Merge branch '0.10' into 0.11 2021-03-24 14:18:22 +01:00
sebres d135aeea16 fixes restore of original logging withing tests (LogCaptureTestCase.tearDown) - python 3 seemed still to log wordy after tear down (setting of log.level does not restore the level for related log objects - e. g. for logger of fail2ban.jail etc, so fail2ban-testcases '(testVersion|testLongName).*servertest' generating messages in stdout handler in testLongName) 2021-03-24 14:14:47 +01:00
sebres 8757563be1 close fork 2021-03-23 14:20:10 +01:00
sebres 996920cdaa in operation mode the filter reads only complete lines (ended with new-line) now, otherwise it would wait for end of line (for its completion) 2021-03-22 01:17:26 +01:00
sebres 061fab898a Merge branch '0.10' into 0.11 2021-03-22 00:58:03 +01:00
sebres e587526ede tests: add missing constraint (causing incomplete comparison in below cycle if fewer lines as expected was found) 2021-03-22 00:56:40 +01:00
sebres 343ccd7e8a small optimization 2021-03-21 23:35:38 +01:00
sebres 9bdc4be6cc stability: better recognition of rotation (e. g. on hash collision, consider current size and last known position now), no hash of empty file (or not fulfilled line), etc;
performance: avoid unnecessary seek to start of file and hash calculation - now it occurs only if file really rotated (ino changing or size shrinking), otherwise not earlier than in 30 seconds;
avoid unneeded log-rotation in tests
2021-03-21 23:35:09 +01:00
sebres 725354c793 action info extended with new members for jail info (usable as tags in command actions):
`jail.found`, `jail.found_total` - current and total found failures
  `jail.banned`, `jail.banned_total` - current and total bans
closes #10
2021-03-20 22:33:31 +01:00
oukb 529866b2bb nsd.conf: fix for the current log format
New nsd 4.3.5 log format:

|  [2021-03-05 05:25:14.562] nsd[160800]: info: axfr for example.com. from 192.35.168.32 refused, no acl matches
|  [2021-03-06 05:24:33.223] nsd[356033]: info: axfr for localhost. from 192.35.168.160 refused, no acl matches
|  [2021-03-07 05:23:26.641] nsd[547893]: info: axfr for example.com. from 192.35.168.64 refused, no acl matches
|  [2021-03-08 05:18:54.067] nsd[739606]: info: axfr for example.com. from 192.35.168.32 refused, no acl matches
2021-03-08 19:14:28 +03:00
Mike Gabriel f15ed35619 config/: Add support for filtering out detected port scans via scanlogd. 2021-03-05 16:35:13 +01:00
Sergey G. Brester 08393f9d82 Update filter_request.md 2021-03-03 20:28:27 +01:00
sebres df5e024fb8 new issue templates 2021-03-03 20:16:34 +01:00
sebres fb08534ed7 Merge branch '0.11' 2021-03-03 18:17:35 +01:00
sebres 3eaefe8da0 Merge branch '0.10' into 0.11 2021-03-03 18:16:47 +01:00
sebres 04aba6168c fixed typo, -- is not expected in options declaration, so --dump-pretty did never work (only --dp is working) 2021-03-03 13:02:00 +01:00
sebres a45b1c974c filter.d/ignorecommands/apache-fakegooglebot: added timeout parameter (default 55 seconds) - avoid fail with timeout (default 1 minute) by reverse lookup on some slow DNS services (googlebots must be resolved fast);
closes gh-2951
2021-03-02 19:35:27 +01:00
sebres 63acc862b1 action.d/nginx-block-map.conf: reload nginx only if it is running (also avoid error in nginx-errorlog, gh-2949) and better test coverage for the action 2021-02-24 18:21:42 +01:00
sebres fb6315ea5e Merge branch '0.10' into 0.11 2021-02-24 13:16:36 +01:00
sebres 6f4b6ec8cc action.d/badips.* removed (badips.com is no longer active, gh-2889) 2021-02-24 13:05:04 +01:00
sebres e3d43d1241 Merge branch 'fix-rc-on-too-many-failures' into 0.10: resolves RC with uncontrolled growth of failure list (jail with too many matches that did not cause ban, gh-2945) 2021-02-24 12:45:15 +01:00
sebres 92a2242174 amend fixing journal tests (systemd backend only) 2021-02-23 15:54:48 +01:00
sebres e353fb8024 fixed test cases (ban ASAP also followed in test suite now, so failure reached maxretry causes immediate ban now) 2021-02-23 02:46:44 +01:00
sebres 55d7d9e214 *WiP* try to solve RC on jails with too many failures without ban, gh-2945 ... 2021-02-22 18:39:58 +01:00
sebres 884cbbd6e1 Merge branch '0.11' 2021-02-17 19:04:23 +01:00
sebres abc5a4e062 ChangeLog (#2742) 2021-02-17 19:02:22 +01:00
sebres a0352182e8 Merge branch '0.10' into 0.11 2021-02-17 18:57:38 +01:00
sebres 294ec73f62 Merge branch 'py-3-10-alpha-5' into 0.10 2021-02-17 18:49:06 +01:00
Sergey G. Brester 9f1d1f4fbd amend for Mapping (jails) 2021-02-17 18:47:42 +01:00
Sergey G. Brester 42dee38ad2 amend for Mapping 2021-02-17 18:47:40 +01:00
Sergey G. Brester 2b6bb2c1be follow bpo-37324: :ref:collections-abstract-base-classes moved to the :mod:collections.abc module
(since 3.10-alpha.5 `MutableMapping` is missing in collections module)
2021-02-17 18:47:38 +01:00
Sergey G. Brester 8ae9208454 try to provide coverage for 3.10-alpha.5 (#2931) 2021-02-17 18:47:32 +01:00
Sergey G. Brester a2f0dbad87 Merge pull request #2742 from aresxc/patch-1
Update  drupal-auth.conf
2021-02-11 19:10:55 +01:00
Sergey G. Brester f4f92aa72d more tests covering different cases, injections attempt etc 2021-02-11 18:56:53 +01:00
Sergey G. Brester d678440658 more precise RE (avoids weakness with catch-all's and is injection safe) 2021-02-11 18:32:32 +01:00
sebres ea26509594 Merge branch '0.11' 2021-02-03 14:59:00 +01:00
sebres 6198b4566c Merge branch '0.10' into 0.11 2021-02-03 14:47:56 +01:00
sebres 366c64cb9d extractOptions: ensure options are parsed completely - avoids unexpected skip or truncate of parameters, produces more verbose error message in case of incorrect syntax; added more tests covering several cases
WARN: potential incompatibility (since it doesn't silently ignore wrong syntax anymore)
2021-02-03 14:45:30 +01:00
sebres 409348394e Merge pull request #2913
Add transport to asterisk RE
2021-02-03 12:41:29 +01:00
Brian J. Murrell 7f185a828e Update date in failJSON
The date format in failJSON is specific, so convert the date to use that format.
2021-01-31 15:22:16 +01:00
Brian J. Murrell 69c96c00c0 Log entries for updated failregex
Add a sample failregex.

Signed-off-by: Brian J. Murrell <brian@interlinx.bc.ca>
2021-01-31 15:22:16 +01:00
Brian J. Murrell dc4ee5aa47 Add transport to asterisk RE
Call rejection messages from Asterisk can have the transport prefixed to the IP address.

Signed-off-by: Brian J. Murrell <brian@interlinx.bc.ca>
2021-01-31 15:22:16 +01:00
sebres c75748c5d3 fail2ban.conf: added new fail2ban configuration option "allowipv6" (default auto), can be used to allow or disallow IPv6 interface in fail2ban immediately by start (e. g. if fail2ban starts before network interfaces).
closes gh-2804
2021-01-27 17:06:14 +01:00
sebres 3700a9e523 invalidate IP/DNS caches by reload, so inter alia would allow to recognize IPv6IsAllowed immediately, previously retarded up to cache max-time (5m);
closes gh-2804
2021-01-26 20:35:14 +01:00
sebres 21dd317870 Merge branch '0.11' 2021-01-21 19:13:13 +01:00
sebres dbc77c47c3 Merge branch '0.10' into 0.11 2021-01-21 19:11:01 +01:00
sebres 913c37db80 more fixes and optimizations, better RE's for patterns, allow parse date without time with such a datepattern (assume 00:00:00 then), etc 2021-01-21 19:00:56 +01:00
sebres 0f44a3408a amend to 747d468322:
fail2ban-regex: loosen up date patterns %ExY, %Exy - let accept every year from 19xx up to current century (+3 years)
2021-01-21 19:00:53 +01:00
Sergey G. Brester 164105fab1 added new parameter namespace for systemd backend
closes gh-2910
2021-01-16 17:10:12 +01:00
Sergey G. Brester 5f3f4d1e2f action.d/cloudflare.conf: better IPv6 capability
closes gh-2891
2021-01-11 15:23:40 +01:00
sebres 9df332fdef filter.d/apache-overflows.conf: extended to match AH00126 error (Invalid URI ...);
closes gh-2908
2021-01-11 15:10:53 +01:00
Michael Haro 2781e7b9d1 Add blank line so markdown renders correctly 2021-01-09 13:38:33 +01:00
Sergey G. Brester 2d4c3edeb6 Merge pull request #2906 from fail2ban/ci-py-3.10
CI: add python 3.10 (alpha) to github actions
2021-01-06 14:45:11 +01:00
Sergey G. Brester c9907bef0d CI: 3.10.0-alpha.4 2021-01-06 14:37:34 +01:00
Sergey G. Brester 097d9ea7fe try wildcard (3.10 is still alpha) 2021-01-06 14:36:09 +01:00
Sergey G. Brester 3c8aa0e6ba amend with correct yaml notation (float vs string) 2021-01-06 14:34:08 +01:00
Sergey G. Brester 0a7f5b7b5c CI: add python 3.10 to github actions 2021-01-06 14:29:18 +01:00
sebres e60b10392d Merge branch '0.11' into master 2021-01-04 02:50:33 +01:00
sebres f259dac747 Merge branch '0.10' into 0.11 2021-01-04 02:48:49 +01:00
sebres 747d468322 fixes century selector of %ExY and %Exy in datepattern for tests, considering interval from 2005 (alternate now) to now; + better grouping algorithm for resulting century RE 2021-01-04 02:45:16 +01:00
sebres 2c60d08b28 Merge '0.11' (fix gh-2899) into master 2020-12-29 21:27:02 +01:00
sebres fe334590cd Merge branch '0.10' into 0.11 2020-12-29 21:25:09 +01:00
sebres 73b39e0894 filter.d/named-refused.conf: fixes prefix for messages from systemd journal (no mandatory space ahead, because don't have timestamp)
closes gh-2899
2020-12-29 21:22:47 +01:00
Sergey G. Brester 6b5cc2dee8 Merge pull request #2898 from defanor/postscreen-pregreet-hangup
Handle postscreen's PREGREET and HANGUP messages in ddos and aggressive mode
2020-12-29 13:21:47 +01:00
defanor ba7daef86c Handle postscreen's PREGREET and HANGUP messages
Provoking those seems to be a popular activity among spammers.
2020-12-24 17:29:09 +03:00
Tim Gates 3bb19ecc9d docs: fix simple typo, litle -> little
There is a small typo in fail2ban/client/fail2banclient.py, fail2ban/server/observer.py.

Should read `little` rather than `litle`.
2020-12-23 12:59:03 +01:00
sebres 7d256681a4 Merge branch '0.11' into master 2020-12-22 20:41:41 +01:00
sebres 567039f261 Merge branch '0.10' into 0.11 2020-12-22 20:40:52 +01:00
sebres 27e435a7f5 fix cymru test cases 2020-12-22 20:36:01 +01:00
stepodev cecc3d62ff add mode explanation to nginx-http-auth in jail.conf 2020-11-30 12:26:32 +01:00
stepodev d0ba27cf46 move nginx-tls-fallback rules to nginx-http-auth 2020-11-30 12:14:49 +01:00
Sergey G. Brester d959f6d199 Update nginx-tls-fallback.conf
more precise and conclusive regex without catch-all's
2020-11-26 12:25:32 +01:00
stepodev c0256724a7 fix monitoring wrong error log. was access log, should be error.log 2020-11-25 21:30:21 +01:00
stepodev 27c40a77a3 add nginx-tls-downgrade 2020-11-25 20:59:43 +01:00
sebres b8e8a87ee9 small amend to 0f27a8add8 - datedetector, strptime: token %Z recognizes all known zone abbreviation besides Z, GMT, UTC correctly, if it is matching (%z remains unchanged for backwards-compatibility, see comment in code); test cases fixed (PDT zone will be found now). 2020-11-24 20:23:39 +01:00
sebres 0f27a8add8 datedetector, strptime: token %Z must recognize zone abbreviation Z (GMT/UTC) also, similar to %z;
more test cases added.
2020-11-24 19:28:46 +01:00
sebres a03109d096 Merge branch '0.11' into master (0.11.2 released) 2020-11-24 12:41:10 +01:00
sebres eea1881b73 release 0.11.2 -- heal-the-world-with-security-tools
CI / build (2.7) (push) Canceled after 0s
CI / build (3.5) (push) Canceled after 0s
CI / build (pypy2) (push) Canceled after 0s
CI / build (3.6) (push) Canceled after 0s
CI / build (3.7) (push) Canceled after 0s
CI / build (3.8) (push) Canceled after 0s
CI / build (3.9) (push) Canceled after 0s
CI / build (pypy3) (push) Canceled after 0s
2020-11-23 21:43:03 +01:00
sebres b78d1e439a Merge branch '0.10' into 0.11 2020-11-23 21:35:32 +01:00
sebres e768f8637a release 0.10.6 -- just what the doctor ordered
CI / build (2.7) (push) Canceled after 0s
CI / build (3.5) (push) Canceled after 0s
CI / build (3.6) (push) Canceled after 0s
CI / build (3.7) (push) Canceled after 0s
CI / build (3.8) (push) Canceled after 0s
CI / build (3.9) (push) Canceled after 0s
CI / build (pypy2) (push) Canceled after 0s
CI / build (pypy3) (push) Canceled after 0s
2020-11-23 19:37:26 +01:00
sebres 79b61e009a ChangeLog 2020-11-23 19:18:35 +01:00
Sergey G. Brester 753fff9c15 amend to #2750, add jail for new filter nginx-bad-request 2020-11-23 18:38:41 +01:00
Sergey G. Brester 071048b8f2 Merge pull request #2750 from janprzy/master
Added filter nginx-bad-request
2020-11-23 18:28:07 +01:00
sebres 7965d652a1 filter.d/dovecot.conf: allow more verbose logging
closes #2573
2020-11-23 18:17:29 +01:00
sebres a6de9459fc typo 2020-11-23 18:08:38 +01:00
RyuaNerin bba8844af8 typo 2020-11-23 18:07:49 +01:00
sebres 31a4a27ee3 better assert message in sample regex factory 2020-11-23 18:06:13 +01:00
Sergey G. Brester fe716743ed Merge pull request #2795 from mateusz834/managesieve-dovecot
add managesieve and submission support in dovecot filter
2020-11-23 17:50:16 +01:00
sebres 8672950c15 added test cases covering PR #2795 2020-11-23 17:47:47 +01:00
mpoliwczak834 595ee7ed74 add submission 2020-11-23 17:42:12 +01:00
mpoliwczak834 0c12cb7970 add managesieve support dovecot filter 2020-11-23 17:42:11 +01:00
sebres cc64ef25f6 filter.d/apache-noscript.conf: extended to match "script not found" with error AH02811 (and cgi-bin path segment in script)
closes gh-2805
2020-11-23 17:25:41 +01:00
sebres 5d0e74d2ab man/jail.conf.5: documentation extended (prefregex, etc)
closes gh-2820
2020-11-23 16:55:55 +01:00
sebres d04c6c13ed merge point 2020-11-23 15:02:05 +01:00
sebres a107a8e7d2 setup.py: cherry-pick from 0.11 (option --without-tests) 2020-11-23 14:59:45 +01:00
sebres 1cefb7fdc6 setup.py: small amend to d2d3762ba9: allow build without tests also (both build and install accepting --without-tests option now) 2020-11-23 14:45:24 +01:00
sebres f5ea40c7da Merge branch '0.11' into master 2020-11-11 11:19:05 +01:00
sebres adbfdc222d Merge branch '0.10' into 0.11 2020-11-11 11:17:15 +01:00
sebres ca4da9d1d3 actions: extend tags replacement in non ticket-based commands (actionstart, actionstop, etc);
fixes regression by interpolation of tag `<bantime>` introduced in 0.11 with dynamic bantime (due to `bantime.increment`, see #2869)
2020-11-11 11:08:23 +01:00
Sergey G. Brester 9c8dcbd6eb Merge pull request #2855 from benrubson/grafana
Add Grafana jail
2020-11-10 15:12:46 +01:00
Sergey G. Brester 1c1a9b868c no catch-alls, user name and error message stored in ticket 2020-11-09 15:36:30 +01:00
benrubson 840f0ff10a Add Grafana jail 2020-11-09 15:31:06 +01:00
Sergey G. Brester 267cbf5861 Merge pull request #2778 from Mart124/bitwarden
Add Bitwarden syslog support
2020-11-09 13:47:04 +01:00
sebres 25e006e137 review and small tweaks (more precise and safe RE) 2020-11-09 13:43:59 +01:00
Mart124 2a18b82f5f Support alternative Bitwarden log format 2020-11-09 13:34:41 +01:00
Mart124 df659a0cbc Add Bitwarden syslog support 2020-11-09 13:34:39 +01:00
Sergey G. Brester 472bdc437b Merge pull request #2723 from benrubson/softether
Add SoftEtherVPN jail
2020-11-09 13:23:25 +01:00
Sergey G. Brester 010e76406f small tweaks (both 2nd time and facility are optional, avoid catch-all, etc) 2020-11-09 13:19:25 +01:00
sebres 9f635c66fb Merge branch '0.11' into master 2020-11-09 12:45:54 +01:00
sebres 66ff90408f Merge branch '0.10' into 0.11 2020-11-09 12:45:29 +01:00
sebres d4adec7797 Merge branch '0.9' into 0.10 2020-11-09 12:44:07 +01:00
sebres 5430091acb jail counter-strike: removed link to site with redirect to malicious page (gh-2868) 2020-11-09 12:43:34 +01:00
benrubson ec873e2dc3 Add SoftEtherVPN jail 2020-11-05 23:56:30 +01:00
sebres e700ccc667 filter apache-modsecurity: added coverage for different log-format (apache 2.4 and php-fpm, gh-2717) 2020-11-05 16:51:49 +01:00
sebres 690ad20958 Merge branch '0.11' into master 2020-11-05 16:16:17 +01:00
sebres 6ef69b48ca Merge branch '0.10' into 0.11 2020-11-05 16:12:31 +01:00
sebres 55d6408b13 tweaks to speedup test-cases (test-suite seems to be time stable now, so we could shorten sleeping intervals) 2020-11-05 15:31:11 +01:00
sebres 7f0010be68 attempt to install systemd-python module 2020-11-05 14:12:39 +01:00
Sergey G. Brester 7cb6412f68 1st try of GH actions flow (CI only, no coverage atm) 2020-11-05 14:12:37 +01:00
Sergey G. Brester 9d77fb2b4c 1st try of GH actions flow (CI only, no coverage atm) 2020-11-03 15:38:06 +01:00
Sergey G. Brester a07e6fe1a2 reduce default maxmatches from 50 to 5: avoid too large memory consumption if maxretry is large and many failures don't cause ban (but accumulated in fail-manager with all the matched lines);
closes gh-2843
2020-10-30 14:17:47 +01:00
sebres 02525d7b6f filter.d/sshd.conf: mode ddos (and aggressive) extended with new rule closing flood attack vector, matching:
error: kex_exchange_identification: Connection closed by remote host
(gh-2850)
2020-10-08 21:07:51 +02:00
sebres c8059bf9b3 ban/unban: increase responsiveness of actions thread by (un)banning process, better waiting timeout considering pending tickets for unban (_nextUnbanTime) 2020-09-29 16:27:17 +02:00
sebres 2817a8144c action.d/bsd-ipfw.conf: small amend (gh-2836) simplifying awk condition/code (position starts from <lowest_rule_num> and increases whilst used) 2020-09-29 13:33:40 +02:00
sebres 1418bcdf5b action.d/bsd-ipfw.conf: fixed selection of rule-no by large list or initial lowest_rule_num, exit code can't be larger than 255 (gh-2836) 2020-09-29 12:35:49 +02:00
sebres 960e30cfcd Merge branch '0.11' 2020-09-23 19:41:04 +02:00
sebres d253e60a8b Merge branch '0.10' into 0.11 2020-09-23 19:39:50 +02:00
sebres 24093de32d small amend (simplifying formatted help and man) 2020-09-23 19:35:17 +02:00
Nathan Henrie f518d42c59 Add a note about journalflags options to systemd-journal backend
Also adds systemd backend configuration examples to jail.conf(5)

Closes #2696
2020-09-23 19:09:42 +02:00
sebres 4c2539856c Merge branch 'speedup-client-status' into 0.10 2020-09-23 13:03:45 +02:00
Sergey G. Brester d977d81ef7 action.d/abuseipdb.conf: removed broken link, simplified usage example, fixed typos 2020-09-17 12:39:08 +02:00
sebres f381b98246 introduces new flavor short for fail2ban-client status $jail short: output total and current counts only, without banned IPs list in order to speedup it and to provide more clear output (gh-2819), flavor basic (still default) is unmodified for backwards compatibility;
it can be changed later to `short`, so for full list of IPs in newer version one should better use:
  - `fail2ban-client status $jail basic`
  - `fail2ban-client get $jail banned` or `fail2ban-client banned`
2020-09-10 11:53:26 +02:00
sebres e8ee3ba544 resolves a bottleneck within transmitting of large data between server and client: speedup search of communications end-marker and increase max buffer size (up to 32KB) 2020-09-10 11:52:25 +02:00
sebres 5abc4ba4ae amend to 39d4bb3c35 (#2758): better reaction on broken pipe (on long output), don't close stdout explicitly (allows usage of modules like cProfile, which outputs result on exit), just flush it before exit. 2020-09-09 17:32:10 +02:00
sebres f555ff45e9 attempt to speedup ban- and fail-manager (e. g. fail2ban-client status, see gh-2819), remove unneeded lock (GIL is enough here) 2020-09-07 19:08:52 +02:00
sebres 74b73bce8a Merge branch '0.10' into 0.11 2020-09-04 13:09:47 +02:00
sebres a038fd5dfe action.d/firewallcmd-*.conf (multiport only): fixed port range selector, replacing : with -;
small optimizations on `firewallcmd-rich-rules.conf` and `firewallcmd-rich-logging.conf` simplifying both and provide a dependency (rich-logging is a derivative of rich-rules);
closes gh-2821
2020-09-03 16:41:23 +02:00
Sergey G. Brester 70c601e9e5 involve config parameter (replaces hard-coded path); fixed typo in actionban (looks like copy&paste from trimmed tty) 2020-09-02 20:47:05 +02:00
sebres 4d2734dd86 Merge branch '0.10' into 0.11 2020-09-02 20:23:07 +02:00
sebres ed20d457b2 jail.conf: removed action parameter name that set on jail-name (name=%(__name__)s is default in action reader) 2020-09-02 20:14:31 +02:00
sebres f09ba1b399 action in jail-config extended to consider space as separator now (splitWithOptions separates by space between mains words, but not in options), so defining action = a b would specify 2 actions a and b;
it is additionally more precise now (see fixed typo with closed bracket `]` instead of comma in testServerReloadTest)
2020-09-02 20:09:06 +02:00
sebres a3a148078e fail2ban-regex: more informative output for datepattern (e. g. set from filter) - pattern : description, example:
Use      datepattern : ^%Y-%m-%d %H:%M:%S : ^Year-Month-Day 24hour:Minute:Second
2020-08-28 14:12:57 +02:00
sebres 17a6ba44b3 fail2ban-regex: speedup formatted output (bypass unneeded stats creation);
fail2ban-regex: extended with prefregex statistic
2020-08-28 13:52:09 +02:00
sebres db1f3477cc amend to 3f04cba9f9: sendmail-auth has 2 failregex now, so rewritten with prefregex 2020-08-27 18:07:42 +02:00
sebres 3f04cba9f9 filter sendmail-auth extended to follow new authentication failure message introduced in sendmail 8.16.1, AUTH_FAIL_LOG_USER (gh-2757) 2020-08-27 17:44:25 +02:00
sebres 07fa9f2912 fixes gh-2787: allow to match did not issue MAIL/EXPN/VRFY/ETRN during connection non-anchored with extra mode (default names may deviate);
additionally provides common addr-tag for IPv4/IPv6 (`(?:IPv6:<IP6>|<IP4>)`) and test-coverage for IPv6
2020-08-27 17:04:19 +02:00
sebres d0d1f8c362 improve result for get/set prefregex 2020-08-26 16:54:18 +02:00
sebres 8bc7623388 Merge branch '0.11' 2020-08-26 13:49:41 +02:00
sebres be3115cda0 fix year overflow (9999) by format of datetime (time2str for end of ban of persistent ticket);
closes gh-2817
2020-08-26 13:31:29 +02:00
sebres b2036c1d62 Merge branch '0.10' into 0.11 2020-08-26 12:22:17 +02:00
sebres e569281d6b avoids overwrite of known/option with unmodified (not available) value of option from .local config file,
so it wouldn't cause self-recursion if `option` already has a reference to `known/option` (from some include) in .conf file;
closes gh-2751
2020-08-26 12:08:04 +02:00
sebres 5a2cc4e1c5 substituteRecursiveTags: more precise self- or cyclic-recursion prevention (don't clear replacement counts of tags, rather consider replacement count by tax X in tag Y) 2020-08-26 12:05:20 +02:00
sebres e9071b642a Merge branch '0.10' into 0.11 2020-08-25 18:28:18 +02:00
Sergey G. Brester 81fb28e146 Merge pull request #2631 from benrubson/guacamole
`filter.d/guacamole.conf` extended with `logging` parameter to follow webapp-logging if it's configured
2020-08-25 18:27:18 +02:00
sebres 2945fe8cbd changelog 2020-08-25 18:25:32 +02:00
sebres d9b8796792 amend with better (common) handling, documentation and tests 2020-08-25 18:01:34 +02:00
sebres 7b05c1ce7a do type-convert only in getCombined (otherwise int/bool conversion prevents substitution or section-related interpolation of tags) 2020-08-25 14:52:22 +02:00
benrubson 1707560df8 Enhance Guacamole jail 2020-08-25 13:01:50 +02:00
sebres 41b88b4f4f Merge branch '0.10' into 0.11 2020-08-24 16:42:19 +02:00
TorontoMedia 1e3da21c68 Remove duplicate method and rename invalid parameter
(cherry picked from commit fd25c4cbb8)
2020-08-24 16:41:55 +02:00
sebres ad51fb7e1e partial cherry-pick fd25c4cbb8 (#2768) 2020-08-24 16:41:22 +02:00
Sergey G. Brester 57caf8ec90 Merge pull request #2768 from TorontoMedia/patch
Remove duplicate method and rename invalid parameter
2020-08-24 16:39:25 +02:00
sebres 7327fee2c8 Merge branch '0.11' 2020-08-24 16:33:30 +02:00
sebres 4bc8bc9d5f Merge branch '0.10' into 0.11 2020-08-24 16:31:48 +02:00
Sergey G. Brester 8da663a67e Merge pull request #2814 from sebres/0.10-date-opt
extended datepattern handling (TZ issues, no datepattern, etc)
2020-08-24 16:27:35 +02:00
sebres 295630cccf documentation and changelog 2020-08-24 16:12:55 +02:00
sebres 76e5d2b199 amend to f21c58dc72, better follow previous handling with last known datetime (compatibility for multi-line logs, in case of second line without a timestamp) 2020-08-21 17:53:02 +02:00
sebres f21c58dc72 implements special datepattern {NONE} - allow to find failures without date-time in log messages (filter use now as timestamp)
closes gh-2802
2020-08-20 20:28:29 +02:00
sebres b82f584a96 added test case covering new date handling (simulation, unknown format, warnings, etc) 2020-08-20 19:46:41 +02:00
sebres d2cef96f33 filter: implement mode inOperation, which gets activated if filter starts processing of new messages; better interaction with non-matching optional datepattern or invalid timestamps (or timezone) - assuming now instead of bypass;
fixed test cases gathering new failures now in operation mode
2020-08-20 18:52:00 +02:00
sebres 7e8d98c4ed code review, fix simplest TZ issue - avoid date adjustment by assuming of last year (date without year in the future) by wrong zone (don't adjust by offset up to +24 hours) 2020-08-13 19:20:27 +02:00
sebres 3ca69c8c0a amend to #2791: unban subnet when subnet is in supplied subnet 2020-08-11 17:14:21 +02:00
sebres 7d172faa50 implements gh-2791: fail2ban-client extended to unban IP range(s) by subnet (CIDR/mask) or hostname (DNS) 2020-08-11 16:01:52 +02:00
sebres 39d4bb3c35 closes gh-2758: no explicit flush (close std-channels on exit, it would cause implicit flush without to produce an error 32 "Broken pipe" on closed pipe) 2020-08-11 13:57:36 +02:00
sebres a7ad3e00dd amend to 91eca4fdeb (#2634): server creates a RTM-directory for socket/pid file automatically (don't check its existence in client) 2020-08-11 11:58:02 +02:00
Chris Caron 2216fd8da4 Add Apprise Support (50+ Notifications) 2020-08-04 19:04:05 -04:00
sebres 1ea36c3045 Merge branch '0.11' 2020-08-04 17:19:51 +02:00
sebres 9d076af9a2 Merge branch '0.11-combine-multiple-captures' into 0.11 2020-08-04 17:15:28 +02:00
sebres 98983adf76 update ChangeLog 2020-08-04 17:14:13 +02:00
sebres 067b76fc9e Merge branch '0.10' into 0.11 2020-08-04 15:40:59 +02:00
sebres 253d47d33c compat: some 2.x pypy versions produce UnicodeEncodeError: 'ascii' codec can't encode character on surrogates (uni_string must be fixed also for UTF-8 system encoding) 2020-08-04 15:08:02 +02:00
sebres 9510346507 typo in skip message 2020-08-04 14:31:11 +02:00
sebres 0ef8f6675d fix travis builds (pipy in xenial, don't error if doc missing in default path after install) 2020-08-04 14:25:31 +02:00
sebres 9100d07c03 Merge branch '0.10-ipset-tout' into 0.10, amend to #2703: resolves names conflict (command action timeout and ipset timeout); closes #2790 2020-08-04 13:53:21 +02:00
sebres 62a6771b33 Merge remote-tracking branch 'sebres:0.10' into 0.10; closes gh-2763
action.d/nftables.conf (type=multiport only): fixed port range selector (replacing `:` with `-`)
2020-08-04 13:51:20 +02:00
sebres 73a8175bb0 resolves names conflict (command action timeout and ipset timeout); closes gh-2790 2020-08-04 13:22:02 +02:00
Sergey G. Brester ea35f2ad75 default loglevel is INFO 2020-07-03 13:47:46 +02:00
Sergey G. Brester 08dbe4abd5 fixed comment for loglevel, default is INFO 2020-07-03 13:45:29 +02:00
TorontoMedia fd25c4cbb8 Remove duplicate method and rename invalid parameter 2020-06-28 12:58:41 -04:00
sebres 309c8dddd7 action.d/nftables.conf (type=multiport only): fixed port range selector (replacing : with -) 2020-06-24 19:20:36 +02:00
Jan Przybylak 56fefe9240 Added test file "nginx-bad-request"
I tested with `./fail2ban-testcases testSampleRegex`, which did not return any errors.
2020-06-21 18:25:27 +02:00
Jan Przybylak a5ab4406d8 Removed unnecessary escape sequence
This commit also contains changes to match requests that are 100% empty (by using "*" instead of "+" in the regex)
2020-06-21 18:24:09 +02:00
sebres ec3000798d ensure that set of alternate tags or combine tuple tags take place ordered (sort the lists by its name or index) 2020-06-12 21:25:42 +02:00
sebres dd8081ade5 extends capturing alternate tags in filter, implementing new tag prefix <F-TUPLE_ (that would combine value of <F-V> with all value of <F-TUPLE_V?_n?> tags), for examples see new tests in fail2banregextestcase;
closes gh-2755 (extends #1454 and #1698).
2020-06-12 20:00:42 +02:00
Jan Przybylak d7ef5d166d Removed vulnerable catchall & anchor 2020-06-11 16:44:48 +02:00
sebres 78fc99ec7e Merge branch '0.11' 2020-06-11 12:52:34 +02:00
sebres 1da9ab78be Merge branch '0.10' into 0.11 2020-06-11 12:52:13 +02:00
sebres 5a0edf61c9 filter.d/sshd.conf: normalizing of user pattern in all RE's, allowing empty user (gh-2749) 2020-06-08 14:38:26 +02:00
Jan Przybylak 3c83c19070 Added filter nginx-bad-request 2020-06-06 19:51:46 +02:00
aresdr 412120ac3c Update drupal-auth.conf
Small fix for Drupal 8. D8 uses "Login attempt failed from" while D7 uses "Login attempt failed for".
The referer part is a must currently, but some requests did not have one and are not failing.
2020-05-30 15:25:31 -07:00
sebres 9b6da03c90 amend to e786dbf132: removes space between name and [pid] by normal non-verbose logging, padding without truncate now; test coverage for getVerbosityFormat;
closes #2734
2020-05-26 13:14:37 +02:00
sebres 6cff2bb007 Merge branch '0.11' 2020-05-25 19:09:29 +02:00
sebres 1588200274 Merge branch '0.10' into 0.11 2020-05-25 18:58:05 +02:00
sebres b8e2b77265 Merge branch '0.10-extend-proto-banned' into 0.10 2020-05-25 15:04:12 +02:00
sebres fa1ff4c5d8 assertSortedEqual: fixed sort of nested lists, switch default of nestedOnly to False (comparison of unsorted lists is rarely needed) 2020-05-25 14:45:24 +02:00
sebres 54b2208690 extends protocol/client with banned status (retrieve information whether an IP is banned and/or in which jails), implements FR gh-2725 2020-05-20 16:31:54 +02:00
sebres 0ae2ef68be ensure iterator is safe (traverse over the list in snapshot created within a lock), avoids getting modified state as well as "dictionary changed size during iteration" errors 2020-05-20 15:36:06 +02:00
sebres afb7a93163 amend to 368aa9e775: fix time in gitlab test (GMT in log due to TZ-suffix Z, CEST in test-suite) 2020-05-20 15:27:48 +02:00
Sergey G. Brester 43f699b872 grammar / typos 2020-05-06 17:32:13 +02:00
Sergey G. Brester 368aa9e775 Merge pull request #2689 from benrubson/gitlab
New Gitlab jail
2020-05-04 19:19:13 +02:00
Sergey G. Brester f2aec43d8a Merge pull request #2140 from szepeviktor/patch-9
CloudFlare started to indent their API responses
2020-04-27 19:39:27 +02:00
Sergey G. Brester 42aef09d69 Update ChangeLog 2020-04-27 19:38:48 +02:00
Sergey G. Brester 01e92ce4a6 added fallback using tr and sed (jq is optional now) 2020-04-27 19:26:46 +02:00
Sergey G. Brester 1c1b671c74 Update cloudflare.conf 2020-04-27 19:26:44 +02:00
Sergey G. Brester 5b8fc3b51a cloudflare: fixes ip to id conversion by unban using jq
normalized URIs and parameters, notes gets a jail-name (should be possible to differentiate the same IP across several jails)
2020-04-27 19:26:43 +02:00
Viktor Szépe 852670bc99 CloudFlare started to indent their API responses
We need to use https://github.com/stedolan/jq to parse it.
2020-04-27 19:26:39 +02:00
Ilya 8b3b9addd1 Change tool from 'cut' to 'sed'
Sed regex was tested - it works.
2020-04-27 19:12:36 +02:00
Ilya 5da2422f61 Fix actionunban
Add command to remove new line character. Needed for working removing rule from cloudflare firewall.
2020-04-27 19:12:35 +02:00
Sergey G. Brester fe84b158a5 Merge pull request #2703 from sebres/0.10-ipset-tout
0.10 / ipset timeout removal
2020-04-26 12:39:37 +02:00
Sergey G. Brester da1652d0d7 Update ChangeLog 2020-04-26 12:26:55 +02:00
sebres 12be3ed77d test cases fixed 2020-04-25 15:17:42 +02:00
sebres 87a1a2f1a1 action.d/*-ipset*.conf: several ipset actions fixed (no timeout per default anymore), so no discrepancy between ipset and fail2ban (removal from ipset will be managed by fail2ban only) 2020-04-25 14:52:38 +02:00
sebres 6b90ca820f filter.d/traefik-auth.conf: filter extended with parameter mode (normal, ddos, aggressive) to handle the match of username differently:
- `normal`: matches 401 with supplied username only
  - `ddos`: matches 401 without supplied username only
  - `aggressive`: matches 401 and any variant (with and without username)
closes gh-2693
2020-04-23 13:08:24 +02:00
sebres affd9cef5f filter.d/courier-smtp.conf: prefregex extended to consider port in log-message (closes gh-2697) 2020-04-21 13:32:17 +02:00
sebres 06b46e92eb jail.conf: don't specify action directly in jails (use action_ or banaction instead);
no mails-action added per default anymore (e. g. to allow that `action = %(action_mw)s` should be specified per jail or in default section in jail.local), closes gh-2357;
ensure we've unique action name per jail (also if parameter `actname` is not set but name deviates from standard name, gh-2686);
don't use %(banaction)s interpolation because it can be complex value (containing `[...]`), so would bother the action interpolation.
2020-04-15 19:00:49 +02:00
sebres 7e3061e7ac fail2ban.service systemd unit template: don't add user site directory to python system path (avoids accessing of /root/.local directory, prevents SE linux audit warning at daemon startup, gh-2688) 2020-04-15 17:35:04 +02:00
Sergey G. Brester 78651de7e5 Update ChangeLog 2020-04-14 12:25:18 +02:00
benrubson 2912bc640b New Gitlab jail 2020-04-09 16:42:08 +02:00
sebres 136781d627 filter.d/sshd.conf: fixed regex for mode extra - "No authentication methods available" (supported seems to be optional now, gh-2682) 2020-04-08 12:17:59 +02:00
sebres d21a24de8e more test cases for IP/DNS (and use dummies if no-network set by testing) 2020-04-06 12:39:36 +02:00
sebres fc175fa78a performance: optimize simplest case whether the ignoreip is a single IP (not subnet/dns) - uses a set instead of list (holds single IPs and subnets/dns in different lists);
decrease log level for ignored duplicates (warning is too heavy here)
2020-04-06 12:12:23 +02:00
Jordi Sanfeliu ede2009708 added new jail (and filter) Monitorix 2020-04-03 12:52:19 +02:00
sebres 343ec1cdd2 test-causes: avoid host-depending issue (mistakenly ignoring IP 127.0.0.2 as own address) - replace loop-back addr with test sub-net addr (and disable ignoreself) 2020-03-18 20:40:31 +01:00
sebres 38b32a9a72 Merge branch '0.10' into 0.11 2020-03-18 19:53:55 +01:00
sebres 22a04dae05 Merge branch '0.9' into 0.10 (gh-2246) 2020-03-18 16:11:53 +01:00
Sergey G. Brester b1e1cab4b7 Merge pull request #2246 from shaneforsythe/shaneforsythe-patch-2
Improve regex in proftpd.conf
2020-03-18 15:49:18 +01:00
sebres 606bf110c9 filter.d/sshd.conf (mode ddos): fixed "connection reset" regex (seems to have same syntax now as closed), so both regex's combined now to single RE
(closes gh-2662)
2020-03-16 17:31:39 +01:00
sebres 6e570b8644 Merge branch '0.11' 2020-03-13 23:23:32 +01:00
sebres 5b16973f08 Merge branch '0.10' into 0.11 2020-03-13 23:23:03 +01:00
sebres 8547ea7ea0 resolve sporadic minor issue - check pending can refresh watcher (monitor) that gets deleting, and there may be no wdInt to delete 2020-03-13 23:16:04 +01:00
sebres 9905904bba Merge branch '0.11' 2020-03-13 22:43:22 +01:00
sebres 00c5d33e45 Merge branch '0.10' into 0.11 2020-03-13 22:39:19 +01:00
sebres b64a435b0e ignore only not banned old (repeated and ignored) tickets 2020-03-13 22:34:15 +01:00
sebres b43dc147b5 amend to RC-fix 9f1c6f1617 (gh-2660):
resolves bottleneck by initial scanning of a lot of messages (or evildoers generating many messages) causes repeated ban, that will be ignored but could cause entering of "long" sleep in actions thread previously;
speedup recognition banning queue has entries to begin check-ban process in actions thread
2020-03-13 22:22:42 +01:00
sebres bc2b81133c pyinotify backend: guarantees initial scanning of log-file by start (retarded via pending event if filter not yet active) 2020-03-13 22:07:32 +01:00
sebres 68f827e1f3 small optimization for manually (via client / protocol) signaled attempt (performBan only if maxretry gets reached) 2020-03-13 18:03:27 +01:00
sebres 4c22d4a801 Merge branch '0.11' 2020-03-13 17:47:03 +01:00
sebres d42ec210cc Merge branch '0.10' into 0.11 2020-03-13 17:44:29 +01:00
sebres 9f1c6f1617 filter stability fix: prevent race condition - no ban if filter (backend) is continuously busy if too many messages will be found in log, e. g. initial scan of large log-file or journal (gh-2660) 2020-03-13 17:34:37 +01:00
sebres ab363a2c0e small amend with fix still one test (ban unexpected in this old artificial test-cases, todo - such tests should be rewritten or removed) 2020-03-13 17:28:33 +01:00
sebres e3737bb7c0 filter stability fix: prevent race condition - no ban if filter (backend) is continuously busy if too many messages will be found in log, e. g. initial scan of large log-file or journal (gh-2660) 2020-03-13 17:20:19 +01:00
Sergey G. Brester 428c75d1cd Merge pull request #2651 from fail2ban/0.10-travis-3.9-dev
python 3.9 compatibility + CI
2020-03-06 20:46:02 +01:00
Sergey G. Brester d4da9afd7f Update ChangeLog 2020-03-06 20:29:48 +01:00
Sergey G. Brester 9d7388e684 Thread: is_alive instead of isAlive (removed in py-3.9) 2020-03-06 20:04:18 +01:00
Sergey G. Brester 55e76c0b80 restore isAlive method removed in python 3.9 2020-03-06 19:41:16 +01:00
Sergey G. Brester 781a25512b travis CI: add 3.9-dev as target 2020-03-06 19:04:39 +01:00
sebres 8b43d54878 Merge branch '0.11' 2020-03-05 14:32:42 +01:00
sebres 32f02ef3b3 Merge branch '0.10' into 0.11 2020-03-05 14:01:14 +01:00
sebres 42714d0849 filter.d/common.conf: closes gh-2650, avoid substitute of default values in related lt_* section, __prefix_line should be interpolated in definition section (after the config considers all sections that can overwrite it);
amend to 62b1712d22 (PR #2387, backend-related option `logtype`);
testSampleRegexsZZZ-GENERIC-EXAMPLE covering now negative case also (other daemon in prefix line)
2020-03-05 13:47:11 +01:00
sebres 2ddf687c31 Merge branch '0.10' into 0.11 - test cases only (add ban to database was moved to observer in 0.11) 2020-03-02 19:17:16 +01:00
sebres 15158e4474 closes gh-2647: add ban to database is moved from jail.putFailTicket to actions.__CheckBan; be sure manual ban is written to database, so can be restored by restart; reload/restart test extended 2020-03-02 18:58:59 +01:00
sebres f088e7bf76 Merge branch '0.10' into 0.11 2020-03-02 17:10:48 +01:00
sebres 6281dc3633 failmanager, ticket: avoid reset of retry count by pause between attempts near to findTime - adjust time of ticket will now change current attempts considering findTime as an estimation from rate by previous known interval (if it exceeds the findTime);
this should avoid some false positives as well as provide more safe handling around `maxretry/findtime` relation especially on busy circumstances.
2020-03-02 17:05:00 +01:00
sebres 4766547e1f performance optimization of datepattern (better search algorithm);
datetemplate: improved anchor detection for capturing groups `(^...)`; introduced new prefix `{UNB}` for `datepattern` to disable word boundaries in regex;
datedetector: speedup special case if only one template is defined (every match wins - no collision, no sorting, no other best match possible)
2020-02-28 14:27:21 +01:00
sebres ef1eaf9b37 Merge branch '0.11' 2020-02-25 17:18:50 +01:00
sebres c15c300d2a Merge branch '0.10' into 0.11 2020-02-25 17:11:29 +01:00
sebres e6ca04ca9d Merge branch '0.10' into 0.11 + version bump (back to dev) 2020-02-25 16:10:31 +01:00
Sergey G. Brester 2e42b98cd3 Merge pull request #2638 from gurnec/pypy-ulimit-fix
close Popen() pipes explicitly for PyPy
2020-02-25 15:31:31 +01:00
sebres 6c6cf2a956 small amend (avoid possible error by close of not existing pipe) 2020-02-25 15:06:04 +01:00
Christopher Gurnee df885586d4 close Popen() pipes explicitly for PyPy
Waiting for garbage collection to close pipes opened by Popen() can
lead to "Too many open files" errors with PyPy; close them explicitly.
2020-02-25 14:55:10 +01:00
sebres e57e950ef5 version bump (back to dev) 2020-02-25 14:51:54 +01:00
sebres ab3a7fc6d2 filter.d/sshd.conf: mode ddos (and aggressive) extended to detect port scanner sending unexpected ident string after connect 2020-02-17 16:24:42 +01:00
sebres 35591db3e8 Merge branch '0.11' 2020-02-14 12:14:51 +01:00
sebres 7282cf91b0 Merge branch '0.10' into 0.11 2020-02-14 12:13:29 +01:00
sebres b3644ad413 code normalization and optimization (strip of trailing new-line, date parsing, ignoreregex mechanism, etc) 2020-02-13 21:52:54 +01:00
sebres 91eca4fdeb automatically create not-existing path (last level folder only) for pidfile, socket and database (with default permissions) 2020-02-13 13:50:17 +01:00
sebres 14e68eed72 performance: set fetch handler getGroups depending on presence of alternate tags in RE (simplest variant or merged with alt-tags) in regex constructor 2020-02-13 12:31:15 +01:00
sebres 9137c7bb23 filter processing:
- avoid duplicates in "matches" (previously always added matches of pending failures to every next real failure, or nofail-helper recognized IP, now first failure only);
  - several optimizations of merge mechanism (multi-line parsing);
fail2ban-regex: better output handling, extended with tag substitution (ex.: `-o 'fail <ip>, user <F-USER>: <msg>'`); consider a string containing new-line as multi-line log-excerpt (not as a single log-line)
filter.d/sshd.conf: introduced parameter `publickey` (allowing change behavior of "Failed publickey" failures):
  - `nofail` (default) - consider failed publickey (legitimate users) as no failure (helper to get IP and user-name only)
  - `invalid` - consider failed publickey for invalid users only;
  - `any` - consider failed publickey for valid users too;
  - `ignore` - ignore "Failed publickey ..." failures (don't consider failed publickey at all)
tests/samplestestcase.py: SampleRegexsFactory gets new failJSON option `constraint` to allow ignore of some tests depending on filter name, options and test parameters
2020-02-13 12:28:07 +01:00
sebres 1492ab2247 improve processing of pending failures (lines without ID/IP) - fail2ban-regex would show those in matched lines now (as well as increase count of matched RE);
avoid overwrite of data with empty tags by ticket constructed from multi-line failures;
amend to d1b7e2b5fb: better output (as well as ignoring of pending lines) using `--out msg`;
filter.d/sshd.conf: don't forget mlf-cache on "disconnecting: too many authentication failures" - message does not have IP (must be followed by "closed [preauth]" to obtain host-IP).
2020-02-11 18:44:36 +01:00
Sergey G. Brester ac8e8db814 travis: switch 3.8-dev to 3.8 (released) 2020-02-11 14:18:58 +01:00
Sergey G. Brester d7643fe538 Merge pull request #2630 from fail2ban/gh-2200-postfix
filter.d/postfix.conf: extended mode ddos and aggressive covering multiple disconnects without auth
2020-02-11 12:44:21 +01:00
Sergey G. Brester 88cf5bcd93 Update postfix 2020-02-10 13:41:28 +01:00
Sergey G. Brester 774dda6105 filter.d/postfix.conf: extended mode ddos and aggressive covering multiple disconnects without auth 2020-02-10 13:29:16 +01:00
Sergey G. Brester 34d63fccfe close gh-2629 - jail.conf (action_blocklist_de interpolation): replace service parameter (use jail name instead of filter, which can be empty) 2020-02-10 13:03:55 +01:00
sebres 65ce64ba6d Merge branch '0.11' 2020-02-07 13:57:00 +01:00
sebres 01333fc3e2 Merge branch '0.10' into 0.11 2020-02-07 13:55:20 +01:00
sebres 7a28861fc7 review of command line: more long-named options can be supplied via command line 2020-02-07 13:52:45 +01:00
sebres 3f48907064 amend to f3dbc9dda1: change main thread-name back to fail2ban-server;
implements new command line option `--pname` to specify it by start of server (default `fail2ban-server`);
closes gh-2623 (revert change of main thread-name, because it can affect process-name too, so `pgrep` & co. may be confused)
2020-02-07 11:08:01 +01:00
sebres 9c7bd80807 fail2ban-regex: stop endless logging on closed streams (redirected pipes like ... | head -n 100), exit if stdout channel is closed 2020-02-03 20:09:13 +01:00
Mihail Politaev 303861d7c7 Using native firewalld ipset implementation
By creating additional action file firewallcmd-ipset-native.conf
2020-01-30 21:17:32 +02:00
sebres ccbc0c7405 Merge branch '0.11' 2020-01-30 10:23:14 +01:00
sebres a7c68ea19f Merge branch '0.10' into 0.11 2020-01-28 21:47:55 +01:00
sebres 12b3ac684a closes #2615: systemd backend would seek to last known position (or now - findtime) in journal at start. 2020-01-28 21:45:30 +01:00
sebres cd42cb26d6 database: try to fix out of sequence error on some old platform / sqlite versions (#2613) - repack iterator as long as in lock (although dirty read has no matter here and only writing operations should be serialized, but to be sure and exclude this as source of that errors). 2020-01-27 12:57:29 +01:00
sebres 569dea2b19 filter.d/mysqld-auth.conf: capture user name in filter (can be more strict if user switched, used in action or fail2ban-regex output);
also add coverage for mariadb 10.4 log format (gh-2611)
2020-01-22 17:24:40 +01:00
sebres 9e6d07d928 testSampleRegexsFactory: time is not mandatory anymore (check time only if set in json), allows usage of same line(s) matching different logtype option:
`# filterOptions: [{"logtype": "file"}, {"logtype": "short"}, {"logtype": "journal"}]`
2020-01-22 17:19:35 +01:00
sebres 3befbb1770 improved wait for observer stop on server quit (second stop would force quit), this also cause reset db in observer (to avoid out of sequence errors) before database gets ultimately closed at end of server stop process (gh-2608) 2020-01-20 16:45:01 +01:00
sebres 7f1b578af4 Merge branch 'gh-488-check-on-error' 2020-01-16 16:52:44 +01:00
sebres 8cbc1e0ebb ChangeLog (change actioncheck behavior) 2020-01-16 16:51:57 +01:00
sebres 546fff8dc0 Merge branch '0.11' 2020-01-16 16:25:20 +01:00
Sergey G. Brester d2d3762ba9 Merge pull request #2605 from angeloc/0.11
Fixing --withouth-test install option
2020-01-16 13:45:49 +01:00
Angelo Compagnucci 5fa1f69264 setup.py: adding option to install without tests
Tests files are not always needed especially when installing on low
resource systems like an embedded one.
This patch adds the --without-tests option to skip installing the
tests files.

Signed-off-by: Angelo Compagnucci <angelo@amarulasolutions.com>
2020-01-16 12:28:42 +01:00
Angelo Compagnucci 3965d690b1 Revert "setup.py: adding option to install without tests"
Test should actually removed from the stup data in finalize_options
instead of being added back.

This reverts commit 9b918bba2f.

Signed-off-by: Angelo Compagnucci <angelo@amarulasolutions.com>
2020-01-16 12:05:13 +01:00
sebres 50fbcda8b6 Merge branch '0.10' into 0.11 2020-01-15 21:54:37 +01:00
sebres 8dc6f30cdd closes #2596: fixed supplying of backend-related logtype to the jail filter - don't merge it (provide as init parameter if not set in definition section), init parameters don't affect config-cache (better implementation as in #2387 and it covered now with new test) 2020-01-15 21:49:51 +01:00
sebres ed4b5b8bdc change actioncheck behavior (on error only, gh-488) 2020-01-15 14:54:31 +01:00
sebres 94b64055e1 Merge branch '0.11' 2020-01-15 14:53:28 +01:00
sebres 9f701bb611 Merge branch '0.10' into 0.11 2020-01-15 13:26:46 +01:00
sebres 05f9e53660 Merge branch '0.10-invariant-improve' into 0.10 2020-01-15 13:26:15 +01:00
sebres d4c921c22a amend to 31b8d91ba2: tag <family> is normally dynamic tag (ticket related), so better to replace it this way (may avoid confusing if tag is used directly during restore sane env process for both families); conditional replacement is not affected here 2020-01-15 13:22:55 +01:00
Sergey G. Brester 3f5c382a98 readme: amend to bump version (v.1.0.1 is master now) 2020-01-14 20:55:24 +01:00
sebres bb0f732ae6 version bump (master is 1.0.x-dev now) 2020-01-14 20:38:26 +01:00
sebres 8694c54728 increase test stack size to 128K (on some platforms min size is greater then 32K), closes gh-2597 2020-01-14 11:51:27 +01:00
sebres 70e47c9621 Merge branch '0.10' into 0.11 2020-01-14 11:44:35 +01:00
sebres ec37b1942c action.d/nginx-block-map.conf: fixed backslash substitution (different echo behavior in some shells, gh-2596) 2020-01-14 11:39:13 +01:00
sebres 31a6c8cf5d closes gh-2599: fixes splitwords for unicode string 2020-01-13 20:12:16 +01:00
sebres b158f83aa3 testIPAddr_CompareDNS: add missing network constraint (gh-2596) 2020-01-13 12:37:19 +01:00
sebres d004a2c79b release 0.11.1 -- This is the Way 2020-01-11 11:01:00 +01:00
sebres 27fb4790fb Merge branch '0.10' into 0.11 2020-01-10 15:17:54 +01:00
sebres 4860d69909 Merge branch '0.10' into 0.11 2020-01-09 20:55:00 +01:00
sebres ac41b8f3be some logging level got changed between 0.10/0.11 (9 is lowest log level to capture messages in LogCaptureTestCase now) 2020-01-08 21:43:27 +01:00
sebres 587e4ff573 Merge branch '0.10' into 0.11
(conflicts resolved)
2020-01-08 21:27:23 +01:00
sebres 5dd85bf4f8 Merge branch '0.10' into 0.11 2019-12-12 21:45:50 +01:00
sebres b2e8d610a0 small amend: adjust name of observer thread (more similar to other threads) 2019-12-12 21:31:26 +01:00
sebres 1bcb39c699 Merge branch '0.10' into 0.11 2019-12-12 21:29:13 +01:00
sebres 24d1ea9aa2 Merge branch '0.10' into 0.11 2019-11-25 01:58:55 +01:00
sebres 3515d06979 Merge branch '0.10' into 0.11 2019-10-18 19:19:21 +02:00
sebres 0824ad0d73 Merge branch '0.10' into 0.11 2019-10-18 12:04:38 +02:00
sebres 8c6a547215 Merge branch '0.10' into 0.11 2019-10-11 03:01:46 +02:00
sebres f51712d275 Merge branch '0.10' into 0.11 2019-09-11 19:41:30 +02:00
sebres 990c410877 Merge branch '0.10' into 0.11
# Conflicts (resolved):
#	fail2ban/client/jailreader.py
2019-09-11 16:18:09 +02:00
sebres 822f8adb6a Merge branch '0.10' into 0.11 2019-08-22 21:33:58 +02:00
sebres 6b7825b8c8 closes gh-2506: don't increase attempt count if bantime.increment is not enabled for the jail 2019-08-22 14:11:08 +02:00
sebres 15734a923b Merge branch '0.10' into 0.11 2019-07-29 14:25:19 +02:00
sebres 1cdd618232 Merge branch '0.10' into 0.11 2019-07-29 13:26:37 +02:00
sebres 5d5253dd70 Merge branch '0.10' into 0.11 2019-07-29 13:25:49 +02:00
sebres 581f13c2db Merge branch '0.10' into 0.11 2019-07-22 19:07:15 +02:00
sebres 0a209f01c2 Merge branch '0.10' into 0.11 2019-07-11 13:28:47 +02:00
sebres af611db859 Merge branch '0.10' into 0.11 2019-07-10 12:47:03 +02:00
sebres 439f97fc52 Merge branch '0.10' into 0.11 2019-07-09 20:07:59 +02:00
sebres 80f97eaf02 Merge branch '0.10' into 0.11 2019-06-26 17:29:08 +02:00
sebres 5045c4bb00 Merge branch '0.10' into 0.11 2019-06-12 16:28:57 +02:00
sebres 2e7a600851 Merge branch '0.10' into 0.11 2019-06-12 11:44:05 +02:00
sebres 686a8bdc54 Merge branch '0.10' into 0.11 2019-06-12 00:13:39 +02:00
sebres 03b2b79c41 Merge branch '0.10' into 0.11 2019-06-11 15:51:10 +02:00
sebres 0ed3a63151 Merge branch '0.10' into 0.11 2019-06-07 16:29:38 +02:00
sebres 3d4044084a Merge branch '0.10' into 0.11 2019-06-07 14:48:10 +02:00
sebres 759f7274f8 Merge branch '0.10' into 0.11 2019-06-05 12:28:44 +02:00
sebres ca49f2c71c actions: provide <bantime> as integer value (for actions expecting timeout parameters) 2019-05-28 10:12:24 +02:00
sebres c024c93ec6 fix sporadic test error (avoid purge timer-event execution in the middle of test) 2019-05-28 09:54:54 +02:00
sebres 7c7dfab8db fixed missing return value (attempts) in addFailure in case of observed/banned tickets (could cause error '>=' not supported between instances of 'NoneType' and 'int' with python 3.x, gh-2432) 2019-05-28 09:21:55 +02:00
sebres f48677db7d Merge branch '0.10' into 0.11 2019-05-24 16:18:32 +02:00
sebres 5137cd2ec8 Merge branch '0.10' into 0.11 2019-05-14 21:40:50 +02:00
sebres 939f0d43e0 amend for 3036ed1889: resolve deprecated syntax (eliminate "invalid sequence" warnings) 2019-05-14 20:42:05 +02:00
sebres f69a8693fc Merge branch '0.10' into 0.11 2019-05-14 20:19:29 +02:00
sebres ca85ddc866 Merge branch '0.10' into 0.11 2019-05-10 16:23:50 +02:00
sebres 74eac6c94f Merge branch '0.10' into 0.11 2019-05-02 15:28:44 +02:00
sebres 633b179b19 Merge branch '0.10' into 0.11 2019-04-26 13:35:43 +02:00
sebres c47bb523b7 Merge branch '0.10' into 0.11 2019-04-24 21:58:27 +02:00
sebres f0c5bd56f4 Merge branch '0.10' into 0.11 (conflicts resolved) 2019-04-19 13:20:38 +02:00
sebres 337be4b36c Merge remote-tracking branch 'remotes/gh-upstream/0.10' into 0.11 2019-04-18 13:47:44 +02:00
sebres 1e59d53bbe fixed typo 2019-03-27 13:48:53 +01:00
sebres 17a4f81e23 Merge branch '0.10' into 0.11 2019-03-27 13:46:56 +01:00
sebres 7f0bba94ba Merge pull request #2174 from eli-schwartz/0.11 (rebased) 2019-03-13 13:35:48 +01:00
sebres 4e2c7b9fdd Merge branch '0.10' into 0.11 2019-03-12 17:01:03 +01:00
sebres 324f0ed7cc Merge branch '0.10' into 0.11 2019-03-01 12:36:07 +01:00
sebres a3b7a0525a Merge branch '0.10' into 0.11 2019-02-22 13:22:52 +01:00
sebres e046b09c8a coverage for get ban --with-time 2019-02-21 17:56:31 +01:00
sebres e44cd671b2 Merge branch '0.10' into 0.11 (conflicts resolved, tests fixed) 2019-02-21 17:29:04 +01:00
sebres 4a829cb51b Merge branch '0.10' into 0.11 2019-02-18 17:19:33 +01:00
Yaroslav Halchenko 31e6ec3c5b Merge pull request #2323 from todgru/fix-spelling-abuseipdb-conf
fix: correct spelling category
2019-02-15 17:08:45 -05:00
sebres 1647d0090e Merge branch '0.10' into 0.11 2019-02-11 19:19:44 +01:00
todgru 39ed016a1e fix: correct spelling category 2019-01-14 22:08:38 -08:00
sebres d88ce7181c Merge branch '0.10' into 0.11 2019-01-07 01:51:59 +01:00
Sergey G. Brester 53684af0e3 Merge pull request #2315 from psvi/ban_list
New command `fail2ban-client get <JAIL> banip`
2019-01-07 01:11:28 +01:00
sebres 59688d7cd5 move helper to test, normalize invocations in order to emphasize assert comparison. 2019-01-07 00:05:27 +01:00
sebres 963e14c685 resolve sporadic timing errors (unban if ban still not occurred, resp. get list of IPs if not yet banned);
simplify helper procedure for testJailBanList.
2019-01-06 23:49:05 +01:00
sebres 4b934c784d normalized time to string calls. 2019-01-06 23:33:28 +01:00
sebres f959f58e15 extend protocol (command-line) and regenerate man's 2019-01-06 22:45:48 +01:00
sebres df97fd33cf ip-list is sorted now (by end of ban) per default;
extended with new option `--with-time` to provide more pretty and informative result (separated by new-line, including time strings: time of ban + ban-time = end of ban):
  192.0.2.1    2019-01-06 22:24:48 + 300 = 2019-01-06 22:29:48
  192.0.2.2    2019-01-06 22:24:48 + 600 = 2019-01-06 22:34:48
also it is possible now to provide separator-character as extra-parameter after `get <jail> banip ?sep-char?` (default is space).
removed unneeded test-cases (test code-base minimization) and unexpected manually changed files.
2019-01-06 22:31:23 +01:00
SP 7f5f7017db ENH: added new test cases for fail2ban-client get <JAIL> banip command (gh-1916) 2019-01-04 18:00:38 +03:00
SP 3d477d229d ENH: added new command fail2ban-client get <JAIL> banip to get the banned ip addresses (gh-1916) 2019-01-03 23:55:35 +03:00
sebres 966fa1be89 Merge branch '0.10' into 0.11 2018-12-27 20:09:15 +01:00
sebres 2010dda6fa Merge branch '0.10' into 0.11 2018-12-19 12:20:10 +01:00
Sergey G. Brester cadcc69bc0 minor amend for better readability 2018-12-17 18:42:28 +01:00
Sergey G. Brester 3fa54559e5 Update ChangeLog 2018-12-17 18:39:31 +01:00
Sergey G. Brester f87a43487e Merge pull request #2287 from angeloc/0.11
setup.py: adding option `--without-tests` to skip building and
installing of tests files
2018-12-17 18:37:08 +01:00
Sergey G. Brester 3b8842e618 Merge pull request #2284 from jedie/patch-1
Add link to https://fail2ban.readthedocs.io in README
2018-11-26 13:12:52 +01:00
Sergey G. Brester c4c713ca6e Update README.md 2018-11-26 13:10:30 +01:00
Angelo Compagnucci 9b918bba2f setup.py: adding option to install without tests
Tests files are not always needed especially when installing on low
resource systems like an embedded one.
This patch adds the --without-tests option to skip building and
installing of tests files.

Signed-off-by: Angelo Compagnucci <angelo@amarulasolutions.com>
2018-11-26 08:47:36 +01:00
Jens Diemer 52f6bfc2df Add link to https://fail2ban.readthedocs.io in README 2018-11-23 15:47:37 +01:00
sebres b49c1ab4b3 Merge branch '0.10' into 0.11 2018-11-21 13:06:44 +01:00
sebres d518868691 Merge branch '0.10' into 0.11 2018-10-09 22:13:43 +02:00
sebres f9f7e29295 Merge branch '0.10' into 0.11 (version bump after r.0.10.4) 2018-10-04 13:08:25 +02:00
Shane Forsythe 8614ca8c41 Update proftpd.conf
proftpd 1.3.5e can leave inconsistent error message if ftp or mod_sftp is used

Oct  2 15:45:31 ftp01 proftpd[5516]: 10.10.2.13 (10.10.2.189[10.10.2.189]) - SECURITY VIOLATION: Root login attempted
Oct  2 15:45:44 ftp01 proftpd[5517]: 10.10.2.13 (10.10.2.189[10.10.2.189]) - SECURITY VIOLATION: Root login attempted.

Fix regex to make trailing period optional, otherwise brute force attacks against root account using ftp are not blocked correctly.
2018-10-02 17:24:33 -04:00
sebres a462966cf6 Merge branch '0.10' into 0.11 2018-09-27 13:13:28 +02:00
sebres 6b52f90ad6 Merge branch '0.10' into 0.11 2018-09-21 15:54:16 +02:00
sebres 8a0c06ba9e Merge branch '0.10' into 0.11 2018-09-14 11:01:40 +02:00
sebres 714fd8c915 Merge branch '0.10' into 0.11 2018-08-14 16:01:00 +02:00
sebres addd26ae55 Merge branch '0.10' into 0.11 2018-08-14 11:13:15 +02:00
sebres 606761b3c7 Merge branch '0.10' into 0.11 2018-08-03 12:06:13 +02:00
sebres eb1156b099 Merge branch '0.10' into 0.11 2018-07-18 15:57:39 +02:00
sebres 6a81cc9d8c Merge branch '0.10' into 0.11 2018-07-17 15:18:44 +02:00
sebres 4c18a04439 Merge branch '0.10' into 0.11 2018-07-11 13:22:48 +02:00
sebres d65d7fd4d0 Merge branch '0.10' into 0.11 2018-07-10 20:04:48 +02:00
sebres 57f2d9e31c Merge branch '0.10' into 0.11 2018-07-06 18:06:54 +02:00
sebres 6e40cb12ab fix ban-time correction of restored tickets, could be set to persistent (-1) if increment allowed and no maxtime was specified. 2018-07-06 15:53:42 +02:00
sebres 9de1657aab Merge branch '0.10' into 0.11 2018-07-06 11:43:56 +02:00
sebres 7c0ac467bb getCurrentBans: ignore tickets with the ban-time changed after correction (if other max ban-time of jail as in the database) 2018-07-05 13:54:37 +02:00
sebres 76cb1c64ce Merge branch '0.10-fix-decoding-issues' into 0.11 2018-07-04 20:47:34 +02:00
Sergey G. Brester ddff67acb3 Update README.md
removed travis-test refernce to 0.9th branch
2018-06-28 14:17:18 +02:00
sebres 1aebd55f26 Merge branch '0.10' into 0.11 2018-06-14 15:57:59 +02:00
sebres 0eaa0ecd86 Merge branch '0.10' into 0.11 2018-06-14 12:36:22 +02:00
sebres 9fdc6e0e82 Merge branch '0.10' into 0.11 2018-06-11 14:36:35 +02:00
sebres 47d3a1213c Merge branch '0.10' into 0.11 2018-05-28 19:15:18 +02:00
Sergey G. Brester f5f5423cc9 Merge pull request #2138 from glaslos/patch-1
replacing badly scaling png badges with svg
2018-05-24 14:15:34 +02:00
Lukas Rist c256bfc02e replacing badly scaling png badges with svg 2018-05-22 13:13:39 +02:00
sebres 7a3932efc0 amend for 1b4ba602ba: use common bool-converter 2018-04-26 16:52:40 +02:00
sebres 532cb35aa8 Merge branch '0.10' into 0.11 2018-04-26 16:48:37 +02:00
sebres eba8bd4faa Merge branch '0.10' into 0.11 2018-04-26 16:24:53 +02:00
sebres 0d40dd42b1 Merge branch '0.10' into 0.11 2018-04-26 13:43:15 +02:00
sebres a92f25b48e Merge branch '0.10' into 0.11 2018-04-09 14:44:52 +02:00
sebres 0707695146 Merge branch '0.10' into 0.11, version bump
# Conflicts resolved:
#	fail2ban/server/database.py
2018-04-05 12:58:11 +02:00
sebres 70d099bbd6 Merge branch '0.10' into 0.11 2018-04-04 18:59:44 +02:00
sebres aac6398517 Merge branch '0.10' into 0.11 2018-04-04 18:02:05 +02:00
sebres 1fdad90b4d Merge branch '0.10' into 0.11 2018-04-04 16:49:57 +02:00
sebres f877980da9 Merge branch '0.10' into 0.11 2018-04-04 15:55:59 +02:00
sebres 7dfd61f462 Merge branch '0.10' into 0.11-2 2018-04-03 14:14:44 +02:00
Sergey G. Brester 02114ea073 Merge pull request #1912 from alxnorden/patch-1
Update README.md with clarifications
2018-03-22 11:10:06 +01:00
Sergey G. Brester 1b8840d333 Update README.md 2018-03-22 11:09:49 +01:00
Sergey G. Brester 8796c3b27e Merge pull request #2093 from ravage84/patch-1
Improve wording
2018-03-22 11:02:50 +01:00
Marc Würth 077f58b228 Improve wording 2018-03-21 17:53:05 +01:00
sebres ccb1daf30a Merge branch '0.10' into 0.11 2018-03-02 21:42:07 +01:00
sebres 2b282ead09 Merge branch '0.10' into 0.11 2018-03-02 19:48:15 +01:00
sebres 5ea76789c6 Merge branch '0.10' into 0.11 2018-03-02 17:18:37 +01:00
sebres 47a7f83a0b Merge branch '0.10' into 0.11 2018-02-26 19:30:54 +01:00
sebres a5155f55e7 Merge branch '0.10' into 0.11 2018-02-21 09:31:35 +01:00
sebres 730e760666 Merge branch '0.10' into 0.11 2018-02-06 18:19:50 +01:00
sebres 5c2fba0398 Merge branch '0.10' into 0.11 2018-02-01 19:41:26 +01:00
sebres 201ae0dac2 Merge branch '0.10' into 0.11 2018-01-31 12:20:34 +01:00
sebres 4942578de0 Merge branch '0.10' into 0.11 2018-01-24 20:36:22 +01:00
sebres faab77cc79 Merge branch '0.10' into 0.11, with resolved conflicts. 2018-01-24 17:56:58 +01:00
sebres 077a45cc93 Merge branch '0.11-fix-get-current-bans-v2' into 0.11 2018-01-23 09:42:11 +01:00
sebres 7526f50706 amend to a54b401ee2 (0.11-fix-get-current-bans):
- differentiate between unknown ban-time after upgrade (-2) and persistent ban-time (-1);
- better handling to correct current ban-time, uses `bantime.maxtime` (if increment allowed) or `bantime` of jail;
- extended test-cases in order to cover the change of `bantime.maxtime`.
2018-01-23 09:41:43 +01:00
sebres 7e1bc59f80 code review after merge (removed unnecessary code-pieces resp. code-duplication) 2018-01-22 11:10:22 +01:00
sebres 05951a23a5 Merge branch '0.10' into 0.11 2018-01-22 11:08:25 +01:00
Sergey G. Brester 757ff8a7d4 Merge pull request #2022 from sebres/0.11-fix-get-current-bans
0.11: fix get current bans (after upgrade DB)
2018-01-22 10:00:57 +01:00
sebres 9440956575 Update ChangeLog 2018-01-19 19:37:37 +01:00
sebres a54b401ee2 upgrade database: update new created bips table with entries from table bans (allows restore current bans after upgrade from version <= 0.10);
algorithm of restore current bans after restart changed: update the restored ban-time (and therefore end of ban) of the ticket with ban-time of jail (as maximum), for all tickets with ban-time greater (or persistent); not affected if ban-time of the jail is unchanged between stop/start.
2018-01-19 19:35:31 +01:00
sebres 0a4a76c4c4 Merge branch '0.10' into 0.11 2018-01-19 12:32:48 +01:00
sebres c50875ccf6 Update ChangeLog: all major 0.11 changes combined in 0.11th block now 2018-01-19 11:41:54 +01:00
sebres aa47937d4f Merge branch '0.10' into 0.11: bum version after release of 0.10.2 2018-01-18 16:47:13 +01:00
sebres 1ca3df877b Merge branch '0.10' into 0.11 2018-01-18 14:32:00 +01:00
sebres 38b3290516 Merge branch '0.10' into 0.11 2018-01-17 16:43:45 +01:00
sebres 576eeb70dd Merge branch '0.10' into 0.11 2018-01-15 18:17:18 +01:00
sebres 416240e80e Merge branch '0.10' into 0.11 2018-01-15 17:21:23 +01:00
sebres 0befbfd766 Merge branch '0.10' into 0.11 2018-01-11 20:23:55 +01:00
sebres 5ddab17089 Merge branch '0.10' into 0.11 2018-01-11 13:28:31 +01:00
sebres da86ebca31 Merge branch '0.10' into 0.11 2018-01-11 11:21:02 +01:00
sebres 039ac7c7c4 Merge branch '0.10' into 0.11 2018-01-11 10:29:46 +01:00
sebres 0e68c9a720 Merge branch '0.10' into 0.11 2018-01-10 12:22:31 +01:00
sebres a83a6c38e4 Merge branch '0.10' into 0.11
# Conflicts:
#	fail2ban/server/database.py
2018-01-09 12:25:30 +01:00
Serg G. Brester 2deb356356 Update observer.py
Change log-level to debug for purge-event message
2018-01-08 10:14:50 +01:00
sebres 19c2d24c29 merge point 2017-12-22 17:22:11 +01:00
sebres 5028f17f64 Merge branch '0.10' into 0.11, rewrite updateDb because it can be executed after repair, and some tables can be missing.
# Conflicts:
#	fail2ban/server/database.py
#	fail2ban/tests/fail2banclienttestcase.py
#	fail2ban/tests/sockettestcase.py
2017-12-22 17:05:45 +01:00
sebres 309a1cb337 restore timeout for ipset-based actions: on some systems ipset created without default timeout may cause "Kernel error received: Unknown error -1" (gh-1994);
thus new option `default-timeout` introduced (because of dynamical bantime in 0.10, it cannot be used here).
2017-12-06 02:38:10 +01:00
sebres 2179db3692 Merge branch '0.10' into 0.11 2017-12-06 01:41:29 +01:00
sebres 7e5d8f37fd Merge branch '0.10' into 0.11
# Conflicts:
#	config/action.d/firewallcmd-ipset.conf
#	fail2ban/server/jail.py
#	fail2ban/tests/servertestcase.py
2017-12-06 00:14:23 +01:00
sebres cc153888d5 Merge branch '0.10' into 0.11 2017-12-01 15:55:10 +01:00
sebres 5cc0abbb02 Merge branch '0.10' into 0.11
# Conflicts:
#	fail2ban/tests/fail2banclienttestcase.py
2017-11-28 16:37:51 +01:00
sebres 12b55bb8cc Merge remote-tracking branch '0.10' into 0.11 2017-11-27 12:02:46 +01:00
sebres 95f29f457a Merge branch '0.10' into 0.11 2017-11-24 13:45:43 +01:00
sebres 8aeaaf06ee Merge branch '0.10' into 0.11 2017-11-23 22:57:21 +01:00
sebres 70b933f405 Merge branch '0.10' into 0.11 2017-11-06 18:57:53 +01:00
sebres 12419b75f2 Merge branch '0.10' into 0.11
# Conflicts:
#	fail2ban/tests/servertestcase.py
2017-10-30 14:02:41 +01:00
sebres a99513a43e version bump (0.11.0.dev0) after merge 0.10 2017-10-18 19:05:20 +02:00
sebres 76f5e3659e Merge branch '0.10' into 0.11 2017-10-18 19:03:08 +02:00
Alex 8175a53826 Update README.md with clarifications
+ Added new user clarification for installing from source with git clone.
? Right now it is not clear where the  fail2ban-0.11.0.tar.bz2 is available for download.
+ Added command for checking fail2ban version.
2017-10-10 23:15:56 +02:00
sebres 93634dd822 Merge branch '0.10' into 0.11 2017-10-04 14:25:02 +02:00
sebres 6c1d481135 Merge branch '0.10' into 0.11 2017-10-04 09:57:43 +02:00
sebres 037a0be3ae Merge branch '0.10' into 0.11 2017-10-02 15:43:55 +02:00
sebres e0fede621e Merge branch '0.10' into 0.11 2017-09-08 11:33:19 +02:00
sebres 32058ed268 Merge remote-tracking branch 'remotes/gh-upstream/0.10' into 0.11 2017-09-01 10:37:52 +02:00
sebres b80692f602 Merge branch '0.10' into 0.11 2017-08-18 15:44:43 +02:00
sebres 9dc9477e71 Merge branch '0.10' into 0.11 (pull request gh-1868) 2017-08-18 14:03:40 +02:00
sebres eca63ab32a No functional changes, just merge point for "PR #1867 cherry picked into 0.10". 2017-08-18 13:33:25 +02:00
Serg G. Brester 579d2477f5 Merge pull request #1867 from distler/0.11
Tweaks to action.d/pf.conf: introduced parameter `block` with default `block quick`
2017-08-17 17:34:05 +02:00
Jacques Distler d646d06e91 Tweaks to action.d/pf.conf
Document recent changes.
Add an option to customize the pf block rule (surely, what the user
really wants, here, is "block quick").
2017-08-17 09:13:32 -05:00
sebres fdcd847f4a Merge branch '0.10' into 0.11 2017-08-16 21:26:00 +02:00
sebres 870a33247b Merge branch '0.10' into 0.11 2017-08-16 20:54:53 +02:00
sebres aa140f0fa7 Merge branch 0.10 to 0.11, restores merge-point after rebased PR gh-1866 (mistakenly created and merged on 0.11th base); 2017-08-16 17:58:52 +02:00
Serg G. Brester 7c01a9c7b9 Merge pull request #1866 from koeppea/patch-1
Update pf.conf fixing #1863: erroneous flush of all rulesets, also not created with fail2ban.
2017-08-16 17:49:30 +02:00
sebres 3f83b22de2 action.d/pf.conf: anchored call arguments combined as <pfctl> parameter;
test cases fixed;
2017-08-16 11:58:39 +02:00
Alexander Köppe 55baf93635 Update pf.conf fixing #1863
Fix #1863
Introduce own PF anchors for fail2ban rules.
2017-08-16 11:33:45 +02:00
sebres 099e35103f Merge branch '0.10' into 0.11 2017-08-14 18:31:52 +02:00
Serg G. Brester 409de18a65 Update README.md
0.11: CI stats, etc.
2017-08-10 15:45:50 +02:00
Serg G. Brester b5dd5adb08 Merge pull request #1460 from sebres/0.10-full
0.11 ban-time-incr
2017-08-10 15:23:18 +02:00
sebres 1c06a8b1ef 0.11 - prepared new development edition: README.md, ChangeLog, version.py 2017-08-10 15:19:43 +02:00
sebres d2c39d2e45 Merge branch '0.10' into 0.10-full
# Conflicts:
#	fail2ban/server/database.py - resolved and test-case with persistent ban-time fixed/extended (bantime presents in database)
2017-06-16 09:35:27 +02:00
sebres 8403eab2c4 Merge branch '0.10-incr-dynamic-bantime' into 0.10-full 2017-05-17 21:30:20 +02:00
sebres 17a03ebc11 changelog update / typos fixed 2017-05-17 21:03:35 +02:00
sebres 1842f30359 [ticket] remove unneeded code - ticket will be just wrapped from FailTicket to BanTicket;
normalize increment of ban-count or time (count increased in BanManager now, some dual increments fixed in the test-cases);
introduced new action-tag `<bancount>`, that is always incremented by each ban (starting by 1), opposite to tag `<bantime>` which can be prolonged retarded (up to 10 seconds)
2017-05-17 19:54:52 +02:00
sebres 157a85451a [tickets] use slots in ticket (saves memory, and have better performance); uses the same ticket between Fail- and BanManagers, so makes possible operate with more actual data between workers (e. g. ban count and time by increment from observer) 2017-05-17 17:58:26 +02:00
sebres b893356c49 avoid sporadic errors on time-related test-cases: observer can prolong ticket (increase ban-time) before banning, so blocked before banFound called, to test prolong case. 2017-05-17 15:40:24 +02:00
sebres c21b4e4d56 [ban-time-incr] prolong ban, dynamic bantime, etc.:
- dynamic bantime: introduces new action-tag `<bantime>` corresponds to the current ban-time of the ticket;
  Note: because it is dynamic, it should be normally removed from `jail.conf` (resp. `jail.local`).
- introduced new action command `actionprolong`, used for prolongation of the timeout (ban-time of the ticket);
- removed default `timeout` from `actionstart` of several actions;
- faster and safer function escapeTag (replacement at once in one run, '\n' and '\r' escaped also);
2017-05-17 13:25:06 +02:00
sebres 54729f9ef3 Merge branch '0.10' into 0.10-full 2017-05-17 12:24:01 +02:00
sebres 6724de54e6 Merge branch '0.10' into 0.10-full 2017-05-17 11:35:33 +02:00
sebres ef975307c4 errors on closed socket are too sporadic to cover it (prevents "coverage decreased" over and over again) 2017-03-14 16:24:45 +01:00
sebres 5ff63b66a0 Merge branch '0.10' into 0.10-full 2017-03-14 13:36:32 +01:00
sebres 3cf068670c Merge branch '0.10' into 0.10-full 2017-03-14 11:47:38 +01:00
sebres 875295320e Merge remote-tracking branch 'remotes/gh-upstream/0.10' into 0.10-full 2017-03-13 02:12:39 +01:00
sebres bae38a9fdf Merge remote-tracking branch 'remotes/gh-upstream/0.10' into 0.10-full 2017-03-01 15:24:28 +01:00
sebres 4b53c6b975 socket, asyncserver: several fixes, python version dependency removed + test coverage extended 2017-02-28 19:52:44 +01:00
sebres 9129a414e3 small fix (missing import of logging) + test coverage 2017-02-28 17:04:01 +01:00
sebres 28b5262976 Merge branch '0.10' into 0.10-full 2017-02-28 15:14:51 +01:00
sebres fa20b0aff2 Merge branch 'py-3.6-compat' into 0.10-full 2017-02-15 19:18:35 +01:00
sebres a4ec017d1c Merge branch '0.10' into 0.10-full 2017-02-15 09:26:01 +01:00
sebres 8c54675750 fix sporadic time related errors after fail2ban restart resp. reload jail:
- ValueError: need more than N values to unpack
- empty banip from restoreCurrentBans, etc.
2017-01-23 11:45:29 +01:00
sebres 0636b3247d observer fix: wait it becomes idle in reload test case (complete writing of failures to database); 2017-01-23 09:52:04 +01:00
sebres 8e2711681c small performance fix after merge with 0.10 2017-01-23 09:51:52 +01:00
sebres 99634638ba Merge branch '0.10' into 0.10-full 2017-01-23 09:51:36 +01:00
sebres ce2b4fe634 amend after newest merge of 0.10:
- database duplicate code removed resp. merged with incr. version;
  - ignores expired ban ticket directly in ban manager;
  - don't change start of ban time for restored tickets in restoreCurrentBans (because of possible timing issues in the test-cases);
  - small code review;
2016-10-15 19:53:54 +02:00
sebres cbfecea112 Merge remote-tracking branch 'remotes/gh-upstream/0.10' into 0.10-full 2016-10-15 19:19:58 +02:00
sebres 53adc9d84a Merge branch 0.10-full with 0.10
Resolved several conflicts and code review after merge
2016-10-14 19:55:20 +02:00
sebres 18ebd9ac21 Merge branches 0.10-full and 0.10 2016-08-17 18:00:25 +02:00
sebres 3bbbe640c0 MANIFEST update for release ban-time-incr version of 0.10 2016-07-15 10:48:02 +02:00
sebres 922213f3d9 Merge tag '0.10.0a1' into 0.10-full 2016-07-15 10:32:42 +02:00
sebres 334bfd50ff Merge branch '0.10' into 0.10-full 2016-06-12 15:12:50 +02:00
sebres facda17945 Prevent travis failure with "The log length has exceeded the limit of 4 MB. The job has been terminated" 2016-06-10 02:12:11 +02:00
sebres 12ff119841 Merge branch 'ban-time-incr' into 0.10-full 2016-06-09 22:50:31 +02:00
sebres e3ab10196e Merge remote-tracking branch 'remotes/gh-origin/f2b-perfom-prepare-716-cs-0.10' into 0.10-full 2016-06-09 22:13:48 +02:00
sebres 1ec6782f32 fix test cases by testing with multi-threaded execution (wait for threaded execution done) 2016-03-06 18:37:52 +01:00
sebres bf0adc1fdf Merge remote-tracking branch 'f2b-perfom-prepare-716-cs' into ban-time-incr (+ conflicts resolved) 2016-03-06 15:12:48 +01:00
sebres 27659c85e6 Merge remote-tracking branch 'master' into f2b-perfom-prepare-716-cs 2016-02-15 21:03:51 +01:00
sebres 70c329e235 increase verbosity for travis/py3 (currently "debug", use "heavydebug" for more details if needed) 2016-02-15 20:44:35 +01:00
sebres 95af3c63ac increase readability and details level by increased verbosity 2016-02-15 20:42:12 +01:00
sebres 0fef5022f0 reader bug fix: prevent to silent "load" of not existing jail;
coverage of test cases increased;
2016-02-15 20:41:20 +01:00
sebres 4ec70d7851 code review, timeout fix, better tracing (and test coverage) by start of server/client (with or without fork) 2016-02-15 19:19:31 +01:00
sebres 6cd19894e9 some compatibility fixes (prevent forking of testcase-process, code review), wait 4 server ready, test cases fixed (py2/py3) 2016-02-15 14:41:12 +01:00
sebres 0e11d81adb several bug fixed: fork in client-server test cases prohibited, all worker threads daemonized (to prevent hanging on exit). 2016-02-11 21:39:06 +01:00
sebres f120877756 client/server (bin) test cases introduced, ultimate closes #1121, closes #1139
small code review and fixing of some bugs during client-server communication process (in the test cases);
2016-02-11 17:57:23 +01:00
sebres 4d696d69a0 starting of the server (and client/server communication behavior during start and daemonize) completely rewritten:
- client/server functionality moved away from bin and using now the common interface (introduced in fail2bancmdline);
  - start in foreground fixed;
  - server can act as client corresponding command line;
  - command "restart" added: in opposite to "reload" in reality restarts the server (new process);
  - several client/server bugs during starting process fixed.
2016-02-11 08:56:12 +01:00
sebres 3fda77227e temporary commit (move client/server from bin) 2016-02-11 08:52:41 +01:00
sebres 44490664f5 try to start server in foreground
# Conflicts:
#	fail2ban/server/server.py
2016-02-10 22:00:42 +01:00
sebres 6daa152c0c Merge branch 'f2b-perfom-prepare-716' into ban-time-incr 2015-12-29 19:53:07 +01:00
sebres b3d4ce291e start observer together with the server (parametrized to prevent constantly start/stop of observer by addJail in test cases) 2015-12-29 19:52:16 +01:00
sebres 9d4f163e88 code review and minor repair after merge with performance branch (changed naming convention, wrong resolved conflicts, etc) 2015-12-29 17:36:00 +01:00
sebres 21f058a9f7 Merge remote-tracking branch 'remotes/gh-origin/f2b-perfom-prepare-716' into ban-time-incr 2015-12-29 14:04:41 +01:00
sebres 386da502ba Merge remote-tracking branch 'master' into 'ban-time-incr' 2015-07-13 16:19:33 +02:00
sebres d5ebe542f9 Merge branch 'master' into 'sebres:ban-time-incr' 2015-01-05 19:14:51 +01:00
sebres 27bc2e012d Merge remote-tracking branch 'master' into sebres:ban-time-incr 2014-12-05 17:41:45 +01:00
sebres ef7f3230ec added a test case for upgrade database from v2 (additionally to existing v1); 2014-12-03 10:54:32 +01:00
sebres 4dbc77dbbb code review, test case extended; 2014-12-02 11:57:43 +01:00
sebres 697da99f8f code review and few new test cases 2014-12-02 01:01:10 +01:00
sebres 5ca275876b Merge remote-tracking branch 'remotes/upstream/master' into sebres:ban-time-incr 2014-12-01 23:28:58 +01:00
sebres 5dc1a583b4 Merge remote-tracking branch 'remotes/upstream/master' into sebres:ban-time-incr
Conflicts:
	fail2ban/server/actions.py
	fail2ban/server/database.py
	fail2ban/tests/databasetestcase.py
	fail2ban/tests/servertestcase.py
2014-12-01 13:57:51 +01:00
sebres 595edc8d46 increase code coverage 2014-10-28 21:57:16 +01:00
sebres c1db282fcd Merge remote-tracking branch 'remotes/upstream/master' into sebres:ban-time-incr 2014-10-28 16:38:26 +01:00
sebres 286ef6aa87 code review 2014-10-26 22:14:57 +01:00
sebres 361c220846 Merge remote-tracking branch 'remotes/upstream/master' into sebres:ban-time-incr;
normalize code to python >= 2.6;
2014-10-25 19:05:53 +02:00
sebres 3c01dcb01f Merge remote-tracking branch 'remotes/origin/_tent/cache-config-read-fix1' into ban-time-incr 2014-10-24 05:55:25 +02:00
sebres 2b1e645eb4 Merge remote-tracking branch 'remotes/origin/_tent/cache-config-read-fix1' into ban-time-incr 2014-10-24 05:12:18 +02:00
sebres 293a5066d2 normalizing time config entries: use time abbreviation (str2seconds) for all time options such 'dbpurgeage', 'bantime', 'findtime', ex.: default '1d' instead '86400';
code review and test case extended;
2014-10-24 01:32:04 +02:00
sebres 48cd1262fe Merge 'upstream/master' into sebres:ban-time-incr 2014-10-23 23:34:43 +02:00
sebres 8f2561e289 Merge remote-tracking branch 'remotes/origin/_tent/cache-config-read' into ban-time-incr 2014-10-20 01:37:36 +02:00
sebres f1d8272693 bug fix (in master): option 'dbpurgeage' was never set (default always) by start of fail2ban, because of invalid sorting of options ('dbfile' should be always set before other database options) / python3 compatibility fix 2014-10-20 01:35:02 +02:00
sebres 1ba48f8627 Merge remote-tracking branch 'remotes/origin/cache-config-read-820' into ban-time-incr 2014-10-09 15:41:52 +02:00
sebres ec77338e0c Merge remote-tracking branch 'sebres:cache-config-read-820' into ban-time-incr 2014-10-09 15:13:22 +02:00
sebres 20e6989c73 Merge 'upstream/master' into ban-time-incr:
Merge remote-tracking branch 'sebres:cache-config-read-820' into ban-time-incr:
config cache optimized - prevent to read the same config file inside different resources multiple times;
test case: read jail file only once;
+ optimized merge: use OrderedDict.update instead of merge in cycle;
2014-10-08 16:37:07 +02:00
sebres 704357467a test case for check the read of config files will be cached; 2014-10-07 14:30:51 +02:00
sebres f70656cdd7 caching of read config files, to make start of fail2ban faster, see issue #820 2014-10-02 22:29:09 +02:00
sebres e6127a278e The tricky bug fixed - last position of log file will be never retrieved (#795):
addJail (executed before addLog) early uses a "INSERT OR REPLACE" statement to update "enabled" to 1 (and add jail the first time used at once), but this syntax in sqlite always deletes an entry (cause of constraint) and inserts it again, so because of CASCADE all log entries with this jail will be also deleted from logs table.
2014-09-25 18:29:10 +02:00
sebres 7688db2628 observer: logging optimized, some log messages switched to debug level (because long time stable) 2014-09-24 15:22:48 +02:00
sebres 145a9fb891 filter, datedetector, datetemplate: performance optimizing of combination datedetector.matchTime/getTime2, because early getTime search a template and call template.matchTime again (so the date parsing was really executed twice, now just once);
debug logging optimized;
added info line log "Start Fail2ban ..." after changed logging target;
2014-09-24 13:21:37 +02:00
sebres 2b38d46fb5 actions: bug fix in lambdas in checkBan, because getBansMerged could return None (purge resp. asynchronous addBan), make the logic all around more stable;
test cases: extended with test to check action together with database functionality (ex.: to verify lambdas in checkBan);
database: getBansMerged should work within lock, using reentrant lock (cause call of getBans inside of getBansMerged);
2014-09-23 19:57:55 +02:00
sebres 6c2937affc python3/pypy compatibility fix + removing obsolete code 2014-09-16 18:12:21 +02:00
sebres 96de888ac7 python3/pypy compatibility fix 2014-09-16 17:51:57 +02:00
sebres 0dce32405f python3 compatibility fix 2014-09-16 17:27:21 +02:00
sebres c1637e97b2 now polling backend only: prevent completely read of big files first time (after start of service), initial seek to start time using half-interval search algorithm (see issue #795):
disabled for gamin and pyinotify backends;
2014-09-16 17:06:49 +02:00
sebres 930678cc0e Merge remote-tracking branch 'remotes/upstream/master' into ban-time-incr 2014-09-16 13:53:15 +02:00
sebres 53a30a2d42 prevent completely read of big files first time (after start of service), initial seek to start time using half-interval search algorithm (see issue #795) 2014-09-16 13:50:32 +02:00
sebres 62c755c1d5 Merge remote-tracking branch 'upstream/master' into ban-time-incr
Conflicts resolved:
	fail2ban/server/database.py
	fail2ban/tests/servertestcase.py
delBan modified (if manually unban):
	delete from "bips" also (bad ips)
	delete all tickets of this ip, also if currently not banned
2014-08-15 11:39:55 +02:00
sebres 6d2b596bb4 observer inherits from JailThread + test cases for bad run; 2014-07-08 10:56:19 +02:00
sebres e70406d5a1 @commitandrollback decorator added; missing logging module reference added; 2014-07-07 10:28:46 +02:00
sebres 00b7205a3c Merge remote-tracking branch 'remotes/upstream/master', fix test cases (see bellow)
Conflicts resolved:
	ChangeLog
	fail2ban/server/filter.py
	fail2ban/server/jail.py
	fail2ban/tests/actionstestcase.py
Test cases fixed:
	testBanActionsAInfo - fail ticket with current time (otherwise ticket will be ignored - ban time too old)
	testFail2BanExceptHook - use local sys.__excepthook__ to check was really executed and prevent write error in stderr.
2014-06-24 14:02:24 +02:00
sebres de0beeff9f new test cases added (increase coverage);
prepared to merge with upstream/master;
2014-06-24 12:39:53 +02:00
sebres 819e4eb540 relict of obsolete code removed; 2014-06-19 18:06:07 +02:00
sebres ccf2521a6d Merge branch 'master' of https://github.com/fail2ban/fail2ban into ban-time-incr;
Conflicts in ChangeLog resolved;
obsolete imports removed;
2014-06-19 17:40:00 +02:00
sebres 6ecd7ddddf testExecuteTimeout fixed: give a test still 1 second, because system could be too busy 2014-06-10 13:45:29 +02:00
sebres a82cc3bcbf prevent to early exit from main loop (tast case bug by multi-threaded execution / wait for completion);
idle state fixed (if observer really sleeps only);
2014-06-10 13:24:13 +02:00
sebres 00fdf5ce0a test cases extended;
code review
2014-06-10 12:31:55 +02:00
sebres bb6655e696 small fix and clarifying code and log messages 2014-06-10 10:24:55 +02:00
sebres bb0a181056 testcases extended and observer optimized to run test cases faster;
code review
2014-06-07 04:37:06 +02:00
sebres e7bd8ed619 not used import removed 2014-06-06 19:52:42 +02:00
sebres 70080b112a Merge branch 'master' of https://github.com/fail2ban/fail2ban into ban-time-incr 2014-06-06 19:46:38 +02:00
sebres 681bc2ef07 observer functionality introduced (asynchronous events in separate service thread);
ban time increment feature nearly completely moved into observer;
purge database will be called hourly in observer;
bug fixing and code review;
2014-06-06 18:44:59 +02:00
sebres 02055ba4eb ignore already known tickets (from filter after restart);
bug fixing and optimizing;
2014-06-05 14:09:43 +02:00
sebres 8fd083a1ea Merge remote-tracking branch 'remotes/kwirk/sebres-strptime-bug' into ban-time-incr 2014-05-15 17:12:11 +02:00
sebres addfea6614 static method forgotten; 2014-05-15 15:16:53 +02:00
sebres ec3ed0e4ae introduced string to seconds (str2seconds) for configuration entries with time;
todo: expands it for all time config entries;
2014-05-14 16:01:35 +02:00
sebres f492aa7ac9 remove affected check, to delete jails always (pass testPurge) 2014-05-14 12:32:30 +02:00
sebres 99c9cbf470 code review, manually ban uses by addFailure the count "maxRetry" directly;
log ticket time (found in line)
2014-05-14 12:17:28 +02:00
sebres d22ab320e2 "magic" formula for auto increasing of retry count for known (bad) ip, corresponding banCount of it
(one try will count than 2, 3, 5, 9 ...)
2014-05-14 11:21:31 +02:00
sebres 0121e09907 default formula faster and more readable, comparable with "multipliers", like 2**N, default factor for both solutions is 1 now 2014-05-07 13:28:04 +02:00
sebres 7d17fb5c6c python >= 3.x, local variable 'lastBanTime' reference bug fixed 2014-05-06 20:55:41 +02:00
sebres a4837da899 Merge branch 'ban-time-incr' of https://github.com/sebres/fail2ban into ban-time-incr 2014-05-06 20:32:23 +02:00
sebres 3a75c8a752 ban time incr: 2st test case added (code optimized for test cases), to test both stand-alone:
python ./bin/fail2ban-testcases -l debug 'BanTimeIncr'
2014-05-06 20:30:12 +02:00
sebres 6c8327e39f indentation level fix 2014-05-06 20:24:49 +02:00
sebres 14167ed778 ban time incr: 2st test case added (code optimized for test cases), to test both stand-alone:
python ./bin/fail2ban-testcases -l debug 'BanTimeIncr'
2014-05-06 20:14:23 +02:00
sebres 237706e39f ban time incr: 1st test case added, to test it stand-alone:
python ./bin/fail2ban-testcases -l debug 'BanTimeIncr'
2014-05-06 17:57:11 +02:00
sebres c48e404e63 option "multipliers" added, how proposed from @yarikoptic;
the calculate formula is rewritten to lambda / compiled solution (up to 10 million times per seconds);
code review;
2014-05-06 16:07:16 +02:00
sebres ccacfc1047 code review 2014-05-05 15:17:22 +02:00
sebres ccf07c4b21 - some bug fixed to pass all test cases;
- database_v1.db/bans/jail-name bug fixed - cause of different jail name in jails and bans, in test case (by updateDb): FOREIGN KEY constraint failed:
  $ sqlite3 fail2ban/tests/files/database_v1.db
  sqlite> select distinct jail from bans;
  DummyJail #16244880 with 0 tickets
  sqlite> select distinct name from jails;
  DummyJail #29162448 with 0 tickets
  sqlite> update bans set jail = (select distinct name from jails);
2014-05-05 14:47:50 +02:00
sebres 6f7c9b7d0f introduced new feature "ban time exponential increasing":
"bantimeextra.enabled" in jail.conf allows to use database for searching of previously banned ip's to increase a default ban time using special formula,
   by default, each next ban it will be original banTime * 1, 2, 4, 8, 16, 32...
see "jail.conf" for some other options of "bantimeextra";
additional we can configure a little randomization of ban time, to prevent "clever" botnets calculate exact time IP can be unbanned.
WARNING: by first start the server upgrades sqlite database (table "bans" will recreated with another schema);
2014-05-05 12:38:54 +02:00
179 changed files with 6383 additions and 2253 deletions
+1
View File
@@ -0,0 +1 @@
ChangeLog linguist-language=Markdown
-49
View File
@@ -1,49 +0,0 @@
_We will be very grateful, if your problem was described as completely as possible,
enclosing excerpts from logs (if possible within DEBUG mode, if no errors evident
within INFO mode), and configuration in particular of effected relevant settings
(e.g., with ` fail2ban-client -d | grep 'affected-jail-name' ` for a particular
jail troubleshooting).
Thank you in advance for the details, because such issues like "It does not work"
alone could not help to resolve anything!
Thanks! (remove this paragraph and other comments upon reading)_
### Environment:
_Fill out and check (`[x]`) the boxes which apply. If your Fail2Ban version is outdated,
and you can't verify that the issue persists in the recent release, better seek support
from the distribution you obtained Fail2Ban from_
- Fail2Ban version (including any possible distribution suffixes):
- OS, including release name/version:
- [ ] Fail2Ban installed via OS/distribution mechanisms
- [ ] You have not applied any additional foreign patches to the codebase
- [ ] Some customizations were done to the configuration (provide details below is so)
### The issue:
_Summary here_
#### Steps to reproduce
#### Expected behavior
#### Observed behavior
#### Any additional information
### Configuration, dump and another helpful excerpts
#### Any customizations done to /etc/fail2ban/ configuration
```
```
#### Relevant parts of /var/log/fail2ban.log file:
_preferably obtained while running fail2ban with `loglevel = 4`_
```
```
#### Relevant lines from monitored log files in question:
```
```
+70
View File
@@ -0,0 +1,70 @@
---
name: Bug report
about: Report a bug within the fail2ban engines (not filters or jails)
title: '[BR]: '
labels: bug
assignees: ''
---
<!--
- Before reporting, please make sure to search the open and closed issues for any reports in the past.
- Use this issue template to report a bug in the fail2ban engine (not in a filter or jail).
- If you want to request a feature or a new filter, please use "Feature request" or "Filter request" instead.
- If you have rather some question, please open or join to some discussion.
We will be very grateful, if your problem was described as completely as possible,
enclosing excerpts from logs (if possible within DEBUG mode, if no errors evident
within INFO mode), and configuration in particular of effected relevant settings
(e.g., with ` fail2ban-client -d | grep 'affected-jail-name' ` for a particular
jail troubleshooting).
Thank you in advance for the details, because such issues like "It does not work"
alone could not help to resolve anything!
Thanks!
(you can remove this paragraph and other comments upon reading)
-->
### Environment:
<!--
Fill out and check (`[x]`) the boxes which apply. If your Fail2Ban version is outdated,
and you can't verify that the issue persists in the recent release, better seek support
from the distribution you obtained Fail2Ban from
-->
- Fail2Ban version <!-- including any possible distribution suffixes --> :
- OS, including release name/version :
- [ ] Fail2Ban installed via OS/distribution mechanisms
- [ ] You have not applied any additional foreign patches to the codebase
- [ ] Some customizations were done to the configuration (provide details below is so)
### The issue:
<!-- summary here -->
#### Steps to reproduce
#### Expected behavior
#### Observed behavior
#### Any additional information
### Configuration, dump and another helpful excerpts
#### Any customizations done to /etc/fail2ban/ configuration
<!-- put your configuration excerpts between next 2 lines -->
```
```
#### Relevant parts of /var/log/fail2ban.log file:
<!-- preferably obtained while running fail2ban with `loglevel = 4` -->
<!-- put your log excerpt between next 2 lines -->
```
```
#### Relevant lines from monitored log files:
<!-- put your log excerpt between next 2 lines -->
```
```
+35
View File
@@ -0,0 +1,35 @@
---
name: Feature request
about: Suggest an idea or an enhancement for this project
title: '[RFE]: '
labels: enhancement
assignees: ''
---
<!--
- Before requesting, please make sure to search the open and closed issues for any requests in the past.
- Use this issue template to request a feature in the fail2ban engine (not a new filter or jail).
- If you want to request a new filter or failregex, please use "Filter request" instead.
- If you have rather some question, please open or join to some discussion.
-->
#### Feature request type
<!--
Please provide a summary description of the feature request.
-->
#### Description
<!--
Please describe the feature in more detail.
-->
#### Considered alternatives
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
#### Any additional information
<!--
Add any other context or screenshots about the feature request here.
-->
+59
View File
@@ -0,0 +1,59 @@
---
name: Filter request
about: Request a new jail or filter to be supported or existing filter extended with new failregex
title: '[FR]: '
labels: filter-request
assignees: ''
---
<!--
- Before requesting, please make sure to search the open and closed issues for any requests in the past.
- Sometimes failregex have been already requested before but are not implemented yet due to various reasons.
- If there are no hits for your concerns, please proceed otherwise add a comment to the related issue (also if it is closed).
- If you want to request a new feature, please use "Feature request" instead.
- If you have rather some question, please open or join to some discussion.
-->
### Environment:
<!--
Fill out and check (`[x]`) the boxes which apply.
-->
- Fail2Ban version <!-- including any possible distribution suffixes --> :
- OS, including release name/version :
#### Service, project or product which log or journal should be monitored
- Name of filter or jail in Fail2Ban (if already exists) :
- Service, project or product name, including release name/version :
- Repository or URL (if known) :
- Service type :
- Ports and protocols the service is listening :
#### Log or journal information
<!-- Delete unrelated group -->
<!-- Log file -->
- Log file name(s) :
<!-- Systemd journal -->
- Journal identifier or unit name :
#### Any additional information
### Relevant lines from monitored log files:
#### failures in sense of fail2ban filter (fail2ban must match):
<!-- put your log excerpt between next 2 lines -->
```
```
#### legitimate messages (fail2ban should not consider as failures):
<!-- put your log excerpt between next 2 lines -->
```
```
+2 -1
View File
@@ -1,7 +1,8 @@
Before submitting your PR, please review the following checklist:
- [ ] **CHOOSE CORRECT BRANCH**: if filing a bugfix/enhancement
against 0.9.x series, choose `master` branch
against certain release version, choose `0.9`, `0.10` or `0.11` branch,
for dev-edition use `master` branch
- [ ] **CONSIDER adding a unit test** if your PR resolves an issue
- [ ] **LIST ISSUES** this PR resolves
- [ ] **MAKE SURE** this PR doesn't break existing tests
+98
View File
@@ -0,0 +1,98 @@
name: CI
# Controls when the action will run. Triggers the workflow on push or pull request
# events but only for the master branch
on:
push:
paths-ignore:
- 'doc/**'
- 'files/**'
- 'man/**'
pull_request:
paths-ignore:
- 'doc/**'
- 'files/**'
- 'man/**'
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-20.04
strategy:
matrix:
python-version: [2.7, 3.5, 3.6, 3.7, 3.8, 3.9, '3.10', '3.11.0-alpha.1', pypy2, pypy3]
fail-fast: false
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Grant systemd-journal access
run: sudo usermod -a -G systemd-journal "$USER" || echo 'no systemd-journal access'
- name: Python version
run: |
F2B_PY=$(python -c "import sys; print(sys.version)")
echo "Python: ${{ matrix.python-version }} -- ${F2B_PY/$'\n'/ }"
F2B_PYV=$(echo "${F2B_PY}" | grep -oP '^\d+(?:\.\d+)')
F2B_PY=${F2B_PY:0:1}
echo "Set F2B_PY=$F2B_PY, F2B_PYV=$F2B_PYV"
echo "F2B_PY=$F2B_PY" >> $GITHUB_ENV
echo "F2B_PYV=$F2B_PYV" >> $GITHUB_ENV
# for GHA we need to monitor all journals, since it cannot be found using SYSTEM_ONLY(4):
echo "F2B_SYSTEMD_DEFAULT_FLAGS=0" >> $GITHUB_ENV
- name: Install dependencies
run: |
if [[ "$F2B_PY" = 3 ]]; then python -m pip install --upgrade pip || echo "can't upgrade pip"; fi
if [[ "$F2B_PY" = 3 ]] && ! command -v 2to3x -v 2to3 > /dev/null; then
#pip install 2to3
sudo apt-get -y install 2to3
fi
#sudo apt-get -y install python${F2B_PY/2/}-pyinotify || echo 'inotify not available'
python -m pip install pyinotify || echo 'inotify not available'
#sudo apt-get -y install python${F2B_PY/2/}-systemd || echo 'systemd not available'
sudo apt-get -y install libsystemd-dev || echo 'systemd dependencies seems to be unavailable'
python -m pip install systemd-python || echo 'systemd not available'
- name: Before scripts
run: |
cd "$GITHUB_WORKSPACE"
# Manually execute 2to3 for now
if [[ "$F2B_PY" = 3 ]]; then echo "2to3 ..." && ./fail2ban-2to3; fi
_debug() { echo -n "$1 "; err=$("${@:2}" 2>&1) && echo 'OK' || echo -e "FAIL\n$err"; }
# (debug) output current preferred encoding:
_debug 'Encodings:' python -c 'import locale, sys; from fail2ban.helpers import PREFER_ENC; print(PREFER_ENC, locale.getpreferredencoding(), (sys.stdout and sys.stdout.encoding))'
# (debug) backend availabilities:
echo 'Backends:'
_debug '- systemd:' python -c 'from fail2ban.server.filtersystemd import FilterSystemd'
#_debug '- systemd (root): ' sudo python -c 'from fail2ban.server.filtersystemd import FilterSystemd'
_debug '- pyinotify:' python -c 'from fail2ban.server.filterpyinotify import FilterPyinotify'
- name: Test suite
run: |
if [[ "$F2B_PY" = 2 ]]; then
python setup.py test
elif dpkg --compare-versions "$F2B_PYV" lt 3.10; then
python bin/fail2ban-testcases --verbosity=2
else
echo "Skip systemd backend since systemd-python module must be fixed for python >= v.3.10 in GHA ..."
python bin/fail2ban-testcases --verbosity=2 -i "[sS]ystemd|[jJ]ournal"
fi
#- name: Test suite (debug some systemd tests only)
#run: python bin/fail2ban-testcases --verbosity=2 "[sS]ystemd|[jJ]ournal"
#run: python bin/fail2ban-testcases --verbosity=2 -l 5 "test_WrongChar"
- name: Build
run: python setup.py build
#- name: Test initd scripts
# run: shellcheck -s bash -e SC1090,SC1091 files/debian-initd
+5 -13
View File
@@ -10,22 +10,14 @@ dist: xenial
matrix:
fast_finish: true
include:
- python: 2.6
dist: trusty # required for Python 2.6
- python: 2.7
dist: trusty # required for packages like gamin
name: 2.7 (trusty)
- python: 2.7
name: 2.7 (xenial)
- python: pypy
dist: trusty
- python: 3.3
dist: trusty
#- python: pypy
- python: 3.4
- python: 3.5
- python: 3.6
- python: 3.7
- python: 3.8-dev
- python: 3.8
- python: 3.9-dev
- python: pypy3.5
before_install:
- echo "running under $TRAVIS_PYTHON_VERSION"
@@ -69,8 +61,8 @@ script:
- if [[ "$F2B_PY" = 3 ]]; then coverage run bin/fail2ban-testcases --verbosity=2; fi
# Use $VENV_BIN (not python) or else sudo will always run the system's python (2.7)
- sudo $VENV_BIN/pip install .
# Doc files should get installed on Travis under Linux (python >= 3.8 seem to use another path segment)
- if [[ $TRAVIS_PYTHON_VERSION < 3.8 ]]; then test -e /usr/share/doc/fail2ban/FILTERS; fi
# Doc files should get installed on Travis under Linux (some builds/python's seem to use another path segment)
- test -e /usr/share/doc/fail2ban/FILTERS && echo 'found' || echo 'not found'
# Test initd script
- shellcheck -s bash -e SC1090,SC1091 files/debian-initd
after_success:
+160 -18
View File
@@ -6,29 +6,160 @@
Fail2Ban: Changelog
===================
Incompatibility list (compared to v.0.9):
ver. 1.0.1-dev-1 (20??/??/??) - development nightly edition
-----------
* Filter (or `failregex`) internal capture-groups:
### Compatibility:
* potential incompatibility by parsing of options of `backend`, `filter` and `action` parameters (if they
are partially incorrect), because fail2ban could throw an error now (doesn't silently bypass it anymore).
* to v.0.11:
- due to change of `actioncheck` behavior (gh-488), some actions can be incompatible as regards
the invariant check, if `actionban` or `actionunban` would not throw an error (exit code
different from 0) in case of unsane environment.
- If you've your own `failregex` or custom filters using conditional match `(?P=host)`, you should
rewrite the regex like in example below resp. using `(?:(?P=ip4)|(?P=ip6)` instead of `(?P=host)`
(or `(?:(?P=ip4)|(?P=ip6)|(?P=dns))` corresponding your `usedns` and `raw` settings).
### Fixes
* readline fixed to consider interim new-line character as part of code point in multi-byte logs
(e. g. unicode encoding like utf-16be, utf-16le);
* `action.d/ufw.conf`:
- fixed handling on IPv6 (using prepend, gh-2331, gh-3018)
- application names containing spaces can be used now (gh-656, gh-1532, gh-3018)
* `filter.d/drupal-auth.conf` more strict regex, extended to match "Login attempt failed from" (gh-2742)
Of course you can always define your own capture-group (like below `_cond_ip_`) to do this.
```
testln="1500000000 failure from 192.0.2.1: bad host 192.0.2.1"
fail2ban-regex "$testln" "^\s*failure from (?P<_cond_ip_><HOST>): bad host (?P=_cond_ip_)$"
```
- New internal groups (currently reserved for internal usage):
`ip4`, `ip6`, `dns`, `fid`, `fport`, additionally `user` and another captures in lower case if
mapping from tag `<F-*>` used in failregex (e. g. `user` by `<F-USER>`).
### New Features and Enhancements
* `actioncheck` behavior is changed now (gh-488), so invariant check as well as restore or repair
of sane environment (in case of recognized unsane state) would only occur on action errors (e. g.
if ban or unban operations are exiting with other code as 0)
* better recognition of log rotation, better performance by reopen: avoid unnecessary seek to begin of file
(and hash calculation)
* file filter reads only complete lines (ended with new-line) now, so waits for end of line (for its completion)
* `action.d/ufw.conf` (gh-3018):
- new option `add` (default `prepend`), can be supplied as `insert 1` for ufw versions before v.0.36 (gh-2331, gh-3018)
- new options `kill-mode` and `kill` to drop established connections of intruder (see action for details, gh-3018)
* `filter.d/nginx-http-auth.conf` - extended with parameter mode, so additionally to `auth` (or `normal`)
mode `fallback` (or combined as `aggressive`) can find SSL errors while SSL handshaking, gh-2881
* v.0.10 uses more precise date template handling, that can be theoretically incompatible to some
user configurations resp. `datepattern`.
* Since v0.10 fail2ban supports the matching of IPv6 addresses, but not all ban actions are
IPv6-capable now.
ver. 0.11.2 (2020/11/23) - heal-the-world-with-security-tools
-----------
### Compatibility:
* to v.0.10:
- 0.11 is totally compatible to 0.10 (configuration- and API-related stuff), but the database
got some new tables and fields (auto-converted during the first start), so once updated to 0.11, you
have to remove the database /var/lib/fail2ban/fail2ban.sqlite3 (or its different to 0.10 schema)
if you would need to downgrade to 0.10 for some reason.
* to v.0.9:
- Filter (or `failregex`) internal capture-groups:
* If you've your own `failregex` or custom filters using conditional match `(?P=host)`, you should
rewrite the regex like in example below resp. using `(?:(?P=ip4)|(?P=ip6)` instead of `(?P=host)`
(or `(?:(?P=ip4)|(?P=ip6)|(?P=dns))` corresponding your `usedns` and `raw` settings).
Of course you can always define your own capture-group (like below `_cond_ip_`) to do this.
```
testln="1500000000 failure from 192.0.2.1: bad host 192.0.2.1"
fail2ban-regex "$testln" "^\s*failure from (?P<_cond_ip_><HOST>): bad host (?P=_cond_ip_)$"
```
* New internal groups (currently reserved for internal usage):
`ip4`, `ip6`, `dns`, `fid`, `fport`, additionally `user` and another captures in lower case if
mapping from tag `<F-*>` used in failregex (e. g. `user` by `<F-USER>`).
- v.0.10 and 0.11 use more precise date template handling, that can be theoretically incompatible to some
user configurations resp. `datepattern`.
- Since v0.10 fail2ban supports the matching of IPv6 addresses, but not all ban actions are
IPv6-capable now.
### Fixes
* [stability] prevent race condition - no ban if filter (backend) is continuously busy if
too many messages will be found in log, e. g. initial scan of large log-file or journal (gh-2660)
* pyinotify-backend sporadically avoided initial scanning of log-file by start
* python 3.9 compatibility (and Travis CI support)
* restoring a large number (500+ depending on files ulimit) of current bans when using PyPy fixed
* manual ban is written to database, so can be restored by restart (gh-2647)
* `jail.conf`: don't specify `action` directly in jails (use `action_` or `banaction` instead)
* no mails-action added per default anymore (e. g. to allow that `action = %(action_mw)s` should be specified
per jail or in default section in jail.local), closes gh-2357
* ensure we've unique action name per jail (also if parameter `actname` is not set but name deviates from standard name, gh-2686)
* don't use `%(banaction)s` interpolation because it can be complex value (containing `[...]` and/or quotes),
so would bother the action interpolation
* fixed type conversion in config readers (take place after all interpolations get ready), that allows to
specify typed parameters variable (as substitutions) as well as to supply it in other sections or as init parameters.
* `action.d/*-ipset*.conf`: several ipset actions fixed (no timeout per default anymore), so no discrepancy
between ipset and fail2ban (removal from ipset will be managed by fail2ban only, gh-2703)
* `action.d/cloudflare.conf`: fixed `actionunban` (considering new-line chars and optionally real json-parsing
with `jq`, gh-2140, gh-2656)
* `action.d/nftables.conf` (type=multiport only): fixed port range selector, replacing `:` with `-` (gh-2763)
* `action.d/firewallcmd-*.conf` (multiport only): fixed port range selector, replacing `:` with `-` (gh-2821)
* `action.d/bsd-ipfw.conf`: fixed selection of rule-no by large list or initial `lowest_rule_num` (gh-2836)
* `filter.d/common.conf`: avoid substitute of default values in related `lt_*` section, `__prefix_line`
should be interpolated in definition section (inside the filter-config, gh-2650)
* `filter.d/dovecot.conf`:
- add managesieve and submission support (gh-2795);
- accept messages with more verbose logging (gh-2573);
* `filter.d/courier-smtp.conf`: prefregex extended to consider port in log-message (gh-2697)
* `filter.d/traefik-auth.conf`: filter extended with parameter mode (`normal`, `ddos`, `aggressive`) to handle
the match of username differently (gh-2693):
- `normal`: matches 401 with supplied username only
- `ddos`: matches 401 without supplied username only
- `aggressive`: matches 401 and any variant (with and without username)
* `filter.d/sshd.conf`: normalizing of user pattern in all RE's, allowing empty user (gh-2749)
### New Features and Enhancements
* fail2ban-regex:
- speedup formatted output (bypass unneeded stats creation)
- extended with prefregex statistic
- more informative output for `datepattern` (e. g. set from filter) - pattern : description
* parsing of action in jail-configs considers space between action-names as separator also
(previously only new-line was allowed), for example `action = a b` would specify 2 actions `a` and `b`
* new filter and jail for GitLab recognizing failed application logins (gh-2689)
* new filter and jail for Grafana recognizing failed application logins (gh-2855)
* new filter and jail for SoftEtherVPN recognizing failed application logins (gh-2723)
* `filter.d/guacamole.conf` extended with `logging` parameter to follow webapp-logging if it's configured (gh-2631)
* `filter.d/bitwarden.conf` enhanced to support syslog (gh-2778)
* introduced new prefix `{UNB}` for `datepattern` to disable word boundaries in regex;
* datetemplate: improved anchor detection for capturing groups `(^...)`;
* datepattern: improved handling with wrong recognized timestamps (timezones, no datepattern, etc)
as well as some warnings signaling user about invalid pattern or zone (gh-2814):
- filter gets mode in-operation, which gets activated if filter starts processing of new messages;
in this mode a timestamp read from log-line that appeared recently (not an old line), deviating too much
from now (up too 24h), will be considered as now (assuming a timezone issue), so could avoid unexpected
bypass of failure (previously exceeding `findtime`);
- better interaction with non-matching optional datepattern or invalid timestamps;
- implements special datepattern `{NONE}` - allow to find failures totally without date-time in log messages,
whereas filter will use now as timestamp (gh-2802)
* performance optimization of `datepattern` (better search algorithm in datedetector, especially for single template);
* fail2ban-client: extended to unban IP range(s) by subnet (CIDR/mask) or hostname (DNS), gh-2791;
* extended capturing of alternate tags in filter, allowing combine of multiple groups to single tuple token with new tag
prefix `<F-TUPLE_`, that would combine value of `<F-V>` with all value of `<F-TUPLE_V?_n?>` tags (gh-2755)
ver. 0.11.1 (2020/01/11) - this-is-the-way
-----------
### Fixes
* purge database will be executed now (within observer).
* restoring currently banned ip after service restart fixed
(now < timeofban + bantime), ignore old log failures (already banned)
* upgrade database: update new created table `bips` with entries from table `bans` (allows restore
current bans after upgrade from version <= 0.10)
### New Features
* Increment ban time (+ observer) functionality introduced.
* Database functionality extended with bad ips.
* New tags (usable in actions):
- `<bancount>` - ban count of this offender if known as bad (started by 1 for unknown)
- `<bantime>` - current ban-time of the ticket (prolongation can be retarded up to 10 sec.)
* Introduced new action command `actionprolong` to prolong ban-time (e. g. set new timeout if expected);
Several actions (like ipset, etc.) rewritten using net logic with `actionprolong`.
Note: because ban-time is dynamic, it was removed from jail.conf as timeout argument (check jail.local).
### Enhancements
* algorithm of restore current bans after restart changed: update the restored ban-time (and therefore
end of ban) of the ticket with ban-time of jail (as maximum), for all tickets with ban-time greater
(or persistent); not affected if ban-time of the jail is unchanged between stop/start.
* added new setup-option `--without-tests` to skip building and installing of tests files (gh-2287).
* added new command `fail2ban-client get <JAIL> banip ?sep-char|--with-time?` to get the banned ip addresses (gh-1916).
ver. 0.10.5 (2020/01/10) - deserve-more-respect-a-jedis-weapon-must
@@ -91,7 +222,7 @@ Yes, Hrrrm...
### New Features
* new replacement tags for failregex to match subnets in form of IP-addresses with CIDR mask (gh-2559):
- `<CIDR>` - helper regex to match CIDR (simple integer form of net-mask);
- `<SUBNET>` - regex to match sub-net adresses (in form of IP/CIDR, also single IP is matched, so part /CIDR is optional);
- `<SUBNET>` - regex to match sub-net addresses (in form of IP/CIDR, also single IP is matched, so part /CIDR is optional);
* grouped tags (`<ADDR>`, `<HOST>`, `<SUBNET>`) recognize IP addresses enclosed in square brackets
* new failregex-flag tag `<F-MLFGAINED>` for failregex, signaled that the access to service was gained
(ATM used similar to tag `<F-NOFAIL>`, but it does not add the log-line to matches, gh-2279)
@@ -409,9 +540,14 @@ TODO: implementing of options resp. other tasks from PR #1346
- `<fid>` - failure identifier (if raw resp. failures without IP address)
- `<ip-rev>` - PTR reversed representation of IP address
- `<ip-host>` - host name of the IP address
- `<bancount>` - ban count of this offender if known as bad (started by 1 for unknown)
- `<bantime>` - current ban-time of the ticket (prolongation can be retarded up to 10 sec.)
- `<F-...>` - interpolates to the corresponding filter group capture `...`
- `<fq-hostname>` - fully-qualified name of host (the same as `$(hostname -f)`)
- `<sh-hostname>` - short hostname (the same as `$(uname -n)`)
* Introduced new action command `actionprolong` to prolong ban-time (e. g. set new timeout if expected);
Several actions (like ipset, etc.) rewritten using net logic with `actionprolong`.
Note: because ban-time is dynamic, it was removed from jail.conf as timeout argument (check jail.local).
* Allow to use filter options by `fail2ban-regex`, example:
fail2ban-regex text.log "sshd[mode=aggressive]"
* Samples test case factory extended with filter options - dict in JSON to control
@@ -485,6 +621,9 @@ ver. 0.10.0-alpha-1 (2016/07/14) - ipv6-support-etc
* testSocket: sporadical bug repaired - wait for server thread starts a socket (listener)
* testExecuteTimeoutWithNastyChildren: sporadical bug repaired - wait for pid file inside bash,
kill tree in any case (gh-1155)
* purge database will be executed now (within observer).
* restoring currently banned ip after service restart fixed
(now < timeofban + bantime), ignore old log failures (already banned)
* Fixed high-load of pyinotify-backend,
see https://github.com/fail2ban/fail2ban/issues/885#issuecomment-248964591
* Database: stability fix - repack cursor iterator as long as locked
@@ -522,6 +661,9 @@ ver. 0.10.0-alpha-1 (2016/07/14) - ipv6-support-etc
- new conditional section functionality used in config resp. includes:
- [Init?family=inet4] - IPv4 qualified hosts only
- [Init?family=inet6] - IPv6 qualified hosts only
* Increment ban time (+ observer) functionality introduced.
Thanks Serg G. Brester (sebres)
* Database functionality extended with bad ips.
* New reload functionality (now totally without restart, unbanning/rebanning, etc.),
see gh-1557
* Several commands extended and new commands introduced:
+1
View File
@@ -278,6 +278,7 @@ to tune it. fail2ban-regex -D ... will present Debuggex URLs for the regexs
and sample log files that you pass into it.
In general use when using regex debuggers for generating fail2ban filters:
* use regex from the ./fail2ban-regex output (to ensure all substitutions are
done)
* replace <HOST> with (?&.ipv4)
+14 -3
View File
@@ -3,10 +3,9 @@ bin/fail2ban-regex
bin/fail2ban-server
bin/fail2ban-testcases
ChangeLog
config/action.d/apprise.conf
config/action.d/abuseipdb.conf
config/action.d/apf.conf
config/action.d/badips.conf
config/action.d/badips.py
config/action.d/blocklist_de.conf
config/action.d/bsd-ipfw.conf
config/action.d/cloudflare.conf
@@ -100,6 +99,8 @@ config/filter.d/exim.conf
config/filter.d/exim-spam.conf
config/filter.d/freeswitch.conf
config/filter.d/froxlor-auth.conf
config/filter.d/gitlab.conf
config/filter.d/grafana.conf
config/filter.d/groupoffice.conf
config/filter.d/gssftpd.conf
config/filter.d/guacamole.conf
@@ -139,6 +140,7 @@ config/filter.d/sendmail-auth.conf
config/filter.d/sendmail-reject.conf
config/filter.d/sieve.conf
config/filter.d/slapd.conf
config/filter.d/softethervpn.conf
config/filter.d/sogo-auth.conf
config/filter.d/solid-pop3d.conf
config/filter.d/squid.conf
@@ -207,6 +209,7 @@ fail2ban/server/jail.py
fail2ban/server/jails.py
fail2ban/server/jailthread.py
fail2ban/server/mytime.py
fail2ban/server/observer.py
fail2ban/server/server.py
fail2ban/server/strptime.py
fail2ban/server/ticket.py
@@ -216,7 +219,6 @@ fail2ban/setup.py
fail2ban-testcases-all
fail2ban-testcases-all-python3
fail2ban/tests/action_d/__init__.py
fail2ban/tests/action_d/test_badips.py
fail2ban/tests/action_d/test_smtp.py
fail2ban/tests/actionstestcase.py
fail2ban/tests/actiontestcase.py
@@ -226,6 +228,8 @@ fail2ban/tests/clientreadertestcase.py
fail2ban/tests/config/action.d/action.conf
fail2ban/tests/config/action.d/brokenaction.conf
fail2ban/tests/config/fail2ban.conf
fail2ban/tests/config/filter.d/checklogtype.conf
fail2ban/tests/config/filter.d/checklogtype_test.conf
fail2ban/tests/config/filter.d/simple.conf
fail2ban/tests/config/filter.d/test.conf
fail2ban/tests/config/filter.d/test.local
@@ -261,8 +265,11 @@ fail2ban/tests/files/config/apache-auth/digest_wrongrelm/.htpasswd
fail2ban/tests/files/config/apache-auth/noentry/.htaccess
fail2ban/tests/files/config/apache-auth/README
fail2ban/tests/files/database_v1.db
fail2ban/tests/files/database_v2.db
fail2ban/tests/files/filter.d/substition.conf
fail2ban/tests/files/filter.d/testcase01.conf
fail2ban/tests/files/filter.d/testcase02.conf
fail2ban/tests/files/filter.d/testcase02.local
fail2ban/tests/files/filter.d/testcase-common.conf
fail2ban/tests/files/ignorecommand.py
fail2ban/tests/files/logs/3proxy
@@ -297,6 +304,8 @@ fail2ban/tests/files/logs/exim
fail2ban/tests/files/logs/exim-spam
fail2ban/tests/files/logs/freeswitch
fail2ban/tests/files/logs/froxlor-auth
fail2ban/tests/files/logs/gitlab
fail2ban/tests/files/logs/grafana
fail2ban/tests/files/logs/groupoffice
fail2ban/tests/files/logs/gssftpd
fail2ban/tests/files/logs/guacamole
@@ -334,6 +343,7 @@ fail2ban/tests/files/logs/sendmail-auth
fail2ban/tests/files/logs/sendmail-reject
fail2ban/tests/files/logs/sieve
fail2ban/tests/files/logs/slapd
fail2ban/tests/files/logs/softethervpn
fail2ban/tests/files/logs/sogo-auth
fail2ban/tests/files/logs/solid-pop3d
fail2ban/tests/files/logs/squid
@@ -366,6 +376,7 @@ fail2ban/tests/files/zzz-sshd-obsolete-multiline.log
fail2ban/tests/filtertestcase.py
fail2ban/tests/__init__.py
fail2ban/tests/misctestcase.py
fail2ban/tests/observertestcase.py
fail2ban/tests/samplestestcase.py
fail2ban/tests/servertestcase.py
fail2ban/tests/sockettestcase.py
+20 -9
View File
@@ -2,7 +2,7 @@
/ _|__ _(_) |_ ) |__ __ _ _ _
| _/ _` | | |/ /| '_ \/ _` | ' \
|_| \__,_|_|_/___|_.__/\__,_|_||_|
v0.10.3.dev1 20??/??/??
v1.0.1.dev1 20??/??/??
## Fail2Ban: ban hosts that cause multiple authentication errors
@@ -18,11 +18,12 @@ attempts, it cannot eliminate the risk presented by weak authentication.
Set up services to use only two factor, or public/private authentication
mechanisms if you really want to protect services.
<img src="http://www.worldipv6launch.org/wp-content/themes/ipv6/downloads/World_IPv6_launch_logo.svg" height="52pt"/> | Since v0.10 fail2ban supports the matching of the IPv6 addresses.
<img src="http://www.worldipv6launch.org/wp-content/themes/ipv6/downloads/World_IPv6_launch_logo.svg" height="52pt"/> | Since v0.10 fail2ban supports the matching of IPv6 addresses.
------|------
This README is a quick introduction to Fail2Ban. More documentation, FAQ, and HOWTOs
to be found on fail2ban(1) manpage, [Wiki](https://github.com/fail2ban/fail2ban/wiki)
to be found on fail2ban(1) manpage, [Wiki](https://github.com/fail2ban/fail2ban/wiki),
[Developers documentation](https://fail2ban.readthedocs.io/)
and the website: https://www.fail2ban.org
Installation:
@@ -33,6 +34,7 @@ this case, you should use that instead.**
Required:
- [Python2 >= 2.6 or Python >= 3.2](https://www.python.org) or [PyPy](https://pypy.org)
- python-setuptools, python-distutils or python3-setuptools for installation from source
Optional:
- [pyinotify >= 0.8.3](https://github.com/seb-m/pyinotify), may require:
@@ -45,10 +47,16 @@ Optional:
To install:
tar xvfj fail2ban-0.10.3.tar.bz2
cd fail2ban-0.10.3
python setup.py install
tar xvfj fail2ban-1.0.1.tar.bz2
cd fail2ban-1.0.1
sudo python setup.py install
Alternatively, you can clone the source from GitHub to a directory of Your choice, and do the install from there. Pick the correct branch, for example, master or 0.11
git clone https://github.com/fail2ban/fail2ban.git
cd fail2ban
sudo python setup.py install
This will install Fail2Ban into the python library directory. The executable
scripts are placed into `/usr/bin`, and configuration in `/etc/fail2ban`.
@@ -58,6 +66,9 @@ Fail2Ban should be correctly installed now. Just type:
to see if everything is alright. You should always use fail2ban-client and
never call fail2ban-server directly.
You can verify that you have the correct version installed with
fail2ban-client version
Please note that the system init/service script is not automatically installed.
To enable fail2ban as an automatic service, simply copy the script for your
@@ -79,11 +90,11 @@ fail2ban(1) and jail.conf(5) manpages for further references.
Code status:
------------
* [![tests status](https://secure.travis-ci.org/fail2ban/fail2ban.png?branch=0.10)](https://travis-ci.org/fail2ban/fail2ban?branch=0.10) travis-ci.org (0.10 branch) / [![tests status](https://secure.travis-ci.org/fail2ban/fail2ban.png?branch=master)](https://travis-ci.org/fail2ban/fail2ban) travis-ci.org (master branch)
* travis-ci.org: [![tests status](https://secure.travis-ci.org/fail2ban/fail2ban.svg?branch=master)](https://travis-ci.org/fail2ban/fail2ban?branch=master) / [![tests status](https://secure.travis-ci.org/fail2ban/fail2ban.svg?branch=0.11)](https://travis-ci.org/fail2ban/fail2ban?branch=0.11) (0.11 branch) / [![tests status](https://secure.travis-ci.org/fail2ban/fail2ban.svg?branch=0.10)](https://travis-ci.org/fail2ban/fail2ban?branch=0.10) (0.10 branch)
* [![Coverage Status](https://coveralls.io/repos/fail2ban/fail2ban/badge.png?branch=0.10)](https://coveralls.io/github/fail2ban/fail2ban?branch=0.10)
* coveralls.io: [![Coverage Status](https://coveralls.io/repos/fail2ban/fail2ban/badge.svg?branch=master)](https://coveralls.io/github/fail2ban/fail2ban?branch=master) / [![Coverage Status](https://coveralls.io/repos/fail2ban/fail2ban/badge.svg?branch=0.11)](https://coveralls.io/github/fail2ban/fail2ban?branch=0.11) (0.11 branch) / [![Coverage Status](https://coveralls.io/repos/fail2ban/fail2ban/badge.svg?branch=0.10)](https://coveralls.io/github/fail2ban/fail2ban?branch=0.10) / (0.10 branch)
* [![codecov.io](https://codecov.io/gh/fail2ban/fail2ban/coverage.svg?branch=0.10)](https://codecov.io/gh/fail2ban/fail2ban/branch/0.10)
* codecov.io: [![codecov.io](https://codecov.io/gh/fail2ban/fail2ban/coverage.svg?branch=master)](https://codecov.io/gh/fail2ban/fail2ban/branch/master) / [![codecov.io](https://codecov.io/gh/fail2ban/fail2ban/coverage.svg?branch=0.11)](https://codecov.io/gh/fail2ban/fail2ban/branch/0.11) (0.11 branch) / [![codecov.io](https://codecov.io/gh/fail2ban/fail2ban/coverage.svg?branch=0.10)](https://codecov.io/gh/fail2ban/fail2ban/branch/0.10) (0.10 branch)
Contact:
--------
+1 -1
View File
@@ -111,7 +111,7 @@ Russell Odom
SATO Kentaro
Sean DuBois
Sebastian Arcus
Serg G. Brester
Serg G. Brester (sebres)
Sergey Safarov
Shaun C.
Sireyessire
+4 -5
View File
@@ -21,14 +21,13 @@
#
# Example, for ssh bruteforce (in section [sshd] of `jail.local`):
# action = %(known/action)s
# %(action_abuseipdb)s[abuseipdb_apikey="my-api-key", abuseipdb_category="18,22"]
# abuseipdb[abuseipdb_apikey="my-api-key", abuseipdb_category="18,22"]
#
# See below for catagories.
# See below for categories.
#
# Original Ref: https://wiki.shaunc.com/wikka.php?wakka=ReportingToAbuseIPDBWithFail2Ban
# Added to fail2ban by Andrew James Collett (ajcollett)
## abuseIPDB Catagories, `the abuseipdb_category` MUST be set in the jail.conf action call.
## abuseIPDB Categories, `the abuseipdb_category` MUST be set in the jail.conf action call.
# Example, for ssh bruteforce: action = %(action_abuseipdb)s[abuseipdb_category="18,22"]
# ID Title Description
# 3 Fraud Orders
@@ -101,5 +100,5 @@ actionunban =
# Notes Your API key from abuseipdb.com
# Values: STRING Default: None
# Register for abuseipdb [https://www.abuseipdb.com], get api key and set below.
# You will need to set the catagory in the action call.
# You will need to set the category in the action call.
abuseipdb_apikey =
+49
View File
@@ -0,0 +1,49 @@
# Fail2Ban configuration file
#
# Author: Chris Caron <lead2gold@gmail.com>
#
#
[Definition]
# Option: actionstart
# Notes.: command executed once at the start of Fail2Ban.
# Values: CMD
#
actionstart = printf %%b "The jail <name> as been started successfully." | <apprise> -t "[Fail2Ban] <name>: started on `uname -n`"
# Option: actionstop
# Notes.: command executed once at the end of Fail2Ban
# Values: CMD
#
actionstop = printf %%b "The jail <name> has been stopped." | <apprise> -t "[Fail2Ban] <name>: stopped on `uname -n`"
# Option: actioncheck
# Notes.: command executed once before each actionban command
# Values: CMD
#
actioncheck =
# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionban = printf %%b "The IP <ip> has just been banned by Fail2Ban after <failures> attempts against <name>" | <apprise> -n "warning" -t "[Fail2Ban] <name>: banned <ip> from `uname -n`"
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionunban =
[Init]
# Define location of the default apprise configuration file to use
#
config = /etc/fail2ban/apprise.conf
#
apprise = apprise -c "<config>"
-19
View File
@@ -1,19 +0,0 @@
# Fail2ban reporting to badips.com
#
# Note: This reports an IP only and does not actually ban traffic. Use
# another action in the same jail if you want bans to occur.
#
# Set the category to the appropriate value before use.
#
# To get see register and optional key to get personalised graphs see:
# http://www.badips.com/blog/personalized-statistics-track-the-attackers-of-all-your-servers-with-one-key
[Definition]
actionban = curl --fail --user-agent "<agent>" http://www.badips.com/add/<category>/<ip>
[Init]
# Option: category
# Notes.: Values are from the list here: http://www.badips.com/get/categories
category =
-391
View File
@@ -1,391 +0,0 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :
# This file is part of Fail2Ban.
#
# Fail2Ban 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 2 of the License, or
# (at your option) any later version.
#
# Fail2Ban 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 Fail2Ban; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import sys
if sys.version_info < (2, 7): # pragma: no cover
raise ImportError("badips.py action requires Python >= 2.7")
import json
import threading
import logging
if sys.version_info >= (3, ): # pragma: 2.x no cover
from urllib.request import Request, urlopen
from urllib.parse import urlencode
from urllib.error import HTTPError
else: # pragma: 3.x no cover
from urllib2 import Request, urlopen, HTTPError
from urllib import urlencode
from fail2ban.server.actions import Actions, ActionBase, BanTicket
from fail2ban.helpers import splitwords, str2LogLevel
class BadIPsAction(ActionBase): # pragma: no cover - may be unavailable
"""Fail2Ban action which reports bans to badips.com, and also
blacklist bad IPs listed on badips.com by using another action's
ban method.
Parameters
----------
jail : Jail
The jail which the action belongs to.
name : str
Name assigned to the action.
category : str
Valid badips.com category for reporting failures.
score : int, optional
Minimum score for bad IPs. Default 3.
age : str, optional
Age of last report for bad IPs, per badips.com syntax.
Default "24h" (24 hours)
banaction : str, optional
Name of banaction to use for blacklisting bad IPs. If `None`,
no blacklist of IPs will take place.
Default `None`.
bancategory : str, optional
Name of category to use for blacklisting, which can differ
from category used for reporting. e.g. may want to report
"postfix", but want to use whole "mail" category for blacklist.
Default `category`.
bankey : str, optional
Key issued by badips.com to retrieve personal list
of blacklist IPs.
updateperiod : int, optional
Time in seconds between updating bad IPs blacklist.
Default 900 (15 minutes)
loglevel : int/str, optional
Log level of the message when an IP is (un)banned.
Default `DEBUG`.
Can be also supplied as two-value list (comma- or space separated) to
provide level of the summary message when a group of IPs is (un)banned.
Example `DEBUG,INFO`.
agent : str, optional
User agent transmitted to server.
Default `Fail2Ban/ver.`
Raises
------
ValueError
If invalid `category`, `score`, `banaction` or `updateperiod`.
"""
TIMEOUT = 10
_badips = "https://www.badips.com"
def _Request(self, url, **argv):
return Request(url, headers={'User-Agent': self.agent}, **argv)
def __init__(self, jail, name, category, score=3, age="24h",
banaction=None, bancategory=None, bankey=None, updateperiod=900,
loglevel='DEBUG', agent="Fail2Ban", timeout=TIMEOUT):
super(BadIPsAction, self).__init__(jail, name)
self.timeout = timeout
self.agent = agent
self.category = category
self.score = score
self.age = age
self.banaction = banaction
self.bancategory = bancategory or category
self.bankey = bankey
loglevel = splitwords(loglevel)
self.sumloglevel = str2LogLevel(loglevel[-1])
self.loglevel = str2LogLevel(loglevel[0])
self.updateperiod = updateperiod
self._bannedips = set()
# Used later for threading.Timer for updating badips
self._timer = None
@staticmethod
def isAvailable(timeout=1):
try:
response = urlopen(Request("/".join([BadIPsAction._badips]),
headers={'User-Agent': "Fail2Ban"}), timeout=timeout)
return True, ''
except Exception as e: # pragma: no cover
return False, e
def logError(self, response, what=''): # pragma: no cover - sporadical (502: Bad Gateway, etc)
messages = {}
try:
messages = json.loads(response.read().decode('utf-8'))
except:
pass
self._logSys.error(
"%s. badips.com response: '%s'", what,
messages.get('err', 'Unknown'))
def getCategories(self, incParents=False):
"""Get badips.com categories.
Returns
-------
set
Set of categories.
Raises
------
HTTPError
Any issues with badips.com request.
ValueError
If badips.com response didn't contain necessary information
"""
try:
response = urlopen(
self._Request("/".join([self._badips, "get", "categories"])), timeout=self.timeout)
except HTTPError as response: # pragma: no cover
self.logError(response, "Failed to fetch categories")
raise
else:
response_json = json.loads(response.read().decode('utf-8'))
if not 'categories' in response_json:
err = "badips.com response lacked categories specification. Response was: %s" \
% (response_json,)
self._logSys.error(err)
raise ValueError(err)
categories = response_json['categories']
categories_names = set(
value['Name'] for value in categories)
if incParents:
categories_names.update(set(
value['Parent'] for value in categories
if "Parent" in value))
return categories_names
def getList(self, category, score, age, key=None):
"""Get badips.com list of bad IPs.
Parameters
----------
category : str
Valid badips.com category.
score : int
Minimum score for bad IPs.
age : str
Age of last report for bad IPs, per badips.com syntax.
key : str, optional
Key issued by badips.com to fetch IPs reported with the
associated key.
Returns
-------
set
Set of bad IPs.
Raises
------
HTTPError
Any issues with badips.com request.
"""
try:
url = "?".join([
"/".join([self._badips, "get", "list", category, str(score)]),
urlencode({'age': age})])
if key:
url = "&".join([url, urlencode({'key': key})])
self._logSys.debug('badips.com: get list, url: %r', url)
response = urlopen(self._Request(url), timeout=self.timeout)
except HTTPError as response: # pragma: no cover
self.logError(response, "Failed to fetch bad IP list")
raise
else:
return set(response.read().decode('utf-8').split())
@property
def category(self):
"""badips.com category for reporting IPs.
"""
return self._category
@category.setter
def category(self, category):
if category not in self.getCategories():
self._logSys.error("Category name '%s' not valid. "
"see badips.com for list of valid categories",
category)
raise ValueError("Invalid category: %s" % category)
self._category = category
@property
def bancategory(self):
"""badips.com bancategory for fetching IPs.
"""
return self._bancategory
@bancategory.setter
def bancategory(self, bancategory):
if bancategory != "any" and bancategory not in self.getCategories(incParents=True):
self._logSys.error("Category name '%s' not valid. "
"see badips.com for list of valid categories",
bancategory)
raise ValueError("Invalid bancategory: %s" % bancategory)
self._bancategory = bancategory
@property
def score(self):
"""badips.com minimum score for fetching IPs.
"""
return self._score
@score.setter
def score(self, score):
score = int(score)
if 0 <= score <= 5:
self._score = score
else:
raise ValueError("Score must be 0-5")
@property
def banaction(self):
"""Jail action to use for banning/unbanning.
"""
return self._banaction
@banaction.setter
def banaction(self, banaction):
if banaction is not None and banaction not in self._jail.actions:
self._logSys.error("Action name '%s' not in jail '%s'",
banaction, self._jail.name)
raise ValueError("Invalid banaction")
self._banaction = banaction
@property
def updateperiod(self):
"""Period in seconds between banned bad IPs will be updated.
"""
return self._updateperiod
@updateperiod.setter
def updateperiod(self, updateperiod):
updateperiod = int(updateperiod)
if updateperiod > 0:
self._updateperiod = updateperiod
else:
raise ValueError("Update period must be integer greater than 0")
def _banIPs(self, ips):
for ip in ips:
try:
ai = Actions.ActionInfo(BanTicket(ip), self._jail)
self._jail.actions[self.banaction].ban(ai)
except Exception as e:
self._logSys.error(
"Error banning IP %s for jail '%s' with action '%s': %s",
ip, self._jail.name, self.banaction, e,
exc_info=self._logSys.getEffectiveLevel()<=logging.DEBUG)
else:
self._bannedips.add(ip)
self._logSys.log(self.loglevel,
"Banned IP %s for jail '%s' with action '%s'",
ip, self._jail.name, self.banaction)
def _unbanIPs(self, ips):
for ip in ips:
try:
ai = Actions.ActionInfo(BanTicket(ip), self._jail)
self._jail.actions[self.banaction].unban(ai)
except Exception as e:
self._logSys.error(
"Error unbanning IP %s for jail '%s' with action '%s': %s",
ip, self._jail.name, self.banaction, e,
exc_info=self._logSys.getEffectiveLevel()<=logging.DEBUG)
else:
self._logSys.log(self.loglevel,
"Unbanned IP %s for jail '%s' with action '%s'",
ip, self._jail.name, self.banaction)
finally:
self._bannedips.remove(ip)
def start(self):
"""If `banaction` set, blacklists bad IPs.
"""
if self.banaction is not None:
self.update()
def update(self):
"""If `banaction` set, updates blacklisted IPs.
Queries badips.com for list of bad IPs, removing IPs from the
blacklist if no longer present, and adds new bad IPs to the
blacklist.
"""
if self.banaction is not None:
if self._timer:
self._timer.cancel()
self._timer = None
try:
ips = self.getList(
self.bancategory, self.score, self.age, self.bankey)
# Remove old IPs no longer listed
s = self._bannedips - ips
m = len(s)
self._unbanIPs(s)
# Add new IPs which are now listed
s = ips - self._bannedips
p = len(s)
self._banIPs(s)
if m != 0 or p != 0:
self._logSys.log(self.sumloglevel,
"Updated IPs for jail '%s' (-%d/+%d)",
self._jail.name, m, p)
self._logSys.debug(
"Next update for jail '%' in %i seconds",
self._jail.name, self.updateperiod)
finally:
self._timer = threading.Timer(self.updateperiod, self.update)
self._timer.start()
def stop(self):
"""If `banaction` set, clears blacklisted IPs.
"""
if self.banaction is not None:
if self._timer:
self._timer.cancel()
self._timer = None
self._unbanIPs(self._bannedips.copy())
def ban(self, aInfo):
"""Reports banned IP to badips.com.
Parameters
----------
aInfo : dict
Dictionary which includes information in relation to
the ban.
Raises
------
HTTPError
Any issues with badips.com request.
"""
try:
url = "/".join([self._badips, "add", self.category, str(aInfo['ip'])])
self._logSys.debug('badips.com: ban, url: %r', url)
response = urlopen(self._Request(url), timeout=self.timeout)
except HTTPError as response: # pragma: no cover
self.logError(response, "Failed to ban")
raise
else:
messages = json.loads(response.read().decode('utf-8'))
self._logSys.debug(
"Response from badips.com report: '%s'",
messages['suc'])
Action = BadIPsAction
+4 -1
View File
@@ -14,7 +14,10 @@
# Notes.: command executed on demand at the first ban (or at the start of Fail2Ban if actionstart_on_demand is set to false).
# Values: CMD
#
actionstart = ipfw show | fgrep -c -m 1 -s 'table(<table>)' > /dev/null 2>&1 || ( ipfw show | awk 'BEGIN { b = <lowest_rule_num> } { if ($1 < b) {} else if ($1 == b) { b = $1 + 1 } else { e = b } } END { if (e) exit e <br> else exit b }'; num=$?; ipfw -q add $num <blocktype> <block> from table\(<table>\) to me <port>; echo $num > "<startstatefile>" )
actionstart = ipfw show | fgrep -c -m 1 -s 'table(<table>)' > /dev/null 2>&1 || (
num=$(ipfw show | awk 'BEGIN { b = <lowest_rule_num> } { if ($1 == b) { b = $1 + 1 } } END { print b }');
ipfw -q add "$num" <blocktype> <block> from table\(<table>\) to me <port>; echo "$num" > "<startstatefile>"
)
# Option: actionstop
+17 -7
View File
@@ -5,7 +5,7 @@
#
# Please set jail.local's permission to 640 because it contains your CF API key.
#
# This action depends on curl.
# This action depends on curl (and optionally jq).
# Referenced from http://www.normyee.net/blog/2012/02/02/adding-cloudflare-support-to-fail2ban by NORM YEE
#
# To get your CloudFlare API Key: https://www.cloudflare.com/a/account/my-account
@@ -43,9 +43,9 @@ actioncheck =
# API v1
#actionban = curl -s -o /dev/null https://www.cloudflare.com/api_json.html -d 'a=ban' -d 'tkn=<cftoken>' -d 'email=<cfuser>' -d 'key=<ip>'
# API v4
actionban = curl -s -o /dev/null -X POST -H 'X-Auth-Email: <cfuser>' -H 'X-Auth-Key: <cftoken>' \
-H 'Content-Type: application/json' -d '{ "mode": "block", "configuration": { "target": "ip", "value": "<ip>" } }' \
https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules
actionban = curl -s -o /dev/null -X POST <_cf_api_prms> \
-d '{"mode":"block","configuration":{"target":"<cftarget>","value":"<ip>"},"notes":"Fail2Ban <name>"}' \
<_cf_api_url>
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
@@ -58,9 +58,14 @@ actionban = curl -s -o /dev/null -X POST -H 'X-Auth-Email: <cfuser>' -H 'X-Auth-
# API v1
#actionunban = curl -s -o /dev/null https://www.cloudflare.com/api_json.html -d 'a=nul' -d 'tkn=<cftoken>' -d 'email=<cfuser>' -d 'key=<ip>'
# API v4
actionunban = curl -s -o /dev/null -X DELETE -H 'X-Auth-Email: <cfuser>' -H 'X-Auth-Key: <cftoken>' \
https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules/$(curl -s -X GET -H 'X-Auth-Email: <cfuser>' -H 'X-Auth-Key: <cftoken>' \
'https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules?mode=block&configuration_target=ip&configuration_value=<ip>&page=1&per_page=1' | cut -d'"' -f6)
actionunban = id=$(curl -s -X GET <_cf_api_prms> \
"<_cf_api_url>?mode=block&configuration_target=<cftarget>&configuration_value=<ip>&page=1&per_page=1&notes=Fail2Ban%%20<name>" \
| { jq -r '.result[0].id' 2>/dev/null || tr -d '\n' | sed -nE 's/^.*"result"\s*:\s*\[\s*\{\s*"id"\s*:\s*"([^"]+)".*$/\1/p'; })
if [ -z "$id" ]; then echo "<name>: id for <ip> cannot be found"; exit 0; fi;
curl -s -o /dev/null -X DELETE <_cf_api_prms> "<_cf_api_url>/$id"
_cf_api_url = https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules
_cf_api_prms = -H 'X-Auth-Email: <cfuser>' -H 'X-Auth-Key: <cftoken>' -H 'Content-Type: application/json'
[Init]
@@ -76,3 +81,8 @@ actionunban = curl -s -o /dev/null -X DELETE -H 'X-Auth-Email: <cfuser>' -H 'X-A
cftoken =
cfuser =
cftarget = ip
[Init?family=inet6]
cftarget = ip6
+1 -1
View File
@@ -102,7 +102,7 @@ logpath = /dev/null
# Notes.: Your system mail command. Is passed 2 args: subject and recipient
# Values: CMD
#
mailcmd = mail -s
mailcmd = mail -E 'set escape' -s
# Option: mailargs
# Notes.: Additional arguments to mail command. e.g. for standard Unix mail:
+1 -1
View File
@@ -179,7 +179,7 @@ tcpflags =
# Notes.: Your system mail command. Is passed 2 args: subject and recipient
# Values: CMD
#
mailcmd = mail -s
mailcmd = mail -E 'set escape' -s
# Option: mailargs
# Notes.: Additional arguments to mail command. e.g. for standard Unix mail:
+53 -10
View File
@@ -18,19 +18,46 @@ before = firewallcmd-common.conf
[Definition]
actionstart = ipset create <ipmset> hash:ip timeout <bantime><familyopt>
actionstart = <ipstype_<ipsettype>/actionstart>
firewall-cmd --direct --add-rule <family> filter <chain> 0 <actiontype> -m set --match-set <ipmset> src -j <blocktype>
actionflush = ipset flush <ipmset>
actionflush = <ipstype_<ipsettype>/actionflush>
actionstop = firewall-cmd --direct --remove-rule <family> filter <chain> 0 <actiontype> -m set --match-set <ipmset> src -j <blocktype>
<actionflush>
ipset destroy <ipmset>
<ipstype_<ipsettype>/actionstop>
actionban = ipset add <ipmset> <ip> timeout <bantime> -exist
actionban = <ipstype_<ipsettype>/actionban>
# actionprolong = %(actionban)s
actionunban = <ipstype_<ipsettype>/actionunban>
[ipstype_ipset]
actionstart = ipset create <ipmset> hash:ip timeout <default-ipsettime> <familyopt>
actionflush = ipset flush <ipmset>
actionstop = ipset destroy <ipmset>
actionban = ipset add <ipmset> <ip> timeout <ipsettime> -exist
actionunban = ipset del <ipmset> <ip> -exist
[ipstype_firewalld]
actionstart = firewall-cmd --direct --new-ipset=<ipmset> --type=hash:ip --option=timeout=<default-ipsettime> <firewalld_familyopt>
# TODO: there doesn't seem to be an explicit way to invoke the ipset flush function using firewall-cmd
actionflush =
actionstop = firewall-cmd --direct --delete-ipset=<ipmset>
actionban = firewall-cmd --ipset=<ipmset> --add-entry=<ip>
actionunban = firewall-cmd --ipset=<ipmset> --remove-entry=<ip>
[Init]
# Option: chain
@@ -40,11 +67,25 @@ actionunban = ipset del <ipmset> <ip> -exist
#
chain = INPUT_direct
# Option: bantime
# Notes: specifies the bantime in seconds (handled internally rather than by fail2ban)
# Values: [ NUM ] Default: 600
# Option: default-ipsettime
# Notes: specifies default timeout in seconds (handled default ipset timeout only)
# Values: [ NUM ] Default: 0 (no timeout, managed by fail2ban by unban)
default-ipsettime = 0
bantime = 600
# Option: ipsettime
# Notes: specifies ticket timeout (handled ipset timeout only)
# Values: [ NUM ] Default: 0 (managed by fail2ban by unban)
ipsettime = 0
# expresion to caclulate timeout from bantime, example:
# banaction = %(known/banaction)s[ipsettime='<timeout-bantime>']
timeout-bantime = $([ "<bantime>" -le 2147483 ] && echo "<bantime>" || echo 0)
# Option: ipsettype
# Notes.: defines type of ipset used for match-set (firewalld or ipset)
# Values: firewalld or ipset
# Default: ipset
ipsettype = ipset
# Option: actiontype
# Notes.: defines additions to the blocking rule
@@ -65,14 +106,16 @@ multiport = -p <protocol> -m multiport --dports <port>
ipmset = f2b-<name>
familyopt =
firewalld_familyopt =
[Init?family=inet6]
ipmset = f2b-<name>6
familyopt = <sp>family inet6
familyopt = family inet6
firewalld_familyopt = --option=family=inet6
# DEV NOTES:
#
# Author: Edgar Hoch and Daniel Black
# Author: Edgar Hoch, Daniel Black, Sergey Brester and Mihail Politaev
# firewallcmd-new / iptables-ipset-proto6 combined for maximium goodness
+4 -26
View File
@@ -1,6 +1,6 @@
# Fail2Ban configuration file
#
# Author: Donald Yandt
# Authors: Donald Yandt, Sergey G. Brester
#
# Because of the rich rule commands requires firewalld-0.3.1+
# This action uses firewalld rich-rules which gives you a cleaner iptables since it stores rules according to zones and not
@@ -10,36 +10,15 @@
#
# If you use the --permanent rule you get a xml file in /etc/firewalld/zones/<zone>.xml that can be shared and parsed easliy
#
# Example commands to view rules:
# firewall-cmd [--zone=<zone>] --list-rich-rules
# firewall-cmd [--zone=<zone>] --list-all
# firewall-cmd [--zone=zone] --query-rich-rule='rule'
# This is an derivative of firewallcmd-rich-rules.conf, see there for details and other parameters.
[INCLUDES]
before = firewallcmd-common.conf
before = firewallcmd-rich-rules.conf
[Definition]
actionstart =
actionstop =
actioncheck =
# you can also use zones and/or service names.
#
# zone example:
# firewall-cmd --zone=<zone> --add-rich-rule="rule family='<family>' source address='<ip>' port port='<port>' protocol='<protocol>' log prefix='f2b-<name>' level='<level>' limit value='<rate>/m' <rich-blocktype>"
#
# service name example:
# firewall-cmd --zone=<zone> --add-rich-rule="rule family='<family>' source address='<ip>' service name='<service>' log prefix='f2b-<name>' level='<level>' limit value='<rate>/m' <rich-blocktype>"
#
# Because rich rules can only handle single or a range of ports we must split ports and execute the command for each port. Ports can be single and ranges separated by a comma or space for an example: http, https, 22-60, 18 smtp
actionban = ports="<port>"; for p in $(echo $ports | tr ", " " "); do firewall-cmd --add-rich-rule="rule family='<family>' source address='<ip>' port port='$p' protocol='<protocol>' log prefix='f2b-<name>' level='<level>' limit value='<rate>/m' <rich-blocktype>"; done
actionunban = ports="<port>"; for p in $(echo $ports | tr ", " " "); do firewall-cmd --remove-rich-rule="rule family='<family>' source address='<ip>' port port='$p' protocol='<protocol>' log prefix='f2b-<name>' level='<level>' limit value='<rate>/m' <rich-blocktype>"; done
rich-suffix = log prefix='f2b-<name>' level='<level>' limit value='<rate>/m' <rich-blocktype>
[Init]
@@ -48,4 +27,3 @@ level = info
# log rate per minute
rate = 1
+5 -3
View File
@@ -35,8 +35,10 @@ actioncheck =
#
# Because rich rules can only handle single or a range of ports we must split ports and execute the command for each port. Ports can be single and ranges separated by a comma or space for an example: http, https, 22-60, 18 smtp
actionban = ports="<port>"; for p in $(echo $ports | tr ", " " "); do firewall-cmd --add-rich-rule="rule family='<family>' source address='<ip>' port port='$p' protocol='<protocol>' <rich-blocktype>"; done
fwcmd_rich_rule = rule family='<family>' source address='<ip>' port port='$p' protocol='<protocol>' %(rich-suffix)s
actionban = ports="<port>"; for p in $(echo $ports | tr ", " " "); do firewall-cmd --add-rich-rule="%(fwcmd_rich_rule)s"; done
actionunban = ports="<port>"; for p in $(echo $ports | tr ", " " "); do firewall-cmd --remove-rich-rule="rule family='<family>' source address='<ip>' port port='$p' protocol='<protocol>' <rich-blocktype>"; done
actionunban = ports="<port>"; for p in $(echo $ports | tr ", " " "); do firewall-cmd --remove-rich-rule="%(fwcmd_rich_rule)s"; done
rich-suffix = <rich-blocktype>
@@ -26,7 +26,7 @@ before = iptables-common.conf
# Notes.: command executed on demand at the first ban (or at the start of Fail2Ban if actionstart_on_demand is set to false).
# Values: CMD
#
actionstart = ipset create <ipmset> hash:ip timeout <bantime><familyopt>
actionstart = ipset create <ipmset> hash:ip timeout <default-ipsettime> <familyopt>
<iptables> -I <chain> -m set --match-set <ipmset> src -j <blocktype>
# Option: actionflush
@@ -49,7 +49,9 @@ actionstop = <iptables> -D <chain> -m set --match-set <ipmset> src -j <blocktype
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionban = ipset add <ipmset> <ip> timeout <bantime> -exist
actionban = ipset add <ipmset> <ip> timeout <ipsettime> -exist
# actionprolong = %(actionban)s
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
@@ -61,11 +63,19 @@ actionunban = ipset del <ipmset> <ip> -exist
[Init]
# Option: bantime
# Notes: specifies the bantime in seconds (handled internally rather than by fail2ban)
# Values: [ NUM ] Default: 600
#
bantime = 600
# Option: default-ipsettime
# Notes: specifies default timeout in seconds (handled default ipset timeout only)
# Values: [ NUM ] Default: 0 (no timeout, managed by fail2ban by unban)
default-ipsettime = 0
# Option: ipsettime
# Notes: specifies ticket timeout (handled ipset timeout only)
# Values: [ NUM ] Default: 0 (managed by fail2ban by unban)
ipsettime = 0
# expresion to caclulate timeout from bantime, example:
# banaction = %(known/banaction)s[ipsettime='<timeout-bantime>']
timeout-bantime = $([ "<bantime>" -le 2147483 ] && echo "<bantime>" || echo 0)
ipmset = f2b-<name>
familyopt =
@@ -74,4 +84,4 @@ familyopt =
[Init?family=inet6]
ipmset = f2b-<name>6
familyopt = <sp>family inet6
familyopt = family inet6
+18 -8
View File
@@ -26,7 +26,7 @@ before = iptables-common.conf
# Notes.: command executed on demand at the first ban (or at the start of Fail2Ban if actionstart_on_demand is set to false).
# Values: CMD
#
actionstart = ipset create <ipmset> hash:ip timeout <bantime><familyopt>
actionstart = ipset create <ipmset> hash:ip timeout <default-ipsettime> <familyopt>
<iptables> -I <chain> -p <protocol> -m multiport --dports <port> -m set --match-set <ipmset> src -j <blocktype>
# Option: actionflush
@@ -49,7 +49,9 @@ actionstop = <iptables> -D <chain> -p <protocol> -m multiport --dports <port> -m
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionban = ipset add <ipmset> <ip> timeout <bantime> -exist
actionban = ipset add <ipmset> <ip> timeout <ipsettime> -exist
# actionprolong = %(actionban)s
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
@@ -61,11 +63,19 @@ actionunban = ipset del <ipmset> <ip> -exist
[Init]
# Option: bantime
# Notes: specifies the bantime in seconds (handled internally rather than by fail2ban)
# Values: [ NUM ] Default: 600
#
bantime = 600
# Option: default-ipsettime
# Notes: specifies default timeout in seconds (handled default ipset timeout only)
# Values: [ NUM ] Default: 0 (no timeout, managed by fail2ban by unban)
default-ipsettime = 0
# Option: ipsettime
# Notes: specifies ticket timeout (handled ipset timeout only)
# Values: [ NUM ] Default: 0 (managed by fail2ban by unban)
ipsettime = 0
# expresion to caclulate timeout from bantime, example:
# banaction = %(known/banaction)s[ipsettime='<timeout-bantime>']
timeout-bantime = $([ "<bantime>" -le 2147483 ] && echo "<bantime>" || echo 0)
ipmset = f2b-<name>
familyopt =
@@ -74,4 +84,4 @@ familyopt =
[Init?family=inet6]
ipmset = f2b-<name>6
familyopt = <sp>family inet6
familyopt = family inet6
+4 -4
View File
@@ -17,7 +17,7 @@ actionstart = printf %%b "Hi,\n
The jail <name> has been started successfully.\n
Output will be buffered until <lines> lines are available.\n
Regards,\n
Fail2Ban"|mail -s "[Fail2Ban] <name>: started on <fq-hostname>" <dest>
Fail2Ban"|mail -E 'set escape' -s "[Fail2Ban] <name>: started on <fq-hostname>" <dest>
# Option: actionstop
# Notes.: command executed at the stop of jail (or at the end of Fail2Ban)
@@ -28,13 +28,13 @@ actionstop = if [ -f <tmpfile> ]; then
These hosts have been banned by Fail2Ban.\n
`cat <tmpfile>`
Regards,\n
Fail2Ban"|mail -s "[Fail2Ban] <name>: Summary from <fq-hostname>" <dest>
Fail2Ban"|mail -E 'set escape' -s "[Fail2Ban] <name>: Summary from <fq-hostname>" <dest>
rm <tmpfile>
fi
printf %%b "Hi,\n
The jail <name> has been stopped.\n
Regards,\n
Fail2Ban"|mail -s "[Fail2Ban] <name>: stopped on <fq-hostname>" <dest>
Fail2Ban"|mail -E 'set escape' -s "[Fail2Ban] <name>: stopped on <fq-hostname>" <dest>
# Option: actioncheck
# Notes.: command executed once before each actionban command
@@ -55,7 +55,7 @@ actionban = printf %%b "`date`: <ip> (<failures> failures)\n" >> <tmpfile>
These hosts have been banned by Fail2Ban.\n
`cat <tmpfile>`
\nRegards,\n
Fail2Ban"|mail -s "[Fail2Ban] <name>: Summary" <dest>
Fail2Ban"|mail -E 'set escape' -s "[Fail2Ban] <name>: Summary" <dest>
rm <tmpfile>
fi
+1 -1
View File
@@ -72,7 +72,7 @@ actionunban =
# Notes.: Your system mail command. Is passed 2 args: subject and recipient
# Values: CMD
#
mailcmd = mail -s
mailcmd = mail -E 'set escape' -s
# Default name of the chain
#
+3 -3
View File
@@ -20,7 +20,7 @@ norestored = 1
actionstart = printf %%b "Hi,\n
The jail <name> has been started successfully.\n
Regards,\n
Fail2Ban"|mail -s "[Fail2Ban] <name>: started on <fq-hostname>" <dest>
Fail2Ban"|mail -E 'set escape' -s "[Fail2Ban] <name>: started on <fq-hostname>" <dest>
# Option: actionstop
# Notes.: command executed at the stop of jail (or at the end of Fail2Ban)
@@ -29,7 +29,7 @@ actionstart = printf %%b "Hi,\n
actionstop = printf %%b "Hi,\n
The jail <name> has been stopped.\n
Regards,\n
Fail2Ban"|mail -s "[Fail2Ban] <name>: stopped on <fq-hostname>" <dest>
Fail2Ban"|mail -E 'set escape' -s "[Fail2Ban] <name>: stopped on <fq-hostname>" <dest>
# Option: actioncheck
# Notes.: command executed once before each actionban command
@@ -49,7 +49,7 @@ actionban = printf %%b "Hi,\n
Here is more information about <ip> :\n
`%(_whois_command)s`\n
Regards,\n
Fail2Ban"|mail -s "[Fail2Ban] <name>: banned <ip> from <fq-hostname>" <dest>
Fail2Ban"|mail -E 'set escape' -s "[Fail2Ban] <name>: banned <ip> from <fq-hostname>" <dest>
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
+3 -3
View File
@@ -16,7 +16,7 @@ norestored = 1
actionstart = printf %%b "Hi,\n
The jail <name> has been started successfully.\n
Regards,\n
Fail2Ban"|mail -s "[Fail2Ban] <name>: started on <fq-hostname>" <dest>
Fail2Ban"|mail -E 'set escape' -s "[Fail2Ban] <name>: started on <fq-hostname>" <dest>
# Option: actionstop
# Notes.: command executed at the stop of jail (or at the end of Fail2Ban)
@@ -25,7 +25,7 @@ actionstart = printf %%b "Hi,\n
actionstop = printf %%b "Hi,\n
The jail <name> has been stopped.\n
Regards,\n
Fail2Ban"|mail -s "[Fail2Ban] <name>: stopped on <fq-hostname>" <dest>
Fail2Ban"|mail -E 'set escape' -s "[Fail2Ban] <name>: stopped on <fq-hostname>" <dest>
# Option: actioncheck
# Notes.: command executed once before each actionban command
@@ -43,7 +43,7 @@ actionban = printf %%b "Hi,\n
The IP <ip> has just been banned by Fail2Ban after
<failures> attempts against <name>.\n
Regards,\n
Fail2Ban"|mail -s "[Fail2Ban] <name>: banned <ip> from <fq-hostname>" <dest>
Fail2Ban"|mail -E 'set escape' -s "[Fail2Ban] <name>: banned <ip> from <fq-hostname>" <dest>
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
+1 -1
View File
@@ -34,7 +34,7 @@ type = multiport
rule_match-custom =
rule_match-allports = meta l4proto \{ <protocol> \}
rule_match-multiport = $proto dport \{ <port> \}
rule_match-multiport = $proto dport \{ $(echo '<port>' | sed s/:/-/g) \}
match = <rule_match-<type>>
# Option: rule_stat
+13 -4
View File
@@ -84,8 +84,15 @@ srv_cfg_path = /etc/nginx/
#srv_cmd = nginx -c %(srv_cfg_path)s/nginx.conf
srv_cmd = nginx
# first test configuration is correct, hereafter send reload signal:
blck_lst_reload = %(srv_cmd)s -qt; if [ $? -eq 0 ]; then
# pid file (used to check nginx is running):
srv_pid = /run/nginx.pid
# command used to check whether nginx is running and configuration is valid:
srv_is_running = [ -f "%(srv_pid)s" ]
srv_check_cmd = %(srv_is_running)s && %(srv_cmd)s -qt
# first test nginx is running and configuration is correct, hereafter send reload signal:
blck_lst_reload = %(srv_check_cmd)s; if [ $? -eq 0 ]; then
%(srv_cmd)s -s reload; if [ $? -ne 0 ]; then echo 'reload failed.'; fi;
fi;
@@ -103,6 +110,8 @@ actionstop = %(actionflush)s
actioncheck =
actionban = echo "\\\\<fid> 1;" >> '%(blck_lst_file)s'; %(blck_lst_reload)s
_echo_blck_row = printf '\%%s 1;\n' "<fid>"
actionunban = id=$(echo "<fid>" | sed -e 's/[]\/$*.^|[]/\\&/g'); sed -i "/^\\\\$id 1;$/d" %(blck_lst_file)s; %(blck_lst_reload)s
actionban = %(_echo_blck_row)s >> '%(blck_lst_file)s'; %(blck_lst_reload)s
actionunban = id=$(%(_echo_blck_row)s | sed -e 's/[]\/$*.^|[]/\\&/g'); sed -i "/^$id$/d" %(blck_lst_file)s; %(blck_lst_reload)s
+2 -2
View File
@@ -12,5 +12,5 @@ actioncheck =
actionban = /usr/libexec/afctl -a <ip> -t <bantime>
actionunban = /usr/libexec/afctl -r <ip>
[Init]
bantime = 2880
actionprolong = %(actionunban)s && %(actionban)s
+16 -8
View File
@@ -51,7 +51,7 @@
# Values: CMD
#
actionstart = if ! ipset -quiet -name list f2b-<name> >/dev/null;
then ipset -quiet -exist create f2b-<name> hash:ip timeout <bantime>;
then ipset -quiet -exist create f2b-<name> hash:ip timeout <default-ipsettime>;
fi
# Option: actionstop
@@ -66,7 +66,9 @@ actionstop = ipset flush f2b-<name>
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionban = ipset add f2b-<name> <ip> timeout <bantime> -exist
actionban = ipset add f2b-<name> <ip> timeout <ipsettime> -exist
# actionprolong = %(actionban)s
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
@@ -76,10 +78,16 @@ actionban = ipset add f2b-<name> <ip> timeout <bantime> -exist
#
actionunban = ipset del f2b-<name> <ip> -exist
[Init]
# Option: default-ipsettime
# Notes: specifies default timeout in seconds (handled default ipset timeout only)
# Values: [ NUM ] Default: 0 (no timeout, managed by fail2ban by unban)
default-ipsettime = 0
# Option: bantime
# Notes: specifies the bantime in seconds (handled internally rather than by fail2ban)
# Values: [ NUM ] Default: 600
#
bantime = 600
# Option: ipsettime
# Notes: specifies ticket timeout (handled ipset timeout only)
# Values: [ NUM ] Default: 0 (managed by fail2ban by unban)
ipsettime = 0
# expresion to caclulate timeout from bantime, example:
# banaction = %(known/banaction)s[ipsettime='<timeout-bantime>']
timeout-bantime = $([ "<bantime>" -le 2147483 ] && echo "<bantime>" || echo 0)
+40 -7
View File
@@ -13,16 +13,45 @@ actionstop =
actioncheck =
actionban = [ -n "<application>" ] && app="app <application>"
ufw insert <insertpos> <blocktype> from <ip> to <destination> $app
# ufw does "quickly process packets for which we already have a connection" in before.rules,
# therefore all related sockets should be closed
# actionban is using `ss` to do so, this only handles IPv4 and IPv6.
actionunban = [ -n "<application>" ] && app="app <application>"
ufw delete <blocktype> from <ip> to <destination> $app
actionban = if [ -n "<application>" ] && ufw app info "<application>"
then
ufw <add> <blocktype> from <ip> to <destination> app "<application>" comment "<comment>"
else
ufw <add> <blocktype> from <ip> to <destination> comment "<comment>"
fi
<kill>
actionunban = if [ -n "<application>" ] && ufw app info "<application>"
then
ufw delete <blocktype> from <ip> to <destination> app "<application>"
else
ufw delete <blocktype> from <ip> to <destination>
fi
# Option: kill-mode
# Notes.: can be set to ss or conntrack (may be extended later with other modes) to immediately drop all connections from banned IP, default empty (no kill)
# Example: banaction = ufw[kill-mode=ss]
kill-mode =
# intern conditional parameter used to provide killing mode after ban:
_kill_ =
_kill_ss = ss -K dst "[<ip>]"
_kill_conntrack = conntrack -D -s "<ip>"
# Option: kill
# Notes.: can be used to specify custom killing feature, by default depending on option kill-mode
# Examples: banaction = ufw[kill='ss -K "( sport = :http || sport = :https )" dst "[<ip>]"']
# banaction = ufw[kill='cutter "<ip>"']
kill = <_kill_<kill-mode>>
[Init]
# Option: insertpos
# Notes.: The position number in the firewall list to insert the block rule
insertpos = 1
# Option: add
# Notes.: can be set to "insert 1" to insert a rule at certain position (here 1):
add = prepend
# Option: blocktype
# Notes.: reject or deny
@@ -36,6 +65,10 @@ destination = any
# Notes.: application from sudo ufw app list
application =
# Option: comment
# Notes.: comment for rule added by fail2ban
comment = by Fail2Ban after <failures> attempts against <name>
# DEV NOTES:
#
# Author: Guilhem Lettron
+7 -1
View File
@@ -19,7 +19,7 @@
# NOTICE
# INFO
# DEBUG
# Values: [ LEVEL ] Default: ERROR
# Values: [ LEVEL ] Default: INFO
#
loglevel = INFO
@@ -55,6 +55,12 @@ socket = /var/run/fail2ban/fail2ban.sock
#
pidfile = /var/run/fail2ban/fail2ban.pid
# Option: allowipv6
# Notes.: Allows IPv6 interface:
# Default: auto
# Values: [ auto yes (on, true, 1) no (off, false, 0) ] Default: auto
#allowipv6 = auto
# Options: dbfile
# Notes.: Set the file for the fail2ban persistent data to be stored.
# A value of ":memory:" means database is only stored in memory
+2 -2
View File
@@ -2,11 +2,11 @@
[Definition]
failregex = ^<HOST> .*Googlebot.*$
failregex = ^\s*<HOST> \S+ \S+(?: \S+)?\s+\S+ "[A-Z]+ /\S* [^"]*" \d+ \d+ \"[^"]*\" "[^"]*\bGooglebot/[^"]*"
ignoreregex =
datepattern = ^[^\[]*\[({DATE})
datepattern = ^[^\[]*(\[{DATE}\s*\])
{^LN-BEG}
# DEV Notes:
+2 -2
View File
@@ -17,9 +17,9 @@ before = apache-common.conf
[Definition]
script = /\S*(?:php(?:[45]|[.-]cgi)?|\.asp|\.exe|\.pl)
script = /\S*(?:php(?:[45]|[.-]cgi)?|\.asp|\.exe|\.pl|\bcgi-bin/)
prefregex = ^%(_apache_error_client)s (?:AH0(?:01(?:28|30)|1(?:264|071)): )?(?:(?:[Ff]ile|script|[Gg]ot) )<F-CONTENT>.+</F-CONTENT>$
prefregex = ^%(_apache_error_client)s (?:AH0(?:01(?:28|30)|1(?:264|071)|2811): )?(?:(?:[Ff]ile|script|[Gg]ot) )<F-CONTENT>.+</F-CONTENT>$
failregex = ^(?:does not exist|not found or unable to stat): <script>\b
^'<script>\S*' not found or unable to stat
+1 -1
View File
@@ -8,7 +8,7 @@ before = apache-common.conf
[Definition]
failregex = ^%(_apache_error_client)s (?:(?:AH0013[456]: )?Invalid (method|URI) in request\b|(?:AH00565: )?request failed: URI too long \(longer than \d+\)|request failed: erroneous characters after protocol string:|(?:AH00566: )?request failed: invalid characters in URI\b)
failregex = ^%(_apache_error_client)s (?:(?:AH001[23][456]: )?Invalid (method|URI) in request\b|(?:AH00565: )?request failed: URI too long \(longer than \d+\)|request failed: erroneous characters after protocol string:|(?:AH00566: )?request failed: invalid characters in URI\b)
ignoreregex =
+1 -1
View File
@@ -21,7 +21,7 @@ log_prefix= (?:NOTICE|SECURITY|WARNING)%(__pid_re)s:?(?:\[C-[\da-f]*\])?:? [^:]+
prefregex = ^%(__prefix_line)s%(log_prefix)s <F-CONTENT>.+</F-CONTENT>$
failregex = ^Registration from '[^']*' failed for '<HOST>(:\d+)?' - (?:Wrong password|Username/auth name mismatch|No matching peer found|Not a local domain|Device does not match ACL|Peer is not supposed to register|ACL error \(permit/deny\)|Not a local domain)$
^Call from '[^']*' \(<HOST>:\d+\) to extension '[^']*' rejected because extension not found in context
^Call from '[^']*' \((?:(?:TCP|UDP):)?<HOST>:\d+\) to extension '[^']*' rejected because extension not found in context
^(?:Host )?<HOST> (?:failed (?:to authenticate\b|MD5 authentication\b)|tried to authenticate with nonexistent user\b)
^No registration for peer '[^']*' \(from <HOST>\)$
^hacking attempt detected '<HOST>'$
+8 -1
View File
@@ -2,5 +2,12 @@
# Detecting failed login attempts
# Logged in bwdata/logs/identity/Identity/log.txt
[INCLUDES]
before = common.conf
[Definition]
failregex = ^\s*\[WRN\]\s+Failed login attempt(?:, 2FA invalid)?\. <HOST>$
_daemon = Bitwarden-Identity
failregex = ^%(__prefix_line)s\s*\[(?:W(?:RN|arning)|Bit\.Core\.[^\]]+)\]\s+Failed login attempt(?:, 2FA invalid)?\. <ADDR>$
# DEV Notes:
# __prefix_line can result to an empty string, so it can support syslog and non-syslog at once.
+4 -4
View File
@@ -25,7 +25,7 @@ __pid_re = (?:\[\d+\])
# Daemon name (with optional source_file:line or whatever)
# EXAMPLES: pam_rhosts_auth, [sshd], pop(pam_unix)
__daemon_re = [\[\(]?%(_daemon)s(?:\(\S+\))?[\]\)]?:?
__daemon_re = [\[\(]?<_daemon>(?:\(\S+\))?[\]\)]?:?
# extra daemon info
# EXAMPLE: [ID 800047 auth.info]
@@ -33,7 +33,7 @@ __daemon_extra_re = \[ID \d+ \S+\]
# Combinations of daemon name and PID
# EXAMPLES: sshd[31607], pop(pam_unix)[4920]
__daemon_combs_re = (?:%(__pid_re)s?:\s+%(__daemon_re)s|%(__daemon_re)s%(__pid_re)s?:?)
__daemon_combs_re = (?:<__pid_re>?:\s+<__daemon_re>|<__daemon_re><__pid_re>?:?)
# Some messages have a kernel prefix with a timestamp
# EXAMPLES: kernel: [769570.846956]
@@ -69,12 +69,12 @@ datepattern = <lt_<logtype>/datepattern>
[lt_file]
# Common line prefixes for logtype "file":
__prefix_line = %(__date_ambit)s?\s*(?:%(__bsd_syslog_verbose)s\s+)?(?:%(__hostname)s\s+)?(?:%(__kernel_prefix)s\s+)?(?:%(__vserver)s\s+)?(?:%(__daemon_combs_re)s\s+)?(?:%(__daemon_extra_re)s\s+)?
__prefix_line = <__date_ambit>?\s*(?:<__bsd_syslog_verbose>\s+)?(?:<__hostname>\s+)?(?:<__kernel_prefix>\s+)?(?:<__vserver>\s+)?(?:<__daemon_combs_re>\s+)?(?:<__daemon_extra_re>\s+)?
datepattern = {^LN-BEG}
[lt_short]
# Common (short) line prefix for logtype "journal" (corresponds output of formatJournalEntry):
__prefix_line = \s*(?:%(__hostname)s\s+)?(?:%(_daemon)s%(__pid_re)s?:?\s+)?(?:%(__kernel_prefix)s\s+)?
__prefix_line = \s*(?:<__hostname>\s+)?(?:<_daemon><__pid_re>?:?\s+)?(?:<__kernel_prefix>\s+)?
datepattern = %(lt_file/datepattern)s
[lt_journal]
__prefix_line = %(lt_short/__prefix_line)s
+1 -1
View File
@@ -12,7 +12,7 @@ before = common.conf
_daemon = courieresmtpd
prefregex = ^%(__prefix_line)serror,relay=<HOST>,<F-CONTENT>.+</F-CONTENT>$
prefregex = ^%(__prefix_line)serror,relay=<HOST>,(?:port=\d+,)?<F-CONTENT>.+</F-CONTENT>$
failregex = ^[^:]*: 550 User (<.*> )?unknown\.?$
^msg="535 Authentication failed\.",cmd:( AUTH \S+)?( [0-9a-zA-Z\+/=]+)?(?: \S+)$
+6 -5
View File
@@ -8,17 +8,18 @@ before = common.conf
[Definition]
_auth_worker = (?:dovecot: )?auth(?:-worker)?
_auth_worker_info = (?:conn \w+:auth(?:-worker)? \(uid=\w+\): auth(?:-worker)?<\d+>: )?
_daemon = (?:dovecot(?:-auth)?|auth)
prefregex = ^%(__prefix_line)s(?:%(_auth_worker)s(?:\([^\)]+\))?: )?(?:%(__pam_auth)s(?:\(dovecot:auth\))?: |(?:pop3|imap)-login: )?(?:Info: )?<F-CONTENT>.+</F-CONTENT>$
prefregex = ^%(__prefix_line)s(?:%(_auth_worker)s(?:\([^\)]+\))?: )?(?:%(__pam_auth)s(?:\(dovecot:auth\))?: |(?:pop3|imap|managesieve|submission)-login: )?(?:Info: )?%(_auth_worker_info)s<F-CONTENT>.+</F-CONTENT>$
failregex = ^authentication failure; logname=<F-ALT_USER1>\S*</F-ALT_USER1> uid=\S* euid=\S* tty=dovecot ruser=<F-USER>\S*</F-USER> rhost=<HOST>(?:\s+user=<F-ALT_USER>\S*</F-ALT_USER>)?\s*$
^(?:Aborted login|Disconnected)(?::(?: [^ \(]+)+)? \((?:auth failed, \d+ attempts(?: in \d+ secs)?|tried to use (?:disabled|disallowed) \S+ auth|proxy dest auth failed)\):(?: user=<<F-USER>[^>]*</F-USER>>,)?(?: method=\S+,)? rip=<HOST>(?:[^>]*(?:, session=<\S+>)?)\s*$
^pam\(\S+,<HOST>(?:,\S*)?\): pam_authenticate\(\) failed: (?:User not known to the underlying authentication module: \d+ Time\(s\)|Authentication failure \(password mismatch\?\)|Permission denied)\s*$
^[a-z\-]{3,15}\(\S*,<HOST>(?:,\S*)?\): (?:unknown user|invalid credentials|Password mismatch)\s*$
^(?:Aborted login|Disconnected|Remote closed connection|Client has quit the connection)(?::(?: [^ \(]+)+)? \((?:auth failed, \d+ attempts(?: in \d+ secs)?|tried to use (?:disabled|disallowed) \S+ auth|proxy dest auth failed)\):(?: user=<<F-USER>[^>]*</F-USER>>,)?(?: method=\S+,)? rip=<HOST>(?:[^>]*(?:, session=<\S+>)?)\s*$
^pam\(\S+,<HOST>(?:,\S*)?\): pam_authenticate\(\) failed: (?:User not known to the underlying authentication module: \d+ Time\(s\)|Authentication failure \([Pp]assword mismatch\?\)|Permission denied)\s*$
^[a-z\-]{3,15}\(\S*,<HOST>(?:,\S*)?\): (?:[Uu]nknown user|[Ii]nvalid credentials|[Pp]assword mismatch)
<mdre-<mode>>
mdre-aggressive = ^(?:Aborted login|Disconnected)(?::(?: [^ \(]+)+)? \((?:no auth attempts|disconnected before auth was ready,|client didn't finish \S+ auth,)(?: (?:in|waited) \d+ secs)?\):(?: user=<[^>]*>,)?(?: method=\S+,)? rip=<HOST>(?:[^>]*(?:, session=<\S+>)?)\s*$
mdre-aggressive = ^(?:Aborted login|Disconnected|Remote closed connection|Client has quit the connection)(?::(?: [^ \(]+)+)? \((?:no auth attempts|disconnected before auth was ready,|client didn't finish \S+ auth,)(?: (?:in|waited) \d+ secs)?\):(?: user=<[^>]*>,)?(?: method=\S+,)? rip=<HOST>(?:[^>]*(?:, session=<\S+>)?)\s*$
mdre-normal =
+1 -1
View File
@@ -14,7 +14,7 @@ before = common.conf
[Definition]
failregex = ^%(__prefix_line)s(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})(\/[\w\.-]+)*\|\d{10}\|user\|<HOST>\|.+\|.+\|\d\|.*\|Login attempt failed for .+\.$
failregex = ^%(__prefix_line)s(?:https?:\/\/)[^|]+\|[^|]+\|[^|]+\|<ADDR>\|(?:[^|]*\|)*Login attempt failed (?:for|from) <F-USER>[^|]+</F-USER>\.$
ignoreregex =
+1 -1
View File
@@ -12,7 +12,7 @@ after = exim-common.local
host_info_pre = (?:H=([\w.-]+ )?(?:\(\S+\) )?)?
host_info_suf = (?::\d+)?(?: I=\[\S+\](:\d+)?)?(?: U=\S+)?(?: P=e?smtp)?(?: F=(?:<>|[^@]+@\S+))?\s
host_info = %(host_info_pre)s\[<HOST>\]%(host_info_suf)s
pid = (?: \[\d+\])?
pid = (?: \[\d+\]| \w+ exim\[\d+\]:)?
# DEV Notes:
# From exim source code: ./src/receive.c:add_host_info_for_log
+6
View File
@@ -0,0 +1,6 @@
# Fail2Ban filter for Gitlab
# Detecting unauthorized access to the Gitlab Web portal
# typically logged in /var/log/gitlab/gitlab-rails/application.log
[Definition]
failregex = ^: Failed Login: username=<F-USER>.+</F-USER> ip=<HOST>$
+9
View File
@@ -0,0 +1,9 @@
# Fail2Ban filter for Grafana
# Detecting unauthorized access
# Typically logged in /var/log/grafana/grafana.log
[Init]
datepattern = ^t=%%Y-%%m-%%dT%%H:%%M:%%S%%z
[Definition]
failregex = ^(?: lvl=err?or)? msg="Invalid username or password"(?: uname=(?:"<F-ALT_USER>[^"]+</F-ALT_USER>"|<F-USER>\S+</F-USER>)| error="<F-ERROR>[^"]+</F-ERROR>"| \S+=(?:\S*|"[^"]+"))* remote_addr=<ADDR>$
+38 -12
View File
@@ -5,21 +5,47 @@
[Definition]
# Option: failregex
# Notes.: regex to match the password failures messages in the logfile.
# Values: TEXT
#
logging = catalina
failregex = <L_<logging>/failregex>
maxlines = <L_<logging>/maxlines>
datepattern = <L_<logging>/datepattern>
[L_catalina]
failregex = ^.*\nWARNING: Authentication attempt from <HOST> for user "[^"]*" failed\.$
# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex =
# "maxlines" is number of log lines to buffer for multi-line regex searches
maxlines = 2
datepattern = ^%%b %%d, %%ExY %%I:%%M:%%S %%p
^WARNING:()**
{^LN-BEG}
{^LN-BEG}
[L_webapp]
failregex = ^ \[\S+\] WARN \S+ - Authentication attempt from <HOST> for user "<F-USER>[^"]+</F-USER>" failed.
maxlines = 1
datepattern = ^%%H:%%M:%%S.%%f
# DEV Notes:
#
# failregex is based on the default pattern given in Guacamole documentation :
# https://guacamole.apache.org/doc/gug/configuring-guacamole.html#webapp-logging
#
# The following logback.xml Guacamole configuration file can then be used accordingly :
# <configuration>
# <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
# <file>/var/log/guacamole.log</file>
# <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
# <fileNamePattern>/var/log/guacamole.%d.log.gz</fileNamePattern>
# <maxHistory>32</maxHistory>
# </rollingPolicy>
# <encoder>
# <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
# </encoder>
# </appender>
# <root level="info">
# <appender-ref ref="FILE" />
# </root>
# </configuration>
@@ -6,24 +6,35 @@
#
import sys
from fail2ban.server.ipdns import DNSUtils, IPAddr
from threading import Thread
def process_args(argv):
if len(argv) != 2:
raise ValueError("Please provide a single IP as an argument. Got: %s\n"
% (argv[1:]))
if len(argv) - 1 not in (1, 2):
raise ValueError("Usage %s ip ?timeout?. Got: %s\n"
% (argv[0], argv[1:]))
ip = argv[1]
if not IPAddr(ip).isValid:
raise ValueError("Argument must be a single valid IP. Got: %s\n"
% ip)
return ip
return argv[1:]
google_ips = None
def is_googlebot(ip):
def is_googlebot(ip, timeout=55):
import re
host = DNSUtils.ipToName(ip)
timeout = float(timeout or 0)
if timeout:
def ipToNameTO(host, ip, timeout):
host[0] = DNSUtils.ipToName(ip)
host = [None]
th = Thread(target=ipToNameTO, args=(host, ip, timeout)); th.daemon=True; th.start()
th.join(timeout)
host = host[0]
else:
host = DNSUtils.ipToName(ip)
if not host or not re.match(r'.*\.google(bot)?\.com$', host):
return False
host_ips = DNSUtils.dnsToIp(host)
@@ -31,7 +42,7 @@ def is_googlebot(ip):
if __name__ == '__main__': # pragma: no cover
try:
ret = is_googlebot(process_args(sys.argv))
ret = is_googlebot(*process_args(sys.argv))
except ValueError as e:
sys.stderr.write(str(e))
sys.exit(2)
+1 -1
View File
@@ -3,7 +3,7 @@
[Definition]
failregex = ^: \((?:http|mod)_auth\.c\.\d+\) (?:password doesn\'t match .* username: .*|digest: auth failed for .*: wrong password|get_password failed), IP: <HOST>\s*$
failregex = ^\s*(?:: )?\(?(?:http|mod)_auth\.c\.\d+\) (?:password doesn\'t match for (?:\S+|.*?) username:\s+<F-USER>(?:\S+|.*?)</F-USER>\s*|digest: auth failed(?: for\s+<F-ALT_USER>(?:\S+|.*?)</F-ALT_USER>\s*)?: (?:wrong password|uri mismatch \([^\)]*\))|get_password failed),? IP: <HOST>\s*$
ignoreregex =
+6 -2
View File
@@ -8,13 +8,17 @@
# common.local
before = common.conf
# [DEFAULT]
# logtype = short
[Definition]
_daemon = monit
_prefix = Warning|HttpRequest
# Regexp for previous (accessing monit httpd) and new (access denied) versions
failregex = ^\[\s*\]\s*error\s*:\s*Warning:\s+Client '<HOST>' supplied (?:unknown user '[^']+'|wrong password for user '[^']*') accessing monit httpd$
^%(__prefix_line)s\w+: access denied -- client <HOST>: (?:unknown user '[^']+'|wrong password for user '[^']*'|empty password)$
failregex = ^%(__prefix_line)s(?:error\s*:\s+)?(?:%(_prefix)s):\s+(?:access denied\s+--\s+)?[Cc]lient '?<HOST>'?(?:\s+supplied|\s*:)\s+(?:unknown user '<F-ALT_USER>[^']+</F-ALT_USER>'|wrong password for user '<F-USER>[^']*</F-USER>'|empty password)
# Ignore login with empty user (first connect, no user specified)
# ignoreregex = %(__prefix_line)s\w+: access denied -- client <HOST>: (?:unknown user '')
+25
View File
@@ -0,0 +1,25 @@
# Fail2Ban filter for Monitorix (HTTP built-in server)
#
[INCLUDES]
before = common.conf
[Definition]
_daemon = monitorix-httpd
# Option: failregex
# Notes.: regex to match the password failures messages in the logfile. The
# host must be matched by a group named "host". The tag "<HOST>" can
# be used for standard IP/hostname matching and is only an alias for
# (?:::f{4,6}:)?(?P<host>\S+)
# Values: TEXT
#
failregex = ^(?:\s+-)?\s*(?:NOTEXIST|AUTHERR|NOTALLOWED) - <ADDR>\b
# Option: ignoreregex
# Notes.: regex to ignore. If this regex matches, the line is ignored.
# Values: TEXT
#
ignoreregex =
+15
View File
@@ -0,0 +1,15 @@
# Fail2Ban filter for failed MSSQL Server authentication attempts
[Definition]
failregex = ^\s*Logon\s+Login failed for user '<F-USER>(?:[^']*|.*)</F-USER>'\. [^'\[]+\[CLIENT: <ADDR>\]$
# DEV Notes:
# Tested with SQL Server 2019 on Ubuntu 18.04
#
# Example:
# 2020-02-24 14:48:55.12 Logon Login failed for user 'root'. Reason: Could not find a login matching the name provided. [CLIENT: 127.0.0.1]
#
# Author: Rüdiger Olschewsky
#
+1 -1
View File
@@ -17,7 +17,7 @@ before = common.conf
_daemon = mysqld
failregex = ^%(__prefix_line)s(?:(?:\d{6}|\d{4}-\d{2}-\d{2})[ T]\s?\d{1,2}:\d{2}:\d{2} )?(?:\d+ )?\[\w+\] (?:\[[^\]]+\] )*Access denied for user '[^']+'@'<HOST>' (to database '[^']*'|\(using password: (YES|NO)\))*\s*$
failregex = ^%(__prefix_line)s(?:(?:\d{6}|\d{4}-\d{2}-\d{2})[ T]\s?\d{1,2}:\d{2}:\d{2} )?(?:\d+ )?\[\w+\] (?:\[[^\]]+\] )*Access denied for user '<F-USER>[^']+</F-USER>'@'<HOST>' (to database '[^']*'|\(using password: (YES|NO)\))*\s*$
ignoreregex =
+1 -1
View File
@@ -32,7 +32,7 @@ __daemon_combs_re=(?:%(__pid_re)s?:\s+%(__daemon_re)s|%(__daemon_re)s%(__pid_re)
# hostname daemon_id spaces
# this can be optional (for instance if we match named native log files)
__line_prefix=(?:\s\S+ %(__daemon_combs_re)s\s+)?
__line_prefix=(?:\s*\S+ %(__daemon_combs_re)s\s+)?
prefregex = ^%(__line_prefix)s(?: error:)?\s*client(?: @\S*)? <HOST>#\S+(?: \([\S.]+\))?: <F-CONTENT>.+</F-CONTENT>\s(?:denied|\(NOTAUTH\))\s*$
+16
View File
@@ -0,0 +1,16 @@
# Fail2Ban filter to match bad requests to nginx
#
[Definition]
# The request often doesn't contain a method, only some encoded garbage
# This will also match requests that are entirely empty
failregex = ^<HOST> - \S+ \[\] "[^"]*" 400
datepattern = {^LN-BEG}%%ExY(?P<_sep>[-/.])%%m(?P=_sep)%%d[T ]%%H:%%M:%%S(?:[.,]%%f)?(?:\s*%%z)?
^[^\[]*\[({DATE})
{^LN-BEG}
journalmatch = _SYSTEMD_UNIT=nginx.service + _COMM=nginx
# Author: Jan Przybylak
+3 -1
View File
@@ -17,7 +17,9 @@ datepattern = {^LN-BEG}%%ExY(?P<_sep>[-/.])%%m(?P=_sep)%%d[T ]%%H:%%M:%%S(?:[.,]
^[^\[]*\[({DATE})
{^LN-BEG}
journalmatch = _SYSTEMD_UNIT=nginx.service + _COMM=nginx
# DEV Notes:
# Based on apache-botsearch filter
#
# Author: Frantisek Sumsal
# Author: Frantisek Sumsal
+18 -1
View File
@@ -3,15 +3,32 @@
[Definition]
mode = normal
failregex = ^ \[error\] \d+#\d+: \*\d+ user "(?:[^"]+|.*?)":? (?:password mismatch|was not found in "[^\"]*"), client: <HOST>, server: \S*, request: "\S+ \S+ HTTP/\d+\.\d+", host: "\S+"(?:, referrer: "\S+")?\s*$
mdre-auth = ^\s*\[error\] \d+#\d+: \*\d+ user "(?:[^"]+|.*?)":? (?:password mismatch|was not found in "[^\"]*"), client: <HOST>, server: \S*, request: "\S+ \S+ HTTP/\d+\.\d+", host: "\S+"(?:, referrer: "\S+")?\s*$
mdre-fallback = ^\s*\[crit\] \d+#\d+: \*\d+ SSL_do_handshake\(\) failed \(SSL: error:\S+(?: \S+){1,3} too (?:long|short)\)[^,]*, client: <HOST>
mdre-normal = %(mdre-auth)s
mdre-aggressive = %(mdre-auth)s
%(mdre-fallback)s
failregex = <mdre-<mode>>
ignoreregex =
datepattern = {^LN-BEG}
journalmatch = _SYSTEMD_UNIT=nginx.service + _COMM=nginx
# DEV NOTES:
# mdre-auth:
# Based on samples in https://github.com/fail2ban/fail2ban/pull/43/files
# Extensive search of all nginx auth failures not done yet.
#
# Author: Daniel Black
# mdre-fallback:
# Ban people checking for TLS_FALLBACK_SCSV repeatedly
# https://stackoverflow.com/questions/28010492/nginx-critical-error-with-ssl-handshaking/28010608#28010608
# Author: Stephan Orlowsky
+3
View File
@@ -44,3 +44,6 @@ failregex = ^\s*\[[a-z]+\] \d+#\d+: \*\d+ limiting requests, excess: [\d\.]+ by
ignoreregex =
datepattern = {^LN-BEG}
journalmatch = _SYSTEMD_UNIT=nginx.service + _COMM=nginx
+3 -3
View File
@@ -22,10 +22,10 @@ _daemon = nsd
# (?:::f{4,6}:)?(?P<host>[\w\-.^_]+)
# Values: TEXT
failregex = ^%(__prefix_line)sinfo: ratelimit block .* query <HOST> TYPE255$
^%(__prefix_line)sinfo: .* <HOST> refused, no acl matches\.$
failregex = ^%(__prefix_line)sinfo: ratelimit block .* query <ADDR> TYPE255$
^%(__prefix_line)sinfo: .* from(?: client)? <ADDR> refused, no acl matches\.?$
ignoreregex =
datepattern = {^LN-BEG}Epoch
{^LN-BEG}
{^LN-BEG}
+1 -1
View File
@@ -1,4 +1,4 @@
# Fail2Ban fitler for the phpMyAdmin-syslog
# Fail2Ban filter for the phpMyAdmin-syslog
#
[INCLUDES]
+10 -9
View File
@@ -12,16 +12,15 @@ before = common.conf
_daemon = postfix(-\w+)?/\w+(?:/smtp[ds])?
_port = (?::\d+)?
_pref = [A-Z]{4}
prefregex = ^%(__prefix_line)s<mdpr-<mode>> <F-CONTENT>.+</F-CONTENT>$
mdpr-normal = (?:\w+: reject:|(?:improper command pipelining|too many errors) after \S+)
mdre-normal=^RCPT from [^[]*\[<HOST>\]%(_port)s: 55[04] 5\.7\.1\s
^RCPT from [^[]*\[<HOST>\]%(_port)s: 45[04] 4\.7\.\d+ (?:Service unavailable\b|Client host rejected: cannot find your (reverse )?hostname\b)
^RCPT from [^[]*\[<HOST>\]%(_port)s: 450 4\.7\.\d+ (<[^>]*>)?: Helo command rejected: Host not found\b
^EHLO from [^[]*\[<HOST>\]%(_port)s: 504 5\.5\.\d+ (<[^>]*>)?: Helo command rejected: need fully-qualified hostname\b
^(RCPT|VRFY) from [^[]*\[<HOST>\]%(_port)s: 550 5\.1\.1\s
^RCPT from [^[]*\[<HOST>\]%(_port)s: 450 4\.1\.\d+ (<[^>]*>)?: Sender address rejected: Domain not found\b
# Extended RE for normal mode to match reject by unknown users or undeliverable address, can be set to empty to avoid this:
exre-user = |[Uu](?:ser unknown|ndeliverable address)
mdpr-normal = (?:\w+: (?:milter-)?reject:|(?:improper command pipelining|too many errors) after \S+)
mdre-normal=^%(_pref)s from [^[]*\[<HOST>\]%(_port)s: [45][50][04] [45]\.\d\.\d+ (?:(?:<[^>]*>)?: )?(?:(?:Helo command|(?:Sender|Recipient) address) rejected: )?(?:Service unavailable|(?:Client host|Command|Data command) rejected|Relay access denied|(?:Host|Domain) not found|need fully-qualified hostname|match%(exre-user)s)\b
^from [^[]*\[<HOST>\]%(_port)s:?
mdpr-auth = warning:
@@ -31,13 +30,15 @@ mdre-auth2= ^[^[]*\[<HOST>\]%(_port)s: SASL ((?i)LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5
# Mode "rbl" currently included in mode "normal", but if needed for jail "postfix-rbl" only:
mdpr-rbl = %(mdpr-normal)s
mdre-rbl = ^RCPT from [^[]*\[<HOST>\]%(_port)s: [45]54 [45]\.7\.1 Service unavailable; Client host \[\S+\] blocked\b
mdre-rbl = ^%(_pref)s from [^[]*\[<HOST>\]%(_port)s: [45]54 [45]\.7\.1 Service unavailable; Client host \[\S+\] blocked\b
# Mode "rbl" currently included in mode "normal" (within 1st rule)
mdpr-more = %(mdpr-normal)s
mdre-more = %(mdre-normal)s
mdpr-ddos = lost connection after(?! DATA) [A-Z]+
# Includes some of the log messages described in
# <http://www.postfix.org/POSTSCREEN_README.html>.
mdpr-ddos = (?:lost connection after(?! DATA) [A-Z]+|disconnect(?= from \S+(?: \S+=\d+)* auth=0/(?:[1-9]|\d\d+))|(?:PREGREET \d+|HANGUP) after \S+|COMMAND (?:TIME|COUNT|LENGTH) LIMIT)
mdre-ddos = ^from [^[]*\[<HOST>\]%(_port)s:?
mdpr-extra = (?:%(mdpr-auth)s|%(mdpr-normal)s)
+6 -7
View File
@@ -1,4 +1,4 @@
# Fail2Ban fitler for the Proftpd FTP daemon
# Fail2Ban filter for the Proftpd FTP daemon
#
# Set "UseReverseDNS off" in proftpd.conf to avoid the need for DNS.
# See: http://www.proftpd.org/docs/howto/DNS.html
@@ -14,16 +14,15 @@ before = common.conf
_daemon = proftpd
__suffix_failed_login = (User not authorized for login|No such user found|Incorrect password|Password expired|Account disabled|Invalid shell: '\S+'|User in \S+|Limit (access|configuration) denies login|Not a UserAlias|maximum login length exceeded).?
__suffix_failed_login = ([uU]ser not authorized for login|[nN]o such user found|[iI]ncorrect password|[pP]assword expired|[aA]ccount disabled|[iI]nvalid shell: '\S+'|[uU]ser in \S+|[lL]imit (access|configuration) denies login|[nN]ot a UserAlias|[mM]aximum login length exceeded)
prefregex = ^%(__prefix_line)s%(__hostname)s \(\S+\[<HOST>\]\)[: -]+ <F-CONTENT>(?:USER|SECURITY|Maximum).+</F-CONTENT>$
prefregex = ^%(__prefix_line)s%(__hostname)s \(\S+\[<HOST>\]\)[: -]+ <F-CONTENT>(?:USER|SECURITY|Maximum) .+</F-CONTENT>$
failregex = ^USER .*: no such user found from \S+ \[\S+\] to \S+:\S+ *$
^USER .* \(Login failed\): %(__suffix_failed_login)s\s*$
^SECURITY VIOLATION: .* login attempted\. *$
^Maximum login attempts \(\d+\) exceeded *$
failregex = ^USER <F-USER>\S+|.*?</F-USER>(?: \(Login failed\))?: %(__suffix_failed_login)s
^SECURITY VIOLATION: <F-USER>\S+|.*?</F-USER> login attempted
^Maximum login attempts \(\d+\) exceeded
ignoreregex =
+17
View File
@@ -0,0 +1,17 @@
# Fail2Ban filter for port scans detected by scanlogd
[INCLUDES]
# Read common prefixes. If any customizations available -- read them from
# common.local
before = common.conf
[Definition]
_daemon = scanlogd
failregex = ^%(__prefix_line)s<ADDR>(?::<F-PORT/>)? to \S+ ports\b
ignoreregex =
# Author: Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
+5 -2
View File
@@ -8,11 +8,14 @@ before = common.conf
[Definition]
_daemon = (?:sendmail|sm-(?:mta|acceptingconnections))
# "\w{14,20}" will give support for IDs from 14 up to 20 characters long
__prefix_line = %(known/__prefix_line)s(?:\w{14,20}: )?
addr = (?:IPv6:<IP6>|<IP4>)
# "w{14,20}" will give support for IDs from 14 up to 20 characters long
failregex = ^%(__prefix_line)s(\S+ )?\[(?:IPv6:<IP6>|<IP4>)\]( \(may be forged\))?: possible SMTP attack: command=AUTH, count=\d+$
prefregex = ^<F-MLFID>%(__prefix_line)s</F-MLFID><F-CONTENT>.+</F-CONTENT>$
failregex = ^(\S+ )?\[%(addr)s\]( \(may be forged\))?: possible SMTP attack: command=AUTH, count=\d+$
^AUTH failure \([^\)]+\):(?: [^:]+:)? (?:authentication failure|user not found): [^,]*, user=<F-USER>(?:\S+|.*?)</F-USER>, relay=(?:\S+ )?\[%(addr)s\](?: \(may be forged\))?$
ignoreregex =
journalmatch = _SYSTEMD_UNIT=sendmail.service
+7 -6
View File
@@ -21,19 +21,20 @@ before = common.conf
_daemon = (?:(sm-(mta|acceptingconnections)|sendmail))
__prefix_line = %(known/__prefix_line)s(?:\w{14,20}: )?
addr = (?:(?:IPv6:)?<IP6>|<IP4>)
prefregex = ^<F-MLFID>%(__prefix_line)s</F-MLFID><F-CONTENT>.+</F-CONTENT>$
cmnfailre = ^ruleset=check_rcpt, arg1=(?P<email><\S+@\S+>), relay=(\S+ )?\[(?:IPv6:<IP6>|<IP4>)\](?: \(may be forged\))?, reject=(550 5\.7\.1 (?P=email)\.\.\. Relaying denied\. (IP name possibly forged \[(\d+\.){3}\d+\]|Proper authentication required\.|IP name lookup failed \[(\d+\.){3}\d+\])|553 5\.1\.8 (?P=email)\.\.\. Domain of sender address \S+ does not exist|550 5\.[71]\.1 (?P=email)\.\.\. (Rejected: .*|User unknown))$
^ruleset=check_relay, arg1=(?P<dom>\S+), arg2=(?:IPv6:<IP6>|<IP4>), relay=((?P=dom) )?\[(\d+\.){3}\d+\](?: \(may be forged\))?, reject=421 4\.3\.2 (Connection rate limit exceeded\.|Too many open connections\.)$
^rejecting commands from (\S* )?\[(?:IPv6:<IP6>|<IP4>)\] due to pre-greeting traffic after \d+ seconds$
^(?:\S+ )?\[(?:IPv6:<IP6>|<IP4>)\]: (?:(?i)expn|vrfy) \S+ \[rejected\]$
cmnfailre = ^ruleset=check_rcpt, arg1=(?P<email><\S+@\S+>), relay=(\S+ )?\[%(addr)s\](?: \(may be forged\))?, reject=(?:550 5\.7\.1(?: (?P=email)\.\.\.)?(?: Relaying denied\.)? (?:IP name possibly forged \[(\d+\.){3}\d+\]|Proper authentication required\.|IP name lookup failed \[(\d+\.){3}\d+\]|Fix reverse DNS for \S+)|553 5\.1\.8(?: (?P=email)\.\.\.)? Domain of sender address \S+ does not exist|550 5\.[71]\.1 (?P=email)\.\.\. (Rejected: .*|User unknown))$
^ruleset=check_relay(?:, arg\d+=\S*)*, relay=(\S+ )?\[%(addr)s\](?: \(may be forged\))?, reject=421 4\.3\.2 (Connection rate limit exceeded\.|Too many open connections\.)$
^rejecting commands from (\S* )?\[%(addr)s\] due to pre-greeting traffic after \d+ seconds$
^(?:\S+ )?\[%(addr)s\]: (?:(?i)expn|vrfy) \S+ \[rejected\]$
^<[^@]+@[^>]+>\.\.\. No such user here$
^<F-NOFAIL>from=<[^@]+@[^>]+></F-NOFAIL>, size=\d+, class=\d+, nrcpts=\d+, bodytype=\w+, proto=E?SMTP, daemon=MTA, relay=\S+ \[(?:IPv6:<IP6>|<IP4>)\]$
^<F-NOFAIL>from=<[^@]+@[^>]+></F-NOFAIL>, size=\d+, class=\d+, nrcpts=\d+, bodytype=\w+, proto=E?SMTP, daemon=MTA, relay=\S+ \[%(addr)s\]$
mdre-normal =
mdre-extra = ^(?:\S+ )?\[(?:IPv6:<IP6>|<IP4>)\](?: \(may be forged\))? did not issue (?:[A-Z]{4}[/ ]?)+during connection to (?:TLS)?M(?:TA|S[PA])(?:-\w+)?$
mdre-extra = ^(?:\S+ )?\[%(addr)s\](?: \(may be forged\))? did not issue \S+ during connection
mdre-aggressive = %(mdre-extra)s
+9
View File
@@ -0,0 +1,9 @@
# Fail2Ban filter for SoftEtherVPN
# Detecting unauthorized access to SoftEtherVPN
# typically logged in /usr/local/vpnserver/security_log/*/sec.log, or in syslog, depending on configuration
[INCLUDES]
before = common.conf
[Definition]
failregex = ^%(__prefix_line)s(?:(?:\([\d\-]+ [\d:.]+\) )?<SECURITY_LOG>: )?Connection "[^"]+": User authentication failed. The user name that has been provided was "<F-USER>(?:[^"]+|.+)</F-USER>", from <ADDR>\.$
+31 -14
View File
@@ -25,7 +25,7 @@ __pref = (?:(?:error|fatal): (?:PAM: )?)?
__suff = (?: (?:port \d+|on \S+|\[preauth\])){0,3}\s*
__on_port_opt = (?: (?:port \d+|on \S+)){0,2}
# close by authenticating user:
__authng_user = (?: (?:invalid|authenticating) user <F-USER>\S+|.+?</F-USER>)?
__authng_user = (?: (?:invalid|authenticating) user <F-USER>\S+|.*?</F-USER>)?
# for all possible (also future) forms of "no matching (cipher|mac|MAC|compression method|key exchange method|host key type) found",
# see ssherr.c for all possible SSH_ERR_..._ALG_MATCH errors.
@@ -40,39 +40,45 @@ prefregex = ^<F-MLFID>%(__prefix_line)s</F-MLFID>%(__pref)s<F-CONTENT>.+</F-CONT
cmnfailre = ^[aA]uthentication (?:failure|error|failed) for <F-USER>.*</F-USER> from <HOST>( via \S+)?%(__suff)s$
^User not known to the underlying authentication module for <F-USER>.*</F-USER> from <HOST>%(__suff)s$
^Failed publickey for invalid user <F-USER>(?P<cond_user>\S+)|(?:(?! from ).)*?</F-USER> from <HOST>%(__on_port_opt)s(?: ssh\d*)?(?(cond_user): |(?:(?:(?! from ).)*)$)
^Failed \b(?!publickey)\S+ for (?P<cond_inv>invalid user )?<F-USER>(?P<cond_user>\S+)|(?(cond_inv)(?:(?! from ).)*?|[^:]+)</F-USER> from <HOST>%(__on_port_opt)s(?: ssh\d*)?(?(cond_user): |(?:(?:(?! from ).)*)$)
<cmnfailre-failed-pub-<publickey>>
^Failed <cmnfailed> for (?P<cond_inv>invalid user )?<F-USER>(?P<cond_user>\S+)|(?(cond_inv)(?:(?! from ).)*?|[^:]+)</F-USER> from <HOST>%(__on_port_opt)s(?: ssh\d*)?(?(cond_user): |(?:(?:(?! from ).)*)$)
^<F-USER>ROOT</F-USER> LOGIN REFUSED FROM <HOST>
^[iI](?:llegal|nvalid) user <F-USER>.*?</F-USER> from <HOST>%(__suff)s$
^User <F-USER>.+</F-USER> from <HOST> not allowed because not listed in AllowUsers%(__suff)s$
^User <F-USER>.+</F-USER> from <HOST> not allowed because listed in DenyUsers%(__suff)s$
^User <F-USER>.+</F-USER> from <HOST> not allowed because not in any group%(__suff)s$
^User <F-USER>\S+|.*?</F-USER> from <HOST> not allowed because not listed in AllowUsers%(__suff)s$
^User <F-USER>\S+|.*?</F-USER> from <HOST> not allowed because listed in DenyUsers%(__suff)s$
^User <F-USER>\S+|.*?</F-USER> from <HOST> not allowed because not in any group%(__suff)s$
^refused connect from \S+ \(<HOST>\)
^Received <F-MLFFORGET>disconnect</F-MLFFORGET> from <HOST>%(__on_port_opt)s:\s*3: .*: Auth fail%(__suff)s$
^User <F-USER>.+</F-USER> from <HOST> not allowed because a group is listed in DenyGroups%(__suff)s$
^User <F-USER>.+</F-USER> from <HOST> not allowed because none of user's groups are listed in AllowGroups%(__suff)s$
^User <F-USER>\S+|.*?</F-USER> from <HOST> not allowed because a group is listed in DenyGroups%(__suff)s$
^User <F-USER>\S+|.*?</F-USER> from <HOST> not allowed because none of user's groups are listed in AllowGroups%(__suff)s$
^<F-NOFAIL>%(__pam_auth)s\(sshd:auth\):\s+authentication failure;</F-NOFAIL>(?:\s+(?:(?:logname|e?uid|tty)=\S*)){0,4}\s+ruser=<F-ALT_USER>\S*</F-ALT_USER>\s+rhost=<HOST>(?:\s+user=<F-USER>\S*</F-USER>)?%(__suff)s$
^(error: )?maximum authentication attempts exceeded for <F-USER>.*</F-USER> from <HOST>%(__on_port_opt)s(?: ssh\d*)?%(__suff)s$
^User <F-USER>.+</F-USER> not allowed because account is locked%(__suff)s
^maximum authentication attempts exceeded for <F-USER>.*</F-USER> from <HOST>%(__on_port_opt)s(?: ssh\d*)?%(__suff)s$
^User <F-USER>\S+|.*?</F-USER> not allowed because account is locked%(__suff)s
^<F-MLFFORGET>Disconnecting</F-MLFFORGET>(?: from)?(?: (?:invalid|authenticating)) user <F-USER>\S+</F-USER> <HOST>%(__on_port_opt)s:\s*Change of username or service not allowed:\s*.*\[preauth\]\s*$
^<F-MLFFORGET>Disconnecting</F-MLFFORGET>: Too many authentication failures(?: for <F-USER>.+?</F-USER>)?%(__suff)s$
^Disconnecting: Too many authentication failures(?: for <F-USER>\S+|.*?</F-USER>)?%(__suff)s$
^<F-NOFAIL>Received <F-MLFFORGET>disconnect</F-MLFFORGET></F-NOFAIL> from <HOST>%(__on_port_opt)s:\s*11:
<mdre-<mode>-other>
^<F-MLFFORGET><F-MLFGAINED>Accepted \w+</F-MLFGAINED></F-MLFFORGET> for <F-USER>\S+</F-USER> from <HOST>(?:\s|$)
cmnfailed-any = \S+
cmnfailed-ignore = \b(?!publickey)\S+
cmnfailed-invalid = <cmnfailed-ignore>
cmnfailed-nofail = (?:<F-NOFAIL>publickey</F-NOFAIL>|\S+)
cmnfailed = <cmnfailed-<publickey>>
mdre-normal =
# used to differentiate "connection closed" with and without `[preauth]` (fail/nofail cases in ddos mode)
mdre-normal-other = ^<F-NOFAIL><F-MLFFORGET>(Connection closed|Disconnected)</F-MLFFORGET></F-NOFAIL> (?:by|from)%(__authng_user)s <HOST>(?:%(__suff)s|\s*)$
mdre-ddos = ^Did not receive identification string from <HOST>
^kex_exchange_identification: (?:[Cc]lient sent invalid protocol identifier|[Cc]onnection closed by remote host)
^Bad protocol version identification '.*' from <HOST>
^Connection <F-MLFFORGET>reset</F-MLFFORGET> by <HOST>
^<F-NOFAIL>SSH: Server;Ltype:</F-NOFAIL> (?:Authname|Version|Kex);Remote: <HOST>-\d+;[A-Z]\w+:
^Read from socket failed: Connection <F-MLFFORGET>reset</F-MLFFORGET> by peer
# same as mdre-normal-other, but as failure (without <F-NOFAIL>) and [preauth] only:
mdre-ddos-other = ^<F-MLFFORGET>(Connection closed|Disconnected)</F-MLFFORGET> (?:by|from)%(__authng_user)s <HOST>%(__on_port_opt)s\s+\[preauth\]\s*$
mdre-ddos-other = ^<F-MLFFORGET>(Connection (?:closed|reset)|Disconnected)</F-MLFFORGET> (?:by|from)%(__authng_user)s <HOST>%(__on_port_opt)s\s+\[preauth\]\s*$
mdre-extra = ^Received <F-MLFFORGET>disconnect</F-MLFFORGET> from <HOST>%(__on_port_opt)s:\s*14: No supported authentication methods available
mdre-extra = ^Received <F-MLFFORGET>disconnect</F-MLFFORGET> from <HOST>%(__on_port_opt)s:\s*14: No(?: supported)? authentication methods available
^Unable to negotiate with <HOST>%(__on_port_opt)s: no matching <__alg_match> found.
^Unable to negotiate a <__alg_match>
^no matching <__alg_match> found:
@@ -84,6 +90,17 @@ mdre-aggressive = %(mdre-ddos)s
# mdre-extra-other is fully included within mdre-ddos-other:
mdre-aggressive-other = %(mdre-ddos-other)s
# Parameter "publickey": nofail (default), invalid, any, ignore
publickey = nofail
# consider failed publickey for invalid users only:
cmnfailre-failed-pub-invalid = ^Failed publickey for invalid user <F-USER>(?P<cond_user>\S+)|(?:(?! from ).)*?</F-USER> from <HOST>%(__on_port_opt)s(?: ssh\d*)?(?(cond_user): |(?:(?:(?! from ).)*)$)
# consider failed publickey for valid users too (don't need RE, see cmnfailed):
cmnfailre-failed-pub-any =
# same as invalid, but consider failed publickey for valid users too, just as no failure (helper to get IP and user-name only, see cmnfailed):
cmnfailre-failed-pub-nofail = <cmnfailre-failed-pub-invalid>
# don't consider failed publickey as failures (don't need RE, see cmnfailed):
cmnfailre-failed-pub-ignore =
cfooterre = ^<F-NOFAIL>Connection from</F-NOFAIL> <HOST>
failregex = %(cmnfailre)s
+21 -1
View File
@@ -51,6 +51,26 @@
[Definition]
failregex = ^<HOST> \- (?!- )\S+ \[\] \"(GET|POST|HEAD) [^\"]+\" 401\b
# Parameter "method" can be used to specifiy request method
req-method = \S+
# Usage example (for jail.local):
# filter = traefik-auth[req-method="GET|POST|HEAD"]
failregex = ^<HOST> \- <usrre-<mode>> \[\] \"(?:<req-method>) [^\"]+\" 401\b
ignoreregex =
# Parameter "mode": normal (default), ddos or aggressive
# Usage example (for jail.local):
# [traefik-auth]
# mode = aggressive
# # or another jail (rewrite filter parameters of jail):
# [traefik-auth-ddos]
# filter = traefik-auth[mode=ddos]
#
mode = normal
# part of failregex matches user name (must be available in normal mode, must be empty in ddos mode, and both for aggressive mode):
usrre-normal = (?!- )<F-USER>\S+</F-USER>
usrre-ddos = -
usrre-aggressive = <F-USER>\S+</F-USER>
+11 -5
View File
@@ -5,17 +5,23 @@ before = apache-common.conf
[Definition]
# pattern: [Wed Apr 27 23:12:07.736196 2016] [:error] [pid 2460] [client 10.1.1.1:47296] WAR [Login denied for user "test"], referer: https://zoneminderurl/index.php
#
# patterns: [Mon Mar 28 16:50:49.522240 2016] [:error] [pid 1795] [client 10.1.1.1:50700] WAR [Login denied for user "username1"], referer: https://zoneminder/
# [Sun Mar 28 16:53:00.472693 2021] [php7:notice] [pid 11328] [client 10.1.1.1:39568] ERR [Could not retrieve user test details], referer: https://zm/
# [Sun Mar 28 16:59:14.150625 2021] [php7:notice] [pid 11336] [client 10.1.1.1:39654] ERR [Login denied for user "john"], referer: https://zm/
#
# Option: failregex
# Notes.: regex to match the password failure messages in the logfile.
# Notes.: regex to match the login failure and non-existent user error messages in the logfile.
failregex = ^%(_apache_error_client)s WAR \[Login denied for user "[^"]*"\]
prefregex = ^%(_apache_error_client)s (?:ERR|WAR) <F-CONTENT>\[(?:Login denied|Could not retrieve).*</F-CONTENT>$
failregex = ^\[Login denied for user "<F-USER>[^"]*</F-USER>"\]
^\[Could not retrieve user <F-USER>\S*</F-USER>
ignoreregex =
# Notes:
# Tested on Zoneminder 1.29.0
# Tested on Zoneminder 1.29 and 1.35.21
#
# Zoneminder versions > 1.3x use "ERR" and < 1.3x use "WAR" level logs, so i've kept both for compatibility reasons
#
# Author: John Marzella
+103 -38
View File
@@ -44,6 +44,44 @@ before = paths-debian.conf
# MISCELLANEOUS OPTIONS
#
# "bantime.increment" allows to use database for searching of previously banned ip's to increase a
# default ban time using special formula, default it is banTime * 1, 2, 4, 8, 16, 32...
#bantime.increment = true
# "bantime.rndtime" is the max number of seconds using for mixing with random time
# to prevent "clever" botnets calculate exact time IP can be unbanned again:
#bantime.rndtime =
# "bantime.maxtime" is the max number of seconds using the ban time can reach (doesn't grow further)
#bantime.maxtime =
# "bantime.factor" is a coefficient to calculate exponent growing of the formula or common multiplier,
# default value of factor is 1 and with default value of formula, the ban time
# grows by 1, 2, 4, 8, 16 ...
#bantime.factor = 1
# "bantime.formula" used by default to calculate next value of ban time, default value below,
# the same ban time growing will be reached by multipliers 1, 2, 4, 8, 16, 32...
#bantime.formula = ban.Time * (1<<(ban.Count if ban.Count<20 else 20)) * banFactor
#
# more aggressive example of formula has the same values only for factor "2.0 / 2.885385" :
#bantime.formula = ban.Time * math.exp(float(ban.Count+1)*banFactor)/math.exp(1*banFactor)
# "bantime.multipliers" used to calculate next value of ban time instead of formula, corresponding
# previously ban count and given "bantime.factor" (for multipliers default is 1);
# following example grows ban time by 1, 2, 4, 8, 16 ... and if last ban count greater as multipliers count,
# always used last multiplier (64 in example), for factor '1' and original ban time 600 - 10.6 hours
#bantime.multipliers = 1 2 4 8 16 32 64
# following example can be used for small initial ban time (bantime=60) - it grows more aggressive at begin,
# for bantime=60 the multipliers are minutes and equal: 1 min, 5 min, 30 min, 1 hour, 5 hour, 12 hour, 1 day, 2 day
#bantime.multipliers = 1 5 30 60 300 720 1440 2880
# "bantime.overalljails" (if true) specifies the search of IP in the database will be executed
# cross over all jails, if false (default), only current jail of the ban IP will be searched
#bantime.overalljails = false
# --------------------
# "ignoreself" specifies whether the local resp. own IP addresses should be ignored
# (default is true). Fail2ban will not ban a host which matches such addresses.
#ignoreself = true
@@ -171,28 +209,37 @@ banaction = iptables-multiport
banaction_allports = iptables-allports
# The simplest action to take: ban only
action_ = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
action_ = %(banaction)s[port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
# ban & send an e-mail with whois report to the destemail.
action_mw = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
%(mta)s-whois[name=%(__name__)s, sender="%(sender)s", dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s"]
action_mw = %(action_)s
%(mta)s-whois[sender="%(sender)s", dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s"]
# ban & send an e-mail with whois report and relevant log lines
# to the destemail.
action_mwl = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
%(mta)s-whois-lines[name=%(__name__)s, sender="%(sender)s", dest="%(destemail)s", logpath="%(logpath)s", chain="%(chain)s"]
action_mwl = %(action_)s
%(mta)s-whois-lines[sender="%(sender)s", dest="%(destemail)s", logpath="%(logpath)s", chain="%(chain)s"]
# See the IMPORTANT note in action.d/xarf-login-attack for when to use this action
#
# ban & send a xarf e-mail to abuse contact of IP address and include relevant log lines
# to the destemail.
action_xarf = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]
action_xarf = %(action_)s
xarf-login-attack[service=%(__name__)s, sender="%(sender)s", logpath="%(logpath)s", port="%(port)s"]
# ban & send a notification to one or more of the 50+ services supported by Apprise.
# See https://github.com/caronc/apprise/wiki for details on what is supported.
#
# You may optionally over-ride the default configuration line (containing the Apprise URLs)
# by using 'apprise[config="/alternate/path/to/apprise.cfg"]' otherwise
# /etc/fail2ban/apprise.conf is sourced for your supported notification configuration.
# action = %(action_)s
# apprise
# ban IP on CloudFlare & send an e-mail with whois report and relevant log lines
# to the destemail.
action_cf_mwl = cloudflare[cfuser="%(cfemail)s", cftoken="%(cfapikey)s"]
%(mta)s-whois-lines[name=%(__name__)s, sender="%(sender)s", dest="%(destemail)s", logpath="%(logpath)s", chain="%(chain)s"]
%(mta)s-whois-lines[sender="%(sender)s", dest="%(destemail)s", logpath="%(logpath)s", chain="%(chain)s"]
# Report block via blocklist.de fail2ban reporting service API
#
@@ -202,21 +249,7 @@ action_cf_mwl = cloudflare[cfuser="%(cfemail)s", cftoken="%(cfapikey)s"]
# in your `jail.local` globally (section [DEFAULT]) or per specific jail section (resp. in
# corresponding jail.d/my-jail.local file).
#
action_blocklist_de = blocklist_de[email="%(sender)s", service=%(filter)s, apikey="%(blocklist_de_apikey)s", agent="%(fail2ban_agent)s"]
# Report ban via badips.com, and use as blacklist
#
# See BadIPsAction docstring in config/action.d/badips.py for
# documentation for this action.
#
# NOTE: This action relies on banaction being present on start and therefore
# should be last action defined for a jail.
#
action_badips = badips.py[category="%(__name__)s", banaction="%(banaction)s", agent="%(fail2ban_agent)s"]
#
# Report ban via badips.com (uses action.d/badips.conf for reporting only)
#
action_badips_report = badips[category="%(__name__)s", agent="%(fail2ban_agent)s"]
action_blocklist_de = blocklist_de[email="%(sender)s", service="%(__name__)s", apikey="%(blocklist_de_apikey)s", agent="%(fail2ban_agent)s"]
# Report ban via abuseipdb.com.
#
@@ -333,12 +366,15 @@ maxretry = 1
[openhab-auth]
filter = openhab
action = iptables-allports[name=NoAuthFailures]
banaction = %(banaction_allports)s
logpath = /opt/openhab/logs/request.log
# To use more aggressive http-auth modes set filter parameter "mode" in jail.local:
# normal (default), aggressive (combines all), auth or fallback
# See "tests/files/logs/nginx-http-auth" or "filter.d/nginx-http-auth.conf" for usage example and details.
[nginx-http-auth]
# mode = normal
port = http,https
logpath = %(nginx_error_log)s
@@ -354,8 +390,10 @@ logpath = %(nginx_error_log)s
port = http,https
logpath = %(nginx_error_log)s
maxretry = 2
[nginx-bad-request]
port = http,https
logpath = %(nginx_access_log)s
# Ban attackers that try to use PHP's URL-fopen() functionality
# through GET/POST variables. - Experimental, with more than a year
@@ -440,6 +478,7 @@ backend = %(syslog_backend)s
port = http,https
logpath = /var/log/tomcat*/catalina.out
#logpath = /var/log/guacamole.log
[monit]
#Ban clients brute-forcing the monit gui login
@@ -706,8 +745,8 @@ logpath = /var/log/named/security.log
[nsd]
port = 53
action = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp]
%(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp]
action_ = %(default/action_)s[name=%(__name__)s-tcp, protocol="tcp"]
%(default/action_)s[name=%(__name__)s-udp, protocol="udp"]
logpath = /var/log/nsd.log
@@ -718,9 +757,8 @@ logpath = /var/log/nsd.log
[asterisk]
port = 5060,5061
action = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp]
%(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp]
%(mta)s-whois[name=%(__name__)s, dest="%(destemail)s"]
action_ = %(default/action_)s[name=%(__name__)s-tcp, protocol="tcp"]
%(default/action_)s[name=%(__name__)s-udp, protocol="udp"]
logpath = /var/log/asterisk/messages
maxretry = 10
@@ -728,9 +766,8 @@ maxretry = 10
[freeswitch]
port = 5060,5061
action = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp]
%(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp]
%(mta)s-whois[name=%(__name__)s, dest="%(destemail)s"]
action_ = %(default/action_)s[name=%(__name__)s-tcp, protocol="tcp"]
%(default/action_)s[name=%(__name__)s-udp, protocol="udp"]
logpath = /var/log/freeswitch.log
maxretry = 10
@@ -760,6 +797,14 @@ logpath = %(mysql_log)s
backend = %(mysql_backend)s
[mssql-auth]
# Default configuration for Microsoft SQL Server for Linux
# See the 'mssql-conf' manpage how to change logpath or port
logpath = /var/opt/mssql/log/errorlog
port = 1433
filter = mssql-auth
# Log wrong MongoDB auth (for details see filter 'filter.d/mongodb-auth.conf')
[mongodb-auth]
# change port when running with "--shardsvr" or "--configsvr" runtime operation
@@ -815,11 +860,23 @@ logpath = /var/log/ejabberd/ejabberd.log
[counter-strike]
logpath = /opt/cstrike/logs/L[0-9]*.log
# Firewall: http://www.cstrike-planet.com/faq/6
tcpport = 27030,27031,27032,27033,27034,27035,27036,27037,27038,27039
udpport = 1200,27000,27001,27002,27003,27004,27005,27006,27007,27008,27009,27010,27011,27012,27013,27014,27015
action = %(banaction)s[name=%(__name__)s-tcp, port="%(tcpport)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp]
%(banaction)s[name=%(__name__)s-udp, port="%(udpport)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp]
action_ = %(default/action_)s[name=%(__name__)s-tcp, port="%(tcpport)s", protocol="tcp"]
%(default/action_)s[name=%(__name__)s-udp, port="%(udpport)s", protocol="udp"]
[softethervpn]
port = 500,4500
protocol = udp
logpath = /usr/local/vpnserver/security_log/*/sec.log
[gitlab]
port = http,https
logpath = /var/log/gitlab/gitlab-rails/application.log
[grafana]
port = http,https
logpath = /var/log/grafana/grafana.log
[bitwarden]
port = http,https
@@ -871,8 +928,8 @@ findtime = 1
[murmur]
# AKA mumble-server
port = 64738
action = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol=tcp, chain="%(chain)s", actname=%(banaction)s-tcp]
%(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol=udp, chain="%(chain)s", actname=%(banaction)s-udp]
action_ = %(default/action_)s[name=%(__name__)s-tcp, protocol="tcp"]
%(default/action_)s[name=%(__name__)s-udp, protocol="udp"]
logpath = /var/log/mumble-server/mumble-server.log
@@ -913,3 +970,11 @@ logpath = %(apache_error_log)s
# see `filter.d/traefik-auth.conf` for details and service example.
port = http,https
logpath = /var/log/traefik/access.log
[scanlogd]
logpath = %(syslog_local0)s
banaction = %(banaction_allports)s
[monitorix]
port = 8080
logpath = /var/log/monitorix-httpd
+2
View File
@@ -26,3 +26,5 @@ exim_main_log = /var/log/exim4/mainlog
# was in debian squeezy but not in wheezy
# /etc/proftpd/proftpd.conf (SystemLog)
proftpd_log = /var/log/proftpd/proftpd.log
roundcube_errors_log = /var/log/roundcube/errors.log
+11 -11
View File
@@ -38,27 +38,32 @@ class ActionReader(DefinitionInitConfigReader):
_configOpts = {
"actionstart": ["string", None],
"actionstart_on_demand": ["string", None],
"actionstart_on_demand": ["bool", None],
"actionstop": ["string", None],
"actionflush": ["string", None],
"actionreload": ["string", None],
"actioncheck": ["string", None],
"actionrepair": ["string", None],
"actionrepair_on_unban": ["string", None],
"actionrepair_on_unban": ["bool", None],
"actionban": ["string", None],
"actionprolong": ["string", None],
"actionreban": ["string", None],
"actionunban": ["string", None],
"norestored": ["string", None],
"norestored": ["bool", None],
}
def __init__(self, file_, jailName, initOpts, **kwargs):
# always supply jail name as name parameter if not specified in options:
n = initOpts.get("name")
if n is None:
initOpts["name"] = n = jailName
actname = initOpts.get("actname")
if actname is None:
actname = file_
# ensure we've unique action name per jail:
if n != jailName:
actname += n[len(jailName):] if n.startswith(jailName) else '-' + n
initOpts["actname"] = actname
# always supply jail name as name parameter if not specified in options:
if initOpts.get("name") is None:
initOpts["name"] = jailName
self._name = actname
DefinitionInitConfigReader.__init__(
self, file_, jailName, initOpts, **kwargs)
@@ -79,11 +84,6 @@ class ActionReader(DefinitionInitConfigReader):
def convert(self):
opts = self.getCombined(
ignore=CommandAction._escapedTags | set(('timeout', 'bantime')))
# type-convert only after combined (otherwise boolean converting prevents substitution):
for o in ('norestored', 'actionstart_on_demand', 'actionrepair_on_unban'):
if opts.get(o):
opts[o] = self._convert_to_boolean(opts[o])
# stream-convert:
head = ["set", self._jailName]
stream = list()
+6
View File
@@ -180,6 +180,12 @@ class Beautifier:
msg = "The jail %s action %s has the following " \
"methods:\n" % (inC[1], inC[3])
msg += ", ".join(response)
elif inC[2] == "banip" and inC[0] == "get":
if isinstance(response, list):
sep = " " if len(inC) <= 3 else inC[3]
if sep == "--with-time":
sep = "\n"
msg = sep.join(response)
except Exception:
logSys.warning("Beautifier error. Please report the error")
logSys.error("Beautify %r with %r failed", response, self.__inputCmd,
+4 -3
View File
@@ -29,7 +29,7 @@ import re
import sys
from ..helpers import getLogger
if sys.version_info >= (3,2):
if sys.version_info >= (3,): # pragma: 2.x no cover
# SafeConfigParser deprecated from Python 3.2 (renamed to ConfigParser)
from configparser import ConfigParser as SafeConfigParser, BasicInterpolation, \
@@ -61,7 +61,7 @@ if sys.version_info >= (3,2):
return super(BasicInterpolationWithName, self)._interpolate_some(
parser, option, accum, rest, section, map, *args, **kwargs)
else: # pragma: no cover
else: # pragma: 3.x no cover
from ConfigParser import SafeConfigParser, \
InterpolationMissingOptionError, NoOptionError, NoSectionError
@@ -372,7 +372,8 @@ after = 1.conf
s2 = alls.get(n)
if isinstance(s2, dict):
# save previous known values, for possible using in local interpolations later:
self.merge_section('KNOWN/'+n, s2, '')
self.merge_section('KNOWN/'+n,
dict(filter(lambda i: i[0] in s, s2.iteritems())), '')
# merge section
s2.update(s)
else:
+56 -23
View File
@@ -34,6 +34,30 @@ from ..helpers import getLogger, _as_bool, _merge_dicts, substituteRecursiveTags
# Gets the instance of the logger.
logSys = getLogger(__name__)
CONVERTER = {
"bool": _as_bool,
"int": int,
}
def _OptionsTemplateGen(options):
"""Iterator over the options template with default options.
Each options entry is composed of an array or tuple with:
[[type, name, ?default?], ...]
Or it is a dict:
{name: [type, default], ...}
"""
if isinstance(options, (list,tuple)):
for optname in options:
if len(optname) > 2:
opttype, optname, optvalue = optname
else:
(opttype, optname), optvalue = optname, None
yield opttype, optname, optvalue
else:
for optname in options:
opttype, optvalue = options[optname]
yield opttype, optname, optvalue
class ConfigReader():
"""Generic config reader class.
@@ -120,6 +144,10 @@ class ConfigReader():
except AttributeError:
return False
def has_option(self, sec, opt, withDefault=True):
return self._cfg.has_option(sec, opt) if withDefault \
else opt in self._cfg._sections.get(sec, {})
def merge_defaults(self, d):
self._cfg.get_defaults().update(d)
@@ -224,31 +252,22 @@ class ConfigReaderUnshared(SafeConfigParserWithIncludes):
# Or it is a dict:
# {name: [type, default], ...}
def getOptions(self, sec, options, pOptions=None, shouldExist=False):
def getOptions(self, sec, options, pOptions=None, shouldExist=False, convert=True):
values = dict()
if pOptions is None:
pOptions = {}
# Get only specified options:
for optname in options:
if isinstance(options, (list,tuple)):
if len(optname) > 2:
opttype, optname, optvalue = optname
else:
(opttype, optname), optvalue = optname, None
else:
opttype, optvalue = options[optname]
for opttype, optname, optvalue in _OptionsTemplateGen(options):
if optname in pOptions:
continue
try:
if opttype == "bool":
v = self.getboolean(sec, optname)
if v is None: continue
elif opttype == "int":
v = self.getint(sec, optname)
if v is None: continue
else:
v = self.get(sec, optname, vars=pOptions)
v = self.get(sec, optname, vars=pOptions)
values[optname] = v
if convert:
conv = CONVERTER.get(opttype)
if conv:
if v is None: continue
values[optname] = conv(v)
except NoSectionError as e:
if shouldExist:
raise
@@ -261,8 +280,8 @@ class ConfigReaderUnshared(SafeConfigParserWithIncludes):
logSys.warning("'%s' not defined in '%s'. Using default one: %r"
% (optname, sec, optvalue))
values[optname] = optvalue
elif logSys.getEffectiveLevel() <= logLevel:
logSys.log(logLevel, "Non essential option '%s' not defined in '%s'.", optname, sec)
# elif logSys.getEffectiveLevel() <= logLevel:
# logSys.log(logLevel, "Non essential option '%s' not defined in '%s'.", optname, sec)
except ValueError:
logSys.warning("Wrong value for '" + optname + "' in '" + sec +
"'. Using default one: '" + repr(optvalue) + "'")
@@ -320,8 +339,9 @@ class DefinitionInitConfigReader(ConfigReader):
pOpts = dict()
if self._initOpts:
pOpts = _merge_dicts(pOpts, self._initOpts)
# type-convert only in combined (otherwise int/bool converting prevents substitution):
self._opts = ConfigReader.getOptions(
self, "Definition", self._configOpts, pOpts)
self, "Definition", self._configOpts, pOpts, convert=False)
self._pOpts = pOpts
if self.has_section("Init"):
# get only own options (without options from default):
@@ -342,10 +362,21 @@ class DefinitionInitConfigReader(ConfigReader):
if opt == '__name__' or opt in self._opts: continue
self._opts[opt] = self.get("Definition", opt)
def convertOptions(self, opts, configOpts):
"""Convert interpolated combined options to expected type.
"""
for opttype, optname, optvalue in _OptionsTemplateGen(configOpts):
conv = CONVERTER.get(opttype)
if conv:
v = opts.get(optname)
if v is None: continue
try:
opts[optname] = conv(v)
except ValueError:
logSys.warning("Wrong %s value %r for %r. Using default one: %r",
opttype, v, optname, optvalue)
opts[optname] = optvalue
def _convert_to_boolean(self, value):
return _as_bool(value)
def getCombOption(self, optname):
"""Get combined definition option (as string) using pre-set and init
options as preselection (values with higher precedence as specified in section).
@@ -380,6 +411,8 @@ class DefinitionInitConfigReader(ConfigReader):
ignore=ignore, addrepl=self.getCombOption)
if not opts:
raise ValueError('recursive tag definitions unable to be resolved')
# convert options after all interpolations:
self.convertOptions(opts, self._configOpts)
return opts
def convert(self):
+9 -5
View File
@@ -48,7 +48,8 @@ class CSocket:
def send(self, msg, nonblocking=False, timeout=None):
# Convert every list member to string
obj = dumps(map(CSocket.convert, msg), HIGHEST_PROTOCOL)
self.__csock.send(obj + CSPROTO.END)
self.__csock.send(obj)
self.__csock.send(CSPROTO.END)
return self.receive(self.__csock, nonblocking, timeout)
def settimeout(self, timeout):
@@ -81,9 +82,12 @@ class CSocket:
msg = CSPROTO.EMPTY
if nonblocking: sock.setblocking(0)
if timeout: sock.settimeout(timeout)
while msg.rfind(CSPROTO.END) == -1:
chunk = sock.recv(512)
if chunk in ('', b''): # python 3.x may return b'' instead of ''
raise RuntimeError("socket connection broken")
bufsize = 1024
while msg.rfind(CSPROTO.END, -32) == -1:
chunk = sock.recv(bufsize)
if not len(chunk):
raise socket.error(104, 'Connection reset by peer')
if chunk == CSPROTO.END: break
msg = msg + chunk
if bufsize < 32768: bufsize <<= 1
return loads(msg)
+1 -14
View File
@@ -168,19 +168,6 @@ class Fail2banClient(Fail2banCmdLine, Thread):
if not ret:
return None
# verify that directory for the socket file exists
socket_dir = os.path.dirname(self._conf["socket"])
if not os.path.exists(socket_dir):
logSys.error(
"There is no directory %s to contain the socket file %s."
% (socket_dir, self._conf["socket"]))
return None
if not os.access(socket_dir, os.W_OK | os.X_OK): # pragma: no cover
logSys.error(
"Directory %s exists but not accessible for writing"
% (socket_dir,))
return None
# Check already running
if not self._conf["force"] and os.path.exists(self._conf["socket"]):
logSys.error("Fail2ban seems to be in unexpected state (not running but the socket exists)")
@@ -243,7 +230,7 @@ class Fail2banClient(Fail2banCmdLine, Thread):
logSys.log(5, ' client phase %s', phase)
if not stream:
return False
# wait a litle bit for phase "start-ready" before enter active waiting:
# wait a little bit for phase "start-ready" before enter active waiting:
if phase is not None:
Utils.wait_for(lambda: phase.get('start-ready', None) is not None, 0.5, 0.001)
phase['configure'] = (True if stream else False)
+37 -23
View File
@@ -27,15 +27,20 @@ import sys
from ..version import version, normVersion
from ..protocol import printFormatted
from ..helpers import getLogger, str2LogLevel, getVerbosityFormat
from ..helpers import getLogger, str2LogLevel, getVerbosityFormat, BrokenPipeError
# Gets the instance of the logger.
logSys = getLogger("fail2ban")
def output(s): # pragma: no cover
print(s)
try:
print(s)
except (BrokenPipeError, IOError) as e: # pragma: no cover
if e.errno != 32: # closed / broken pipe
raise
CONFIG_PARAMS = ("socket", "pidfile", "logtarget", "loglevel", "syslogsocket",)
# Config parameters required to start fail2ban which can be also set via command line (overwrite fail2ban.conf),
CONFIG_PARAMS = ("socket", "pidfile", "logtarget", "loglevel", "syslogsocket")
# Used to signal - we are in test cases (ex: prevents change logging params, log capturing, etc)
PRODUCTION = True
@@ -94,9 +99,10 @@ class Fail2banCmdLine():
output("and bans the corresponding IP addresses using firewall rules.")
output("")
output("Options:")
output(" -c <DIR> configuration directory")
output(" -s <FILE> socket path")
output(" -p <FILE> pidfile path")
output(" -c, --conf <DIR> configuration directory")
output(" -s, --socket <FILE> socket path")
output(" -p, --pidfile <FILE> pidfile path")
output(" --pname <NAME> name of the process (main thread) to identify instance (default fail2ban-server)")
output(" --loglevel <LEVEL> logging level")
output(" --logtarget <TARGET> logging target, use file-name or stdout, stderr, syslog or sysout.")
output(" --syslogsocket auto|<FILE>")
@@ -129,17 +135,15 @@ class Fail2banCmdLine():
"""
for opt in optList:
o = opt[0]
if o == "-c":
if o in ("-c", "--conf"):
self._conf["conf"] = opt[1]
elif o == "-s":
elif o in ("-s", "--socket"):
self._conf["socket"] = opt[1]
elif o == "-p":
elif o in ("-p", "--pidfile"):
self._conf["pidfile"] = opt[1]
elif o.startswith("--log") or o.startswith("--sys"):
self._conf[ o[2:] ] = opt[1]
elif o in ["-d", "--dp", "--dump-pretty"]:
elif o in ("-d", "--dp", "--dump-pretty"):
self._conf["dump"] = True if o == "-d" else 2
elif o == "-t" or o == "--test":
elif o in ("-t", "--test"):
self.cleanConfOnly = True
self._conf["test"] = True
elif o == "-v":
@@ -163,12 +167,14 @@ class Fail2banCmdLine():
from ..server.mytime import MyTime
output(MyTime.str2seconds(opt[1]))
return True
elif o in ["-h", "--help"]:
elif o in ("-h", "--help"):
self.dispUsage()
return True
elif o in ["-V", "--version"]:
elif o in ("-V", "--version"):
self.dispVersion(o == "-V")
return True
elif o.startswith("--"): # other long named params (see also resetConf)
self._conf[ o[2:] ] = opt[1]
return None
def initCmdLine(self, argv):
@@ -185,7 +191,8 @@ class Fail2banCmdLine():
try:
cmdOpts = 'hc:s:p:xfbdtviqV'
cmdLongOpts = ['loglevel=', 'logtarget=', 'syslogsocket=', 'test', 'async',
'timeout=', 'str2sec=', 'help', 'version', 'dp', '--dump-pretty']
'conf=', 'pidfile=', 'pname=', 'socket=',
'timeout=', 'str2sec=', 'help', 'version', 'dp', 'dump-pretty']
optList, self._args = getopt.getopt(self._argv[1:], cmdOpts, cmdLongOpts)
except getopt.GetoptError:
self.dispUsage()
@@ -227,7 +234,8 @@ class Fail2banCmdLine():
if not conf:
self.configurator.readEarly()
conf = self.configurator.getEarlyOptions()
self._conf[o] = conf[o]
if o in conf:
self._conf[o] = conf[o]
logSys.info("Using socket file %s", self._conf["socket"])
@@ -304,18 +312,24 @@ class Fail2banCmdLine():
# since method is also exposed in API via globally bound variable
@staticmethod
def _exit(code=0):
if hasattr(os, '_exit') and os._exit:
os._exit(code)
else:
sys.exit(code)
# implicit flush without to produce broken pipe error (32):
sys.stderr.close()
try:
sys.stdout.flush()
# exit:
if hasattr(sys, 'exit') and sys.exit:
sys.exit(code)
else:
os._exit(code)
except (BrokenPipeError, IOError) as e: # pragma: no cover
if e.errno != 32: # closed / broken pipe
raise
@staticmethod
def exit(code=0):
logSys.debug("Exit with code %s", code)
# because of possible buffered output in python, we should flush it before exit:
logging.shutdown()
sys.stdout.flush()
sys.stderr.flush()
# exit
Fail2banCmdLine._exit(code)
+2
View File
@@ -53,6 +53,7 @@ class Fail2banReader(ConfigReader):
opts = [["string", "loglevel", "INFO" ],
["string", "logtarget", "STDERR"],
["string", "syslogsocket", "auto"],
["string", "allowipv6", "auto"],
["string", "dbfile", "/var/lib/fail2ban/fail2ban.sqlite3"],
["int", "dbmaxmatches", None],
["string", "dbpurgeage", "1d"]]
@@ -74,6 +75,7 @@ class Fail2banReader(ConfigReader):
# Also dbfile should be set before all other database options.
# So adding order indices into items, to be stripped after sorting, upon return
order = {"thread":0, "syslogsocket":11, "loglevel":12, "logtarget":13,
"allowipv6": 14,
"dbfile":50, "dbmaxmatches":51, "dbpurgeage":51}
stream = list()
for opt in self.__opts:
+191 -116
View File
@@ -21,7 +21,6 @@ Fail2Ban reads log file that contains password failure report
and bans the corresponding IP addresses using firewall rules.
This tools can test regular expressions for "fail2ban".
"""
__author__ = "Fail2Ban Developers"
@@ -36,11 +35,11 @@ __license__ = "GPL"
import getopt
import logging
import re
import os
import shlex
import sys
import time
import time
import urllib
from optparse import OptionParser, Option
@@ -53,7 +52,7 @@ except ImportError:
from ..version import version, normVersion
from .filterreader import FilterReader
from ..server.filter import Filter, FileContainer
from ..server.filter import Filter, FileContainer, MyTime
from ..server.failregex import Regex, RegexException
from ..helpers import str2LogLevel, getVerbosityFormat, FormatterWithTraceBack, getLogger, \
@@ -109,19 +108,22 @@ class _f2bOptParser(OptionParser):
def format_help(self, *args, **kwargs):
""" Overwritten format helper with full ussage."""
self.usage = ''
return "Usage: " + usage() + __doc__ + """
return "Usage: " + usage() + "\n" + __doc__ + """
LOG:
string a string representing a log line
filename path to a log file (/var/log/auth.log)
"systemd-journal" search systemd journal (systemd-python required)
string a string representing a log line
filename path to a log file (/var/log/auth.log)
systemd-journal search systemd journal (systemd-python required),
optionally with backend parameters, see `man jail.conf`
for usage and examples (systemd-journal[journalflags=1]).
REGEX:
string a string representing a 'failregex'
filename path to a filter file (filter.d/sshd.conf)
string a string representing a 'failregex'
filter name of filter, optionally with options (sshd[mode=aggressive])
filename path to a filter file (filter.d/sshd.conf)
IGNOREREGEX:
string a string representing an 'ignoreregex'
filename path to a filter file (filter.d/sshd.conf)
string a string representing an 'ignoreregex'
filename path to a filter file (filter.d/sshd.conf)
\n""" + OptionParser.format_help(self, *args, **kwargs) + """\n
Report bugs to https://github.com/fail2ban/fail2ban/issues\n
""" + __copyright__ + "\n"
@@ -252,6 +254,8 @@ class Fail2banRegex(object):
self.share_config=dict()
self._filter = Filter(None)
self._prefREMatched = 0
self._prefREGroups = list()
self._ignoreregex = list()
self._failregex = list()
self._time_elapsed = None
@@ -265,21 +269,26 @@ class Fail2banRegex(object):
self.setJournalMatch(shlex.split(opts.journalmatch))
if opts.timezone:
self._filter.setLogTimeZone(opts.timezone)
self._filter.checkFindTime = False
if True: # not opts.out:
MyTime.setAlternateNow(0); # accept every date (years from 19xx up to end of current century, '%ExY' and 'Exy' patterns)
from ..server.strptime import _updateTimeRE
_updateTimeRE()
if opts.datepattern:
self.setDatePattern(opts.datepattern)
if opts.usedns:
self._filter.setUseDns(opts.usedns)
self._filter.returnRawHost = opts.raw
self._filter.checkFindTime = False
self._filter.checkAllRegex = opts.checkAllRegex and not opts.out
# ignore pending (without ID/IP), added to matches if it hits later (if ID/IP can be retreved)
self._filter.ignorePending = bool(opts.out)
# callback to increment ignored RE's by index (during process):
self._filter.onIgnoreRegex = self._onIgnoreRegex
self._backend = 'auto'
def output(self, line):
if not self._opts.out: output(line)
def decode_line(self, line):
return FileContainer.decode_line('<LOG>', self._encoding, line)
def encode_line(self, line):
return line.encode(self._encoding, 'ignore')
@@ -288,8 +297,8 @@ class Fail2banRegex(object):
self._filter.setDatePattern(pattern)
self._datepattern_set = True
if pattern is not None:
self.output( "Use datepattern : %s" % (
self._filter.getDatePattern()[1], ) )
self.output( "Use datepattern : %s : %s" % (
pattern, self._filter.getDatePattern()[1], ) )
def setMaxLines(self, v):
if not self._maxlines_set:
@@ -318,26 +327,33 @@ class Fail2banRegex(object):
regex = regextype + 'regex'
# try to check - we've case filter?[options...]?:
basedir = self._opts.config
fltName = value
fltFile = None
fltOpt = {}
if regextype == 'fail':
fltName, fltOpt = extractOptions(value)
if fltName is not None:
if "." in fltName[~5:]:
tryNames = (fltName,)
else:
tryNames = (fltName, fltName + '.conf', fltName + '.local')
for fltFile in tryNames:
if not "/" in fltFile:
if os.path.basename(basedir) == 'filter.d':
fltFile = os.path.join(basedir, fltFile)
else:
fltFile = os.path.join(basedir, 'filter.d', fltFile)
if re.search(r'^/{0,3}[\w/_\-.]+(?:\[.*\])?$', value):
try:
fltName, fltOpt = extractOptions(value)
if "." in fltName[~5:]:
tryNames = (fltName,)
else:
basedir = os.path.dirname(fltFile)
if os.path.isfile(fltFile):
break
fltFile = None
tryNames = (fltName, fltName + '.conf', fltName + '.local')
for fltFile in tryNames:
if not "/" in fltFile:
if os.path.basename(basedir) == 'filter.d':
fltFile = os.path.join(basedir, fltFile)
else:
fltFile = os.path.join(basedir, 'filter.d', fltFile)
else:
basedir = os.path.dirname(fltFile)
if os.path.isfile(fltFile):
break
fltFile = None
except Exception as e:
output("ERROR: Wrong filter name or options: %s" % (str(e),))
output(" while parsing: %s" % (value,))
if self._verbose: raise(e)
return False
# if it is filter file:
if fltFile is not None:
if (basedir == self._opts.config
@@ -372,11 +388,8 @@ class Fail2banRegex(object):
if not ret:
output( "ERROR: failed to load filter %s" % value )
return False
# overwrite default logtype (considering that the filter could specify this too in Definition/Init sections):
if not fltOpt.get('logtype'):
reader.merge_defaults({
'logtype': ['file','journal'][int(self._backend.startswith("systemd"))]
})
# set backend-related options (logtype):
reader.applyAutoOptions(self._backend)
# get, interpolate and convert options:
reader.getOptions(None)
# show real options if expected:
@@ -436,71 +449,140 @@ class Fail2banRegex(object):
'add%sRegex' % regextype.title())(regex.getFailRegex())
return True
def testIgnoreRegex(self, line):
found = False
try:
ret = self._filter.ignoreLine([(line, "", "")])
if ret is not None:
found = True
regex = self._ignoreregex[ret].inc()
except RegexException as e: # pragma: no cover
output( 'ERROR: %s' % e )
return False
return found
def _onIgnoreRegex(self, idx, ignoreRegex):
self._lineIgnored = True
self._ignoreregex[idx].inc()
def testRegex(self, line, date=None):
orgLineBuffer = self._filter._Filter__lineBuffer
# duplicate line buffer (list can be changed inplace during processLine):
if self._filter.getMaxLines() > 1:
orgLineBuffer = orgLineBuffer[:]
fullBuffer = len(orgLineBuffer) >= self._filter.getMaxLines()
is_ignored = False
is_ignored = self._lineIgnored = False
try:
found = self._filter.processLine(line, date)
lines = []
line = self._filter.processedLine()
ret = []
for match in found:
# Append True/False flag depending if line was matched by
# more than one regex
match.append(len(ret)>1)
regex = self._failregex[match[0]]
regex.inc()
regex.appendIP(match)
if not self._opts.out:
# Append True/False flag depending if line was matched by
# more than one regex
match.append(len(ret)>1)
regex = self._failregex[match[0]]
regex.inc()
regex.appendIP(match)
if not match[3].get('nofail'):
ret.append(match)
else:
is_ignored = True
if self._opts.out: # (formated) output - don't need stats:
return None, ret, None
# prefregex stats:
if self._filter.prefRegex:
pre = self._filter.prefRegex
if pre.hasMatched():
self._prefREMatched += 1
if self._verbose:
if len(self._prefREGroups) < self._maxlines:
self._prefREGroups.append(pre.getGroups())
else:
if len(self._prefREGroups) == self._maxlines:
self._prefREGroups.append('...')
except RegexException as e: # pragma: no cover
output( 'ERROR: %s' % e )
return False
for bufLine in orgLineBuffer[int(fullBuffer):]:
if bufLine not in self._filter._Filter__lineBuffer:
try:
self._line_stats.missed_lines.pop(
self._line_stats.missed_lines.index("".join(bufLine)))
if self._debuggex:
self._line_stats.missed_lines_timeextracted.pop(
self._line_stats.missed_lines_timeextracted.index(
"".join(bufLine[::2])))
except ValueError:
pass
# if buffering - add also another lines from match:
if self._print_all_matched:
if not self._debuggex:
self._line_stats.matched_lines.append("".join(bufLine))
else:
lines.append(bufLine[0] + bufLine[2])
self._line_stats.matched += 1
self._line_stats.missed -= 1
return None, 0, None
if self._filter.getMaxLines() > 1:
for bufLine in orgLineBuffer[int(fullBuffer):]:
if bufLine not in self._filter._Filter__lineBuffer:
try:
self._line_stats.missed_lines.pop(
self._line_stats.missed_lines.index("".join(bufLine)))
if self._debuggex:
self._line_stats.missed_lines_timeextracted.pop(
self._line_stats.missed_lines_timeextracted.index(
"".join(bufLine[::2])))
except ValueError:
pass
# if buffering - add also another lines from match:
if self._print_all_matched:
if not self._debuggex:
self._line_stats.matched_lines.append("".join(bufLine))
else:
lines.append(bufLine[0] + bufLine[2])
self._line_stats.matched += 1
self._line_stats.missed -= 1
if lines: # pre-lines parsed in multiline mode (buffering)
lines.append(line)
lines.append(self._filter.processedLine())
line = "\n".join(lines)
return line, ret, is_ignored
return line, ret, (is_ignored or self._lineIgnored)
def _prepaireOutput(self):
"""Prepares output- and fetch-function corresponding given '--out' option (format)"""
ofmt = self._opts.out
if ofmt in ('id', 'ip'):
def _out(ret):
for r in ret:
output(r[1])
elif ofmt == 'msg':
def _out(ret):
for r in ret:
for r in r[3].get('matches'):
if not isinstance(r, basestring):
r = ''.join(r for r in r)
output(r)
elif ofmt == 'row':
def _out(ret):
for r in ret:
output('[%r,\t%r,\t%r],' % (r[1],r[2],dict((k,v) for k, v in r[3].iteritems() if k != 'matches')))
elif '<' not in ofmt:
def _out(ret):
for r in ret:
output(r[3].get(ofmt))
else: # extended format with tags substitution:
from ..server.actions import Actions, CommandAction, BanTicket
def _escOut(t, v):
# use safe escape (avoid inject on pseudo tag "\x00msg\x00"):
if t not in ('msg',):
return v.replace('\x00', '\\x00')
return v
def _out(ret):
rows = []
wrap = {'NL':0}
for r in ret:
ticket = BanTicket(r[1], time=r[2], data=r[3])
aInfo = Actions.ActionInfo(ticket)
# if msg tag is used - output if single line (otherwise let it as is to wrap multilines later):
def _get_msg(self):
if not wrap['NL'] and len(r[3].get('matches', [])) <= 1:
return self['matches']
else: # pseudo tag for future replacement:
wrap['NL'] = 1
return "\x00msg\x00"
aInfo['msg'] = _get_msg
# not recursive interpolation (use safe escape):
v = CommandAction.replaceDynamicTags(ofmt, aInfo, escapeVal=_escOut)
if wrap['NL']: # contains multiline tags (msg):
rows.append((r, v))
continue
output(v)
# wrap multiline tag (msg) interpolations to single line:
for r, v in rows:
for r in r[3].get('matches'):
if not isinstance(r, basestring):
r = ''.join(r for r in r)
r = v.replace("\x00msg\x00", r)
output(r)
return _out
def process(self, test_lines):
t0 = time.time()
if self._opts.out: # get out function
out = self._prepaireOutput()
for line in test_lines:
if isinstance(line, tuple):
line_datetimestripped, ret, is_ignored = self.testRegex(
line[0], line[1])
line_datetimestripped, ret, is_ignored = self.testRegex(line[0], line[1])
line = "".join(line[0])
else:
line = line.rstrip('\r\n')
@@ -508,8 +590,10 @@ class Fail2banRegex(object):
# skip comment and empty lines
continue
line_datetimestripped, ret, is_ignored = self.testRegex(line)
if not is_ignored:
is_ignored = self.testIgnoreRegex(line_datetimestripped)
if self._opts.out: # (formated) output:
if len(ret) > 0 and not is_ignored: out(ret)
continue
if is_ignored:
self._line_stats.ignored += 1
@@ -517,42 +601,25 @@ class Fail2banRegex(object):
self._line_stats.ignored_lines.append(line)
if self._debuggex:
self._line_stats.ignored_lines_timeextracted.append(line_datetimestripped)
if len(ret) > 0:
assert(not is_ignored)
if self._opts.out:
if self._opts.out in ('id', 'ip'):
for ret in ret:
output(ret[1])
elif self._opts.out == 'msg':
for ret in ret:
output('\n'.join(map(lambda v:''.join(v for v in v), ret[3].get('matches'))))
elif self._opts.out == 'row':
for ret in ret:
output('[%r,\t%r,\t%r],' % (ret[1],ret[2],dict((k,v) for k, v in ret[3].iteritems() if k != 'matches')))
else:
for ret in ret:
output(ret[3].get(self._opts.out))
continue
elif len(ret) > 0:
self._line_stats.matched += 1
if self._print_all_matched:
self._line_stats.matched_lines.append(line)
if self._debuggex:
self._line_stats.matched_lines_timeextracted.append(line_datetimestripped)
else:
if not is_ignored:
self._line_stats.missed += 1
if not self._print_no_missed and (self._print_all_missed or self._line_stats.missed <= self._maxlines + 1):
self._line_stats.missed_lines.append(line)
if self._debuggex:
self._line_stats.missed_lines_timeextracted.append(line_datetimestripped)
self._line_stats.missed += 1
if not self._print_no_missed and (self._print_all_missed or self._line_stats.missed <= self._maxlines + 1):
self._line_stats.missed_lines.append(line)
if self._debuggex:
self._line_stats.missed_lines_timeextracted.append(line_datetimestripped)
self._line_stats.tested += 1
self._time_elapsed = time.time() - t0
def printLines(self, ltype):
lstats = self._line_stats
assert(self._line_stats.missed == lstats.tested - (lstats.matched + lstats.ignored))
assert(lstats.missed == lstats.tested - (lstats.matched + lstats.ignored))
lines = lstats[ltype]
l = lstats[ltype + '_lines']
multiline = self._filter.getMaxLines() > 1
@@ -610,7 +677,18 @@ class Fail2banRegex(object):
pprint_list(out, " #) [# of hits] regular expression")
return total
# Print title
# Print prefregex:
if self._filter.prefRegex:
#self._filter.prefRegex.hasMatched()
pre = self._filter.prefRegex
out = [pre.getRegex()]
if self._verbose:
for grp in self._prefREGroups:
out.append(" %s" % (grp,))
output( "\n%s: %d total" % ("Prefregex", self._prefREMatched) )
pprint_list(out)
# Print regex's:
total = print_failregexes("Failregex", self._failregex)
_ = print_failregexes("Ignoreregex", self._ignoreregex)
@@ -642,10 +720,6 @@ class Fail2banRegex(object):
return True
def file_lines_gen(self, hdlr):
for line in hdlr:
yield self.decode_line(line)
def start(self, args):
cmd_log, cmd_regex = args[:2]
@@ -664,10 +738,10 @@ class Fail2banRegex(object):
if os.path.isfile(cmd_log):
try:
hdlr = open(cmd_log, 'rb')
test_lines = FileContainer(cmd_log, self._encoding, doOpen=True)
self.output( "Use log file : %s" % cmd_log )
self.output( "Use encoding : %s" % self._encoding )
test_lines = self.file_lines_gen(hdlr)
except IOError as e: # pragma: no cover
output( e )
return False
@@ -689,10 +763,10 @@ class Fail2banRegex(object):
test_lines = journal_lines_gen(flt, myjournal)
else:
# if single line parsing (without buffering)
if self._filter.getMaxLines() <= 1:
if self._filter.getMaxLines() <= 1 and '\n' not in cmd_log:
self.output( "Use single line : %s" % shortstr(cmd_log.replace("\n", r"\n")) )
test_lines = [ cmd_log ]
else: # multi line parsing (with buffering)
else: # multi line parsing (with and without buffering)
test_lines = cmd_log.split("\n")
self.output( "Use multi line : %s line(s)" % len(test_lines) )
for i, l in enumerate(test_lines):
@@ -712,6 +786,7 @@ class Fail2banRegex(object):
def exec_command_line(*args):
logging.exitOnIOError = True
parser = get_opt_parser()
(opts, args) = parser.parse_args(*args)
errors = []
+8
View File
@@ -53,6 +53,14 @@ class FilterReader(DefinitionInitConfigReader):
def getFile(self):
return self.__file
def applyAutoOptions(self, backend):
# set init option to backend-related logtype, considering
# that the filter settings may be overwritten in its local:
if (not self._initOpts.get('logtype') and
not self.has_option('Definition', 'logtype', False)
):
self._initOpts['logtype'] = ['file','journal'][int(backend.startswith("systemd"))]
def convert(self):
stream = list()
opts = self.getCombined()
+17 -12
View File
@@ -98,6 +98,13 @@ class JailReader(ConfigReader):
"maxmatches": ["int", None],
"findtime": ["string", None],
"bantime": ["string", None],
"bantime.increment": ["bool", None],
"bantime.factor": ["string", None],
"bantime.formula": ["string", None],
"bantime.multipliers": ["string", None],
"bantime.maxtime": ["string", None],
"bantime.rndtime": ["string", None],
"bantime.overalljails": ["bool", None],
"ignorecommand": ["string", None],
"ignoreself": ["bool", None],
"ignoreip": ["string", None],
@@ -133,20 +140,18 @@ class JailReader(ConfigReader):
# Read filter
flt = self.__opts["filter"]
if flt:
filterName, filterOpt = extractOptions(flt)
if not filterName:
raise JailDefError("Invalid filter definition %r" % flt)
try:
filterName, filterOpt = extractOptions(flt)
except ValueError as e:
raise JailDefError("Invalid filter definition %r: %s" % (flt, e))
self.__filter = FilterReader(
filterName, self.__name, filterOpt,
share_config=self.share_config, basedir=self.getBaseDir())
ret = self.__filter.read()
if not ret:
raise JailDefError("Unable to read the filter %r" % filterName)
if not filterOpt.get('logtype'):
# overwrite default logtype backend-related (considering that the filter settings may be overwritten):
self.__filter.merge_defaults({
'logtype': ['file','journal'][int(self.__opts.get('backend', '').startswith("systemd"))]
})
# set backend-related options (logtype):
self.__filter.applyAutoOptions(self.__opts.get('backend', ''))
# merge options from filter as 'known/...' (all options unfiltered):
self.__filter.getOptions(self.__opts, all=True)
ConfigReader.merge_section(self, self.__name, self.__filter.getCombined(), 'known/')
@@ -170,10 +175,10 @@ class JailReader(ConfigReader):
if not act: # skip empty actions
continue
# join with previous line if needed (consider possible new-line):
actName, actOpt = extractOptions(act)
prevln = ''
if not actName:
raise JailDefError("Invalid action definition %r" % act)
try:
actName, actOpt = extractOptions(act)
except ValueError as e:
raise JailDefError("Invalid action definition %r: %s" % (act, e))
if actName.endswith(".py"):
self.__actions.append([
"set",
+56 -12
View File
@@ -208,6 +208,26 @@ class FormatterWithTraceBack(logging.Formatter):
return logging.Formatter.format(self, record)
logging.exitOnIOError = False
def __stopOnIOError(logSys=None, logHndlr=None): # pragma: no cover
if logSys and len(logSys.handlers):
logSys.removeHandler(logSys.handlers[0])
if logHndlr:
logHndlr.close = lambda: None
logging.StreamHandler.flush = lambda self: None
#sys.excepthook = lambda *args: None
if logging.exitOnIOError:
try:
sys.stderr.close()
except:
pass
sys.exit(0)
try:
BrokenPipeError = BrokenPipeError
except NameError: # pragma: 3.x no cover
BrokenPipeError = IOError
__origLog = logging.Logger._log
def __safeLog(self, level, msg, args, **kwargs):
"""Safe log inject to avoid possible errors by unsafe log-handlers,
@@ -223,6 +243,10 @@ def __safeLog(self, level, msg, args, **kwargs):
try:
# if isEnabledFor(level) already called...
__origLog(self, level, msg, args, **kwargs)
except (BrokenPipeError, IOError) as e: # pragma: no cover
if e.errno == 32: # closed / broken pipe
__stopOnIOError(self)
raise
except Exception as e: # pragma: no cover - unreachable if log-handler safe in this python-version
try:
for args in (
@@ -237,6 +261,18 @@ def __safeLog(self, level, msg, args, **kwargs):
pass
logging.Logger._log = __safeLog
__origLogFlush = logging.StreamHandler.flush
def __safeLogFlush(self):
"""Safe flush inject stopping endless logging on closed streams (redirected pipe).
"""
try:
__origLogFlush(self)
except (BrokenPipeError, IOError) as e: # pragma: no cover
if e.errno == 32: # closed / broken pipe
__stopOnIOError(None, self)
raise
logging.StreamHandler.flush = __safeLogFlush
def getLogger(name):
"""Get logging.Logger instance with Fail2Ban logger name convention
"""
@@ -267,7 +303,7 @@ def getVerbosityFormat(verbosity, fmt=' %(message)s', addtime=True, padding=True
if addtime:
fmt = ' %(asctime)-15s' + fmt
else: # default (not verbose):
fmt = "%(name)-23.23s [%(process)d]: %(levelname)-7s" + fmt
fmt = "%(name)-24s[%(process)d]: %(levelname)-7s" + fmt
if addtime:
fmt = "%(asctime)s " + fmt
# remove padding if not needed:
@@ -291,7 +327,7 @@ def splitwords(s):
"""
if not s:
return []
return filter(bool, map(str.strip, re.split('[ ,\n]+', s)))
return filter(bool, map(lambda v: v.strip(), re.split('[ ,\n]+', s)))
if sys.version_info >= (3,5):
eval(compile(r'''if 1:
@@ -335,21 +371,27 @@ OPTION_CRE = re.compile(r"^([^\[]+)(?:\[(.*)\])?\s*$", re.DOTALL)
# since v0.10 separator extended with `]\s*[` for support of multiple option groups, syntax
# `action = act[p1=...][p2=...]`
OPTION_EXTRACT_CRE = re.compile(
r'([\w\-_\.]+)=(?:"([^"]*)"|\'([^\']*)\'|([^,\]]*))(?:,|\]\s*\[|$)', re.DOTALL)
r'\s*([\w\-_\.]+)=(?:"([^"]*)"|\'([^\']*)\'|([^,\]]*))(?:,|\]\s*\[|$|(?P<wrngA>.+))|,?\s*$|(?P<wrngB>.+)', re.DOTALL)
# split by new-line considering possible new-lines within options [...]:
OPTION_SPLIT_CRE = re.compile(
r'(?:[^\[\n]+(?:\s*\[\s*(?:[\w\-_\.]+=(?:"[^"]*"|\'[^\']*\'|[^,\]]*)\s*(?:,|\]\s*\[)?\s*)*\])?\s*|[^\n]+)(?=\n\s*|$)', re.DOTALL)
r'(?:[^\[\s]+(?:\s*\[\s*(?:[\w\-_\.]+=(?:"[^"]*"|\'[^\']*\'|[^,\]]*)\s*(?:,|\]\s*\[)?\s*)*\])?\s*|\S+)(?=\n\s*|\s+|$)', re.DOTALL)
def extractOptions(option):
match = OPTION_CRE.match(option)
if not match:
# TODO proper error handling
return None, None
raise ValueError("unexpected option syntax")
option_name, optstr = match.groups()
option_opts = dict()
if optstr:
for optmatch in OPTION_EXTRACT_CRE.finditer(optstr):
if optmatch.group("wrngA"):
raise ValueError("unexpected syntax at %d after option %r: %s" % (
optmatch.start("wrngA"), optmatch.group(1), optmatch.group("wrngA")[0:25]))
if optmatch.group("wrngB"):
raise ValueError("expected option, wrong syntax at %d: %s" % (
optmatch.start("wrngB"), optmatch.group("wrngB")[0:25]))
opt = optmatch.group(1)
if not opt: continue
value = [
val for val in optmatch.group(2,3,4) if val is not None][0]
option_opts[opt.strip()] = value.strip()
@@ -363,8 +405,8 @@ def splitWithOptions(option):
# tags (<tag>) in tagged options.
#
# max tag replacement count:
MAX_TAG_REPLACE_COUNT = 10
# max tag replacement count (considering tag X in tag Y repeat):
MAX_TAG_REPLACE_COUNT = 25
# compiled RE for tag name (replacement name)
TAG_CRE = re.compile(r'<([^ <>]+)>')
@@ -398,6 +440,7 @@ def substituteRecursiveTags(inptags, conditional='',
done = set()
noRecRepl = hasattr(tags, "getRawItem")
# repeat substitution while embedded-recursive (repFlag is True)
repCounts = {}
while True:
repFlag = False
# substitute each value:
@@ -409,7 +452,7 @@ def substituteRecursiveTags(inptags, conditional='',
value = orgval = uni_string(tags[tag])
# search and replace all tags within value, that can be interpolated using other tags:
m = tre_search(value)
refCounts = {}
rplc = repCounts.get(tag, {})
#logSys.log(5, 'TAG: %s, value: %s' % (tag, value))
while m:
# found replacement tag:
@@ -419,13 +462,13 @@ def substituteRecursiveTags(inptags, conditional='',
m = tre_search(value, m.end())
continue
#logSys.log(5, 'found: %s' % rtag)
if rtag == tag or refCounts.get(rtag, 1) > MAX_TAG_REPLACE_COUNT:
if rtag == tag or rplc.get(rtag, 1) > MAX_TAG_REPLACE_COUNT:
# recursive definitions are bad
#logSys.log(5, 'recursion fail tag: %s value: %s' % (tag, value) )
raise ValueError(
"properties contain self referencing definitions "
"and cannot be resolved, fail tag: %s, found: %s in %s, value: %s" %
(tag, rtag, refCounts, value))
(tag, rtag, rplc, value))
repl = None
if conditional:
repl = tags.get(rtag + '?' + conditional)
@@ -445,7 +488,7 @@ def substituteRecursiveTags(inptags, conditional='',
value = value.replace('<%s>' % rtag, repl)
#logSys.log(5, 'value now: %s' % value)
# increment reference count:
refCounts[rtag] = refCounts.get(rtag, 0) + 1
rplc[rtag] = rplc.get(rtag, 0) + 1
# the next match for replace:
m = tre_search(value, m.start())
#logSys.log(5, 'TAG: %s, newvalue: %s' % (tag, value))
@@ -453,6 +496,7 @@ def substituteRecursiveTags(inptags, conditional='',
if orgval != value:
# check still contains any tag - should be repeated (possible embedded-recursive substitution):
if tre_search(value):
repCounts[tag] = rplc
repFlag = True
# copy return tags dict to prevent modifying of inptags:
if id(tags) == id(inptags):
+6 -1
View File
@@ -55,6 +55,8 @@ protocol = [
["stop", "stops all jails and terminate the server"],
["unban --all", "unbans all IP addresses (in all jails and database)"],
["unban <IP> ... <IP>", "unbans <IP> (in all jails and database)"],
["banned", "return jails with banned IPs as dictionary"],
["banned <IP> ... <IP>]", "return list(s) of jails where given IP(s) are banned"],
["status", "gets the current status of the server"],
["ping", "tests if the server is alive"],
["echo", "for internal usage, returns back and outputs a given string"],
@@ -120,6 +122,8 @@ protocol = [
["set <JAIL> action <ACT> <PROPERTY> <VALUE>", "sets the <VALUE> of <PROPERTY> for the action <ACT> for <JAIL>"],
["set <JAIL> action <ACT> <METHOD>[ <JSONKWARGS>]", "calls the <METHOD> with <JSONKWARGS> for the action <ACT> for <JAIL>"],
['', "JAIL INFORMATION", ""],
["get <JAIL> banned", "return banned IPs of <JAIL>"],
["get <JAIL> banned <IP> ... <IP>]", "return 1 if IP is banned in <JAIL> otherwise 0, or a list of 1/0 for multiple IPs"],
["get <JAIL> logpath", "gets the list of the monitored files for <JAIL>"],
["get <JAIL> logencoding", "gets the encoding of the log files for <JAIL>"],
["get <JAIL> journalmatch", "gets the journal filter match for <JAIL>"],
@@ -130,8 +134,9 @@ protocol = [
["get <JAIL> ignoreregex", "gets the list of regular expressions which matches patterns to ignore for <JAIL>"],
["get <JAIL> findtime", "gets the time for which the filter will look back for failures for <JAIL>"],
["get <JAIL> bantime", "gets the time a host is banned for <JAIL>"],
["get <JAIL> datepattern", "gets the patern used to match date/times for <JAIL>"],
["get <JAIL> datepattern", "gets the pattern used to match date/times for <JAIL>"],
["get <JAIL> usedns", "gets the usedns setting for <JAIL>"],
["get <JAIL> banip [<SEP>|--with-time]", "gets the list of of banned IP addresses for <JAIL>. Optionally the separator character ('<SEP>', default is space) or the option '--with-time' (printing the times of ban) may be specified. The IPs are ordered by end of ban."],
["get <JAIL> maxretry", "gets the number of failures allowed for <JAIL>"],
["get <JAIL> maxmatches", "gets the max number of matches stored in memory per ticket in <JAIL>"],
["get <JAIL> maxlines", "gets the number of lines to buffer for <JAIL>"],
+108 -45
View File
@@ -30,7 +30,10 @@ import tempfile
import threading
import time
from abc import ABCMeta
from collections import MutableMapping
try:
from collections.abc import MutableMapping
except ImportError:
from collections import MutableMapping
from .failregex import mapTag2Opt
from .ipdns import DNSUtils
@@ -262,6 +265,10 @@ class ActionBase(object):
"""
return self.ban(aInfo)
@property
def _prolongable(self): # pragma: no cover - abstract
return False
def unban(self, aInfo): # pragma: no cover - abstract
"""Executed when a ban expires.
@@ -274,6 +281,11 @@ class ActionBase(object):
pass
WRAP_CMD_PARAMS = {
'timeout': 'str2seconds',
'bantime': 'ignore',
}
class CommandAction(ActionBase):
"""A action which executes OS shell commands.
@@ -346,7 +358,10 @@ class CommandAction(ActionBase):
def __setattr__(self, name, value):
if not name.startswith('_') and not self.__init and not callable(value):
# special case for some parameters:
if name in ('timeout', 'bantime'):
wrp = WRAP_CMD_PARAMS.get(name)
if wrp == 'ignore': # ignore (filter) dynamic parameters
return
elif wrp == 'str2seconds':
value = MyTime.str2seconds(value)
# parameters changed - clear properties and substitution cache:
self.__properties = None
@@ -392,10 +407,13 @@ class CommandAction(ActionBase):
def _getOperation(self, tag, family):
# replace operation tag (interpolate all values), be sure family is enclosed as conditional value
# (as lambda in addrepl so only if not overwritten in action):
return self.replaceTag(tag, self._properties,
cmd = self.replaceTag(tag, self._properties,
conditional=('family='+family if family else ''),
addrepl=(lambda tag:family if tag == 'family' else None),
cache=self.__substCache)
if not family or '<' not in cmd: return cmd
# replace family as dynamic tags, important - don't cache, no recursion and auto-escape here:
cmd = self.replaceDynamicTags(cmd, {'family':family})
return cmd
def _operationExecuted(self, tag, family, *args):
""" Get, set or delete command of operation considering family.
@@ -440,7 +458,18 @@ class CommandAction(ActionBase):
ret = True
# avoid double execution of same command for both families:
if cmd and cmd not in self._operationExecuted(tag, lambda f: f != famoper):
ret = self.executeCmd(cmd, self.timeout)
realCmd = cmd
if self._jail:
# simulate action info with "empty" ticket:
aInfo = getattr(self._jail.actions, 'actionInfo', None)
if not aInfo:
aInfo = self._jail.actions._getActionInfo(None)
setattr(self._jail.actions, 'actionInfo', aInfo)
aInfo['time'] = MyTime.time()
aInfo['family'] = famoper
# replace dynamical tags, important - don't cache, no recursion and auto-escape here
realCmd = self.replaceDynamicTags(cmd, aInfo)
ret = self.executeCmd(realCmd, self.timeout)
res &= ret
if afterExec: afterExec(famoper, ret)
self._operationExecuted(tag, famoper, cmd if ret else None)
@@ -540,6 +569,26 @@ class CommandAction(ActionBase):
raise RuntimeError("Error banning %(ip)s" % aInfo)
self.__started[family] = self.__started.get(family, 0) | 3; # started and contains items
@property
def _prolongable(self):
return (hasattr(self, 'actionprolong') and self.actionprolong
and not str(self.actionprolong).isspace())
def prolong(self, aInfo):
"""Executes the "actionprolong" command.
Replaces the tags in the action command with actions properties
and ban information, and executes the resulting command.
Parameters
----------
aInfo : dict
Dictionary which includes information in relation to
the ban.
"""
if not self._processCmd('<actionprolong>', aInfo):
raise RuntimeError("Error prolonging %(ip)s" % aInfo)
def unban(self, aInfo):
"""Executes the "actionunban" command.
@@ -649,8 +698,10 @@ class CommandAction(ActionBase):
ret &= False
return ret
@staticmethod
def escapeTag(value):
ESCAPE_CRE = re.compile(r"""[\\#&;`|*?~<>^()\[\]{}$'"\n\r]""")
@classmethod
def escapeTag(cls, value):
"""Escape characters which may be used for command injection.
Parameters
@@ -667,12 +718,15 @@ class CommandAction(ActionBase):
-----
The following characters are escaped::
\\#&;`|*?~<>^()[]{}$'"
\\#&;`|*?~<>^()[]{}$'"\n\r
"""
for c in '\\#&;`|*?~<>^()[]{}$\'"':
if c in value:
value = value.replace(c, '\\' + c)
_map2c = {'\n': 'n', '\r': 'r'}
def substChar(m):
c = m.group()
return '\\' + _map2c.get(c, c)
value = cls.ESCAPE_CRE.sub(substChar, value)
return value
@classmethod
@@ -769,7 +823,7 @@ class CommandAction(ActionBase):
ESCAPE_VN_CRE = re.compile(r"\W")
@classmethod
def replaceDynamicTags(cls, realCmd, aInfo):
def replaceDynamicTags(cls, realCmd, aInfo, escapeVal=None):
"""Replaces dynamical tags in `query` with property values.
**Important**
@@ -794,16 +848,17 @@ class CommandAction(ActionBase):
# array for escaped vars:
varsDict = dict()
def escapeVal(tag, value):
# if the value should be escaped:
if cls.ESCAPE_CRE.search(value):
# That one needs to be escaped since its content is
# out of our control
tag = 'f2bV_%s' % cls.ESCAPE_VN_CRE.sub('_', tag)
varsDict[tag] = value # add variable
value = '$'+tag # replacement as variable
# replacement for tag:
return value
if not escapeVal:
def escapeVal(tag, value):
# if the value should be escaped:
if cls.ESCAPE_CRE.search(value):
# That one needs to be escaped since its content is
# out of our control
tag = 'f2bV_%s' % cls.ESCAPE_VN_CRE.sub('_', tag)
varsDict[tag] = value # add variable
value = '$'+tag # replacement as variable
# replacement for tag:
return value
# additional replacement as calling map:
ADD_REPL_TAGS_CM = CallingMap(ADD_REPL_TAGS)
@@ -827,7 +882,7 @@ class CommandAction(ActionBase):
tickData = aInfo.get("F-*")
if not tickData: tickData = {}
def substTag(m):
tag = mapTag2Opt(m.groups()[0])
tag = mapTag2Opt(m.group(1))
try:
value = uni_string(tickData[tag])
except KeyError:
@@ -922,31 +977,38 @@ class CommandAction(ActionBase):
except (KeyError, TypeError):
family = ''
# invariant check:
if self.actioncheck:
# don't repair/restore if unban (no matter):
def _beforeRepair():
if cmd == '<actionunban>' and not self._properties.get('actionrepair_on_unban'):
self._logSys.error("Invariant check failed. Unban is impossible.")
repcnt = 0
while True:
# got some error, do invariant check:
if repcnt and self.actioncheck:
# don't repair/restore if unban (no matter):
def _beforeRepair():
if cmd == '<actionunban>' and not self._properties.get('actionrepair_on_unban'):
self._logSys.error("Invariant check failed. Unban is impossible.")
return False
return True
# check and repair if broken:
ret = self._invariantCheck(family, _beforeRepair, forceStart=(cmd != '<actionunban>'))
# if not sane (and not restored) return:
if ret != 1:
return False
return True
# check and repair if broken:
ret = self._invariantCheck(family, _beforeRepair, forceStart=(cmd != '<actionunban>'))
# if not sane (and not restored) return:
if ret != 1:
return False
# Replace static fields
realCmd = self.replaceTag(cmd, self._properties,
conditional=('family='+family if family else ''), cache=self.__substCache)
# Replace static fields
realCmd = self.replaceTag(cmd, self._properties,
conditional=('family='+family if family else ''), cache=self.__substCache)
# Replace dynamical tags, important - don't cache, no recursion and auto-escape here
if aInfo is not None:
realCmd = self.replaceDynamicTags(realCmd, aInfo)
else:
realCmd = cmd
# Replace dynamical tags, important - don't cache, no recursion and auto-escape here
if aInfo is not None:
realCmd = self.replaceDynamicTags(realCmd, aInfo)
else:
realCmd = cmd
return self.executeCmd(realCmd, self.timeout)
# try execute command:
ret = self.executeCmd(realCmd, self.timeout)
repcnt += 1
if ret or repcnt > 1:
return ret
@staticmethod
def executeCmd(realCmd, timeout=60, **kwargs):
@@ -971,7 +1033,8 @@ class CommandAction(ActionBase):
RuntimeError
If command execution times out.
"""
logSys.debug(realCmd)
if logSys.getEffectiveLevel() < logging.DEBUG:
logSys.log(9, realCmd)
if not realCmd:
logSys.debug("Nothing to do")
return True
+140 -46
View File
@@ -28,7 +28,10 @@ import logging
import os
import sys
import time
from collections import Mapping
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
try:
from collections import OrderedDict
except ImportError:
@@ -39,6 +42,7 @@ from .ipdns import IPAddr
from .jailthread import JailThread
from .action import ActionBase, CommandAction, CallingMap
from .mytime import MyTime
from .observer import Observers
from .utils import Utils
from ..helpers import getLogger
@@ -80,7 +84,7 @@ class Actions(JailThread, Mapping):
self._jail = jail
self._actions = OrderedDict()
## The ban manager.
self.__banManager = BanManager()
self.banManager = BanManager()
self.banEpoch = 0
self.__lastConsistencyCheckTM = 0
## Precedence of ban (over unban), so max number of tickets banned (to call an unban check):
@@ -199,7 +203,7 @@ class Actions(JailThread, Mapping):
def setBanTime(self, value):
value = MyTime.str2seconds(value)
self.__banManager.setBanTime(value)
self.banManager.setBanTime(value)
logSys.info(" banTime: %s" % value)
##
@@ -208,7 +212,25 @@ class Actions(JailThread, Mapping):
# @return the time
def getBanTime(self):
return self.__banManager.getBanTime()
return self.banManager.getBanTime()
def getBanned(self, ids):
lst = self.banManager.getBanList()
if not ids:
return lst
if len(ids) == 1:
return 1 if ids[0] in lst else 0
return map(lambda ip: 1 if ip in lst else 0, ids)
def getBanList(self, withTime=False):
"""Returns the list of banned IP addresses.
Returns
-------
list
The list of banned IP addresses.
"""
return self.banManager.getBanList(ordered=True, withTime=withTime)
def addBannedIP(self, ip):
"""Ban an IP or list of IPs."""
@@ -243,7 +265,7 @@ class Actions(JailThread, Mapping):
if ip is None:
return self.__flushBan(db)
# Multiple IPs:
if isinstance(ip, list):
if isinstance(ip, (list, tuple)):
missed = []
cnt = 0
for i in ip:
@@ -260,11 +282,19 @@ class Actions(JailThread, Mapping):
if db and self._jail.database is not None:
self._jail.database.delBan(self._jail, ip)
# Find the ticket with the IP.
ticket = self.__banManager.getTicketByID(ip)
ticket = self.banManager.getTicketByID(ip)
if ticket is not None:
# Unban the IP.
self.__unBan(ticket)
else:
# Multiple IPs by subnet or dns:
if not isinstance(ip, IPAddr):
ipa = IPAddr(ip)
if not ipa.isSingle: # subnet (mask/cidr) or raw (may be dns/hostname):
ips = filter(ipa.contains, self.banManager.getBanList())
if ips:
return self.removeBannedIP(ips, db, ifexists)
# not found:
msg = "%s is not banned" % ip
logSys.log(logging.MSG, msg)
if ifexists:
@@ -311,23 +341,33 @@ class Actions(JailThread, Mapping):
self._jail.name, name, e,
exc_info=logSys.getEffectiveLevel()<=logging.DEBUG)
while self.active:
if self.idle:
logSys.debug("Actions: enter idle mode")
Utils.wait_for(lambda: not self.active or not self.idle,
lambda: False, self.sleeptime)
logSys.debug("Actions: leave idle mode")
continue
# wait for ban (stop if gets inactive):
bancnt = Utils.wait_for(lambda: not self.active or self.__checkBan(), self.sleeptime)
cnt += bancnt
# unban if nothing is banned not later than banned tickets >= banPrecedence
if not bancnt or cnt >= self.banPrecedence:
if self.active:
# let shrink the ban list faster
bancnt *= 2
self.__checkUnBan(bancnt if bancnt and bancnt < self.unbanMaxCount else self.unbanMaxCount)
cnt = 0
try:
if self.idle:
logSys.debug("Actions: enter idle mode")
Utils.wait_for(lambda: not self.active or not self.idle,
lambda: False, self.sleeptime)
logSys.debug("Actions: leave idle mode")
continue
# wait for ban (stop if gets inactive, pending ban or unban):
bancnt = 0
wt = min(self.sleeptime, self.banManager._nextUnbanTime - MyTime.time())
logSys.log(5, "Actions: wait for pending tickets %s (default %s)", wt, self.sleeptime)
if Utils.wait_for(lambda: not self.active or self._jail.hasFailTickets, wt):
bancnt = self.__checkBan()
cnt += bancnt
# unban if nothing is banned not later than banned tickets >= banPrecedence
if not bancnt or cnt >= self.banPrecedence:
if self.active:
# let shrink the ban list faster
bancnt *= 2
logSys.log(5, "Actions: check-unban %s, bancnt %s, max: %s", bancnt if bancnt and bancnt < self.unbanMaxCount else self.unbanMaxCount, bancnt, self.unbanMaxCount)
self.__checkUnBan(bancnt if bancnt and bancnt < self.unbanMaxCount else self.unbanMaxCount)
cnt = 0
except Exception as e: # pragma: no cover
logSys.error("[%s] unhandled error in actions thread: %s",
self._jail.name, e,
exc_info=logSys.getEffectiveLevel()<=logging.DEBUG)
self.__flushBan(stop=True)
self.stopActions()
return True
@@ -344,6 +384,8 @@ class Actions(JailThread, Mapping):
"fid": lambda self: self.__ticket.getID(),
"failures": lambda self: self.__ticket.getAttempt(),
"time": lambda self: self.__ticket.getTime(),
"bantime": lambda self: self._getBanTime(),
"bancount": lambda self: self.__ticket.getBanCount(),
"matches": lambda self: "\n".join(self.__ticket.getMatches()),
# to bypass actions, that should not be executed for restored tickets
"restored": lambda self: (1 if self.__ticket.restored else 0),
@@ -355,7 +397,12 @@ class Actions(JailThread, Mapping):
"ipfailures": lambda self: self._mi4ip(True).getAttempt(),
"ipjailfailures": lambda self: self._mi4ip().getAttempt(),
# raw ticket info:
"raw-ticket": lambda self: repr(self.__ticket)
"raw-ticket": lambda self: repr(self.__ticket),
# jail info:
"jail.banned": lambda self: self.__jail.actions.banManager.size(),
"jail.banned_total": lambda self: self.__jail.actions.banManager.getBanTotal(),
"jail.found": lambda self: self.__jail.filter.failManager.size(),
"jail.found_total": lambda self: self.__jail.filter.failManager.getFailTotal()
}
__slots__ = CallingMap.__slots__ + ('__ticket', '__jail', '__mi4ip')
@@ -370,6 +417,11 @@ class Actions(JailThread, Mapping):
def copy(self): # pragma: no cover
return self.__class__(self.__ticket, self.__jail, self.immutable, self.data.copy())
def _getBanTime(self):
btime = self.__ticket.getBanTime()
if btime is None: btime = self.__jail.actions.getBanTime()
return int(btime)
def _mi4ip(self, overalljails=False):
"""Gets bans merged once, a helper for lambda(s), prevents stop of executing action by any exception inside.
@@ -413,7 +465,9 @@ class Actions(JailThread, Mapping):
return mi[idx] if mi[idx] is not None else self.__ticket
def __getActionInfo(self, ticket):
def _getActionInfo(self, ticket):
if not ticket:
ticket = BanTicket("", MyTime.time())
aInfo = Actions.ActionInfo(ticket, self._jail)
return aInfo
@@ -443,16 +497,22 @@ class Actions(JailThread, Mapping):
tickets = self.__getFailTickets(self.banPrecedence)
rebanacts = None
for ticket in tickets:
bTicket = BanManager.createBanTicket(ticket)
bTicket = BanTicket.wrap(ticket)
btime = ticket.getBanTime(self.banManager.getBanTime())
ip = bTicket.getIP()
aInfo = self.__getActionInfo(bTicket)
aInfo = self._getActionInfo(bTicket)
reason = {}
if self.__banManager.addBanTicket(bTicket, reason=reason):
if self.banManager.addBanTicket(bTicket, reason=reason):
cnt += 1
# report ticket to observer, to check time should be increased and hereafter observer writes ban to database (asynchronous)
if Observers.Main is not None and not bTicket.restored:
Observers.Main.add('banFound', bTicket, self._jail, btime)
logSys.notice("[%s] %sBan %s", self._jail.name, ('' if not bTicket.restored else 'Restore '), ip)
# do actions :
for name, action in self._actions.iteritems():
try:
if ticket.restored and getattr(action, 'norestored', False):
if bTicket.restored and getattr(action, 'norestored', False):
continue
if not aInfo.immutable: aInfo.reset()
action.ban(aInfo)
@@ -467,7 +527,10 @@ class Actions(JailThread, Mapping):
if self.banEpoch: # be sure tickets always have the same ban epoch (default 0):
bTicket.banEpoch = self.banEpoch
else:
bTicket = reason['ticket']
if reason.get('expired', 0):
logSys.info('[%s] Ignore %s, expired bantime', self._jail.name, ip)
continue
bTicket = reason.get('ticket', bTicket)
# if already banned (otherwise still process some action)
if bTicket.banned:
# compare time of failure occurrence with time ticket was really banned:
@@ -495,9 +558,11 @@ class Actions(JailThread, Mapping):
cnt += self.__reBan(bTicket, actions=rebanacts)
else: # pragma: no cover - unexpected: ticket is not banned for some reasons - reban using all actions:
cnt += self.__reBan(bTicket)
# add ban to database moved to observer (should previously check not already banned
# and increase ticket time if "bantime.increment" set)
if cnt:
logSys.debug("Banned %s / %s, %s ticket(s) in %r", cnt,
self.__banManager.getBanTotal(), self.__banManager.size(), self._jail.name)
self.banManager.getBanTotal(), self.banManager.size(), self._jail.name)
return cnt
def __reBan(self, ticket, actions=None, log=True):
@@ -513,7 +578,7 @@ class Actions(JailThread, Mapping):
"""
actions = actions or self._actions
ip = ticket.getIP()
aInfo = self.__getActionInfo(ticket)
aInfo = self._getActionInfo(ticket)
if log:
logSys.notice("[%s] Reban %s%s", self._jail.name, aInfo["ip"], (', action %r' % actions.keys()[0] if len(actions) == 1 else ''))
for name, action in actions.iteritems():
@@ -534,18 +599,41 @@ class Actions(JailThread, Mapping):
ticket.banEpoch = self.banEpoch
return 1
def _prolongBan(self, ticket):
# prevent to prolong ticket that was removed in-between,
# if it in ban list - ban time already prolonged (and it stays there):
if not self.banManager._inBanList(ticket): return
# do actions :
aInfo = None
for name, action in self._actions.iteritems():
try:
if ticket.restored and getattr(action, 'norestored', False):
continue
if not action._prolongable:
continue
if aInfo is None:
aInfo = self._getActionInfo(ticket)
if not aInfo.immutable: aInfo.reset()
action.prolong(aInfo)
except Exception as e:
logSys.error(
"Failed to execute ban jail '%s' action '%s' "
"info '%r': %s",
self._jail.name, name, aInfo, e,
exc_info=logSys.getEffectiveLevel()<=logging.DEBUG)
def __checkUnBan(self, maxCount=None):
"""Check for IP address to unban.
Unban IP addresses which are outdated.
"""
lst = self.__banManager.unBanList(MyTime.time(), maxCount)
lst = self.banManager.unBanList(MyTime.time(), maxCount)
for ticket in lst:
self.__unBan(ticket)
cnt = len(lst)
if cnt:
logSys.debug("Unbanned %s, %s ticket(s) in %r",
cnt, self.__banManager.size(), self._jail.name)
cnt, self.banManager.size(), self._jail.name)
return cnt
def __flushBan(self, db=False, actions=None, stop=False):
@@ -559,10 +647,10 @@ class Actions(JailThread, Mapping):
log = True
if actions is None:
logSys.debug(" Flush ban list")
lst = self.__banManager.flushBanList()
lst = self.banManager.flushBanList()
else:
log = False # don't log "[jail] Unban ..." if removing actions only.
lst = iter(self.__banManager)
lst = iter(self.banManager)
cnt = 0
# first we'll execute flush for actions supporting this operation:
unbactions = {}
@@ -599,7 +687,7 @@ class Actions(JailThread, Mapping):
self.__unBan(ticket, actions=actions, log=log)
cnt += 1
logSys.debug(" Unbanned %s, %s ticket(s) in %r",
cnt, self.__banManager.size(), self._jail.name)
cnt, self.banManager.size(), self._jail.name)
return cnt
def __unBan(self, ticket, actions=None, log=True):
@@ -618,7 +706,7 @@ class Actions(JailThread, Mapping):
else:
unbactions = actions
ip = ticket.getIP()
aInfo = self.__getActionInfo(ticket)
aInfo = self._getActionInfo(ticket)
if log:
logSys.notice("[%s] Unban %s", self._jail.name, aInfo["ip"])
for name, action in unbactions.iteritems():
@@ -637,17 +725,23 @@ class Actions(JailThread, Mapping):
"""Status of current and total ban counts and current banned IP list.
"""
# TODO: Allow this list to be printed as 'status' output
supported_flavors = ["basic", "cymru"]
supported_flavors = ["short", "basic", "cymru"]
if flavor is None or flavor not in supported_flavors:
logSys.warning("Unsupported extended jail status flavor %r. Supported: %s" % (flavor, supported_flavors))
# Always print this information (basic)
ret = [("Currently banned", self.__banManager.size()),
("Total banned", self.__banManager.getBanTotal()),
("Banned IP list", self.__banManager.getBanList())]
if flavor != "short":
banned = self.banManager.getBanList()
cnt = len(banned)
else:
cnt = self.banManager.size()
ret = [("Currently banned", cnt),
("Total banned", self.banManager.getBanTotal())]
if flavor != "short":
ret += [("Banned IP list", banned)]
if flavor == "cymru":
cymru_info = self.__banManager.getBanListExtendedCymruInfo()
cymru_info = self.banManager.getBanListExtendedCymruInfo()
ret += \
[("Banned ASN list", self.__banManager.geBanListExtendedASN(cymru_info)),
("Banned Country list", self.__banManager.geBanListExtendedCountry(cymru_info)),
("Banned RIR list", self.__banManager.geBanListExtendedRIR(cymru_info))]
[("Banned ASN list", self.banManager.geBanListExtendedASN(cymru_info)),
("Banned Country list", self.banManager.geBanListExtendedCountry(cymru_info)),
("Banned RIR list", self.banManager.geBanListExtendedRIR(cymru_info))]
return ret
+27 -33
View File
@@ -57,7 +57,7 @@ class BanManager:
## Total number of banned IP address
self.__banTotal = 0
## The time for next unban process (for performance and load reasons):
self.__nextUnbanTime = BanTicket.MAX_TIME
self._nextUnbanTime = BanTicket.MAX_TIME
##
# Set the ban time.
@@ -66,7 +66,6 @@ class BanManager:
# @param value the time
def setBanTime(self, value):
with self.__lock:
self.__banTime = int(value)
##
@@ -76,7 +75,6 @@ class BanManager:
# @return the time
def getBanTime(self):
with self.__lock:
return self.__banTime
##
@@ -85,7 +83,6 @@ class BanManager:
# @param value total number
def setBanTotal(self, value):
with self.__lock:
self.__banTotal = value
##
@@ -94,7 +91,6 @@ class BanManager:
# @return the total number
def getBanTotal(self):
with self.__lock:
return self.__banTotal
##
@@ -102,9 +98,22 @@ class BanManager:
#
# @return IP list
def getBanList(self):
def getBanList(self, ordered=False, withTime=False):
if not ordered:
return list(self.__banList.keys())
with self.__lock:
return self.__banList.keys()
lst = []
for ticket in self.__banList.itervalues():
eob = ticket.getEndOfBanTime(self.__banTime)
lst.append((ticket,eob))
lst.sort(key=lambda t: t[1])
t2s = MyTime.time2str
if withTime:
return ['%s \t%s + %d = %s' % (
t[0].getID(),
t2s(t[0].getTime()), t[0].getBanTime(self.__banTime), t2s(t[1])
) for t in lst]
return [t[0].getID() for t in lst]
##
# Returns a iterator to ban list (used in reload, so idle).
@@ -112,8 +121,8 @@ class BanManager:
# @return ban list iterator
def __iter__(self):
with self.__lock:
return self.__banList.itervalues()
# ensure iterator is safe - traverse over the list in snapshot created within lock (GIL):
return iter(list(self.__banList.values()))
##
# Returns normalized value
@@ -249,21 +258,6 @@ class BanManager:
logSys.exception(e)
return []
##
# Create a ban ticket.
#
# Create a BanTicket from a FailTicket. The timestamp of the BanTicket
# is the current time. This is a static method.
# @param ticket the FailTicket
# @return a BanTicket
@staticmethod
def createBanTicket(ticket):
# we should always use correct time to calculate correct end time (ban time is variable now,
# + possible double banning by restore from database and from log file)
# so use as lastTime always time from ticket.
return BanTicket(ticket=ticket)
##
# Add a ban ticket.
#
@@ -273,6 +267,9 @@ class BanManager:
def addBanTicket(self, ticket, reason={}):
eob = ticket.getEndOfBanTime(self.__banTime)
if eob < MyTime.time():
reason['expired'] = 1
return False
with self.__lock:
# check already banned
fid = ticket.getID()
@@ -294,9 +291,10 @@ class BanManager:
# not yet banned - add new one:
self.__banList[fid] = ticket
self.__banTotal += 1
ticket.incrBanCount()
# correct next unban time:
if self.__nextUnbanTime > eob:
self.__nextUnbanTime = eob
if self._nextUnbanTime > eob:
self._nextUnbanTime = eob
return True
##
@@ -327,12 +325,8 @@ class BanManager:
def unBanList(self, time, maxCount=0x7fffffff):
with self.__lock:
# Permanent banning
if self.__banTime < 0:
return list()
# Check next unban time:
nextUnbanTime = self.__nextUnbanTime
nextUnbanTime = self._nextUnbanTime
if nextUnbanTime > time:
return list()
@@ -345,12 +339,12 @@ class BanManager:
if time > eob:
unBanList[fid] = ticket
if len(unBanList) >= maxCount: # stop search cycle, so reset back the next check time
nextUnbanTime = self.__nextUnbanTime
nextUnbanTime = self._nextUnbanTime
break
elif nextUnbanTime > eob:
nextUnbanTime = eob
self.__nextUnbanTime = nextUnbanTime
self._nextUnbanTime = nextUnbanTime
# Removes tickets.
if len(unBanList):
if len(unBanList) / 2.0 <= len(self.__banList) / 3.0:
+216 -57
View File
@@ -138,7 +138,7 @@ class Fail2BanDb(object):
filename
purgeage
"""
__version__ = 2
__version__ = 4
# Note all SCRIPTS strings must end in ';' for py26 compatibility
_CREATE_SCRIPTS = (
('fail2banDb', "CREATE TABLE IF NOT EXISTS fail2banDb(version INTEGER);")
@@ -166,21 +166,36 @@ class Fail2BanDb(object):
"jail TEXT NOT NULL, " \
"ip TEXT, " \
"timeofban INTEGER NOT NULL, " \
"bantime INTEGER NOT NULL, " \
"bancount INTEGER NOT NULL default 1, " \
"data JSON, " \
"FOREIGN KEY(jail) REFERENCES jails(name) " \
");" \
"CREATE INDEX IF NOT EXISTS bans_jail_timeofban_ip ON bans(jail, timeofban);" \
"CREATE INDEX IF NOT EXISTS bans_jail_ip ON bans(jail, ip);" \
"CREATE INDEX IF NOT EXISTS bans_ip ON bans(ip);")
,('bips', "CREATE TABLE IF NOT EXISTS bips(" \
"ip TEXT NOT NULL, " \
"jail TEXT NOT NULL, " \
"timeofban INTEGER NOT NULL, " \
"bantime INTEGER NOT NULL, " \
"bancount INTEGER NOT NULL default 1, " \
"data JSON, " \
"PRIMARY KEY(ip, jail), " \
"FOREIGN KEY(jail) REFERENCES jails(name) " \
");" \
"CREATE INDEX IF NOT EXISTS bips_timeofban ON bips(timeofban);" \
"CREATE INDEX IF NOT EXISTS bips_ip ON bips(ip);")
)
_CREATE_TABS = dict(_CREATE_SCRIPTS)
def __init__(self, filename, purgeAge=24*60*60):
def __init__(self, filename, purgeAge=24*60*60, outDatedFactor=3):
self.maxMatches = 10
self._lock = RLock()
self._dbFilename = filename
self._purgeAge = purgeAge
self._outDatedFactor = outDatedFactor;
self._connectDB()
def _connectDB(self, checkIntegrity=False):
@@ -366,13 +381,32 @@ class Fail2BanDb(object):
if version < 2 and self._tableExists(cur, "logs"):
cur.executescript("BEGIN TRANSACTION;"
"CREATE TEMPORARY TABLE logs_temp AS SELECT * FROM logs;"
"DROP TABLE logs;"
"%s;"
"INSERT INTO logs SELECT * from logs_temp;"
"DROP TABLE logs_temp;"
"UPDATE fail2banDb SET version = 2;"
"COMMIT;" % Fail2BanDb._CREATE_TABS['logs'])
"CREATE TEMPORARY TABLE logs_temp AS SELECT * FROM logs;"
"DROP TABLE logs;"
"%s;"
"INSERT INTO logs SELECT * from logs_temp;"
"DROP TABLE logs_temp;"
"UPDATE fail2banDb SET version = 2;"
"COMMIT;" % Fail2BanDb._CREATE_TABS['logs'])
if version < 3 and self._tableExists(cur, "bans"):
# set ban-time to -2 (note it means rather unknown, as persistent, will be fixed by restore):
cur.executescript("BEGIN TRANSACTION;"
"CREATE TEMPORARY TABLE bans_temp AS SELECT jail, ip, timeofban, -2 as bantime, 1 as bancount, data FROM bans;"
"DROP TABLE bans;"
"%s;\n"
"INSERT INTO bans SELECT * from bans_temp;"
"DROP TABLE bans_temp;"
"COMMIT;" % Fail2BanDb._CREATE_TABS['bans'])
if version < 4 and not self._tableExists(cur, "bips"):
cur.executescript("BEGIN TRANSACTION;"
"%s;\n"
"UPDATE fail2banDb SET version = 4;"
"COMMIT;" % Fail2BanDb._CREATE_TABS['bips'])
if self._tableExists(cur, "bans"):
cur.execute(
"INSERT OR REPLACE INTO bips(ip, jail, timeofban, bantime, bancount, data)"
" SELECT ip, jail, timeofban, bantime, bancount, data FROM bans order by timeofban")
cur.execute("SELECT version FROM fail2banDb LIMIT 1")
return cur.fetchone()[0]
@@ -455,22 +489,24 @@ class Fail2BanDb(object):
If log was already present in database, value of last position
in the log file; else `None`
"""
return self._addLog(cur, jail, container.getFileName(), container.getPos(), container.getHash())
def _addLog(self, cur, jail, name, pos=0, md5=None):
lastLinePos = None
cur.execute(
"SELECT firstlinemd5, lastfilepos FROM logs "
"WHERE jail=? AND path=?",
(jail.name, container.getFileName()))
(jail.name, name))
try:
firstLineMD5, lastLinePos = cur.fetchone()
except TypeError:
firstLineMD5 = False
firstLineMD5 = None
cur.execute(
"INSERT OR REPLACE INTO logs(jail, path, firstlinemd5, lastfilepos) "
"VALUES(?, ?, ?, ?)",
(jail.name, container.getFileName(),
container.getHash(), container.getPos()))
if container.getHash() != firstLineMD5:
if firstLineMD5 is None and (pos or md5 is not None):
cur.execute(
"INSERT OR REPLACE INTO logs(jail, path, firstlinemd5, lastfilepos) "
"VALUES(?, ?, ?, ?)", (jail.name, name, md5, pos))
if md5 is not None and md5 != firstLineMD5:
lastLinePos = None
return lastLinePos
@@ -499,7 +535,7 @@ class Fail2BanDb(object):
return set(row[0] for row in cur.fetchmany())
@commitandrollback
def updateLog(self, cur, *args, **kwargs):
def updateLog(self, cur, jail, container):
"""Updates hash and last position in log file.
Parameters
@@ -509,14 +545,48 @@ class Fail2BanDb(object):
container : FileContainer
File container of the log file being updated.
"""
self._updateLog(cur, *args, **kwargs)
self._updateLog(cur, jail, container.getFileName(), container.getPos(), container.getHash())
def _updateLog(self, cur, jail, container):
def _updateLog(self, cur, jail, name, pos, md5):
cur.execute(
"UPDATE logs SET firstlinemd5=?, lastfilepos=? "
"WHERE jail=? AND path=?",
(container.getHash(), container.getPos(),
jail.name, container.getFileName()))
"WHERE jail=? AND path=?", (md5, pos, jail.name, name))
# be sure it is set (if not available):
if not cur.rowcount:
cur.execute(
"INSERT OR REPLACE INTO logs(jail, path, firstlinemd5, lastfilepos) "
"VALUES(?, ?, ?, ?)", (jail.name, name, md5, pos))
@commitandrollback
def getJournalPos(self, cur, jail, name, time=0, iso=None):
"""Get journal position from database.
Parameters
----------
jail : Jail
Jail of which the journal belongs to.
name, time, iso :
Journal name (typically systemd-journal) and last known time.
Returns
-------
int (or float)
Last position (as time) if it was already present in database; else `None`
"""
return self._addLog(cur, jail, name, time, iso); # no hash, just time as iso
@commitandrollback
def updateJournal(self, cur, jail, name, time, iso):
"""Updates last position (as time) of journal.
Parameters
----------
jail : Jail
Jail of which the journal belongs to.
name, time, iso :
Journal name (typically systemd-journal) and last known time.
"""
self._updateLog(cur, jail, name, time, iso); # no hash, just time as iso
@commitandrollback
def addBan(self, cur, jail, ticket):
@@ -549,8 +619,13 @@ class Fail2BanDb(object):
data = data.copy()
del data['matches']
cur.execute(
"INSERT INTO bans(jail, ip, timeofban, data) VALUES(?, ?, ?, ?)",
(jail.name, ip, int(round(ticket.getTime())), data))
"INSERT INTO bans(jail, ip, timeofban, bantime, bancount, data) VALUES(?, ?, ?, ?, ?, ?)",
(jail.name, ip, int(round(ticket.getTime())), ticket.getBanTime(jail.actions.getBanTime()), ticket.getBanCount(),
data))
cur.execute(
"INSERT OR REPLACE INTO bips(ip, jail, timeofban, bantime, bancount, data) VALUES(?, ?, ?, ?, ?, ?)",
(ip, jail.name, int(round(ticket.getTime())), ticket.getBanTime(jail.actions.getBanTime()), ticket.getBanCount(),
data))
@commitandrollback
def delBan(self, cur, jail, *args):
@@ -563,16 +638,20 @@ class Fail2BanDb(object):
args : list of IP
IPs to be removed, if not given all tickets of jail will be removed.
"""
query = "DELETE FROM bans WHERE jail = ?"
query1 = "DELETE FROM bips WHERE jail = ?"
query2 = "DELETE FROM bans WHERE jail = ?"
queryArgs = [jail.name];
if not len(args):
cur.execute(query, queryArgs);
cur.execute(query1, queryArgs);
cur.execute(query2, queryArgs);
return
query += " AND ip = ?"
query1 += " AND ip = ?"
query2 += " AND ip = ?"
queryArgs.append('');
for ip in args:
queryArgs[1] = str(ip);
cur.execute(query, queryArgs);
cur.execute(query1, queryArgs);
cur.execute(query2, queryArgs);
@commitandrollback
def _getBans(self, cur, jail=None, bantime=None, ip=None):
@@ -690,18 +769,42 @@ class Fail2BanDb(object):
self._bansMergedCache[cacheKey] = tickets if ip is None else ticket
return tickets if ip is None else ticket
@commitandrollback
def getBan(self, cur, ip, jail=None, forbantime=None, overalljails=None, fromtime=None):
ip = str(ip)
if not overalljails:
query = "SELECT bancount, timeofban, bantime FROM bips"
else:
query = "SELECT sum(bancount), max(timeofban), sum(bantime) FROM bips"
query += " WHERE ip = ?"
queryArgs = [ip]
if not overalljails and jail is not None:
query += " AND jail=?"
queryArgs.append(jail.name)
if forbantime is not None:
query += " AND timeofban > ?"
queryArgs.append(MyTime.time() - forbantime)
if fromtime is not None:
query += " AND timeofban > ?"
queryArgs.append(fromtime)
if overalljails or jail is None:
query += " GROUP BY ip ORDER BY timeofban DESC LIMIT 1"
cur = self._db.cursor()
# repack iterator as long as in lock:
return list(cur.execute(query, queryArgs))
def _getCurrentBans(self, cur, jail = None, ip = None, forbantime=None, fromtime=None):
if fromtime is None:
fromtime = MyTime.time()
queryArgs = []
if jail is not None:
query = "SELECT ip, timeofban, data FROM bans WHERE jail=?"
query = "SELECT ip, timeofban, bantime, bancount, data FROM bips WHERE jail=?"
queryArgs.append(jail.name)
else:
query = "SELECT ip, max(timeofban), data FROM bans WHERE 1"
query = "SELECT ip, max(timeofban), bantime, bancount, data FROM bips WHERE 1"
if ip is not None:
query += " AND ip=?"
queryArgs.append(ip)
query += " AND (timeofban + bantime > ? OR bantime <= -1)"
queryArgs.append(fromtime)
if forbantime not in (None, -1): # not specified or persistent (all)
query += " AND timeofban > ?"
queryArgs.append(fromtime - forbantime)
@@ -712,33 +815,90 @@ class Fail2BanDb(object):
cur = self._db.cursor()
return cur.execute(query, queryArgs)
def getCurrentBans(self, jail = None, ip = None, forbantime=None, fromtime=None, maxmatches=None):
@commitandrollback
def getCurrentBans(self, cur, jail=None, ip=None, forbantime=None, fromtime=None,
correctBanTime=True, maxmatches=None
):
"""Reads tickets (with merged info) currently affected from ban from the database.
There are all the tickets corresponding parameters jail/ip, forbantime,
fromtime (normally now).
If correctBanTime specified (default True) it will fix the restored ban-time
(and therefore endOfBan) of the ticket (normally it is ban-time of jail as maximum)
for all tickets with ban-time greater (or persistent).
"""
if fromtime is None:
fromtime = MyTime.time()
tickets = []
ticket = None
if correctBanTime is True:
correctBanTime = jail.getMaxBanTime() if jail is not None else None
# don't change if persistent allowed:
if correctBanTime == -1: correctBanTime = None
with self._lock:
results = list(self._getCurrentBans(self._db.cursor(),
jail=jail, ip=ip, forbantime=forbantime, fromtime=fromtime))
if results:
for banip, timeofban, data in results:
# logSys.debug('restore ticket %r, %r, %r', banip, timeofban, data)
ticket = FailTicket(banip, timeofban, data=data)
# filter matches if expected (current count > as maxmatches specified):
if maxmatches is None:
maxmatches = self.maxMatches
if maxmatches:
matches = ticket.getMatches()
if matches and len(matches) > maxmatches:
ticket.setMatches(matches[-maxmatches:])
else:
ticket.setMatches(None)
# logSys.debug('restored ticket: %r', ticket)
if ip is not None: return ticket
tickets.append(ticket)
for ticket in self._getCurrentBans(cur, jail=jail, ip=ip,
forbantime=forbantime, fromtime=fromtime
):
# can produce unpack error (database may return sporadical wrong-empty row):
try:
banip, timeofban, bantime, bancount, data = ticket
# additionally check for empty values:
if banip is None or banip == "": # pragma: no cover
raise ValueError('unexpected value %r' % (banip,))
# if bantime unknown (after upgrade-db from earlier version), just use min known ban-time:
if bantime == -2: # todo: remove it in future version
bantime = jail.actions.getBanTime() if jail is not None else (
correctBanTime if correctBanTime else 600)
elif correctBanTime and correctBanTime >= 0:
# if persistent ban (or greater as max), use current max-bantime of the jail:
if bantime == -1 or bantime > correctBanTime:
bantime = correctBanTime
# after correction check the end of ban again:
if bantime != -1 and timeofban + bantime <= fromtime:
# not persistent and too old - ignore it:
logSys.debug("ignore ticket (with new max ban-time %r): too old %r <= %r, ticket: %r",
bantime, timeofban + bantime, fromtime, ticket)
continue
except ValueError as e: # pragma: no cover
logSys.debug("get current bans: ignore row %r - %s", ticket, e)
continue
# logSys.debug('restore ticket %r, %r, %r', banip, timeofban, data)
ticket = FailTicket(banip, timeofban, data=data)
# filter matches if expected (current count > as maxmatches specified):
if maxmatches is None:
maxmatches = self.maxMatches
if maxmatches:
matches = ticket.getMatches()
if matches and len(matches) > maxmatches:
ticket.setMatches(matches[-maxmatches:])
else:
ticket.setMatches(None)
# logSys.debug('restored ticket: %r', ticket)
ticket.setBanTime(bantime)
ticket.setBanCount(bancount)
if ip is not None: return ticket
tickets.append(ticket)
return tickets
def _cleanjails(self, cur):
"""Remove empty jails jails and log files from database.
"""
cur.execute(
"DELETE FROM jails WHERE enabled = 0 "
"AND NOT EXISTS(SELECT * FROM bans WHERE jail = jails.name) "
"AND NOT EXISTS(SELECT * FROM bips WHERE jail = jails.name)")
def _purge_bips(self, cur):
"""Purge old bad ips (jails and log files from database).
Currently it is timed out IP, whose time since last ban is several times out-dated (outDatedFactor is default 3).
Permanent banned ips will be never removed.
"""
cur.execute(
"DELETE FROM bips WHERE timeofban < ? and bantime != -1 and (timeofban + (bantime * ?)) < ?",
(int(MyTime.time()) - self._purgeAge, self._outDatedFactor, int(MyTime.time()) - self._purgeAge))
@commitandrollback
def purge(self, cur):
"""Purge old bans, jails and log files from database.
@@ -747,7 +907,6 @@ class Fail2BanDb(object):
cur.execute(
"DELETE FROM bans WHERE timeofban < ?",
(MyTime.time() - self._purgeAge, ))
cur.execute(
"DELETE FROM jails WHERE enabled = 0 "
"AND NOT EXISTS(SELECT * FROM bans WHERE jail = jails.name)")
self._purge_bips(cur)
self._cleanjails(cur)
+43 -30
View File
@@ -35,7 +35,7 @@ from ..helpers import getLogger
# Gets the instance of the logger.
logSys = getLogger(__name__)
logLevel = 6
logLevel = 5
RE_DATE_PREMATCH = re.compile(r"(?<!\\)\{DATE\}", re.IGNORECASE)
DD_patternCache = Utils.Cache(maxCount=1000, maxTime=60*60)
@@ -282,6 +282,8 @@ class DateDetector(object):
elif "{DATE}" in key:
self.addDefaultTemplate(preMatch=pattern, allDefaults=False)
return
elif key == "{NONE}":
template = _getPatternTemplate('{UNB}^', key)
else:
template = _getPatternTemplate(pattern, key)
@@ -337,65 +339,76 @@ class DateDetector(object):
# if no templates specified - default templates should be used:
if not len(self.__templates):
self.addDefaultTemplate()
logSys.log(logLevel-1, "try to match time for line: %.120s", line)
match = None
log = logSys.log if logSys.getEffectiveLevel() <= logLevel else lambda *args: None
log(logLevel-1, "try to match time for line: %.120s", line)
# first try to use last template with same start/end position:
match = None
found = None, 0x7fffffff, 0x7fffffff, -1
ignoreBySearch = 0x7fffffff
i = self.__lastTemplIdx
if i < len(self.__templates):
ddtempl = self.__templates[i]
template = ddtempl.template
if template.flags & (DateTemplate.LINE_BEGIN|DateTemplate.LINE_END):
if logSys.getEffectiveLevel() <= logLevel-1: # pragma: no cover - very-heavy debug
logSys.log(logLevel-1, " try to match last anchored template #%02i ...", i)
log(logLevel-1, " try to match last anchored template #%02i ...", i)
match = template.matchDate(line)
ignoreBySearch = i
else:
distance, endpos = self.__lastPos[0], self.__lastEndPos[0]
if logSys.getEffectiveLevel() <= logLevel-1:
logSys.log(logLevel-1, " try to match last template #%02i (from %r to %r): ...%r==%r %s %r==%r...",
i, distance, endpos,
line[distance-1:distance], self.__lastPos[1],
line[distance:endpos],
line[endpos:endpos+1], self.__lastEndPos[1])
# check same boundaries left/right, otherwise possible collision/pattern switch:
if (line[distance-1:distance] == self.__lastPos[1] and
line[endpos:endpos+1] == self.__lastEndPos[1]
):
log(logLevel-1, " try to match last template #%02i (from %r to %r): ...%r==%r %s %r==%r...",
i, distance, endpos,
line[distance-1:distance], self.__lastPos[1],
line[distance:endpos],
line[endpos:endpos+1], self.__lastEndPos[2])
# check same boundaries left/right, outside fully equal, inside only if not alnum (e. g. bound RE
# with space or some special char), otherwise possible collision/pattern switch:
if ((
line[distance-1:distance] == self.__lastPos[1] or
(line[distance:distance+1] == self.__lastPos[2] and not self.__lastPos[2].isalnum())
) and (
line[endpos:endpos+1] == self.__lastEndPos[2] or
(line[endpos-1:endpos] == self.__lastEndPos[1] and not self.__lastEndPos[1].isalnum())
)):
# search in line part only:
log(logLevel-1, " boundaries are correct, search in part %r", line[distance:endpos])
match = template.matchDate(line, distance, endpos)
else:
log(logLevel-1, " boundaries show conflict, try whole search")
match = template.matchDate(line)
ignoreBySearch = i
if match:
distance = match.start()
endpos = match.end()
# if different position, possible collision/pattern switch:
if (
len(self.__templates) == 1 or # single template:
template.flags & (DateTemplate.LINE_BEGIN|DateTemplate.LINE_END) or
(distance == self.__lastPos[0] and endpos == self.__lastEndPos[0])
):
logSys.log(logLevel, " matched last time template #%02i", i)
log(logLevel, " matched last time template #%02i", i)
else:
logSys.log(logLevel, " ** last pattern collision - pattern change, search ...")
log(logLevel, " ** last pattern collision - pattern change, reserve & search ...")
found = match, distance, endpos, i; # save current best alternative
match = None
else:
logSys.log(logLevel, " ** last pattern not found - pattern change, search ...")
log(logLevel, " ** last pattern not found - pattern change, search ...")
# search template and better match:
if not match:
logSys.log(logLevel, " search template (%i) ...", len(self.__templates))
found = None, 0x7fffffff, 0x7fffffff, -1
log(logLevel, " search template (%i) ...", len(self.__templates))
i = 0
for ddtempl in self.__templates:
if logSys.getEffectiveLevel() <= logLevel-1:
logSys.log(logLevel-1, " try template #%02i: %s", i, ddtempl.name)
if i == ignoreBySearch:
i += 1
continue
log(logLevel-1, " try template #%02i: %s", i, ddtempl.name)
template = ddtempl.template
match = template.matchDate(line)
if match:
distance = match.start()
endpos = match.end()
if logSys.getEffectiveLevel() <= logLevel:
logSys.log(logLevel, " matched time template #%02i (at %r <= %r, %r) %s",
i, distance, ddtempl.distance, self.__lastPos[0], template.name)
log(logLevel, " matched time template #%02i (at %r <= %r, %r) %s",
i, distance, ddtempl.distance, self.__lastPos[0], template.name)
## last (or single) template - fast stop:
if i+1 >= len(self.__templates):
break
@@ -408,7 +421,7 @@ class DateDetector(object):
## [grave] if distance changed, possible date-match was found somewhere
## in body of message, so save this template, and search further:
if distance > ddtempl.distance or distance > self.__lastPos[0]:
logSys.log(logLevel, " ** distance collision - pattern change, reserve")
log(logLevel, " ** distance collision - pattern change, reserve")
## shortest of both:
if distance < found[1]:
found = match, distance, endpos, i
@@ -422,7 +435,7 @@ class DateDetector(object):
# check other template was found (use this one with shortest distance):
if not match and found[0]:
match, distance, endpos, i = found
logSys.log(logLevel, " use best time template #%02i", i)
log(logLevel, " use best time template #%02i", i)
ddtempl = self.__templates[i]
template = ddtempl.template
# we've winner, incr hits, set distance, usage, reorder, etc:
@@ -432,8 +445,8 @@ class DateDetector(object):
ddtempl.distance = distance
if self.__firstUnused == i:
self.__firstUnused += 1
self.__lastPos = distance, line[distance-1:distance]
self.__lastEndPos = endpos, line[endpos:endpos+1]
self.__lastPos = distance, line[distance-1:distance], line[distance]
self.__lastEndPos = endpos, line[endpos-1], line[endpos:endpos+1]
# if not first - try to reorder current template (bubble up), they will be not sorted anymore:
if i and i != self.__lastTemplIdx:
i = self._reorderTemplate(i)
@@ -442,7 +455,7 @@ class DateDetector(object):
return (match, template)
# not found:
logSys.log(logLevel, " no template.")
log(logLevel, " no template.")
return (None, None)
@property
+16 -8
View File
@@ -36,15 +36,16 @@ logSys = getLogger(__name__)
RE_GROUPED = re.compile(r'(?<!(?:\(\?))(?<!\\)\((?!\?)')
RE_GROUP = ( re.compile(r'^((?:\(\?\w+\))?\^?(?:\(\?\w+\))?)(.*?)(\$?)$'), r"\1(\2)\3" )
RE_EXLINE_NO_BOUNDS = re.compile(r'^\{UNB\}')
RE_EXLINE_BOUND_BEG = re.compile(r'^\{\^LN-BEG\}')
RE_EXSANC_BOUND_BEG = re.compile(r'^\(\?:\^\|\\b\|\\W\)')
RE_EXSANC_BOUND_BEG = re.compile(r'^\((?:\?:)?\^\|\\b\|\\W\)')
RE_EXEANC_BOUND_BEG = re.compile(r'\(\?=\\b\|\\W\|\$\)$')
RE_NO_WRD_BOUND_BEG = re.compile(r'^\(*(?:\(\?\w+\))?(?:\^|\(*\*\*|\(\?:\^)')
RE_NO_WRD_BOUND_BEG = re.compile(r'^\(*(?:\(\?\w+\))?(?:\^|\(*\*\*|\((?:\?:)?\^)')
RE_NO_WRD_BOUND_END = re.compile(r'(?<!\\)(?:\$\)?|\\b|\\s|\*\*\)*)$')
RE_DEL_WRD_BOUNDS = ( re.compile(r'^\(*(?:\(\?\w+\))?\(*\*\*|(?<!\\)\*\*\)*$'),
lambda m: m.group().replace('**', '') )
RE_LINE_BOUND_BEG = re.compile(r'^(?:\(\?\w+\))?(?:\^|\(\?:\^(?!\|))')
RE_LINE_BOUND_BEG = re.compile(r'^(?:\(\?\w+\))?(?:\^|\((?:\?:)?\^(?!\|))')
RE_LINE_BOUND_END = re.compile(r'(?<![\\\|])(?:\$\)?)$')
RE_ALPHA_PATTERN = re.compile(r'(?<!\%)\%[aAbBpc]')
@@ -119,7 +120,7 @@ class DateTemplate(object):
if boundBegin:
self.flags |= DateTemplate.WORD_BEGIN if wordBegin != 'start' else DateTemplate.LINE_BEGIN
if wordBegin != 'start':
regex = r'(?:^|\b|\W)' + regex
regex = r'(?=^|\b|\W)' + regex
else:
regex = r"^(?:\W{0,2})?" + regex
if not self.name.startswith('{^LN-BEG}'):
@@ -128,12 +129,14 @@ class DateTemplate(object):
if boundEnd:
self.flags |= DateTemplate.WORD_END
regex += r'(?=\b|\W|$)'
if RE_LINE_BOUND_BEG.search(regex): self.flags |= DateTemplate.LINE_BEGIN
if RE_LINE_BOUND_END.search(regex): self.flags |= DateTemplate.LINE_END
if not (self.flags & DateTemplate.LINE_BEGIN) and RE_LINE_BOUND_BEG.search(regex):
self.flags |= DateTemplate.LINE_BEGIN
if not (self.flags & DateTemplate.LINE_END) and RE_LINE_BOUND_END.search(regex):
self.flags |= DateTemplate.LINE_END
# remove possible special pattern "**" in front and end of regex:
regex = RE_DEL_WRD_BOUNDS[0].sub(RE_DEL_WRD_BOUNDS[1], regex)
self._regex = regex
logSys.log(7, ' constructed regex %s', regex)
logSys.log(4, ' constructed regex %s', regex)
self._cRegex = None
regex = property(getRegex, setRegex, doc=
@@ -156,6 +159,7 @@ class DateTemplate(object):
"""
if not self._cRegex:
self._compileRegex()
logSys.log(4, " search %s", self.regex)
dateMatch = self._cRegex.search(line, *args); # pos, endpos
if dateMatch:
self.hits += 1
@@ -188,7 +192,7 @@ class DateTemplate(object):
def unboundPattern(pattern):
return RE_EXEANC_BOUND_BEG.sub('',
RE_EXSANC_BOUND_BEG.sub('',
RE_EXLINE_BOUND_BEG.sub('', pattern)
RE_EXLINE_BOUND_BEG.sub('', RE_EXLINE_NO_BOUNDS.sub('', pattern))
)
)
@@ -297,6 +301,10 @@ class DatePatternRegex(DateTemplate):
def setRegex(self, pattern, wordBegin=True, wordEnd=True):
# original pattern:
self._pattern = pattern
# if unbound signalled - reset boundaries left and right:
if RE_EXLINE_NO_BOUNDS.search(pattern):
pattern = RE_EXLINE_NO_BOUNDS.sub('', pattern)
wordBegin = wordEnd = False
# if explicit given {^LN-BEG} - remove it from pattern and set 'start' in wordBegin:
if wordBegin and RE_EXLINE_BOUND_BEG.search(pattern):
pattern = RE_EXLINE_BOUND_BEG.sub('', pattern)
+14 -20
View File
@@ -27,7 +27,7 @@ __license__ = "GPL"
from threading import Lock
import logging
from .ticket import FailTicket
from .ticket import FailTicket, BanTicket
from ..helpers import getLogger, BgService
# Gets the instance of the logger.
@@ -43,26 +43,20 @@ class FailManager:
self.__maxRetry = 3
self.__maxTime = 600
self.__failTotal = 0
self.maxMatches = 50
self.maxMatches = 5
self.__bgSvc = BgService()
def setFailTotal(self, value):
with self.__lock:
self.__failTotal = value
self.__failTotal = value
def getFailTotal(self):
with self.__lock:
return self.__failTotal
return self.__failTotal
def getFailCount(self):
# may be slow on large list of failures, should be used for test purposes only...
with self.__lock:
return len(self.__failList), sum([f.getRetry() for f in self.__failList.values()])
def getFailTotal(self):
with self.__lock:
return self.__failTotal
def setMaxRetry(self, value):
self.__maxRetry = value
@@ -75,7 +69,7 @@ class FailManager:
def getMaxTime(self):
return self.__maxTime
def addFailure(self, ticket, count=1):
def addFailure(self, ticket, count=1, observed=False):
attempts = 1
with self.__lock:
fid = ticket.getID()
@@ -92,10 +86,7 @@ class FailManager:
if attempt <= 0:
attempt += 1
unixTime = ticket.getTime()
fData.setLastTime(unixTime)
if fData.getLastReset() < unixTime - self.__maxTime:
fData.setLastReset(unixTime)
fData.setRetry(0)
fData.adjustTime(unixTime, self.__maxTime)
fData.inc(matches, attempt, count)
# truncate to maxMatches:
if self.maxMatches:
@@ -105,11 +96,14 @@ class FailManager:
else:
fData.setMatches(None)
except KeyError:
# not found - already banned - prevent to add failure if comes from observer:
if observed or isinstance(ticket, BanTicket):
return ticket.getRetry()
# if already FailTicket - add it direct, otherwise create (using copy all ticket data):
if isinstance(ticket, FailTicket):
fData = ticket;
else:
fData = FailTicket(ticket=ticket)
fData = FailTicket.wrap(ticket)
if count > ticket.getAttempt():
fData.setRetry(count)
self.__failList[fid] = fData
@@ -130,13 +124,13 @@ class FailManager:
return attempts
def size(self):
with self.__lock:
return len(self.__failList)
return len(self.__failList)
def cleanup(self, time):
time -= self.__maxTime
with self.__lock:
todelete = [fid for fid,item in self.__failList.iteritems() \
if item.getLastTime() + self.__maxTime <= time]
if item.getTime() <= time]
if len(todelete) == len(self.__failList):
# remove all:
self.__failList = dict()
@@ -150,7 +144,7 @@ class FailManager:
else:
# create new dictionary without items to be deleted:
self.__failList = dict((fid,item) for fid,item in self.__failList.iteritems() \
if item.getLastTime() + self.__maxTime > time)
if item.getTime() > time)
self.__bgSvc.service()
def delFailure(self, fid):
+51 -22
View File
@@ -87,20 +87,24 @@ RH4TAG = {
# default failure groups map for customizable expressions (with different group-id):
R_MAP = {
"ID": "fid",
"PORT": "fport",
"id": "fid",
"port": "fport",
}
def mapTag2Opt(tag):
try: # if should be mapped:
return R_MAP[tag]
except KeyError:
return tag.lower()
tag = tag.lower()
return R_MAP.get(tag, tag)
# alternate names to be merged, e. g. alt_user_1 -> user ...
# complex names:
# ALT_ - alternate names to be merged, e. g. alt_user_1 -> user ...
ALTNAME_PRE = 'alt_'
ALTNAME_CRE = re.compile(r'^' + ALTNAME_PRE + r'(.*)(?:_\d+)?$')
# TUPLE_ - names of parts to be combined to single value as tuple
TUPNAME_PRE = 'tuple_'
COMPLNAME_PRE = (ALTNAME_PRE, TUPNAME_PRE)
COMPLNAME_CRE = re.compile(r'^(' + '|'.join(COMPLNAME_PRE) + r')(.*?)(?:_\d+)?$')
##
# Regular expression class.
@@ -127,17 +131,27 @@ class Regex:
try:
self._regexObj = re.compile(regex, re.MULTILINE if multiline else 0)
self._regex = regex
self._altValues = {}
self._altValues = []
self._tupleValues = []
for k in filter(
lambda k: len(k) > len(ALTNAME_PRE) and k.startswith(ALTNAME_PRE),
self._regexObj.groupindex
lambda k: len(k) > len(COMPLNAME_PRE[0]), self._regexObj.groupindex
):
n = ALTNAME_CRE.match(k).group(1)
self._altValues[k] = n
self._altValues = list(self._altValues.items()) if len(self._altValues) else None
n = COMPLNAME_CRE.match(k)
if n:
g, n = n.group(1), mapTag2Opt(n.group(2))
if g == ALTNAME_PRE:
self._altValues.append((k,n))
else:
self._tupleValues.append((k,n))
self._altValues.sort()
self._tupleValues.sort()
self._altValues = self._altValues if len(self._altValues) else None
self._tupleValues = self._tupleValues if len(self._tupleValues) else None
except sre_constants.error:
raise RegexException("Unable to compile regular expression '%s'" %
regex)
# set fetch handler depending on presence of alternate (or tuple) tags:
self.getGroups = self._getGroupsWithAlt if (self._altValues or self._tupleValues) else self._getGroups
def __str__(self):
return "%s(%r)" % (self.__class__.__name__, self._regex)
@@ -277,18 +291,33 @@ class Regex:
# Returns all matched groups.
#
def getGroups(self):
if not self._altValues:
return self._matchCache.groupdict()
# merge alternate values (e. g. 'alt_user_1' -> 'user' or 'alt_host' -> 'host'):
def _getGroups(self):
return self._matchCache.groupdict()
def _getGroupsWithAlt(self):
fail = self._matchCache.groupdict()
#fail = fail.copy()
for k,n in self._altValues:
v = fail.get(k)
if v and not fail.get(n):
fail[n] = v
# merge alternate values (e. g. 'alt_user_1' -> 'user' or 'alt_host' -> 'host'):
if self._altValues:
for k,n in self._altValues:
v = fail.get(k)
if v and not fail.get(n):
fail[n] = v
# combine tuple values (e. g. 'id', 'tuple_id' ... 'tuple_id_N' -> 'id'):
if self._tupleValues:
for k,n in self._tupleValues:
v = fail.get(k)
t = fail.get(n)
if isinstance(t, tuple):
t += (v,)
else:
t = (t,v,)
fail[n] = t
return fail
def getGroups(self): # pragma: no cover - abstract function (replaced in __init__)
pass
##
# Returns skipped lines.
#
+421 -223
View File
@@ -33,6 +33,7 @@ import time
from .actions import Actions
from .failmanager import FailManagerEmpty, FailManager
from .ipdns import DNSUtils, IPAddr
from .observer import Observers
from .ticket import FailTicket
from .jailthread import JailThread
from .datedetector import DateDetector, validateTimeZone
@@ -80,6 +81,7 @@ class Filter(JailThread):
## Ignore own IPs flag:
self.__ignoreSelf = True
## The ignore IP list.
self.__ignoreIpSet = set()
self.__ignoreIpList = []
## External command
self.__ignoreCommand = False
@@ -92,6 +94,8 @@ class Filter(JailThread):
## Store last time stamp, applicable for multi-line
self.__lastTimeText = ""
self.__lastDate = None
## Next service (cleanup) time
self.__nextSvcTime = -(1<<63)
## if set, treat log lines without explicit time zone to be in this time zone
self.__logtimezone = None
## Default or preferred encoding (to decode bytes from file or journal):
@@ -101,14 +105,26 @@ class Filter(JailThread):
## Error counter (protected, so can be used in filter implementations)
## if it reached 100 (at once), run-cycle will go idle
self._errors = 0
## Next time to update log or journal position in database:
self._nextUpdateTM = 0
## Pending updates (must be executed at next update time or during stop):
self._pendDBUpdates = {}
## return raw host (host is not dns):
self.returnRawHost = False
## check each regex (used for test purposes):
self.checkAllRegex = False
## avoid finding of pending failures (without ID/IP, used in fail2ban-regex):
self.ignorePending = True
## callback called on ignoreregex match :
self.onIgnoreRegex = None
## if true ignores obsolete failures (failure time < now - findTime):
self.checkFindTime = True
## shows that filter is in operation mode (processing new messages):
self.inOperation = True
## Ticks counter
self.ticks = 0
## Processed lines counter
self.procLines = 0
## Thread name:
self.name="f2b/f."+self.jailName
@@ -168,7 +184,7 @@ class Filter(JailThread):
# @param value the regular expression
def addFailRegex(self, value):
multiLine = self.getMaxLines() > 1
multiLine = self.__lineBufferSize > 1
try:
regex = FailRegex(value, prefRegex=self.__prefRegex, multiline=multiLine,
useDns=self.__useDns)
@@ -432,12 +448,23 @@ class Filter(JailThread):
def performBan(self, ip=None):
"""Performs a ban for IPs (or given ip) that are reached maxretry of the jail."""
try: # pragma: no branch - exception is the only way out
while True:
while True:
try:
ticket = self.failManager.toBan(ip)
self.jail.putFailTicket(ticket)
except FailManagerEmpty:
self.failManager.cleanup(MyTime.time())
except FailManagerEmpty:
break
self.jail.putFailTicket(ticket)
if ip: break
self.performSvc()
def performSvc(self, force=False):
"""Performs a service tasks (clean failure list)."""
tm = MyTime.time()
# avoid too early clean up:
if force or tm >= self.__nextSvcTime:
self.__nextSvcTime = tm + 5
# clean up failure list:
self.failManager.cleanup(tm)
def addAttempt(self, ip, *matches):
"""Generate a failed attempt for ip"""
@@ -451,10 +478,10 @@ class Filter(JailThread):
logSys.info(
"[%s] Attempt %s - %s", self.jailName, ip, datetime.datetime.fromtimestamp(unixTime).strftime("%Y-%m-%d %H:%M:%S")
)
self.failManager.addFailure(ticket, len(matches) or 1)
attempts = self.failManager.addFailure(ticket, len(matches) or 1)
# Perform the ban if this attempt is resulted to:
self.performBan(ip)
if attempts >= self.failManager.getMaxRetry():
self.performBan(ip)
return 1
@@ -483,28 +510,36 @@ class Filter(JailThread):
# Create IP address object
ip = IPAddr(ipstr)
# Avoid exact duplicates
if ip in self.__ignoreIpList:
logSys.warn(" Ignore duplicate %r (%r), already in ignore list", ip, ipstr)
if ip in self.__ignoreIpSet or ip in self.__ignoreIpList:
logSys.log(logging.MSG, " Ignore duplicate %r (%r), already in ignore list", ip, ipstr)
return
# log and append to ignore list
logSys.debug(" Add %r to ignore list (%r)", ip, ipstr)
self.__ignoreIpList.append(ip)
# if single IP (not DNS or a subnet) add to set, otherwise to list:
if ip.isSingle:
self.__ignoreIpSet.add(ip)
else:
self.__ignoreIpList.append(ip)
def delIgnoreIP(self, ip=None):
# clear all:
if ip is None:
self.__ignoreIpSet.clear()
del self.__ignoreIpList[:]
return
# delete by ip:
logSys.debug(" Remove %r from ignore list", ip)
self.__ignoreIpList.remove(ip)
if ip in self.__ignoreIpSet:
self.__ignoreIpSet.remove(ip)
else:
self.__ignoreIpList.remove(ip)
def logIgnoreIp(self, ip, log_ignore, ignore_source="unknown source"):
if log_ignore:
logSys.info("[%s] Ignore %s by %s", self.jailName, ip, ignore_source)
def getIgnoreIP(self):
return self.__ignoreIpList
return self.__ignoreIpList + list(self.__ignoreIpSet)
##
# Check if IP address/DNS is in the ignore list.
@@ -544,8 +579,11 @@ class Filter(JailThread):
if self.__ignoreCache: c.set(key, True)
return True
# check if the IP is covered by ignore IP (in set or in subnet/dns):
if ip in self.__ignoreIpSet:
self.logIgnoreIp(ip, log_ignore, ignore_source="ip")
return True
for net in self.__ignoreIpList:
# check if the IP is covered by ignore IP
if ip.isInNet(net):
self.logIgnoreIp(ip, log_ignore, ignore_source=("ip" if net.isValid else "dns"))
if self.__ignoreCache: c.set(key, True)
@@ -568,29 +606,97 @@ class Filter(JailThread):
if self.__ignoreCache: c.set(key, False)
return False
def _logWarnOnce(self, nextLTM, *args):
"""Log some issue as warning once per day, otherwise level 7"""
if MyTime.time() < getattr(self, nextLTM, 0):
if logSys.getEffectiveLevel() <= 7: logSys.log(7, *(args[0]))
else:
setattr(self, nextLTM, MyTime.time() + 24*60*60)
for args in args:
logSys.warning('[%s] ' + args[0], self.jailName, *args[1:])
def processLine(self, line, date=None):
"""Split the time portion from log msg and return findFailures on them
"""
logSys.log(7, "Working on line %r", line)
noDate = False
if date:
tupleLine = line
line = "".join(line)
self.__lastTimeText = tupleLine[1]
self.__lastDate = date
else:
l = line.rstrip('\r\n')
logSys.log(7, "Working on line %r", line)
(timeMatch, template) = self.dateDetector.matchTime(l)
if timeMatch:
tupleLine = (
l[:timeMatch.start(1)],
l[timeMatch.start(1):timeMatch.end(1)],
l[timeMatch.end(1):],
(timeMatch, template)
)
# try to parse date:
timeMatch = self.dateDetector.matchTime(line)
m = timeMatch[0]
if m:
s = m.start(1)
e = m.end(1)
m = line[s:e]
tupleLine = (line[:s], m, line[e:])
if m: # found and not empty - retrive date:
date = self.dateDetector.getTime(m, timeMatch)
if date is not None:
# Lets get the time part
date = date[0]
self.__lastTimeText = m
self.__lastDate = date
else:
logSys.error("findFailure failed to parse timeText: %s", m)
# matched empty value - date is optional or not available - set it to last known or now:
elif self.__lastDate and self.__lastDate > MyTime.time() - 60:
# set it to last known:
tupleLine = ("", self.__lastTimeText, line)
date = self.__lastDate
else:
# set it to now:
date = MyTime.time()
else:
tupleLine = (l, "", "", None)
tupleLine = ("", "", line)
# still no date - try to use last known:
if date is None:
noDate = True
if self.__lastDate and self.__lastDate > MyTime.time() - 60:
tupleLine = ("", self.__lastTimeText, line)
date = self.__lastDate
elif self.checkFindTime and self.inOperation:
date = MyTime.time()
if self.checkFindTime and date is not None:
# if in operation (modifications have been really found):
if self.inOperation:
# if weird date - we'd simulate now for timeing issue (too large deviation from now):
delta = int(date - MyTime.time())
if abs(delta) > 60:
# log timing issue as warning once per day:
self._logWarnOnce("_next_simByTimeWarn",
("Detected a log entry %s %s the current time in operation mode. "
"This looks like a %s problem. Treating such entries as if they just happened.",
MyTime.seconds2str(abs(delta)), "before" if delta < 0 else "after",
"latency" if -3300 <= delta < 0 else "timezone"
),
("Please check a jail for a timing issue. Line with odd timestamp: %s",
line))
# simulate now as date:
date = MyTime.time()
self.__lastDate = date
else:
# in initialization (restore) phase, if too old - ignore:
if date < MyTime.time() - self.getFindTime():
# log time zone issue as warning once per day:
self._logWarnOnce("_next_ignByTimeWarn",
("Ignoring all log entries older than %ss; these are probably" +
" messages generated while fail2ban was not running.",
self.getFindTime()),
("Please check a jail for a timing issue. Line with odd timestamp: %s",
line))
# ignore - too old (obsolete) entry:
return []
# save last line (lazy convert of process line tuple to string on demand):
self.processedLine = lambda: "".join(tupleLine[::2])
return self.findFailure(tupleLine, date)
return self.findFailure(tupleLine, date, noDate=noDate)
def processLineAndAdd(self, line, date=None):
"""Processes the line for failures and populates failManager
@@ -602,13 +708,27 @@ class Filter(JailThread):
fail = element[3]
logSys.debug("Processing line with time:%s and ip:%s",
unixTime, ip)
# ensure the time is not in the future, e. g. by some estimated (assumed) time:
if self.checkFindTime and unixTime > MyTime.time():
unixTime = MyTime.time()
tick = FailTicket(ip, unixTime, data=fail)
if self._inIgnoreIPList(ip, tick):
continue
logSys.info(
"[%s] Found %s - %s", self.jailName, ip, datetime.datetime.fromtimestamp(unixTime).strftime("%Y-%m-%d %H:%M:%S")
"[%s] Found %s - %s", self.jailName, ip, MyTime.time2str(unixTime)
)
self.failManager.addFailure(tick)
attempts = self.failManager.addFailure(tick)
# avoid RC on busy filter (too many failures) - if attempts for IP/ID reached maxretry,
# we can speedup ban, so do it as soon as possible:
if attempts >= self.failManager.getMaxRetry():
self.performBan(ip)
# report to observer - failure was found, for possibly increasing of it retry counter (asynchronous)
if Observers.Main is not None:
Observers.Main.add('failureFound', self.failManager, self.jail, tick)
self.procLines += 1
# every 100 lines check need to perform service tasks:
if self.procLines % 100 == 0:
self.performSvc()
# reset (halve) error counter (successfully processed line):
if self._errors:
self._errors //= 2
@@ -618,7 +738,7 @@ class Filter(JailThread):
# incr common error counter:
self.commonError()
def commonError(self):
def commonError(self, reason="common", exc=None):
# incr error counter, stop processing (going idle) after 100th error :
self._errors += 1
# sleep a little bit (to get around time-related errors):
@@ -628,20 +748,26 @@ class Filter(JailThread):
self._errors //= 2
self.idle = True
##
# Returns true if the line should be ignored.
#
# Uses ignoreregex.
# @param line: the line
# @return: a boolean
def ignoreLine(self, tupleLines):
buf = Regex._tupleLinesBuf(tupleLines)
def _ignoreLine(self, buf, orgBuffer, failRegex=None):
# if multi-line buffer - use matched only, otherwise (single line) - original buf:
if failRegex and self.__lineBufferSize > 1:
orgBuffer = failRegex.getMatchedTupleLines()
buf = Regex._tupleLinesBuf(orgBuffer)
# search ignored:
fnd = None
for ignoreRegexIndex, ignoreRegex in enumerate(self.__ignoreRegex):
ignoreRegex.search(buf, tupleLines)
ignoreRegex.search(buf, orgBuffer)
if ignoreRegex.hasMatched():
return ignoreRegexIndex
return None
fnd = ignoreRegexIndex
logSys.log(7, " Matched ignoreregex %d and was ignored", fnd)
if self.onIgnoreRegex: self.onIgnoreRegex(fnd, ignoreRegex)
# remove ignored match:
if not self.checkAllRegex or self.__lineBufferSize > 1:
# todo: check ignoreRegex.getUnmatchedTupleLines() would be better (fix testGetFailuresMultiLineIgnoreRegex):
if failRegex:
self.__lineBuffer = failRegex.getUnmatchedTupleLines()
if not self.checkAllRegex: break
return fnd
def _updateUsers(self, fail, user=()):
users = fail.get('users')
@@ -651,54 +777,31 @@ class Filter(JailThread):
fail['users'] = users = set()
users.add(user)
return users
return None
# # ATM incremental (non-empty only) merge deactivated ...
# @staticmethod
# def _updateFailure(self, mlfidGroups, fail):
# # reset old failure-ids when new types of id available in this failure:
# fids = set()
# for k in ('fid', 'ip4', 'ip6', 'dns'):
# if fail.get(k):
# fids.add(k)
# if fids:
# for k in ('fid', 'ip4', 'ip6', 'dns'):
# if k not in fids:
# try:
# del mlfidGroups[k]
# except:
# pass
# # update not empty values:
# mlfidGroups.update(((k,v) for k,v in fail.iteritems() if v))
return users
def _mergeFailure(self, mlfid, fail, failRegex):
mlfidFail = self.mlfidCache.get(mlfid) if self.__mlfidCache else None
users = None
nfflgs = 0
if fail.get("mlfgained"):
nfflgs |= 9
nfflgs |= (8|1)
if not fail.get('nofail'):
fail['nofail'] = fail["mlfgained"]
elif fail.get('nofail'): nfflgs |= 1
if fail.get('mlfforget'): nfflgs |= 2
if fail.pop('mlfforget', None): nfflgs |= 2
# if multi-line failure id (connection id) known:
if mlfidFail:
mlfidGroups = mlfidFail[1]
# update users set (hold all users of connect):
users = self._updateUsers(mlfidGroups, fail.get('user'))
# be sure we've correct current state ('nofail' and 'mlfgained' only from last failure)
try:
del mlfidGroups['nofail']
del mlfidGroups['mlfgained']
except KeyError:
pass
# # ATM incremental (non-empty only) merge deactivated (for future version only),
# # it can be simulated using alternate value tags, like <F-ALT_VAL>...</F-ALT_VAL>,
# # so previous value 'val' will be overwritten only if 'alt_val' is not empty...
# _updateFailure(mlfidGroups, fail)
#
if mlfidGroups.pop('nofail', None): nfflgs |= 4
if mlfidGroups.pop('mlfgained', None): nfflgs |= 4
# if we had no pending failures then clear the matches (they are already provided):
if (nfflgs & 4) == 0 and not mlfidGroups.get('mlfpending', 0):
mlfidGroups.pop("matches", None)
# overwrite multi-line failure with all values, available in fail:
mlfidGroups.update(fail)
mlfidGroups.update(((k,v) for k,v in fail.iteritems() if v is not None))
# new merged failure data:
fail = mlfidGroups
# if forget (disconnect/reset) - remove cached entry:
@@ -709,24 +812,19 @@ class Filter(JailThread):
mlfidFail = [self.__lastDate, fail]
self.mlfidCache.set(mlfid, mlfidFail)
# check users in order to avoid reset failure by multiple logon-attempts:
if users and len(users) > 1:
# we've new user, reset 'nofail' because of multiple users attempts:
try:
del fail['nofail']
nfflgs &= ~1 # reset nofail
except KeyError:
pass
if fail.pop('mlfpending', 0) or users and len(users) > 1:
# we've pending failures or new user, reset 'nofail' because of failures or multiple users attempts:
fail.pop('nofail', None)
fail.pop('mlfgained', None)
nfflgs &= ~(8|1) # reset nofail and gained
# merge matches:
if not (nfflgs & 1): # current nofail state (corresponding users)
try:
m = fail.pop("nofail-matches")
m += fail.get("matches", [])
except KeyError:
m = fail.get("matches", [])
if not (nfflgs & 8): # no gain signaled
if (nfflgs & 1) == 0: # current nofail state (corresponding users)
m = fail.pop("nofail-matches", [])
m += fail.get("matches", [])
if (nfflgs & 8) == 0: # no gain signaled
m += failRegex.getMatchedTupleLines()
fail["matches"] = m
elif not (nfflgs & 2) and (nfflgs & 1): # not mlfforget and nofail:
elif (nfflgs & 3) == 1: # not mlfforget and nofail:
fail["nofail-matches"] = fail.get("nofail-matches", []) + failRegex.getMatchedTupleLines()
# return merged:
return fail
@@ -739,7 +837,7 @@ class Filter(JailThread):
# to find the logging time.
# @return a dict with IP and timestamp.
def findFailure(self, tupleLine, date=None):
def findFailure(self, tupleLine, date, noDate=False):
failList = list()
ll = logSys.getEffectiveLevel()
@@ -749,62 +847,33 @@ class Filter(JailThread):
returnRawHost = True
cidr = IPAddr.CIDR_RAW
# Checks if we mut ignore this line.
if self.ignoreLine([tupleLine[::2]]) is not None:
# The ignoreregex matched. Return.
if ll <= 7: logSys.log(7, "Matched ignoreregex and was \"%s\" ignored",
"".join(tupleLine[::2]))
return failList
timeText = tupleLine[1]
if date:
self.__lastTimeText = timeText
self.__lastDate = date
elif timeText:
dateTimeMatch = self.dateDetector.getTime(timeText, tupleLine[3])
if dateTimeMatch is None:
logSys.error("findFailure failed to parse timeText: %s", timeText)
date = self.__lastDate
else:
# Lets get the time part
date = dateTimeMatch[0]
self.__lastTimeText = timeText
self.__lastDate = date
else:
timeText = self.__lastTimeText or "".join(tupleLine[::2])
date = self.__lastDate
if self.checkFindTime and date is not None and date < MyTime.time() - self.getFindTime():
if ll <= 5: logSys.log(5, "Ignore line since time %s < %s - %s",
date, MyTime.time(), self.getFindTime())
return failList
if self.__lineBufferSize > 1:
orgBuffer = self.__lineBuffer = (
self.__lineBuffer + [tupleLine[:3]])[-self.__lineBufferSize:]
self.__lineBuffer.append(tupleLine)
orgBuffer = self.__lineBuffer = self.__lineBuffer[-self.__lineBufferSize:]
else:
orgBuffer = self.__lineBuffer = [tupleLine[:3]]
if ll <= 5: logSys.log(5, "Looking for match of %r", self.__lineBuffer)
buf = Regex._tupleLinesBuf(self.__lineBuffer)
orgBuffer = self.__lineBuffer = [tupleLine]
if ll <= 5: logSys.log(5, "Looking for match of %r", orgBuffer)
buf = Regex._tupleLinesBuf(orgBuffer)
# Checks if we must ignore this line (only if fewer ignoreregex than failregex).
if self.__ignoreRegex and len(self.__ignoreRegex) < len(self.__failRegex) - 2:
if self._ignoreLine(buf, orgBuffer) is not None:
# The ignoreregex matched. Return.
return failList
# Pre-filter fail regex (if available):
preGroups = {}
if self.__prefRegex:
if ll <= 5: logSys.log(5, " Looking for prefregex %r", self.__prefRegex.getRegex())
self.__prefRegex.search(buf, self.__lineBuffer)
self.__prefRegex.search(buf, orgBuffer)
if not self.__prefRegex.hasMatched():
if ll <= 5: logSys.log(5, " Prefregex not matched")
return failList
preGroups = self.__prefRegex.getGroups()
if ll <= 7: logSys.log(7, " Pre-filter matched %s", preGroups)
repl = preGroups.get('content')
repl = preGroups.pop('content', None)
# Content replacement:
if repl:
del preGroups['content']
self.__lineBuffer, buf = [('', '', repl)], None
# Iterates over all the regular expressions.
@@ -822,28 +891,21 @@ class Filter(JailThread):
# The failregex matched.
if ll <= 7: logSys.log(7, " Matched failregex %d: %s", failRegexIndex, fail)
# Checks if we must ignore this match.
if self.ignoreLine(failRegex.getMatchedTupleLines()) \
is not None:
if self.__ignoreRegex and self._ignoreLine(buf, orgBuffer, failRegex) is not None:
# The ignoreregex matched. Remove ignored match.
self.__lineBuffer, buf = failRegex.getUnmatchedTupleLines(), None
if ll <= 7: logSys.log(7, " Matched ignoreregex and was ignored")
buf = None
if not self.checkAllRegex:
break
else:
continue
if date is None:
logSys.warning(
"Found a match for %r but no valid date/time "
"found for %r. Please try setting a custom "
"date pattern (see man page jail.conf(5)). "
"If format is complex, please "
"file a detailed issue on"
" https://github.com/fail2ban/fail2ban/issues "
"in order to get support for this format.",
"\n".join(failRegex.getMatchedLines()), timeText)
continue
if noDate:
self._logWarnOnce("_next_noTimeWarn",
("Found a match but no valid date/time found for %r.", tupleLine[1]),
("Match without a timestamp: %s", "\n".join(failRegex.getMatchedLines())),
("Please try setting a custom date pattern (see man page jail.conf(5)).",)
)
if date is None and self.checkFindTime: continue
# we should check all regex (bypass on multi-line, otherwise too complex):
if not self.checkAllRegex or self.getMaxLines() > 1:
if not self.checkAllRegex or self.__lineBufferSize > 1:
self.__lineBuffer, buf = failRegex.getUnmatchedTupleLines(), None
# merge data if multi-line failure:
raw = returnRawHost
@@ -888,7 +950,8 @@ class Filter(JailThread):
if host is None:
if ll <= 7: logSys.log(7, "No failure-id by mlfid %r in regex %s: %s",
mlfid, failRegexIndex, fail.get('mlfforget', "waiting for identifier"))
if not self.checkAllRegex: return failList
fail['mlfpending'] = 1; # mark failure is pending
if not self.checkAllRegex and self.ignorePending: return failList
ips = [None]
# if raw - add single ip or failure-id,
# otherwise expand host to multiple ips using dns (or ignore it if not valid):
@@ -901,6 +964,9 @@ class Filter(JailThread):
# otherwise, try to use dns conversion:
else:
ips = DNSUtils.textToIp(host, self.__useDns)
# if checkAllRegex we must make a copy (to be sure next RE doesn't change merged/cached failure):
if self.checkAllRegex and mlfid is not None:
fail = fail.copy()
# append failure with match to the list:
for ip in ips:
failList.append([failRegexIndex, ip, date, fail])
@@ -946,7 +1012,7 @@ class FileFilter(Filter):
log.setPos(lastpos)
self.__logs[path] = log
logSys.info("Added logfile: %r (pos = %s, hash = %s)" , path, log.getPos(), log.getHash())
if autoSeek:
if autoSeek and not tail:
self.__autoSeek[path] = autoSeek
self._addLogPath(path) # backend specific
@@ -965,9 +1031,6 @@ class FileFilter(Filter):
log = self.__logs.pop(path)
except KeyError:
return
db = self.jail.database
if db is not None:
db.updateLog(self.jail, log)
logSys.info("Removed logfile: %r", path)
self._delLogPath(path)
return
@@ -1030,7 +1093,8 @@ class FileFilter(Filter):
# MyTime.time()-self.findTime. When a failure is detected, a FailTicket
# is created and is added to the FailManager.
def getFailures(self, filename):
def getFailures(self, filename, inOperation=None):
if self.idle: return False
log = self.getLog(filename)
if log is None:
logSys.error("Unable to get failures in %s", filename)
@@ -1075,15 +1139,26 @@ class FileFilter(Filter):
if has_content:
while not self.idle:
line = log.readline()
if not line or not self.active:
# The jail reached the bottom or has been stopped
if not self.active: break; # jail has been stopped
if line is None:
# The jail reached the bottom, simply set in operation for this log
# (since we are first time at end of file, growing is only possible after modifications):
log.inOperation = True
break
# acquire in operation from log and process:
self.inOperation = inOperation if inOperation is not None else log.inOperation
self.processLineAndAdd(line)
finally:
log.close()
db = self.jail.database
if db is not None:
db.updateLog(self.jail, log)
if self.jail.database is not None:
self._pendDBUpdates[log] = 1
if (
self.ticks % 100 == 0
or MyTime.time() >= self._nextUpdateTM
or not self.active
):
self._updateDBPending()
self._nextUpdateTM = MyTime.time() + Utils.DEFAULT_SLEEP_TIME * 5
return True
##
@@ -1094,7 +1169,9 @@ class FileFilter(Filter):
fs = container.getFileSize()
if logSys.getEffectiveLevel() <= logging.DEBUG:
logSys.debug("Seek to find time %s (%s), file size %s", date,
datetime.datetime.fromtimestamp(date).strftime("%Y-%m-%d %H:%M:%S"), fs)
MyTime.time2str(date), fs)
if not fs:
return
minp = container.getPos()
maxp = fs
tryPos = minp
@@ -1118,8 +1195,8 @@ class FileFilter(Filter):
dateTimeMatch = None
nextp = None
while True:
line = container.readline()
if not line:
line = container.readline(False)
if line is None:
break
(timeMatch, template) = self.dateDetector.matchTime(line)
if timeMatch:
@@ -1173,7 +1250,7 @@ class FileFilter(Filter):
container.setPos(foundPos)
if logSys.getEffectiveLevel() <= logging.DEBUG:
logSys.debug("Position %s from %s, found time %s (%s) within %s seeks", lastPos, fs, foundTime,
(datetime.datetime.fromtimestamp(foundTime).strftime("%Y-%m-%d %H:%M:%S") if foundTime is not None else ''), cntr)
(MyTime.time2str(foundTime) if foundTime is not None else ''), cntr)
def status(self, flavor="basic"):
"""Status of Filter plus files being monitored.
@@ -1183,12 +1260,33 @@ class FileFilter(Filter):
ret.append(("File list", path))
return ret
def stop(self):
"""Stop monitoring of log-file(s)
def _updateDBPending(self):
"""Apply pending updates (log position) to database.
"""
db = self.jail.database
while True:
try:
log, args = self._pendDBUpdates.popitem()
except KeyError:
break
db.updateLog(self.jail, log)
def onStop(self):
"""Stop monitoring of log-file(s). Invoked after run method.
"""
# ensure positions of pending logs are up-to-date:
if self._pendDBUpdates and self.jail.database:
self._updateDBPending()
# stop files monitoring:
for path in self.__logs.keys():
self.delLogPath(path)
def stop(self):
"""Stop filter
"""
# normally onStop will be called automatically in thread after its run ends,
# but for backwards compatibilities we'll invoke it in caller of stop method.
self.onStop()
# stop thread:
super(Filter, self).stop()
@@ -1216,32 +1314,56 @@ except ImportError: # pragma: no cover
class FileContainer:
def __init__(self, filename, encoding, tail = False):
def __init__(self, filename, encoding, tail=False, doOpen=False):
self.__filename = filename
self.waitForLineEnd = True
self.setEncoding(encoding)
self.__tail = tail
self.__handler = None
self.__pos = 0
self.__pos4hash = 0
self.__hash = ''
self.__hashNextTime = time.time() + 30
# Try to open the file. Raises an exception if an error occurred.
handler = open(filename, 'rb')
stats = os.fstat(handler.fileno())
self.__ino = stats.st_ino
if doOpen: # fail2ban-regex only (don't need to reopen it and check for rotation)
self.__handler = handler
return
try:
firstLine = handler.readline()
# Computes the MD5 of the first line.
self.__hash = md5sum(firstLine).hexdigest()
# Start at the beginning of file if tail mode is off.
if tail:
handler.seek(0, 2)
self.__pos = handler.tell()
else:
self.__pos = 0
stats = os.fstat(handler.fileno())
self.__ino = stats.st_ino
if stats.st_size:
firstLine = handler.readline()
# first line available and contains new-line:
if firstLine != firstLine.rstrip(b'\r\n'):
# Computes the MD5 of the first line.
self.__hash = md5sum(firstLine).hexdigest()
# if tail mode scroll to the end of file
if tail:
handler.seek(0, 2)
self.__pos = handler.tell()
finally:
handler.close()
## shows that log is in operation mode (expecting new messages only from here):
self.inOperation = tail
def __hash__(self):
return hash(self.__filename)
def __eq__(self, other):
return (id(self) == id(other) or
self.__filename == (other.__filename if isinstance(other, FileContainer) else other)
)
def __repr__(self):
return 'file-log:'+self.__filename
def getFileName(self):
return self.__filename
def getFileSize(self):
h = self.__handler
if h is not None:
stats = os.fstat(h.fileno())
return stats.st_size
return os.path.getsize(self.__filename);
def setEncoding(self, encoding):
@@ -1260,38 +1382,54 @@ class FileContainer:
def setPos(self, value):
self.__pos = value
def open(self):
self.__handler = open(self.__filename, 'rb')
# Set the file descriptor to be FD_CLOEXEC
fd = self.__handler.fileno()
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
# Stat the file before even attempting to read it
stats = os.fstat(self.__handler.fileno())
if not stats.st_size:
# yoh: so it is still an empty file -- nothing should be
# read from it yet
# print "D: no content -- return"
return False
firstLine = self.__handler.readline()
# Computes the MD5 of the first line.
myHash = md5sum(firstLine).hexdigest()
## print "D: fn=%s hashes=%s/%s inos=%s/%s pos=%s rotate=%s" % (
## self.__filename, self.__hash, myHash, stats.st_ino, self.__ino, self.__pos,
## self.__hash != myHash or self.__ino != stats.st_ino)
## sys.stdout.flush()
# Compare hash and inode
if self.__hash != myHash or self.__ino != stats.st_ino:
logSys.log(logging.MSG, "Log rotation detected for %s", self.__filename)
self.__hash = myHash
self.__ino = stats.st_ino
self.__pos = 0
# Sets the file pointer to the last position.
self.__handler.seek(self.__pos)
def open(self, forcePos=None):
h = open(self.__filename, 'rb')
try:
# Set the file descriptor to be FD_CLOEXEC
fd = h.fileno()
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
myHash = self.__hash
# Stat the file before even attempting to read it
stats = os.fstat(h.fileno())
rotflg = stats.st_size < self.__pos or stats.st_ino != self.__ino
if rotflg or not len(myHash) or time.time() > self.__hashNextTime:
myHash = ''
firstLine = h.readline()
# Computes the MD5 of the first line (if it is complete)
if firstLine != firstLine.rstrip(b'\r\n'):
myHash = md5sum(firstLine).hexdigest()
self.__hashNextTime = time.time() + 30
elif stats.st_size == self.__pos:
myHash = self.__hash
# Compare size, hash and inode
if rotflg or myHash != self.__hash:
if self.__hash != '':
logSys.log(logging.MSG, "Log rotation detected for %s, reason: %r", self.__filename,
(stats.st_size, self.__pos, stats.st_ino, self.__ino, myHash, self.__hash))
self.__ino = stats.st_ino
self.__pos = 0
self.__hash = myHash
# if nothing to read from file yet (empty or no new data):
if forcePos is not None:
self.__pos = forcePos
elif stats.st_size <= self.__pos:
return False
# Sets the file pointer to the last position.
h.seek(self.__pos)
# leave file open (to read content):
self.__handler = h; h = None
finally:
# close (no content or error only)
if h:
h.close(); h = None
return True
def seek(self, offs, endLine=True):
h = self.__handler
if h is None:
self.open(offs)
h = self.__handler
# seek to given position
h.seek(offs, 0)
# goto end of next line
@@ -1309,38 +1447,98 @@ class FileContainer:
try:
return line.decode(enc, 'strict')
except (UnicodeDecodeError, UnicodeEncodeError) as e:
# avoid warning if got incomplete end of line (e. g. '\n' in "...[0A" followed by "00]..." for utf-16le:
if (e.end == len(line) and line[e.start] in b'\r\n'):
return line[0:e.start].decode(enc, 'replace')
global _decode_line_warn
lev = logging.DEBUG
if _decode_line_warn.get(filename, 0) <= MyTime.time():
lev = 7
if not _decode_line_warn.get(filename, 0):
lev = logging.WARNING
_decode_line_warn[filename] = MyTime.time() + 24*60*60
_decode_line_warn.set(filename, 1)
logSys.log(lev,
"Error decoding line from '%s' with '%s'."
" Consider setting logencoding=utf-8 (or another appropriate"
" encoding) for this jail. Continuing"
" to process line ignoring invalid characters: %r",
filename, enc, line)
"Error decoding line from '%s' with '%s'.", filename, enc)
if logSys.getEffectiveLevel() <= lev:
logSys.log(lev,
"Consider setting logencoding to appropriate encoding for this jail. "
"Continuing to process line ignoring invalid characters: %r",
line)
# decode with replacing error chars:
line = line.decode(enc, 'replace')
return line
def readline(self):
def readline(self, complete=True):
"""Read line from file
In opposite to pythons readline it doesn't return new-line,
so returns either the line if line is complete (and complete=True) or None
if line is not complete (and complete=True) or there is no content to read.
If line is complete (and complete is True), it also shift current known
position to begin of next line.
Also it is safe against interim new-line bytes (e. g. part of multi-byte char)
in given encoding.
"""
if self.__handler is None:
return ""
return FileContainer.decode_line(
self.getFileName(), self.getEncoding(), self.__handler.readline())
# read raw bytes up to \n char:
b = self.__handler.readline()
if not b:
return None
bl = len(b)
# convert to log-encoding (new-line char could disappear if it is part of multi-byte sequence):
r = FileContainer.decode_line(
self.getFileName(), self.getEncoding(), b)
# trim new-line at end and check the line was written complete (contains a new-line):
l = r.rstrip('\r\n')
if complete:
if l == r:
# try to fill buffer in order to find line-end in log encoding:
fnd = 0
while 1:
r = self.__handler.readline()
if not r:
break
b += r
bl += len(r)
# convert to log-encoding:
r = FileContainer.decode_line(
self.getFileName(), self.getEncoding(), b)
# ensure new-line is not in the middle (buffered 2 strings, e. g. in utf-16le it is "...[0A"+"00]..."):
e = r.find('\n')
if e >= 0 and e != len(r)-1:
l, r = r[0:e], r[0:e+1]
# back to bytes and get offset to seek after NL:
r = r.encode(self.getEncoding(), 'replace')
self.__handler.seek(-bl+len(r), 1)
return l
# trim new-line at end and check the line was written complete (contains a new-line):
l = r.rstrip('\r\n')
if l != r:
return l
if self.waitForLineEnd:
# not fulfilled - seek back and return:
self.__handler.seek(-bl, 1)
return None
return l
def close(self):
if not self.__handler is None:
# Saves the last position.
if self.__handler is not None:
# Saves the last real position.
self.__pos = self.__handler.tell()
# Closes the file.
self.__handler.close()
self.__handler = None
## print "D: Closed %s with pos %d" % (handler, self.__pos)
## sys.stdout.flush()
_decode_line_warn = {}
def __iter__(self):
return self
def next(self):
line = self.readline()
if line is None:
self.close()
raise StopIteration
return line
_decode_line_warn = Utils.Cache(maxCount=1000, maxTime=24*60*60);
##
+3 -12
View File
@@ -55,7 +55,6 @@ class FilterGamin(FileFilter):
def __init__(self, jail):
FileFilter.__init__(self, jail)
self.__modified = False
# Gamin monitor
self.monitor = gamin.WatchMonitor()
fd = self.monitor.get_fd()
@@ -67,20 +66,9 @@ class FilterGamin(FileFilter):
logSys.log(4, "Got event: " + repr(event) + " for " + path)
if event in (gamin.GAMCreated, gamin.GAMChanged, gamin.GAMExists):
logSys.debug("File changed: " + path)
self.__modified = True
self.ticks += 1
self._process_file(path)
def _process_file(self, path):
"""Process a given file
TODO -- RF:
this is a common logic and must be shared/provided by FileFilter
"""
self.getFailures(path)
self.performBan()
self.__modified = False
##
# Add a log file path
@@ -127,6 +115,9 @@ class FilterGamin(FileFilter):
Utils.wait_for(lambda: not self.active or self._handleEvents(),
self.sleeptime)
self.ticks += 1
if self.ticks % 10 == 0:
self.performSvc()
logSys.debug("[%s] filter terminated", self.jailName)
return True
+6 -9
View File
@@ -27,9 +27,7 @@ __license__ = "GPL"
import os
import time
from .failmanager import FailManagerEmpty
from .filter import FileFilter
from .mytime import MyTime
from .utils import Utils
from ..helpers import getLogger, logging
@@ -55,7 +53,6 @@ class FilterPoll(FileFilter):
def __init__(self, jail):
FileFilter.__init__(self, jail)
self.__modified = False
## The time of the last modification of the file.
self.__prevStats = dict()
self.__file404Cnt = dict()
@@ -111,21 +108,21 @@ class FilterPoll(FileFilter):
modlst = []
Utils.wait_for(lambda: not self.active or self.getModified(modlst),
self.sleeptime)
if not self.active: # pragma: no cover - timing
break
for filename in modlst:
self.getFailures(filename)
self.__modified = True
self.ticks += 1
if self.__modified:
self.performBan()
self.__modified = False
if self.ticks % 10 == 0:
self.performSvc()
except Exception as e: # pragma: no cover
if not self.active: # if not active - error by stop...
break
logSys.error("Caught unhandled exception in main cycle: %r", e,
exc_info=logSys.getEffectiveLevel()<=logging.DEBUG)
# incr common error counter:
self.commonError()
self.commonError("unhandled", e)
logSys.debug("[%s] filter terminated", self.jailName)
return True
@@ -139,7 +136,7 @@ class FilterPoll(FileFilter):
try:
logStats = os.stat(filename)
stats = logStats.st_mtime, logStats.st_ino, logStats.st_size
pstats = self.__prevStats.get(filename, (0))
pstats = self.__prevStats.get(filename, (0,))
if logSys.getEffectiveLevel() <= 4:
# we do not want to waste time on strftime etc if not necessary
dt = logStats.st_mtime - pstats[0]
+30 -20
View File
@@ -75,7 +75,6 @@ class FilterPyinotify(FileFilter):
def __init__(self, jail):
FileFilter.__init__(self, jail)
self.__modified = False
# Pyinotify watch manager
self.__monitor = pyinotify.WatchManager()
self.__notifier = None
@@ -140,8 +139,6 @@ class FilterPyinotify(FileFilter):
"""
if not self.idle:
self.getFailures(path)
self.performBan()
self.__modified = False
def _addPending(self, path, reason, isDir=False):
if path not in self.__pending:
@@ -168,7 +165,7 @@ class FilterPyinotify(FileFilter):
return
found = {}
minTime = 60
for path, (retardTM, isDir) in self.__pending.iteritems():
for path, (retardTM, isDir) in list(self.__pending.items()):
if ntm - self.__pendingChkTime < retardTM:
if minTime > retardTM: minTime = retardTM
continue
@@ -187,10 +184,11 @@ class FilterPyinotify(FileFilter):
for path, isDir in found.iteritems():
self._delPending(path)
# refresh monitoring of this:
self._refreshWatcher(path, isDir=isDir)
if isDir is not None:
self._refreshWatcher(path, isDir=isDir)
if isDir:
# check all files belong to this dir:
for logpath in self.__watchFiles:
for logpath in list(self.__watchFiles):
if logpath.startswith(path + pathsep):
# if still no file - add to pending, otherwise refresh and process:
if not os.path.isfile(logpath):
@@ -270,28 +268,32 @@ class FilterPyinotify(FileFilter):
def _addLogPath(self, path):
self._addFileWatcher(path)
self._process_file(path)
# notify (wake up if in waiting):
if self.active:
self.__pendingMinTime = 0
# retard until filter gets started, isDir=None signals special case: process file only (don't need to refresh monitor):
self._addPending(path, ('INITIAL', path), isDir=None)
##
##
# Delete a log path
#
# @param path the log file to delete
def _delLogPath(self, path):
self._delPending(path)
if not self._delFileWatcher(path): # pragma: no cover
logSys.error("Failed to remove watch on path: %s", path)
self._delPending(path)
path_dir = dirname(path)
for k in self.__watchFiles:
for k in list(self.__watchFiles):
if k.startswith(path_dir + pathsep):
path_dir = None
break
if path_dir:
# Remove watches for the directory
# since there is no other monitored file under this directory
self._delDirWatcher(path_dir)
self._delPending(path_dir)
self._delDirWatcher(path_dir)
# pyinotify.ProcessEvent default handler:
def __process_default(self, event):
@@ -337,16 +339,26 @@ class FilterPyinotify(FileFilter):
self.__notifier.process_events()
# wait for events / timeout:
notify_maxtout = self.__notify_maxtout
def __check_events():
return not self.active or self.__notifier.check_events(timeout=notify_maxtout)
if Utils.wait_for(__check_events, min(self.sleeptime, self.__pendingMinTime)):
return (
not self.active
or bool(self.__notifier.check_events(timeout=self.__notify_maxtout))
or (self.__pendingMinTime and self.__pending)
)
wres = Utils.wait_for(__check_events, min(self.sleeptime, self.__pendingMinTime))
if wres:
if not self.active: break
self.__notifier.read_events()
if not isinstance(wres, dict):
self.__notifier.read_events()
self.ticks += 1
# check pending files/dirs (logrotate ready):
if not self.idle:
self._checkPending()
if self.idle:
continue
self._checkPending()
if self.ticks % 10 == 0:
self.performSvc()
except Exception as e: # pragma: no cover
if not self.active: # if not active - error by stop...
@@ -354,10 +366,8 @@ class FilterPyinotify(FileFilter):
logSys.error("Caught unhandled exception in main cycle: %r", e,
exc_info=logSys.getEffectiveLevel()<=logging.DEBUG)
# incr common error counter:
self.commonError()
self.commonError("unhandled", e)
self.ticks += 1
logSys.debug("[%s] filter exited (pyinotifier)", self.jailName)
self.__notifier = None
+116 -30
View File
@@ -23,6 +23,7 @@ __copyright__ = "Copyright (c) 2013 Steven Hiscocks"
__license__ = "GPL"
import datetime
import os
import time
from distutils.version import LooseVersion
@@ -91,9 +92,14 @@ class FilterSystemd(JournalFilter): # pragma: systemd no cover
try:
args['flags'] = int(kwargs.pop('journalflags'))
except KeyError:
# be sure all journal types will be opened if files specified (don't set flags):
if 'files' not in args or not len(args['files']):
args['flags'] = 4
# be sure all journal types will be opened if files/path specified (don't set flags):
if ('files' not in args or not len(args['files'])) and ('path' not in args or not args['path']):
args['flags'] = int(os.getenv("F2B_SYSTEMD_DEFAULT_FLAGS", 4))
try:
args['namespace'] = kwargs.pop('namespace')
except KeyError:
pass
return args
@@ -190,6 +196,13 @@ class FilterSystemd(JournalFilter): # pragma: systemd no cover
def getJournalReader(self):
return self.__journal
def getJrnEntTime(self, logentry):
""" Returns time of entry as tuple (ISO-str, Posix)."""
date = logentry.get('_SOURCE_REALTIME_TIMESTAMP')
if date is None:
date = logentry.get('__REALTIME_TIMESTAMP')
return (date.isoformat(), time.mktime(date.timetuple()) + date.microsecond/1.0E6)
##
# Format journal log entry into syslog style
#
@@ -222,9 +235,8 @@ class FilterSystemd(JournalFilter): # pragma: systemd no cover
logelements[-1] += v
logelements[-1] += ":"
if logelements[-1] == "kernel:":
if '_SOURCE_MONOTONIC_TIMESTAMP' in logentry:
monotonic = logentry.get('_SOURCE_MONOTONIC_TIMESTAMP')
else:
monotonic = logentry.get('_SOURCE_MONOTONIC_TIMESTAMP')
if monotonic is None:
monotonic = logentry.get('__MONOTONIC_TIMESTAMP')[0]
logelements.append("[%12.6f]" % monotonic.total_seconds())
msg = logentry.get('MESSAGE','')
@@ -235,19 +247,21 @@ class FilterSystemd(JournalFilter): # pragma: systemd no cover
logline = " ".join(logelements)
date = logentry.get('_SOURCE_REALTIME_TIMESTAMP',
logentry.get('__REALTIME_TIMESTAMP'))
date = self.getJrnEntTime(logentry)
logSys.log(5, "[%s] Read systemd journal entry: %s %s", self.jailName,
date.isoformat(), logline)
date[0], logline)
## use the same type for 1st argument:
return ((logline[:0], date.isoformat(), logline.replace('\n', '\\n')),
time.mktime(date.timetuple()) + date.microsecond/1.0E6)
return ((logline[:0], date[0], logline.replace('\n', '\\n')), date[1])
def seekToTime(self, date):
if not isinstance(date, datetime.datetime):
date = datetime.datetime.fromtimestamp(date)
self.__journal.seek_realtime(date)
def inOperationMode(self):
self.inOperation = True
logSys.info("[%s] Jail is in operation now (process new journal entries)", self.jailName)
##
# Main loop.
#
@@ -258,21 +272,46 @@ class FilterSystemd(JournalFilter): # pragma: systemd no cover
if not self.getJournalMatch():
logSys.notice(
"Jail started without 'journalmatch' set. "
"[%s] Jail started without 'journalmatch' set. "
"Jail regexs will be checked against all journal entries, "
"which is not advised for performance reasons.")
"which is not advised for performance reasons.", self.jailName)
# Seek to now - findtime in journal
start_time = datetime.datetime.now() - \
datetime.timedelta(seconds=int(self.getFindTime()))
self.seekToTime(start_time)
# Move back one entry to ensure do not end up in dead space
# if start time beyond end of journal
# Save current cursor position (to recognize in operation mode):
logentry = None
try:
self.__journal.get_previous()
self.__journal.seek_tail()
logentry = self.__journal.get_previous()
self.__journal.get_next()
except OSError:
pass # Reading failure, so safe to ignore
logentry = None # Reading failure, so safe to ignore
if logentry:
# Try to obtain the last known time (position of journal)
startTime = 0
if self.jail.database is not None:
startTime = self.jail.database.getJournalPos(self.jail, 'systemd-journal') or 0
# Seek to max(last_known_time, now - findtime) in journal
startTime = max( startTime, MyTime.time() - int(self.getFindTime()) )
self.seekToTime(startTime)
# Not in operation while we'll read old messages ...
self.inOperation = False
# Save current time in order to check time to switch "in operation" mode
startTime = (1, MyTime.time(), logentry.get('__CURSOR'))
# Move back one entry to ensure do not end up in dead space
# if start time beyond end of journal
try:
self.__journal.get_previous()
except OSError:
pass # Reading failure, so safe to ignore
else:
# empty journal or no entries for current filter:
self.inOperationMode()
# seek_tail() seems to have a bug by no entries (could bypass some entries hereafter), so seek to now instead:
startTime = MyTime.time()
self.seekToTime(startTime)
# for possible future switches of in-operation mode:
startTime = (0, startTime)
line = None
while self.active:
# wait for records (or for timeout in sleeptime seconds):
try:
@@ -282,9 +321,10 @@ class FilterSystemd(JournalFilter): # pragma: systemd no cover
#self.__journal.wait(self.sleeptime) != journal.NOP
##
## wait for entries without sleep in intervals, because "sleeping" in journal.wait:
Utils.wait_for(lambda: not self.active or \
self.__journal.wait(Utils.DEFAULT_SLEEP_INTERVAL) != journal.NOP,
self.sleeptime, 0.00001)
if not logentry:
Utils.wait_for(lambda: not self.active or \
self.__journal.wait(Utils.DEFAULT_SLEEP_INTERVAL) != journal.NOP,
self.sleeptime, 0.00001)
if self.idle:
# because journal.wait will returns immediatelly if we have records in journal,
# just wait a little bit here for not idle, to prevent hi-load:
@@ -303,23 +343,50 @@ class FilterSystemd(JournalFilter): # pragma: systemd no cover
e, exc_info=logSys.getEffectiveLevel() <= logging.DEBUG)
self.ticks += 1
if logentry:
self.processLineAndAdd(
*self.formatJournalEntry(logentry))
line, tm = self.formatJournalEntry(logentry)
# switch "in operation" mode if we'll find start entry (+ some delta):
if not self.inOperation:
if tm >= MyTime.time() - 1: # reached now (approximated):
self.inOperationMode()
elif startTime[0] == 1:
# if it reached start entry (or get read time larger than start time)
if logentry.get('__CURSOR') == startTime[2] or tm > startTime[1]:
# give the filter same time it needed to reach the start entry:
startTime = (0, MyTime.time()*2 - startTime[1])
elif tm > startTime[1]: # reached start time (approximated):
self.inOperationMode()
# process line
self.processLineAndAdd(line, tm)
self.__modified += 1
if self.__modified >= 100: # todo: should be configurable
break
else:
# "in operation" mode since we don't have messages anymore (reached end of journal):
if not self.inOperation:
self.inOperationMode()
break
if self.__modified:
self.performBan()
self.__modified = 0
self.__modified = 0
if self.ticks % 10 == 0:
self.performSvc()
# update position in log (time and iso string):
if self.jail.database:
if line:
self._pendDBUpdates['systemd-journal'] = (tm, line[1])
line = None
if self._pendDBUpdates and (
self.ticks % 100 == 0
or MyTime.time() >= self._nextUpdateTM
or not self.active
):
self._updateDBPending()
self._nextUpdateTM = MyTime.time() + Utils.DEFAULT_SLEEP_TIME * 5
except Exception as e: # pragma: no cover
if not self.active: # if not active - error by stop...
break
logSys.error("Caught unhandled exception in main cycle: %r", e,
exc_info=logSys.getEffectiveLevel()<=logging.DEBUG)
# incr common error counter:
self.commonError()
self.commonError("unhandled", e)
logSys.debug("[%s] filter terminated", self.jailName)
@@ -339,3 +406,22 @@ class FilterSystemd(JournalFilter): # pragma: systemd no cover
ret.append(("Journal matches",
[" + ".join(" ".join(match) for match in self.__matches)]))
return ret
def _updateDBPending(self):
"""Apply pending updates (jornal position) to database.
"""
db = self.jail.database
while True:
try:
log, args = self._pendDBUpdates.popitem()
except KeyError:
break
db.updateJournal(self.jail, log, *args)
def onStop(self):
"""Stop monitoring of journal. Invoked after run method.
"""
# ensure positions of pending logs are up-to-date:
if self._pendDBUpdates and self.jail.database:
self._updateDBPending()
+43 -11
View File
@@ -169,27 +169,31 @@ class DNSUtils:
DNSUtils.CACHE_ipToName.set(key, name)
return name
# key find cached own hostnames (this tuple-key cannot be used elsewhere):
_getSelfNames_key = ('self','dns')
@staticmethod
def getSelfNames():
"""Get own host names of self"""
# try find cached own hostnames (this tuple-key cannot be used elsewhere):
key = ('self','dns')
names = DNSUtils.CACHE_ipToName.get(key)
# try find cached own hostnames:
names = DNSUtils.CACHE_ipToName.get(DNSUtils._getSelfNames_key)
# get it using different ways (a set with names of localhost, hostname, fully qualified):
if names is None:
names = set([
'localhost', DNSUtils.getHostname(False), DNSUtils.getHostname(True)
]) - set(['']) # getHostname can return ''
# cache and return :
DNSUtils.CACHE_ipToName.set(key, names)
DNSUtils.CACHE_ipToName.set(DNSUtils._getSelfNames_key, names)
return names
# key to find cached own IPs (this tuple-key cannot be used elsewhere):
_getSelfIPs_key = ('self','ips')
@staticmethod
def getSelfIPs():
"""Get own IP addresses of self"""
# try find cached own IPs (this tuple-key cannot be used elsewhere):
key = ('self','ips')
ips = DNSUtils.CACHE_nameToIp.get(key)
# to find cached own IPs:
ips = DNSUtils.CACHE_nameToIp.get(DNSUtils._getSelfIPs_key)
# get it using different ways (a set with IPs of localhost, hostname, fully qualified):
if ips is None:
ips = set()
@@ -199,13 +203,30 @@ class DNSUtils:
except Exception as e: # pragma: no cover
logSys.warning("Retrieving own IPs of %s failed: %s", hostname, e)
# cache and return :
DNSUtils.CACHE_nameToIp.set(key, ips)
DNSUtils.CACHE_nameToIp.set(DNSUtils._getSelfIPs_key, ips)
return ips
_IPv6IsAllowed = None
@staticmethod
def setIPv6IsAllowed(value):
DNSUtils._IPv6IsAllowed = value
logSys.debug("IPv6 is %s", ('on' if value else 'off') if value is not None else 'auto')
return value
# key to find cached value of IPv6 allowance (this tuple-key cannot be used elsewhere):
_IPv6IsAllowed_key = ('self','ipv6-allowed')
@staticmethod
def IPv6IsAllowed():
# return os.path.exists("/proc/net/if_inet6") || any((':' in ip) for ip in DNSUtils.getSelfIPs())
return any((':' in ip.ntoa) for ip in DNSUtils.getSelfIPs())
if DNSUtils._IPv6IsAllowed is not None:
return DNSUtils._IPv6IsAllowed
v = DNSUtils.CACHE_nameToIp.get(DNSUtils._IPv6IsAllowed_key)
if v is not None:
return v
v = any((':' in ip.ntoa) for ip in DNSUtils.getSelfIPs())
DNSUtils.CACHE_nameToIp.set(DNSUtils._IPv6IsAllowed_key, v)
return v
##
@@ -337,7 +358,7 @@ class IPAddr(object):
return repr(self.ntoa)
def __str__(self):
return self.ntoa
return self.ntoa if isinstance(self.ntoa, basestring) else str(self.ntoa)
def __reduce__(self):
"""IPAddr pickle-handler, that simply wraps IPAddr to the str
@@ -379,6 +400,12 @@ class IPAddr(object):
"""
return self._family != socket.AF_UNSPEC
@property
def isSingle(self):
"""Returns whether the object is a single IP address (not DNS and subnet)
"""
return self._plen == {socket.AF_INET: 32, socket.AF_INET6: 128}.get(self._family, -1000)
def __eq__(self, other):
if self._family == IPAddr.CIDR_RAW and not isinstance(other, IPAddr):
return self._raw == other
@@ -511,6 +538,11 @@ class IPAddr(object):
return (self.addr & mask) == net.addr
def contains(self, ip):
"""Return whether the object (as network) contains given IP
"""
return isinstance(ip, IPAddr) and (ip == self or ip.isInNet(self))
# Pre-calculated map: addr to maskplen
def __getMaskMap():
m6 = (1 << 128)-1

Some files were not shown because too many files have changed in this diff Show More