-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathblocklist.sh
More file actions
7960 lines (6686 loc) · 306 KB
/
blocklist.sh
File metadata and controls
7960 lines (6686 loc) · 306 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#
# update-ipsets - for FireHOL - A firewall for humans...
#
# Copyright
#
# Copyright (C) 2015-2017 Costa Tsaousis <costa@tsaousis.gr>
# Copyright (C) 2015-2017 Phil Whineray <phil@sanewall.org>
#
# License
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
# See the file COPYING for details.
#
# What this program does:
#
# 1. It downloads a number of IP lists
# - respects network resource: it will download a file only if it has
# been changed on the server (IF_MODIFIED_SINCE)
# - it will not attempt to download a file too frequently
# (it has a maximum frequency per download URL embedded, so that
# even if a server does not support IF_MODIFIED_SINCE it will not
# download the IP list too frequently).
# - it will use compression when possible.
#
# 2. Once a file is downloaded, it will convert it either to
# an ip:hash or a net:hash ipset.
# It can convert:
# - text files
# - snort rules files
# - PIX rules files
# - XML files (like RSS feeds)
# - CSV files
# - compressed files (zip, gz, etc)
# - generally, anything that can be converted using shell commands
#
# 3. For all file types it can keep a history of the processed sets
# that can be merged with the new downloaded one, so that it can
# populate the generated set with all the IPs of the last X days.
#
# 4. For each set updated, it will:
# - save it to disk
# - update a kernel ipset, having the same name
#
# 5. It can commit all successfully updated files to a git repository.
# Just do 'git init' in $SYSCONFDIR/firehol/ipsets to enable it.
# If it is called with -g it will also push the committed changes
# to a remote git server (to have this done by cron, please set
# git to automatically push changes without human action).
#
# 6. It can compare ipsets and keep track of geomaping, history of size,
# age of IPs listed, retention policy, overlaps with other sets.
# To enable it, run it with -c.
#
# -----------------------------------------------------------------------------
#
# How to use it:
#
# This script depends on iprange, found also in firehol.
# It does not depend on firehol. You can use it without firehol.
#
# 1. Run this script. It will give you instructions on which
# IP lists are available and what to do to enable them.
# 2. Enable a few lists, following its instructions.
# 3. Run it again to update the lists.
# 4. Put it in a cron job to do the updates automatically.
# -----------------------------------------------------------------------------
READLINK_CMD=${READLINK_CMD:-readlink}
BASENAME_CMD=${BASENAME_CMD:-basename}
DIRNAME_CMD=${DIRNAME_CMD:-dirname}
function realdir {
local r="$1"; local t=$($READLINK_CMD "$r")
while [ "$t" ]; do
r=$(cd $($DIRNAME_CMD "$r") && cd $($DIRNAME_CMD "$t") && pwd -P)/$($BASENAME_CMD "$t")
t=$($READLINK_CMD "$r")
done
$DIRNAME_CMD "$r"
}
PROGRAM_FILE="$0"
PROGRAM_DIR="${FIREHOL_OVERRIDE_PROGRAM_DIR:-$(realdir "$0")}"
PROGRAM_PWD="${PWD}"
declare -a PROGRAM_ORIGINAL_ARGS=("${@}")
for functions_file in install.config functions.common
do
if [ -r "$PROGRAM_DIR/$functions_file" ]
then
source "$PROGRAM_DIR/$functions_file"
else
1>&2 echo "Cannot access $PROGRAM_DIR/$functions_file"
exit 1
fi
done
common_disable_localization || exit
common_public_umask || exit
marksreset() { :; }
markdef() { :; }
if [ -r "${FIREHOL_CONFIG_DIR}/firehol-defaults.conf" ]
then
source "${FIREHOL_CONFIG_DIR}/firehol-defaults.conf" || exit 1
fi
RUNNING_ON_TERMINAL=0
if [ "z$1" = "z-nc" ]
then
shift
else
common_setup_terminal && RUNNING_ON_TERMINAL=1
fi
$RENICE_CMD 10 $$ >/dev/null 2>/dev/null
# -----------------------------------------------------------------------------
# logging
error() {
echo >&2 -e "${COLOR_BGRED}${COLOR_WHITE}${COLOR_BOLD} ERROR ${COLOR_RESET}: ${@}"
$LOGGER_CMD -p daemon.err -t "update-ipsets.sh[$$]" "${@}"
}
warning() {
echo >&2 -e "${COLOR_BGYELLOW}${COLOR_BLACK}${COLOR_BOLD} WARNING ${COLOR_RESET}: ${@}"
$LOGGER_CMD -p daemon.warning -t "update-ipsets.sh[$$]" "${@}"
}
info() {
echo >&2 "${@}"
$LOGGER_CMD -p daemon.info -t "update-ipsets.sh[$$]" "${@}"
}
verbose() {
[ ${VERBOSE} -eq 1 ] && echo >&2 "${@}"
}
silent() {
[ ${SILENT} -ne 1 ] && echo >&2 "${@}"
}
print_ipset_indent=35
print_ipset_spacer="$(printf "%${print_ipset_indent}s| " "")"
print_ipset_last=
print_ipset_reset() {
print_ipset_last=
}
print_ipset_header() {
local ipset="${1}"
if [ "${ipset}" = "${print_ipset_last}" ]
then
printf >&2 "%${print_ipset_indent}s| " ""
else
[ ${SILENT} -ne 1 ] && echo >&2 "${print_ipset_spacer}"
printf >&2 "${COLOR_GREEN}%${print_ipset_indent}s${COLOR_RESET}| " "${ipset}"
print_ipset_last="${ipset}"
fi
}
ipset_error() {
local ipset="${1}"
shift
print_ipset_header "${ipset}"
echo >&2 -e "${COLOR_BGRED}${COLOR_WHITE}${COLOR_BOLD} ERROR ${COLOR_RESET} ${@}"
$LOGGER_CMD -p daemon.info -t "update-ipsets.sh[$$]" "ERROR: ${ipset}: ${@}"
}
ipset_warning() {
local ipset="${1}"
shift
print_ipset_header "${ipset}"
echo >&2 -e "${COLOR_BGYELLOW}${COLOR_BLACK}${COLOR_BOLD} WARNING ${COLOR_RESET} ${@}"
$LOGGER_CMD -p daemon.info -t "update-ipsets.sh[$$]" "WARNING: ${ipset}: ${@}"
}
ipset_info() {
local ipset="${1}"
shift
print_ipset_header "${ipset}"
echo >&2 "${@}"
$LOGGER_CMD -p daemon.info -t "update-ipsets.sh[$$]" "INFO: ${ipset}: ${@}"
}
ipset_saved() {
local ipset="${1}"
shift
print_ipset_header "${ipset}"
echo >&2 -e "${COLOR_BGGREEN}${COLOR_RED}${COLOR_BOLD} SAVED ${COLOR_RESET} ${@}"
$LOGGER_CMD -p daemon.info -t "update-ipsets.sh[$$]" "SAVED: ${ipset}: ${@}"
}
ipset_loaded() {
local ipset="${1}"
shift
print_ipset_header "${ipset}"
echo >&2 -e "${COLOR_BGGREEN}${COLOR_BLACK}${COLOR_BOLD} LOADED ${COLOR_RESET} ${@}"
$LOGGER_CMD -p daemon.info -t "update-ipsets.sh[$$]" "LOADED: ${ipset}: ${@}"
}
ipset_same() {
local ipset="${1}"
shift
print_ipset_header "${ipset}"
echo >&2 -e "${COLOR_BGWHITE}${COLOR_BLACK}${COLOR_BOLD} SAME ${COLOR_RESET} ${@}"
$LOGGER_CMD -p daemon.info -t "update-ipsets.sh[$$]" "DOWNLOADED SAME: ${ipset}: ${@}"
}
ipset_notupdated() {
local ipset="${1}"
shift
print_ipset_header "${ipset}"
echo >&2 -e "${COLOR_BGWHITE}${COLOR_BLACK}${COLOR_BOLD} NOT UPDATED ${COLOR_RESET} ${@}"
# $LOGGER_CMD -p daemon.info -t "update-ipsets.sh[$$]" "NOT UPDATED: ${ipset}: ${@}"
}
ipset_notyet() {
local ipset="${1}"
shift
print_ipset_header "${ipset}"
echo >&2 -e "${COLOR_BGWHITE}${COLOR_BLACK}${COLOR_BOLD} LATER ${COLOR_RESET} ${@}"
# $LOGGER_CMD -p daemon.info -t "update-ipsets.sh[$$]" "LATER: ${ipset}: ${@}"
}
ipset_disabled() {
local ipset="${1}"
shift
if [ ${SILENT} -eq 0 ]
then
print_ipset_header "${ipset}"
echo >&2 -e "${COLOR_BGWHITE}${COLOR_BLACK}${COLOR_BOLD} DISABLED ${COLOR_RESET} ${@}"
print_ipset_header "${ipset}"
echo >&2 "To enable run: update-ipsets enable ${ipset}"
fi
}
ipset_silent() {
local ipset="${1}"
shift
if [ ${SILENT} -eq 0 ]
then
print_ipset_header "${ipset}"
echo >&2 "${@}"
fi
}
ipset_verbose() {
local ipset="${1}"
shift
if [ ${VERBOSE} -eq 1 ]
then
print_ipset_header "${ipset}"
echo >&2 "${@}"
fi
}
# -----------------------------------------------------------------------------
# find a working iprange command
HAVE_IPRANGE=${IPRANGE_CMD}
if [ ! -z "${IPRANGE_CMD}" ]
then
${IPRANGE_CMD} --has-reduce 2>/dev/null || HAVE_IPRANGE=
fi
if [ -z "$HAVE_IPRANGE" ]
then
error "Cannot find a working iprange command. It should be part of FireHOL but it is not installed."
exit 1
fi
# -----------------------------------------------------------------------------
# CONFIGURATION
if [ "${UID}" = "0" -o -z "${UID}" ]
then
BASE_DIR="${BASE_DIR-${FIREHOL_CONFIG_DIR}/ipsets}"
CONFIG_FILE="${CONFIG_FILE-${FIREHOL_CONFIG_DIR}/update-ipsets.conf}"
RUN_PARENT_DIR="${RUN_PARENT_DIR-$LOCALSTATEDIR/run}"
CACHE_DIR="${CACHE_DIR-$LOCALSTATEDIR/cache/update-ipsets}"
LIB_DIR="${LIB_DIR-$LOCALSTATEDIR/lib/update-ipsets}"
IPSETS_APPLY=1
else
$MKDIR_CMD -p "${HOME}/.update-ipsets" || exit 1
BASE_DIR="${BASE_DIR-${HOME}/ipsets}"
CONFIG_FILE="${CONFIG_FILE-${HOME}/.update-ipsets/update-ipsets.conf}"
RUN_PARENT_DIR="${RUN_PARENT_DIR-${HOME}/.update-ipsets}"
CACHE_DIR="${CACHE_DIR-${HOME}/.update-ipsets/cache}"
LIB_DIR="${LIB_DIR-${HOME}/.update-ipsets/lib}"
IPSETS_APPLY=0
fi
# admin defined ipsets
ADMIN_SUPPLIED_IPSETS="${ADMIN_SUPPLIED_IPSETS-${FIREHOL_CONFIG_DIR}/ipsets.d}"
# distribution defined ipsets
DISTRIBUTION_SUPPLIED_IPSETS="${DISTRIBUTION_SUPPLIED_IPSETS-${FIREHOL_SHARE_DIR}/ipsets.d}"
# user defined ipsets
USER_SUPPLIED_IPSETS="${USER_SUPPLIED_IPSETS-${HOME}/.update-ipsets/ipsets.d}"
# where to keep the history files
HISTORY_DIR="${HISTORY_DIR-${BASE_DIR}/history}"
# where to keep the files we cannot process
# when empty, error files will be deleted
ERRORS_DIR="${ERRORS_DIR-${BASE_DIR}/errors}"
# where to keep the tmp files
# a subdirectory will be created as RUN_DIR
TMP_DIR="${TMP_DIR-/tmp}"
# options to be given to iprange for reducing netsets
IPSET_REDUCE_FACTOR=${IPSET_REDUCE_FACTOR-20}
IPSET_REDUCE_ENTRIES=${IPSET_REDUCE_ENTRIES-65536}
# how many entries the ipset charts should have
WEB_CHARTS_ENTRIES=${WEB_CHARTS_ENTRIES-500}
# if the .git directory is present, push it also
PUSH_TO_GIT=${PUSH_TO_GIT-0}
# when PUSH_TO_GIT is enabled, this controls if each
# ipset will get its own commit, or all files will be
# committed together
PUSH_TO_GIT_MERGED=${PUSH_TO_GIT_MERGED-1}
# additional options to add as the git commit/push lines
PUSH_TO_GIT_COMMIT_OPTIONS=""
PUSH_TO_GIT_PUSH_OPTIONS=""
# if we will also push github gh-pages
PUSH_TO_GIT_WEB=${PUSH_TO_GIT_WEB-${PUSH_TO_GIT}}
# the maximum time in seconds, to connect to the remote web server
MAX_CONNECT_TIME=${MAX_CONNECT_TIME-10}
# agent string to use when performing downloads
USER_AGENT="FireHOL-Update-Ipsets/3.0 (linux-gnu) https://iplists.firehol.org/"
# the maximum time in seconds any download may take
MAX_DOWNLOAD_TIME=${MAX_DOWNLOAD_TIME-300}
# ignore a few download failures
# if the download fails more than these consecutive times, the ipset will be
# penalized X times its failures (ie. MINUTES * ( FAILURES - the following number) )
IGNORE_REPEATING_DOWNLOAD_ERRORS=${IGNORE_REPEATING_DOWNLOAD_ERRORS-10}
# how many DNS queries to execute in parallel when resolving hostnames to IPs
# IMPORTANT: Increasing this too much and you are going to need A LOT of bandwidth!
# IMPORTANT: Giving a lot parallel requests to your name server will create a queue
# that will start filling up as time passes, possibly hitting a quota
# on the name server.
PARALLEL_DNS_QUERIES=${PARALLEL_DNS_QUERIES-10}
# where to put the CSV files for the web server
# if empty or does not exist, web files will not be generated
WEB_DIR=""
# how to chown web files
WEB_OWNER=""
# where is the web url to show info about each ipset
# the ipset name is appended to it
WEB_URL="http://iplists.firehol.org/?ipset="
# the path to copy downloaded files to, using ${WEB_OWNER} permissions
# if empty, do not copy them
WEB_DIR_FOR_IPSETS=""
# options for the web site
# the ipset name will be appended
LOCAL_COPY_URL="https://iplists.firehol.org/files/"
GITHUB_CHANGES_URL="https://github.com/firehol/blocklist-ipsets/commits/master/"
GITHUB_SETINFO="https://github.com/firehol/blocklist-ipsets/tree/master/"
# -----------------------------------------------------------------------------
# Command line parsing
CLEANUP_OLD=0
ENABLE_ALL=0
IGNORE_LASTCHECKED=0
FORCE_WEB_REBUILD=0
REPROCESS_ALL=0
SILENT=0
VERBOSE=0
declare -a LISTS_TO_ENABLE=()
declare -A RUN_ONLY_THESE_IPSETS=()
usage() {
$CAT_CMD <<EOFUSAGE
FireHOL update-ipsets $VERSION
(C) 2015 Costa Tsaousis
USAGE:
${PROGRAM_FILE} [options]
The above will execute an update on the configured ipsets
or
${PROGRAM_FILE} enable ipset1 ipset2 ipset3 ...
The above will only enable the given ipsets and exit
It does not validate that the ipsets exists.
options are:
-s
--silent log less than default
This will not report all the possible ipsets that
can be enabled.
-v
--verbose log more than default
This will produce more log, to see what the program
does (more like debugging info).
-f FILE
--config FILE the configuration file to use, the default is:
${CONFIG_FILE}
-i
--recheck Each ipset has a hardcoded refresh frequency.
When we check if it has been updated on the server
we may find that it has not.
update-ipsets.sh will then attempt to re-check
in half the original frequency.
When this option is given, update-ipsets.sh will
ignore that it has checked it before and attempt
to download all ipsets that have not been updated.
DO NOT ENABLE THIS OPTION WHEN RUNNING VIA CRON.
We have to respect the server resources of the
IP list maintainers' servers!
-g
--push-git In the base directory (default: ${BASE_DIR})
you can setup git (just cd to it and run 'git init').
Once update-ipsets.sh finds a git initialized, it
will automatically commit all ipset and netset files
to it.
This option enables an automatic 'git push' at the
end of all commits.
You have to set it up so that git will not ask for
credentials to do the push (normally this done by
using ssh in the git push URL and configuring the
ssh keys for automatic login - keep in mind that
if update-ipsets is running through cron, the user
that runs it has to have the ssh keys installed).
--enable-all Enable all the ipsets at once
This will also execute an update on them
-r
--rebuild Will re-process all ipsets, even the ones that have
not been updated.
This is required in cases of program updates that
need to trigger a full refresh of the generated
metadata (it only affects the web site).
--cleanup Will cleanup obsolete ipsets that are not
available anymore.
run ipset1 ipset2 ...
Will only process the given ipsets.
This parameter must be the last in command line, it
assumes all parameters after the keyword 'run' are
ipsets names.
EOFUSAGE
}
while [ ! -z "${1}" ]
do
case "${1}" in
enable)
shift
LISTS_TO_ENABLE=("${@}")
break
;;
run)
shift
while [ ! -z "${1}" ]
do
RUN_ONLY_THESE_IPSETS[${1}]="${1}"
shift
done
break
;;
--cleanup) CLEANUP_OLD=1;;
--rebuild|-r) FORCE_WEB_REBUILD=1;;
--reprocess|-p) REPROCESS_ALL=1;;
--silent|-s) SILENT=1;;
--push-git|-g) PUSH_TO_GIT=1;;
--recheck|-i) IGNORE_LASTCHECKED=1;;
--compare|-c) ;; # obsolete
--verbose|-v) VERBOSE=1;;
--config|-f) CONFIG_FILE="${2}"; shift ;;
--enable-all) ENABLE_ALL=1;;
--help|-h) usage; exit 1 ;;
*) error "Unknown command line argument '${1}'".; exit 1 ;;
esac
shift
done
if [ -f "${CONFIG_FILE}" ]
then
info "Loading configuration from ${CONFIG_FILE}"
source "${CONFIG_FILE}"
fi
# -----------------------------------------------------------------------------
# FIX DIRECTORIES
if [ -z "${BASE_DIR}" ]
then
error "BASE_DIR is unset. Set it in '${CONFIG_FILE}'."
exit 1
fi
if [ -z "${RUN_PARENT_DIR}" ]
then
error "RUN_PARENT_DIR is unset. Set it in '${CONFIG_FILE}'."
exit 1
fi
if [ ! -d "${RUN_PARENT_DIR}" ]
then
error "RUN_PARENT_DIR='${RUN_PARENT_DIR}' does not exist. Set it in '${CONFIG_FILE}'."
exit 1
fi
if [ -z "${LIB_DIR}" ]
then
error "LIB_DIR is unset. Probably you empty it in '${CONFIG_FILE}'. Please leave it set."
exit 1
fi
if [ -z "${CACHE_DIR}" ]
then
error "CACHE_DIR is unset. Probably you empty it in '${CONFIG_FILE}'. Please leave it set."
exit 1
fi
if [ -z "${TMP_DIR}" ]
then
error "TMP_DIR is unset. Set it in '${CONFIG_FILE}'."
exit 1
fi
if [ ! -d "${TMP_DIR}" ]
then
error "TMP_DIR='${TMP_DIR}' does not exist. Set it in '${CONFIG_FILE}'."
exit 1
fi
if [ -z "${WEB_DIR}" ]
then
WEB_DIR=
elif [ ! -d "${WEB_DIR}" ]
then
warning "WEB_DIR='${WEB_DIR}' is invalid. Disabling web site updates. Set WEB_DIR in '${CONFIG_FILE}' to enable it."
WEB_DIR=
fi
for d in "${BASE_DIR}" "${HISTORY_DIR}" "${ERRORS_DIR}" "${CACHE_DIR}" "${LIB_DIR}"
do
[ -z "${d}" -o -d "${d}" ] && continue
$MKDIR_CMD -p "${d}" || exit 1
info "Created directory '${d}'."
done
cd "${BASE_DIR}" || exit 1
# -----------------------------------------------------------------------------
# if we are just enabling ipsets
if [ "${#LISTS_TO_ENABLE[@]}" -gt 0 ]
then
for x in "${LISTS_TO_ENABLE[@]}"
do
if [ -f "${BASE_DIR}/${x}.source" ]
then
warning "${x}: is already enabled"
else
info "${x}: Enabling ${x}..."
$TOUCH_CMD -t 0001010000 "${BASE_DIR}/${x}.source" || exit 1
fi
done
exit 0
fi
ipset_shall_be_run() {
local ipset="${1}"
if [ ! -f "${BASE_DIR}/${ipset}.source" ]
then
if [ ${ENABLE_ALL} -eq 1 -a -z "${IPSET_TMP_DO_NOT_ENABLE_WITH_ALL[${ipset}]}" ]
then
ipset_silent "${ipset}" "Enabling due to --enable-all option."
$TOUCH_CMD -t 0001010000 "${BASE_DIR}/${ipset}.source" || return 1
else
ipset_disabled "${ipset}"
# cleanup the cache
[ ! -z "${IPSET_CHECKED_DATE[${ipset}]}" ] && cache_remove_ipset "${ipset}"
return 1
fi
fi
if [ ${#RUN_ONLY_THESE_IPSETS[@]} -ne 0 -a -z "${RUN_ONLY_THESE_IPSETS[${ipset}]}" ]
then
ipset_verbose "${ipset}" "skipping - not requested"
return 2
fi
return 0
}
# -----------------------------------------------------------------------------
# Make sure we are the only process doing this job
# to ensure only one runs
UPDATE_IPSETS_LOCK_FILE="${RUN_PARENT_DIR}/update-ipsets.lock"
exlcusive_lock() {
exec 200>"${UPDATE_IPSETS_LOCK_FILE}"
if [ $? -ne 0 ]; then exit; fi
${FLOCK_CMD} -n 200
if [ $? -ne 0 ]
then
echo >&2 "Already running. Try later..."
exit 1
fi
return 0
}
exlcusive_lock
# -----------------------------------------------------------------------------
# CLEANUP
RUN_DIR=$(${MKTEMP_CMD} -d "${TMP_DIR}/update-ipsets-XXXXXXXXXX")
if [ $? -ne 0 ]
then
error "ERROR: Cannot create temporary directory in ${TMP_DIR}."
exit 1
fi
cd "${RUN_DIR}"
PROGRAM_COMPLETED=0
cleanup() {
# make sure the cache is saved
CACHE_SAVE_ENABLED=1
cache_save
cd "${TMP_DIR}"
if [ ! -z "${RUN_DIR}" -a -d "${RUN_DIR}" ]
then
verbose "Cleaning up temporary files in ${RUN_DIR}."
$RM_CMD -rf "${RUN_DIR}"
fi
trap exit EXIT
if [ ${PROGRAM_COMPLETED} -eq 1 ]
then
verbose "Completed successfully."
exit 0
fi
verbose "Completed with errors."
exit 1
}
trap cleanup EXIT
trap cleanup SIGHUP
trap cleanup INT
# -----------------------------------------------------------------------------
# other preparations
if [ ! -d "${BASE_DIR}/.git" -a ${PUSH_TO_GIT} -ne 0 ]
then
info "Git is not initialized in ${BASE_DIR}. Ignoring git support."
PUSH_TO_GIT=0
else
[ -z "${GIT_CMD}" ] && PUSH_TO_GIT=0
fi
[ -d "${BASE_DIR}/.git" -a ! -f "${BASE_DIR}/.gitignore" ] && printf "*.setinfo\n*.source\n" >"${BASE_DIR}/.gitignore"
# -----------------------------------------------------------------------------
# COMMON FUNCTIONS
# echo all the parameters, sorted
params_sort() {
local x=
for x in "${@}"
do
echo "${x}"
done | $SORT_CMD
}
# convert a number of minutes to a human readable text
mins_to_text() {
local days= hours= mins="${1}"
if [ -z "${mins}" -o $[mins + 0] -eq 0 ]
then
echo "none"
return 0
fi
days=$[mins / (24*60)]
mins=$[mins - (days * 24 * 60)]
hours=$[mins / 60]
mins=$[mins - (hours * 60)]
case ${days} in
0) ;;
1) printf "1 day " ;;
*) printf "%d days " ${days} ;;
esac
case ${hours} in
0) ;;
1) printf "1 hour " ;;
*) printf "%d hours " ${hours} ;;
esac
case ${mins} in
0) ;;
1) printf "1 min " ;;
*) printf "%d mins " ${mins} ;;
esac
printf "\n"
return 0
}
declare -A UPDATED_DIRS=()
declare -A UPDATED_SETS=()
git_add_if_not_already_added() {
local file="${1}"
$GIT_CMD -C "${BASE_DIR}" ls-files "${file}" --error-unmatch >/dev/null 2>&1
if [ $? -ne 0 ]
then
[ ! -f "${BASE_DIR}/${file}" ] && $TOUCH_CMD "${BASE_DIR}/${file}"
verbose "Adding '${file}' to git"
$GIT_CMD -C "${BASE_DIR}" add "${file}"
return $?
fi
return 0
}
git_ignore_file() {
local file="${1}"
local found=$($CAT_CMD "${BASE_DIR}/.gitignore" | $GREP_CMD "^${file}$")
if [ -z "${found}" ]
then
echo "${file}" >>"${BASE_DIR}/.gitignore" || return 1
fi
return 0
}
# http://stackoverflow.com/questions/3046436/how-do-you-stop-tracking-a-remote-branch-in-git
# to delete a branch on git
# localy only - remote will not be affected
#
# BRANCH_TO_DELETE_LOCALY_ONLY="master"
# git branch -d -r origin/${BRANCH_TO_DELETE_LOCALY_ONLY}
# git config --unset branch.${BRANCH_TO_DELETE_LOCALY_ONLY}.remote
# git config --unset branch.${BRANCH_TO_DELETE_LOCALY_ONLY}.merge
# git gc --aggressive --prune=all --force
declare -A IPSET_TMP_DO_NOT_REDISTRIBUTE=()
declare -A IPSET_TMP_ACCEPT_EMPTY=()
declare -A IPSET_TMP_NO_IF_MODIFIED_SINCE=()
declare -A IPSET_TMP_DO_NOT_ENABLE_WITH_ALL=()
commit_to_git() {
cd "${BASE_DIR}" || return 1
if [ -d .git -a ! -z "${!UPDATED_SETS[*]}" ]
then
local d=
for d in "${!UPDATED_DIRS[@]}"
do
[ ! -f ${d}/README-EDIT.md ] && $TOUCH_CMD ${d}/README-EDIT.md
(
$CAT_CMD ${d}/README-EDIT.md
echo
echo "The following list was automatically generated on `$DATE_CMD -u`."
echo
echo "The update frequency is the maximum allowed by internal configuration. A list will never be downloaded sooner than the update frequency stated. A list may also not be downloaded, after this frequency expired, if it has not been modified on the server (as reported by HTTP \`IF_MODIFIED_SINCE\` method)."
echo
echo "name|info|type|entries|update|"
echo ":--:|:--:|:--:|:-----:|:----:|"
$CAT_CMD ${d}/*.setinfo
) >${d}/README.md
UPDATED_SETS[${d}/README.md]="${d}/README.md"
git_add_if_not_already_added "${d}/README.md"
done
declare -a to_be_pushed=()
local ipset=
for ipset in "${!UPDATED_SETS[@]}"
do
[ ! -z "${IPSET_TMP_DO_NOT_REDISTRIBUTE[${ipset}]}" ] && continue
[ ! -f "${UPDATED_SETS[${ipset}]}" ] && continue
to_be_pushed=("${to_be_pushed[@]}" "${UPDATED_SETS[${ipset}]}")
done
info "Generating script to fix timestamps..."
(
echo "#!/bin/bash"
echo "[ ! \"\$1\" = \"YES_I_AM_SURE_DO_IT_PLEASE\" ] && echo \"READ ME NOW\" && exit 1"
for d in $(params_sort "${!IPSET_FILE[@]}")
do
echo "[ -f '${IPSET_FILE[${d}]}' ] && $TOUCH_CMD --date=@${IPSET_SOURCE_DATE[${d}]} '${IPSET_FILE[${d}]}'"
done
) | $SED_CMD "s|'${BASE_DIR}/|'|g" >set_file_timestamps.sh
git_add_if_not_already_added set_file_timestamps.sh
echo >&2
info "Committing ${to_be_pushed[@]} to git repository"
local date="$($DATE_CMD -u)"
if [ ${PUSH_TO_GIT_MERGED} -eq 0 ]
then
# we commit each file alone, to have a clear history per file in github
for d in "${to_be_pushed[@]}" set_file_timestamps.sh
do
echo "${d}..."
$GIT_CMD commit ${PUSH_TO_GIT_COMMIT_OPTIONS} "${d}" -m "${date} update"
done
else
# we commit all files together
$GIT_CMD commit ${PUSH_TO_GIT_COMMIT_OPTIONS} "${to_be_pushed[@]}" set_file_timestamps.sh -m "${date} update"
fi
if [ ${PUSH_TO_GIT} -ne 0 ]
then
echo >&2
info "Pushing git commits to remote server"
$GIT_CMD push ${PUSH_TO_GIT_PUSH_OPTIONS}
fi
fi
}
copy_ipsets_to_web() {
[ -z "${WEB_DIR_FOR_IPSETS}" -o ! -d "${WEB_DIR_FOR_IPSETS}" ] && return 0
local ipset= f= d=
for ipset in "${!UPDATED_SETS[@]}"
do
[ ! -z "${IPSET_TMP_DO_NOT_REDISTRIBUTE[${ipset}]}" ] && continue
[ ! -f "${UPDATED_SETS[${ipset}]}" ] && continue
# relative filename - may include a dir
f="${UPDATED_SETS[${ipset}]}"
d="${f/\/*/}"
[ "${d}" = "${f}" ] && d=
if [ ! -z "${d}" ]
then
echo >&2 "Creating directory ${WEB_DIR_FOR_IPSETS}/${d}"
${MKDIR_CMD} -p "${WEB_DIR_FOR_IPSETS}/${d}"
[ ! -z "${WEB_OWNER}" ] && ${CHOWN_CMD} "${WEB_OWNER}" "${WEB_DIR_FOR_IPSETS}/${d}"
fi
echo >&2 "Copying ${f} to ${WEB_DIR_FOR_IPSETS}/${f}"
${CP_CMD} "${f}" "${WEB_DIR_FOR_IPSETS}/${f}.new"
[ ! -z "${WEB_OWNER}" ] && ${CHOWN_CMD} "${WEB_OWNER}" "${WEB_DIR_FOR_IPSETS}/${f}.new"
${MV_CMD} "${WEB_DIR_FOR_IPSETS}/${f}.new" "${WEB_DIR_FOR_IPSETS}/${f}"
done
}
# touch a file to a relative date in the past
touch_in_the_past() {
local mins_ago="${1}" file="${2}"
local now=$($DATE_CMD +%s)
local date=$($DATE_CMD -d @$[now - (mins_ago * 60)] +"%y%m%d%H%M.%S")
$TOUCH_CMD -t "${date}" "${file}"
}
touch_in_the_past $[7 * 24 * 60] "${RUN_DIR}/.warn_if_last_downloaded_before_this"
# get all the active ipsets in the system
ipset_list_names() {
if [ ${IPSETS_APPLY} -eq 1 ]
then
( $IPSET_CMD --list -t || $IPSET_CMD --list ) | $GREP_CMD "^Name: " | $CUT_CMD -d ' ' -f 2
return $?
fi
return 0
}
echo
echo "`$DATE_CMD`: ${0} ${*}"
echo
if [ ${IPSETS_APPLY} -eq 1 ]
then
# find the active ipsets
info "Getting list of active ipsets..."
declare -A sets=()
for x in $(ipset_list_names)
do
sets[$x]=1
done
silent "Found these ipsets active: ${!sets[@]}"
fi
# -----------------------------------------------------------------------------
# check if a file is too old
check_file_too_old() {
local ipset="${1}" file="${2}"
if [ -f "${file}" -a "${RUN_DIR}/.warn_if_last_downloaded_before_this" -nt "${file}" ]
then
ipset_warning "${ipset}" "DATA ARE TOO OLD!"
return 1
fi
return 0
}
history_keep() {
local ipset="${1}" file="${2}" slot=
slot="`$DATE_CMD -r "${file}" +%s`.set"
if [ ! -d "${HISTORY_DIR}/${ipset}" ]
then
$MKDIR_CMD "${HISTORY_DIR}/${ipset}" || return 2
$CHMOD_CMD 700 "${HISTORY_DIR}/${ipset}"
fi
# copy the new file to the history
# we use the binary format of iprange for fast operations later
$IPRANGE_CMD "${file}" --print-binary >"${HISTORY_DIR}/${ipset}/${slot}"
$TOUCH_CMD -r "${file}" "${HISTORY_DIR}/${ipset}/${slot}"
}
history_cleanup() {
local ipset="${1}" mins="${2}"
# touch a reference file
touch_in_the_past ${mins} "${RUN_DIR}/history.reference" || return 3
for x in ${HISTORY_DIR}/${ipset}/*.set
do
if [ ! "${x}" -nt "${RUN_DIR}/history.reference" ]
then
ipset_verbose "${ipset}" "deleting history file '${x}'"
$RM_CMD "${x}"
fi
done
}
history_get() {
local ipset="${1}" mins="${2}" \
tmp= x=
# touch a reference file
touch_in_the_past ${mins} "${RUN_DIR}/history.reference" || return 3
# get all the history files, that are newer than our reference
${IPRANGE_CMD} --union-all $($FIND_CMD "${HISTORY_DIR}/${ipset}"/*.set -newer "${RUN_DIR}/history.reference")
$RM_CMD "${RUN_DIR}/history.reference"
return 0
}