-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathddos.sh
executable file
·617 lines (519 loc) · 16 KB
/
ddos.sh
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
#!/bin/bash
##############################################################################
# DDoS-Deflate version 0.8 Author: Zaf <[email protected]> #
##############################################################################
# Contributors: #
# Jefferson González <[email protected]> #
##############################################################################
# This program is distributed under the "Artistic License" Agreement #
# #
# The LICENSE file is located in the same directory as this program. Please #
# read the LICENSE file before you make copies or distribute this program #
##############################################################################
#set -x
# Download variables for exclude: trustet network ips, search systems ips, FTP ips and allowed ports
#------------------------------------------------------------------------------------------
load_exclude_vars()
{
EX_VAR="/root/scripts/exclude_variables.conf"
if [ -f "$EX_VAR" ] && [ ! "$EX_VAR" == "" ]; then
source $EX_VAR
else
head
echo "\$EX_VAR not found."
exit 113
fi
}
# Create iptables chain for ddos-deflate
#------------------------------------------------------------------------------------------
load_create_iptables_chain()
{
iptables -nv -L ddos-deflate > /dev/null 2>&1
if [ $? -ne 0 ] # if not equal, not success
then
iptables -N ddos-deflate
fi
iptables -nv -L ddos-deflate | grep RETURN > /dev/null 2>&1
if [ $? -ne 0 ] # if not equal, not success
then
iptables -A ddos-deflate -j RETURN
fi
iptables -nv -L INPUT | grep ddos-deflate > /dev/null 2>&1
if [ $? -ne 0 ] # if not equal, not success
then
iptables -I INPUT 1 -j ddos-deflate
fi
}
################################################################################################
CONF_PATH="/etc/ddos"
CONF_PATH="${CONF_PATH}/"
# Other variables
BANS_IP_LIST="/var/lib/ddos/bans.list"
SERVER_IP_LIST=`ifconfig | grep "inet " | awk '{print $2}' | sed "s/addr://g" | xargs | sed -e 's/ /|/g'`
load_conf()
{
CONF="${CONF_PATH}ddos.conf"
if [ -f "$CONF" ] && [ ! "$CONF" == "" ]; then
source $CONF
else
head
echo "\$CONF not found."
exit 1
fi
}
head()
{
echo "DDoS-Deflate version 0.8"
echo "Copyright (C) 2005, Zaf <[email protected]>"
echo
}
showhelp()
{
head
echo 'Usage: ddos [OPTIONS] [N]'
echo 'N : number of tcp/udp connections (default 150)'
echo
echo 'OPTIONS:'
echo '-h | --help: Show this help screen'
echo '-c | --cron: Create cron job to run this script regularly (default 1 mins)'
echo '-i | --ignore-list: List whitelisted ip addresses'
echo '-d | --start: Initialize a daemon to monitor connections'
echo '-s | --stop: Stop the daemon'
echo '-t | --status: Show status of daemon and pid if currently running'
echo '-v | --view: Display active connections to the server'
echo '-k | --kill: Block all ip addresses making more than N connections'
}
# Check if super user is executing the
# script and exit with message if not.
su_required()
{
user_id=`id -u`
if [ "$user_id" != "0" ]; then
echo "You need super user priviliges for this."
exit
fi
}
log_msg()
{
if [ ! -e /var/log/ddos.log ]; then
touch /var/log/ddos.log
chmod 0640 /var/log/ddos.log
fi
echo "$(date +'[%Y-%m-%d %T]') $1" >> /var/log/ddos.log
}
# Gets a list of ip address to ignore with hostnames on the
# ignore.host.list resolved to ip numbers
# param1 can be set to 1 to also include the bans list
ignore_list()
{
for the_host in $(grep -v "#" "${CONF_PATH}${IGNORE_HOST_LIST}"); do
host_ip=`nslookup $the_host | tail -n +3 | grep "Address" | awk '{print $2}'`
# In case an ip is given instead of hostname
# in the ignore.hosts.list file
if [ "$host_ip" = "" ]; then
echo $the_host
else
for ips in $host_ip; do
echo $ips
done
fi
done
# Get ip's of ethernet interfaces to prevent blocking it self.
#for iface_ip in $(ifconfig | grep "inet " | awk '{print $2}' | sed "s/addr://g"); do
# echo $iface_ip
#done
grep -v "#" "${CONF_PATH}${IGNORE_IP_LIST}"
# Add to ignore list my custom trusted ips from files
if [ -f /root/scripts/joomla_admins.conf ]
then
grep -v "#" /root/scripts/joomla_admins.conf
fi
if [ -f /root/scripts/search_system_ip.conf ]
then
grep -v "#" /root/scripts/search_system_ip.conf
fi
if [ "$1" = "1" ]; then
cut -d" " -f2 "${BANS_IP_LIST}"
fi
}
# Unbans ip's after the amount of time given on BAN_PERIOD
unban_ip_list()
{
current_unban_time=`date +"%s"`
while read line; do
if [ "$line" = "" ]; then
continue
fi
ban_time=`echo "$line" | cut -d" " -f1`
ip=`echo "$line" | cut -d" " -f2`
connections=`echo "$line" | cut -d" " -f3`
if [ $current_unban_time -gt $ban_time ]; then
if [ "$FIREWALL" = "apf" ]; then
$APF -u "$ip"
elif [ "$FIREWALL" = "csf" ]; then
$CSF -dr "$ip"
elif [ "$FIREWALL" = "iptables" ]; then
$IPT -D ddos-deflate -s "$ip" -j DROP
fi
log_msg "unbanned $ip"
# remove the ip from the bans list
grep -v "$ip" "${BANS_IP_LIST}" > "${BANS_IP_LIST}.tmp"
rm "${BANS_IP_LIST}"
mv "${BANS_IP_LIST}.tmp" "${BANS_IP_LIST}"
fi
done < $BANS_IP_LIST
}
add_to_cron()
{
su_required
rm -f $CRON
if [ $FREQ -le 2 ]; then
echo "0-59/$FREQ * * * * root $SBINDIR/ddos -k >/dev/null 2>&1" > $CRON
else
let "START_MINUTE = $RANDOM % ($FREQ - 1)"
let "START_MINUTE = $START_MINUTE + 1"
let "END_MINUTE = 60 - $FREQ + $START_MINUTE"
echo "$START_MINUTE-$END_MINUTE/$FREQ * * * * root $SBINDIR/ddos -k >/dev/null 2>&1" > $CRON
fi
chmod 644 $CRON
log_msg "added cron job"
}
# Check active connections and ban if neccessary.
check_connections()
{
su_required
TMP_PREFIX='/tmp/ddos'
TMP_FILE="mktemp $TMP_PREFIX.XXXXXXXX"
BAD_IP_LIST=`$TMP_FILE`
# Original command to get ip's
#netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr > $BAD_IP_LIST
# Improved command
netstat -ntu | \
# Strip netstat heading
tail -n +3 | \
# Match only the given connection states
grep -E "$CONN_STATES" | \
# Extract only the fourth and fifth column
awk '{print $4" "$5}' | \
# Exclude connections to some FTP ports
grep -vE "$PUREFTP" | \
# Extract only the second column
awk '{print $2}' | \
# Exclude some trusted ips from external file
grep -vE "$EXCLUDE" | \
# Strip port without affecting ipv6 addresses (experimental)
sed "s/:[0-9+]*$//g" | \
# Ignore Server IP
sed -r "/($SERVER_IP_LIST)/Id" | \
# Sort addresses for uniq to work correctly
sort | \
# Group same occurrences of ip and prepend amount of occurences found
uniq -c | \
# Numerical sort in reverse order
sort -nr | \
# Replace ::fff: String on ip
sed 's/::ffff://g' | \
# Only store connections that exceed max allowed
awk "{ if (\$1 >= $NO_OF_CONNECTIONS) print; }" > \
$BAD_IP_LIST
FOUND=$(cat $BAD_IP_LIST)
if [ "$FOUND" = "" ]; then
rm -f $BAD_IP_LIST
if [ $KILL -eq 1 ]; then
echo "No connections exceeding max allowed."
fi
return 0
fi
if [ $KILL -eq 1 ]; then
echo "List of connections that exceed max allowed"
echo "==========================================="
cat $BAD_IP_LIST
fi
BANNED_IP_MAIL=`$TMP_FILE`
BANNED_IP_LIST=`$TMP_FILE`
echo "Banned the following ip addresses on `date`" > $BANNED_IP_MAIL
echo >> $BANNED_IP_MAIL
IP_BAN_NOW=0
while read line; do
CURR_LINE_CONN=$(echo $line | cut -d" " -f1)
CURR_LINE_IP=$(echo $line | cut -d" " -f2)
IGNORE_BAN=`ignore_list "1" | grep -c $CURR_LINE_IP`
if [ $IGNORE_BAN -ge 1 ]; then
continue
fi
IP_BAN_NOW=1
echo "$CURR_LINE_IP with $CURR_LINE_CONN connections" >> $BANNED_IP_MAIL
echo $CURR_LINE_IP >> $BANNED_IP_LIST
current_time=`date +"%s"`
echo "$(($current_time+$BAN_PERIOD)) ${CURR_LINE_IP} ${CURR_LINE_CONN}" >> "${BANS_IP_LIST}"
# execute tcpkill for 60 seconds
timeout -k 60 -s 9 60 \
tcpkill -9 host $CURR_LINE_IP > /dev/null 2>&1 &
if [ "$FIREWALL" = "apf" ]; then
$APF -d $CURR_LINE_IP
elif [ "$FIREWALL" = "csf" ]; then
$CSF -d $CURR_LINE_IP
elif [ "$FIREWALL" = "iptables" ]; then
load_create_iptables_chain
$IPT -I ddos-deflate -s $CURR_LINE_IP -j DROP
fi
log_msg "banned $CURR_LINE_IP with $CURR_LINE_CONN connections for ban period $BAN_PERIOD"
done < $BAD_IP_LIST
if [ $IP_BAN_NOW -eq 1 ]; then
if [ -n "$EMAIL_TO" ]; then
dt=`date +%d-%m-%Y_%H:%M:%S`
cat $BANNED_IP_MAIL | mail -s "IP addresses banned on $HOSTNAME $dt" $EMAIL_TO
fi
if [ $KILL -eq 1 ]; then
echo "==========================================="
echo "Banned IP addresses:"
echo "==========================================="
cat $BANNED_IP_LIST
fi
fi
rm -f $TMP_PREFIX.*
}
# Active connections to server.
view_connections()
{
netstat -ntu | \
# Strip netstat heading
tail -n +3 | \
# Match only the given connection states
grep -E "$CONN_STATES" | \
# Extract only the fourth and fifth column
awk '{print $4" "$5}' | \
# Exclude connections to some FTP ports
grep -vE "$PUREFTP" | \
# Extract only the second column
awk '{print $2}' | \
# Exclude some trusted ips from external file
grep -vE "$EXCLUDE" | \
# Strip port without affecting ipv6 addresses (experimental)
sed "s/:[0-9+]*$//g" | \
# Ignore Server IP
sed -r "/($SERVER_IP_LIST)/Id" | \
# Sort addresses for uniq to work correctly
sort | \
# Group same occurrences of ip and prepend amount of occurences found
uniq -c | \
# Numerical sort in reverse order
sort -nr | \
# Replace ::fff: String on ip
sed 's/::ffff://g'
}
# Executed as a cleanup function when the daemon is stopped
on_daemon_exit()
{
if [ -e /var/run/ddos.pid ]; then
rm -f /var/run/ddos.pid
fi
exit 0
}
# Return the current process id of the daemon or 0 if not running
daemon_pid()
{
if [ -e /var/run/ddos.pid ]; then
echo $(cat /var/run/ddos.pid)
return
fi
echo "0"
}
# Check if daemon is running.
# Outputs 1 if running 0 if not.
daemon_running()
{
if [ -e /var/run/ddos.pid ]; then
running_pid=$(ps -A | grep ddos | awk '{print $1}')
if [ "$running_pid" != "" ]; then
current_pid=$(daemon_pid)
for pid_num in $running_pid; do
if [ "$current_pid" = "$pid_num" ]; then
echo "1"
return
fi
done
fi
fi
echo "0"
}
start_daemon()
{
su_required
if [ $(daemon_running) = "1" ]; then
echo "ddos daemon is already running..."
exit 0
fi
echo "starting ddos daemon..."
if [ ! -e "$BANS_IP_LIST" ]; then
touch "${BANS_IP_LIST}"
fi
nohup $0 -l > /dev/null 2>&1 &
log_msg "daemon started"
}
stop_daemon()
{
su_required
if [ $(daemon_running) = "0" ]; then
echo "ddos daemon is not running..."
exit 0
fi
echo "stopping ddos daemon..."
kill $(daemon_pid)
while [ -e /var/run/ddos.pid ]; do
continue
done
log_msg "daemon stopped"
}
daemon_loop()
{
su_required
if [ $(daemon_running) = "1" ]; then
exit 0
fi
echo "$$" > /var/run/ddos.pid
trap 'on_daemon_exit' INT
trap 'on_daemon_exit' QUIT
trap 'on_daemon_exit' TERM
trap 'on_daemon_exit' EXIT
detect_firewall
# run unban_ip_list after 2 minutes of initialization
ban_check_timer=`date +"%s"`
ban_check_timer=$(($ban_check_timer+120))
while true; do
check_connections
# unban expired ip's every 1 minute
current_loop_time=`date +"%s"`
if [ $current_loop_time -gt $ban_check_timer ]; then
unban_ip_list
ban_check_timer=`date +"%s"`
ban_check_timer=$(($ban_check_timer+60))
fi
sleep $DAEMON_FREQ
done
}
daemon_status()
{
current_pid=$(daemon_pid)
if [ $(daemon_running) = "1" ]; then
echo "ddos status: running with pid $current_pid"
else
echo "ddos status: not running"
fi
}
detect_firewall()
{
if [ "$FIREWALL" = "auto" ] || [ "$FIREWALL" = "" ]; then
apf_where=`whereis apf`;
csf_where=`whereis csf`;
ipt_where=`whereis iptables`;
if [ -e "$APF" ]; then
FIREWALL="apf"
elif [ -e "$CSF" ]; then
FIREWALL="csf"
elif [ -e "$IPT" ]; then
FIREWALL="iptables"
elif [ "$apf_where" != "apf:" ]; then
FIREWALL="apf"
APF="apf"
elif [ "$csf_where" != "csf:" ]; then
FIREWALL="csf"
CSF="csf"
elif [ "$ipt_where" != "iptables:" ]; then
FIREWALL="iptables"
IPT="iptables"
else
echo "error: No valid firewall found."
log_msg "error: no valid firewall found"
exit 1
fi
fi
}
# Set Default settings
PROGDIR="/usr/local/ddos"
SBINDIR="/usr/local/sbin"
PROG="$PROGDIR/ddos.sh"
IGNORE_IP_LIST="ignore.ip.list"
IGNORE_HOST_LIST="ignore.host.list"
CRON="/etc/cron.d/ddos"
APF="/usr/sbin/apf"
CSF="/usr/sbin/csf"
IPT="/sbin/iptables"
FREQ=1
DAEMON_FREQ=5
NO_OF_CONNECTIONS=150
FIREWALL="auto"
EMAIL_TO="root"
BAN_PERIOD=600
CONN_STATES="ESTABLISHED|SYN_SENT|SYN_RECV|FIN_WAIT1|FIN_WAIT2|TIME_WAIT|CLOSE_WAIT|LAST_ACK|CLOSING"
# Load custom settings
load_conf
load_exclude_vars
PUREFTP=$(ifconfig | grep "inet " | awk '{print $2 ":'$FTP_PORTS'"}' | grep -v "127.0.0.1" | sed "s/addr://g" | xargs | sed -e 's/ /|/g')
KILL=0
while [ $1 ]; do
case $1 in
'-h' | '--help' | '?' )
showhelp
exit
;;
'--cron' | '-c' )
add_to_cron
exit
;;
'--ignore-list' | '-i' )
echo "List of currently whitelisted ip's."
echo "==================================="
ignore_list
exit
;;
'--bans-list' | '-b' )
echo "List of currently banned ip's."
echo "==================================="
if [ -e "${BANS_IP_LIST}" ]; then
cat "${BANS_IP_LIST}"
fi
exit
;;
'--start' | '-d' )
start_daemon
exit
;;
'--stop' | '-s' )
stop_daemon
exit
;;
'--status' | '-t' )
daemon_status
exit
;;
'--loop' | '-l' )
# start daemon loop, used internally by --start | -s
daemon_loop
exit
;;
'--view' | '-v' )
view_connections
exit
;;
'--kill' | '-k' )
su_required
KILL=1
;;
*[0-9]* )
NO_OF_CONNECTIONS=$1
;;
* )
showhelp
exit
;;
esac
shift
done
if [ $KILL -eq 1 ]; then
detect_firewall
check_connections
else
showhelp
fi
exit 0