-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcommon_functions
887 lines (783 loc) · 28 KB
/
common_functions
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
#! /usr/bin/env bash
#
# Description: common_functions
# Author: Steve Stonebraker
# useage:
# readonly ourPath="$(dirname $0)"
# readonly commonFunctions="$ourPath/common_functions"
# if [ ! -e "$commonFunctions" ]; then
# echo "common_functions not found... downloading"
# cd $ourPath
# curl -s -O "https://raw.github.com/ssstonebraker/braker-scripts/master/common_functions"
# fi
#
# if [ -e "$commonFunctions" ]; then
# source "$commonFunctions"
# print_good "loaded commonFunctions file"
# else
# echo "common_functions not found... exiting"
# exit 1;
# fi
####################################
# Exit if program echo does not exist (this allows us to do one line if statements)
[ ! -x "$(which echo)" ] && exit 1
########################################
# pretty printing functions
function print_status { echo -e "\x1B[01;34m[*]\x1B[0m $1"; }
function print_good { echo -e "\x1B[01;32m[*]\x1B[0m $1"; }
function print_error { echo -e "\x1B[01;31m[*]\x1B[0m $1"; }
function print_notification { echo -e "\x1B[01;33m[*]\x1B[0m $1"; }
function printline { hr=-------------------------------------------------------------------------------------------------------------------------------
printf '%s\n' "${hr:0:${COLUMNS:-$(tput cols)}}"
}
####################################
# print message and exit program
function die { print_error "$1" >&2;exit 1; }
########################################
#Make sure only root can run our script
function proceed_if_root { if [[ $EUID -ne 0 ]]; then die "This script must be run as root"; fi }
########################################
# Install a list of packages on debian or redhat as appropriate
function install_packages {
if which dpkg &> /dev/null; then
apt-get update
apt-get -y install $@
elif which rpm &> /dev/null; then
yum install -y $@
else
echo "No package manager found."
fi
}
########################################
#
function apache_tune {
# Tunes Apache's memory to use the percentage of RAM you specify, defaulting to 40%
# $1 - the percent of system memory to allocate towards Apache
if [ ! -n "$1" ];
then PERCENT=40
else PERCENT="$1"
fi
PERPROCMEM=$(ps aux | grep 'apache2' | awk '{print $6/1024;}' | awk '{avg += ($1 - avg) / NR;} END {print avg;}' OFMT="%3.0f") # the amount of memory in MB each apache process is likely to utilize
MEM=$(grep MemTotal /proc/meminfo | awk '{ print int($2/1024) }') # how much memory in MB this system has
MAXCLIENTS=$((MEM*PERCENT/100/PERPROCMEM)) # calculate MaxClients
MAXCLIENTS=${MAXCLIENTS/.*} # cast to an integer
sed -i -e "s/\(^[ \t]*MaxClients[ \t]*\)[0-9]*/\1$MAXCLIENTS/" /etc/apache2/apache2.conf
apachectl restart
}
########################################
########################################
# show progress bar
# usage: in a loop use it like this
# showbar $<counter variable> $<total iterations>
function showbar {
percDone=$(echo 'scale=2;'$1/$2*100 | bc)
barLen=$(echo ${percDone%'.00'})
bar=''
fills=''
for (( b=0; b<$barLen; b++ ))
do
bar=$bar"="
done
blankSpaces=$(echo $((100-$barLen)))
for (( f=0; f<$blankSpaces; f++ ))
do
fills=$fills"_"
done
clear
echo '['$bar'>'$fills'] - '$barLen'% - count/total ('$1'/'$2')'
}
#function whatPackageProvides() {
# apt-get install apt-file
# apt-file update
# distro=$(get_distro)
# if [ "$distro" = "ubuntu" ]; then
# which apt-file >/dev/null || { apt-get install -y apt-file; apt-file update; }
# unset i; IFS=$'\x0a'; select i in $( apt-file search "/$@" ); do
# test -n "$i" || break; apt-get install "${i%% *}"; done
# elif [ "$distro" = "redhat" ]
# #to do
# return 1
# fi
#}
#######################################
function checkProgramIsInEnvironment
{
if [ ! -x "$(which $1)" ]; then
print_status "installing package ${1}"
apt-get install -y ${1} &> /dev/null
if [ $? -eq 0 ]; then
print_good "Packages successfully installed."
else
print_error "Packages failed to install!"
exit 1
fi
else
print_status "package ${1} present"
fi
}
#Find out which debian package a command (executable) belongs to on debian-based distros
function whichpkg() { readlink -f "$(which $1)" | xargs --no-run-if-empty dpkg -S; }
########################################
function install_packages_ipset_s3cmd()
{
programs=(s3cmd ipset)
for program in "${programs[@]}"; do
checkProgramIsInEnvironment "$program"
done
}
########################################
function shredFile
{
if [ -f "$1" ]; then
print_status "Shredding ${1}"
shred -u ${1}
if [ $? -eq 0 ]; then
print_good "${1} shredded"
else
print_error "${1} failed to shred!"
fi
else
print_error "Unable to shred ${1}, file does not exist!"
fi
}
########################################
function replaceText
{
sed -i "s|${1}|${2}|g" "${3}"
}
########################################
# Returns 0 if list contains item
#
listcontains() {
for word in $1; do
[[ $word = $2 ]] && return 0
done
return 1
}
########################################
listcontains_SampleUsage () {
#FIND OUT fruit TYPE
#Define list of valid Fruits
list="apple orange grape pineapple"
#Loop until user provides valid value in list
while true; do
print_status "Determine fruit"
print_notification "Please enter one of these fruits \nValid Responses: [apple, orange, grape, pineapple]"
read -p "fruit type: " FRUIT_TYPE
echo ""
#Check if user's response matches our list of fruit types
if listcontains "$list" ${FRUIT_TYPE}; then
print_good "Valid fruit Choice: ${FRUIT_TYPE}"
export FRUIT_TYPE
echo "do something else in the code here if you want"
break
else
print_error "Invalid fruit Type. Please try again."
continue
fi
done
return 0
}
########################################
restart_service_mem_ge_x () {
#
# Description:Restart service if memory usage is greater than x
# usage: restart_service_mem_ge_x process_name max_size
#
# Example: restart_service_mem_ge_x httpd 1024 (restart httpd if using more than 1024MB of memory
process_name=$1
max_size=$2
start_service_command="$3"
actual_size=$( /bin/ps aux | /usr/bin/awk "/$process_name/"'{total+=$6}END{print total/1024}' | /usr/bin/awk '{printf "%.0f\n", $1}' )
if [ $actual_size -ge $max_size ] ; then
/bin/echo "${process_name} is currently using ${actual_size}MB, which is greater than or equal to ${max_size}MB"
/usr/bin/pkill ${process_name}
$start_service_command
else
/bin/echo "${process_name} is currently using ${actual_size}MB, which is less than ${max_size}MB maximum value"
fi
}
#########################################################################
# if directory exists remove it
function delete_dir_if_exist {
[ -d $1 ] && rm --preserve-root -rf $1
}
#########################################################################
# if directory exists remove contents and recreate
function delete_dir_contents_if_exist {
[ -d $1 ] && print_status "found dir $1, removing contents"
[ -d $1 ] && rm --preserve-root -rf $1
mkdir -p $1 || die "unable to create directory $1"
}
########################################
require_not_empty()
{
for var in $@; do
eval x="\$$var"
if [ -z "$x" ]; then
echo "$var not set"
exit 1
fi
done
}
require_dir()
{
for var in $@; do
eval x="\$$var"
if [ ! -d "$x" ]; then
echo "$var [$x]: directory not found"
exit 1
fi
done
}
require_exist()
{
for var in $@; do
eval x="\$$var"
if [ ! -e "$x" ]; then
echo "$var [$x]: not found"
exit 1
fi
done
}
##############
# Get Current Distro
# return value of current distro
# example usage:
# distro=$(get_distro)
# if [ "$distro" = "ubuntu" ]; then
# db_stop || true
# fi
get_distro()
{
local out=$(lsb_release -is 2> /dev/null)
case $out in
RedHatEnterpriseServer)
echo "redhat"
;;
CentOS)
echo "redhat"
;;
Ubuntu)
echo "ubuntu"
;;
*)
# RHEL 6.0 did not have lsb_release, for example, and suse depends on qt3, libqt4, mesa, etc.
# So adding lsb to our dependencies is kind of a pain
if [ -e "/etc/redhat-release" ]; then
echo "redhat"
elif [ -e "/etc/SuSE-release" ] ; then
echo "sles"
else
return 1
fi
esac
}
########################################
kill_process_with_name () {
#!/bin/sh
if [[ $1 -eq "" ]]; then
echo "Usage: pkill.sh <process name>"
exit
fi
for id in `ps -axcopid,command | grep -i -e $1 | awk '{ print $1 }'`; do
kill -9 $id
done
}
########################################
# grep for a process
function psg {
FIRST=`echo $1 | sed -e 's/^\(.\).*/\1/'`
REST=`echo $1 | sed -e 's/^.\(.*\)/\1/'`
ps aux | grep "[$FIRST]$REST"
}
########################################
show_zombie_processes () {
ps aux | awk '{ print $8 " " $2 }' | grep -w Z
}
create_zombie_processes () {
time=${1:-60}
sleep 1 &
exec sleep $time
}
kill_zombie_processes () {
stat=`ps ax | awk '{print $1}' | grep -v "PID" | xargs -n 1 ps lOp | grep -v "UID" | awk '{print"pid: "$3" *** parent_pid: "$4" *** status: "$10" *** process: "$13}' | grep ": Z"`
if ((${#stat} > 0));then
ps ax | awk '{print $1}' | grep -v "PID" | xargs -n 1 ps lOp | grep -v "UID" | awk '{print$4" status:"$10}' | grep "status:Z" | awk '{print $1}' | xargs -n 1 kill -9
echo `date`": killed some zombie proceses!" >> /var/log/zombies.log
fi
}
########################################
#Change hostname on a debian sytem
#ex: system_update_hostname subdomain.example.com
function system_update_hostname {
# system_update_hostname(system hostname)
if [ -z "$1" ]; then
echo "system_update_hostname() requires a hostname as its first argument"
return 1;
fi
#Existing hostname
old_hostname=$(cat /etc/hostname)
#user provided new hostname
new_hostname=$1
#Parse the hostname without any prepending domain
new_hostname_trimmed=$(echo $new_hostname | cut -d "." -f1)
# Make sure new hostname and old hostname are different
old_hostname=$(cat /etc/hostname)
if [ "$new_hostname_trimmed" == "$old_hostname" ]; then
print_error "new hostname and current hostname match!"
return 1
fi
# clean 127.0.0.1 line, removing occurances of current hostname
declare -a localhost_line=(`grep "127.0.0.1" /etc/hosts `);
declare -a old_127_trimmed=( ${localhost_line[@]/$old_hostname*/} )
# if the user didn't provide a FQDN then just append hostname they provided
if [ "$new_hostname" == "$new_hostname_trimmed" ]; then
new_127="${old_127_trimmed[@]} $new_hostname"
# if user provided a FQDN as hostname, append that and hostname
else
new_127="${old_127_trimmed[@]} $new_hostname $new_hostname_trimmed"
fi
# Create new hosts file with our new 127.0.0.1 line first
echo "${new_127}" > hosts.tmp
grep -v "127.0.0.1" /etc/hosts >> hosts.tmp
# Apply the new hosts file
mv hosts.tmp /etc/hosts
# Apply the new hostname
echo "${new_hostname_trimmed}" > /etc/hostname
echo "${new_hostname_trimmed}" > /proc/sys/kernel/hostname
/bin/hostname -F /etc/hostname
/etc/init.d/hostname restart >/dev/null 2>/dev/null
print_good "Hostname Changed: ${new_hostname_trimmed}"
print_good "/etc/hosts Modified: ${new_127}"
print_notification "Logout and then back in to see the new hostname in your bash prompt"
echo -e "\n"
}
########################################
function system_is_link_up () {
#determines if interface is up
iface=$1
ip link show dev ${iface}
if [ "$?" != "0" ]; then
echo "CRITICAL - interface '${iface}' does NOT EXIST!"
exit 2
fi
}
function system_print_ip_for_interface {
# returns the IP assigned to interface passed
# ex: system_print_ip_for_interface eth0
echo $(ifconfig $1 | awk -F: '/inet addr:/ {print $2}' | awk '{ print $1 }')
}
function system_primary_ip {
# returns the primary IP assigned to eth0
echo $(ifconfig eth0 | awk -F: '/inet addr:/ {print $2}' | awk '{ print $1 }')
}
function lower {
# helper function
echo $1 | tr '[:upper:]' '[:lower:]'
}
function system_add_user {
# system_add_user(username, password, groups, shell=/bin/bash)
USERNAME=`lower $1`
PASSWORD=$2
SUDO_GROUP=$3
SHELL=$4
if [ -z "$4" ]; then
SHELL="/bin/bash"
fi
useradd --create-home --shell "$SHELL" --user-group --groups "$SUDO_GROUP" "$USERNAME"
echo "$USERNAME:$PASSWORD" | chpasswd
}
function system_add_system_user {
# system_add_system_user(username, home, shell=/bin/bash)
USERNAME=`lower $1`
HOME_DIR=$2
SHELL=$3
if [ -z "$3" ]; then
SHELL="/bin/bash"
fi
useradd --system --create-home --home-dir "$HOME_DIR" --shell "$SHELL" --user-group $USERNAME
}
function system_lock_user {
# system_lock_user(username)
passwd -l "$1"
}
function system_get_user_home {
# system_get_user_home(username)
cat /etc/passwd | grep "^$1:" | cut --delimiter=":" -f6
}
function system_user_add_ssh_key {
# system_user_add_ssh_key(username, ssh_key)
USERNAME=`lower $1`
USER_HOME=`system_get_user_home "$USERNAME"`
sudo -u "$USERNAME" mkdir "$USER_HOME/.ssh"
sudo -u "$USERNAME" touch "$USER_HOME/.ssh/authorized_keys"
sudo -u "$USERNAME" echo "$2" >> "$USER_HOME/.ssh/authorized_keys"
chmod 0600 "$USER_HOME/.ssh/authorized_keys"
}
function system_sshd_edit_bool {
# system_sshd_edit_bool (param_name, "Yes"|"No")
VALUE=`lower $2`
if [ "$VALUE" == "yes" ] || [ "$VALUE" == "no" ]; then
sed -i "s/^#*\($1\).*/\1 $VALUE/" /etc/ssh/sshd_config
fi
}
function system_sshd_permitrootlogin {
system_sshd_edit_bool "PermitRootLogin" "$1"
}
function system_sshd_passwordauthentication {
system_sshd_edit_bool "PasswordAuthentication" "$1"
}
function system_get_codename {
echo `lsb_release -sc`
}
function system_get_release {
echo `lsb_release -sr`
}
function system_sshd_pubkeyauthentication {
system_sshd_edit_bool "PubkeyAuthentication" "$1"
}
function system_update_locale_en_US_UTF_8 {
# locale-gen en_US.UTF-8
dpkg-reconfigure locales
update-locale LANG=en_US.UTF-8
}
function restart_services {
# restarts upstart services that have a file in /tmp/needs-restart/
for service_name in $(ls /tmp/ | grep restart-* | cut -d- -f2-10); do
service $service_name restart
rm -f /tmp/restart-$service_name
done
}
function restart_initd_services {
# restarts upstart services that have a file in /tmp/needs-restart/
for service_name in $(ls /tmp/ | grep restart_initd-* | cut -d- -f2-10); do
/etc/init.d/$service_name restart
rm -f /tmp/restart_initd-$service_name
done
}
########################################
# Setup directories for a mod_security_installation
function apache_is_module_loaded {
amodule=$1
apachectl -M | grep $1
if [ $? -eq 0 ]; then
print_good "$1 loaded correctly"
else
print_error "$1 failed to load!"
exit 1;
fi
}
########################################
########################################
#Append line to file if doesn't exist
#ex: append_line "Include /opt/modsecurity/etc/modsecurity.conf" /etc/apache2/apache2.conf
function append_line {
string_to_append=$1
somefile=$2
grep -Fxq "$1" "$2"
if [ $? -eq 0 ]; then
print_status "$1 already present in file $2"
else
echo "$1" >> "$2"
print_good "$1 appended to file $2"
fi
}
########################################
#Check for proper ubuntu version
function check_if_ubuntu_12()
{
print_status "OS Version Check."
release=`lsb_release -r|awk '{print $2}'`
if [ $release = "12.04" -o $release = "12.10" -o "13.04" ]
then
print_good "OS is Ubuntu. Good to go."
else
print_notification "This is not Ubuntu 12.04 or 12.10, and has NOT been tested on other platforms."
while true; do
read -p "Continue? (y/n)" warncheck
case $warncheck in
[Yy]* ) break;;
[Nn]* ) print_error "Bailing."; exit;;
* ) print_notification "Please answer yes or no.";;
esac
done
echo " "
fi
}
########################################
# Restart apache if config okay
########################################
function apache_restart {
apachectl -t
if [ "$?" != "0" ]; then
print_error "apache syntax error!"
exit $?
else
apachectl restart
print_status "Apache Restarted"
fi
}
########################################
# Setup directories for a mod_security_installation
function modsecurity_setup_apache_modules {
a2enmod unique_id
cp /usr/local/modsecurity/lib/mod_security2.so /usr/lib/apache2/modules/
chmod 644 /usr/lib/apache2/modules/mod_security2.so
ln -s /usr/lib/x86_64-linux-gnu/libxml2.so /usr/lib/libxml2.so
ln -s /usr/lib/x86_64-linux-gnu/liblua5.1.so /usr/lib/liblua5.1.so
echo -e "# Load libxml2\nLoadFile /usr/lib/libxml2.so" > /etc/apache2/mods-available/security2.load
echo -e "# Load Lua\nLoadFile /usr/lib/liblua5.1.so" >> /etc/apache2/mods-available/security2.load
echo -e "# Finally, load ModSecurity\nLoadModule security2_module /usr/lib/apache2/modules/mod_security2.so" >> /etc/apache2/mods-available/security2.load
a2enmod security2
}
########################################
# Setup directories for a mod_security_installation
function modsecurity_setup_opt_directories {
proceed_if_root
MODSEC_HOME="/opt/modsecurity"
#
# This is the user running the Apache server
#
APACHE_USER="www-data"
APACHE_GROUP="www-data"
DIRS="bin etc var var/audit var/data var/lib var/log var/tmp var/upload"
OWNER_APACHE="$MODSEC_HOME/var/audit $MODSEC_HOME/var/data $MODSEC_HOME/var/tmp $MODSEC_HOME/var/upload"
GROUP_APACHE="$MODSEC_HOME $MODSEC_HOME/var $MODSEC_HOME/var/tmp $MODSEC_HOME/bin"
MODE_750="$MODSEC_HOME $MODSEC_HOME/bin $MODSEC_HOME/var $MODSEC_HOME/var/tmp"
#
# Creating the directory layout
#
for i in $DIRS; do
DIR="$MODSEC_HOME/$i"
echo "Creating $DIR..."
mkdir -p $DIR
chmod 700 $DIR
done
#
# Adjusting ownership...
#
for i in $OWNER_APACHE; do
echo " Changing owner of $i to $APACHE_USER"
chown $APACHE_USER $i
done
#
# Adjusting groups...
#
for i in $GROUP_APACHE; do
echo " Changing group of $i to $APACHE_GROUP"
chgrp $APACHE_GROUP $i
done
#
# Adjust permissions
#
for i in $MODE_750; do
echo "Changing permissions of $i to 750"
chmod 750 $i;
done
printline
print_good "Final Directory Layout"
printline
awk 'BEGIN {printf "%-30s%-9s%-9s%-10s\n","Location","User","Group","Permissions"}'\
;awk 'BEGIN {printf "%-30s%-9s%-9s%-10s\n","--------","----","-----","-----------"}'\
;find /opt/modsecurity/ -printf "%-30p%#-9u%-9g %10M\n" | sort -k1,1
printline
}
########################################
function install_mod_security()
{
# Build modsecurity and install in the current directory
# usage: install_mod_security "2.7.4"
build=`pwd`
cd $build
version_modsec=$1
partial_path_modsec="modsecurity-apache_$version_modsec"
print_status "Downloading modsecurity-apache_$version_modsec"
curl -s -O https://www.modsecurity.org/tarball/$version_modsec/$partial_path_modsec.tar.gz
curl -s -O https://www.modsecurity.org/tarball/$version_modsec/$partial_path_modsec.tar.gz.sha256
sha256sum -c $partial_path_modsec.tar.gz.sha256
if [ $? -eq 0 ]; then
print_good "Valid hash for modsecurity-apache_$version_modse, proceeding...."
else
print_error "Invalid hash!"
exit $?
fi
tar -xzf $partial_path_modsec.tar.gz
cd $partial_path_modsec/
./configure
print_notification "Does the configuration look okay? Do you want to proceed? (note, this is good: is linked with gnutls... no)"
while true; do
read -p "Continue? (y/n)" warncheck
case $warncheck in
[Yy]* ) break;;
[Nn]* ) print_error "Bailing."; exit;;
* ) print_notification "Please answer yes or no.";;
esac
done
echo " "
make
if [ "$?" != "0" ]; then
print_error "make failed!"
exit $?
fi
make install
if [ "$?" != "0" ]; then
print_error "make install failed!"
exit $?
fi
########################################
#Setup directory Layout
modsecurity_setup_opt_directories
########################################
#/bin/cp -f $build/$partial_path_modsec/modsecurity.conf-recommended /opt/modsecurity/etc/main.conf
/bin/cp -f $build/$partial_path_modsec/mlogc/mlogc /opt/modsecurity/bin/mlogc
cat <<EOF > /opt/modsecurity/etc/modsecurity.conf
<IfModule mod_security2.c>
Include /opt/modsecurity/etc/main.conf
Include /opt/modsecurity/etc/rules-first.conf
Include /opt/modsecurity/etc/rules.conf
Include /opt/modsecurity/etc/rules-last.conf
</IfModule>
EOF
#################################################
append_line "Include /opt/modsecurity/etc/modsecurity.conf" /etc/apache2/apache2.conf
touch /opt/modsecurity/etc/rules-first.conf
touch /opt/modsecurity/etc/rules.conf
touch /opt/modsecurity/etc/rules-last.conf
curl -o /opt/modsecurity/etc/main.conf https://raw.github.com/ssstonebraker/braker-scripts/master/working-scripts/modsecurity_conf_files/main.conf
curl -o /opt/modsecurity/etc/mlogc.conf https://raw.github.com/ssstonebraker/braker-scripts/master/working-scripts/modsecurity_conf_files/mlogc.conf
#################################################
#Configure connection to jWall AuditConsole
print_notification "Provide IP address of auditconsole"
read -p "AuditConsoleIP: " AUDIT_CONSOLE_IP
print_notification "Provide Sensor Name"
read -p "Sensor Name: " AUDIT_SENSORNAME
print_notification "Provide Sensor Password"
read -p "Sensor Password: " AUDIT_SENSORPASSWORD
replaceText "IPADDR" ${AUDIT_CONSOLE_IP} /opt/modsecurity/etc/mlogc.conf
replaceText "SENSORNAME" ${AUDIT_SENSORNAME} /opt/modsecurity/etc/mlogc.conf
replaceText "SENSORPASSWORD" ${AUDIT_SENSORPASSWORD} /opt/modsecurity/etc/mlogc.conf
########################################
#Setup directory permissions
modsecurity_setup_opt_directories
#################################################
#setup mod unique and modsecurity apache modules
modsecurity_setup_apache_modules
#################################################
#Test if modules are loaded
apache_is_module_loaded "security2_module"
apache_is_module_loaded "unique_id_module"
apache_restart
}
function install_openjdk6()
{
apt-get purge -y openjdk*
apt-get install openjdk-6-jre-headless
################################################
#Set java enviornment variable
################################################
grep -q 'JAVA_HOME=/usr/lib/jvm/java-6-openjdk-amd64/' /etc/profile \
|| sudo sh -c "echo 'JAVA_HOME=/usr/lib/jvm/java-6-openjdk-amd64/' >> /etc/profile"
export JAVA_HOME=/usr/lib/jvm/java-6-openjdk-amd64/
ln -s /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-openjdk
# source new variables
. /etc/profile
################################################
}
function install_remo() {
apt-get install -y subversion
aptitude install ruby irb libsqlite3-ruby1.8
svn export --force http://svn.berlios.de/svnroot/repos/remo/trunk /opt/remo
mv /opt/remo/remo/* /opt/remo
rm -Rf /opt/remo/remo
cd /opt/remo
ruby script/server &
echo "remo running at http://localhost:3000/main/index"
}
function install_jwall_tools()
{
#This will install jwall-tools (used with mod_security to view rules/logs)
curl -s -O http://download.jwall.org/debian/chris.gpg
apt-key add chris.gpg
append_line "deb http://download.jwall.org/debian/ jwall main" /etc/apt/sources.list
apt-get update
#install audit console
apt-get install -y jwall-tools || print_error "jwall-tools failed to install"
}
function install_mod_security_audit_console()
{
#This will install auditconsole (used with mod_security to view rules/logs)
curl -s -O http://download.jwall.org/debian/chris.gpg
apt-key add chris.gpg
append_line "deb http://download.jwall.org/debian/ jwall main" /etc/apt/sources.list
apt-get update
#install java 6
install_openjdk6
#install audit console
apt-get install -y auditconsole || print_error "auditconsole failed to install"
#start on boot
apt-get install -y chkconfig
ln -s /usr/lib/insserv/insserv /sbin/insserv
chkconfig auditconsole 345
#Download and install MySQL Connnector
current_directory=`pwd`
curl -L 'http://www.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.25.tar.gz/from/http://mysql.he.net/' | \
tar xz && print_good "Downloaded and extracted MySQL Connector" || print_error "Failed to download MySQL Connector"
mysqljar="$current_directory/mysql-connector-java-5.1.25/mysql-connector-java-5.1.25-bin.jar"
if [ -e $mysqljar ]; then
mv $mysqljar /opt/AuditConsole/lib/mysql-connector-java-5.1.25-bin.jar
chown jwall:jwall /opt/AuditConsole/lib/mysql-connector-java-5.1.25-bin.jar
print_status "MySQL Connector Installed"
rm -Rf mysqljar
print_status "Restarting Audit Console"
service auditconsole restart
else
print_error "Failed to install MySQL Connector"
fi
apt-get install -y binutils
wacPassword=`strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 14 | tr -d '\n'; echo`
print_status "DB: AuditConsoleDB"
print_status "user: wacUser"
print_status "pass: $wacPassword"
#We ask the user for the root mysql user's password 3 times, one for each task.
print_notification "The next several steps will need you to enter the mysql root user password."
#1. If the database exists, we blow it away to ensure a clean install.
while true; do
print_notification "Enter the mysql root user password to create the AuditConsole database."
print_notification "If you already have a database named AuditConsoleDB, this WILL drop that database!"
mysql -u root -p -e "drop database if exists AuditConsoleDB; create database if not exists AuditConsoleDB; GRANT ALL ON AuditConsoleDB.* to wacUser@localhost IDENTIFIED BY '$wacPassword'; FLUSH PRIVILEGES; show databases;"
if [ $? != 0 ]; then
print_error "the command did NOT complete successfully. Please see $logfile, confirm the root mysql user password, and try again."
continue
else
print_good "AuditConsoleDB database created!"
break
fi
done
mkdir /home/jwall
chown -R jwall:jwall /home/jwall
install_jwall_tools
echo "config file at: /opt/AuditConsole/conf/AuditConsole.xml"
jwall console-db-check /opt/AuditConsole
}
ipextract ()
{
# example ipextract < filename
egrep --only-matching -E '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
}
cidrextract ()
{
# example cidrextract < filename
grep --only-matching -P '([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$'
}
if [ "$BASH" ]; then
export HISTTIMEFORMAT="%Y-%m-%d_%H:%M:%S "
export PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ; }"'echo "`date +'%y.%m.%d-%H:%M%S:'`" $USER "("$ORIGINAL_USER")" "COMMAND: " "$(history 1 | cut -c8-)" >> /Users/stevestonebraker/log/bash_eternal_history_new'
alias ehistory='cat /Users/stevestonebraker/log/bash_eternal_history_new'
readonly PROMPT_COMMAND
readonly HISTSIZE
readonly HISTFILE
readonly HOME
readonly HISTIGNORE
readonly HISTCONTROL
fi