Archives par mot-clé : Bash

Check DDOS Apache

#!/bin/bash

export LANG="POSIX"

# Get parameters
warning=${1:-"50"}
critical=${2:-"100"}
log_file=${3:-"*access_log"}
pattern=$4

# Get current hour
hour=$(date +%d/%b/%Y:%H -d '1 hours ago')

grep "$hour" /var/log/httpd/${log_file} | awk -v WARNING="${warning}" -v CRITICAL="${critical}" -v pattern="${pattern}" '

$0 ~ pattern {
  counter[$1]++
}

END {
  for (ip in counter) {
    if (counter[ip] > CRITICAL) {
	print "2";
	exit;
    } else if (counter[ip] > WARNING) {
	print "1";
	exit;
    }
  }
  print "0"
}

'

Check faille SSL poodle

#!/bin/bash

host_list="123.123.123.123 233.233.233.666"

port_list="443 993"


for host in $host_list
do
	for port in $port_list
	do
		if [ $(echo quit | timeout 2 openssl s_client -connect $host:$port -ssl3 2>&1 | grep -c 'BEGIN CERTIFICATE') -gt 0 ]
		then
			echo $host:$port : Vulnérable
		fi

	done

	if [ $(echo quit | timeout 2 openssl s_client -starttls ftp -connect $host:21 -ssl3 2>&1 | grep -c 'BEGIN CERTIFICATE') -gt 0 ]
	then
		echo $host:21 : Vulnérable STARTTLS
	fi
	if [ $(echo quit | timeout 2 openssl s_client -starttls smtp -connect $host:25 -ssl3 2>&1 | grep -c 'BEGIN CERTIFICATE') -gt 0 ]
	then
		echo $host:25 : Vulnérable STARTTLS
	fi

	if [ $(echo quit | timeout 2 openssl s_client -starttls smtp -connect $host:465 -ssl3 2>&1 | grep -c 'BEGIN CERTIFICATE') -gt 0 ]
	then
		echo $host:465 : Vulnérable STARTTLS
	fi

	if [ $(echo quit | timeout 2 openssl s_client -starttls smtp -connect $host:587 -ssl3 2>&1 | grep -c 'BEGIN CERTIFICATE') -gt 0 ]
	then
		echo $host:587 : Vulnérable STARTTLS
	fi

	if [ $(echo quit | timeout 2 openssl s_client -starttls imap -connect $host:143 -ssl3 2>&1 | grep -c 'BEGIN CERTIFICATE') -gt 0 ]
	then
		echo $host:143 : Vulnérable STARTTLS
	fi

        if [ $(echo quit | timeout 2 openssl s_client -starttls pop3 -connect $host:110 -ssl3 2>&1 | grep -c 'BEGIN CERTIFICATE') -gt 0 ]
        then
                echo $host:110 : Vulnérable STARTTLS
        fi

        if [ $(echo quit | timeout 2 openssl s_client -starttls xmpp -connect $host:5222 -ssl3 2>&1 | grep -c 'BEGIN CERTIFICATE') -gt 0 ]
        then
                echo $host:5222 : Vulnérable STARTTLS
        fi

done

Script Backup Zimbra

#!/bin/bash

## Autor : infragate
## version 2.0
## tested with zimbra version : 8.7.11.GA.1854.UBUNTU16.64_amd64.deb
## RESTORE mbox
## $ZMBOX -z -m $mbox postRestURL "//?fmt=zip&resolve=reset" $mbox.zip
## mailutils package

## colors

red='\033[0;31m'
RED='\033[1;31m'
green='\033[0;32m'
GREEN='\033[1;32m'
blue='\033[0;34m'
BLUE='\033[1;34m'
purple='\033[0;35m'
PURPLE='\033[1;35m'
cyan='\033[1;36m'
def='\033[0m'

#############
# VARIABLES #
#############
DATE=`date +%Y%m%d`
FQDN=`hostname -f`
ZHOME=/opt/zimbra

ZBACKUP=/backup/$FQDN/$DATE
ZMBOXBACKUP=$ZBACKUP/mailbox

ZCONFD=$ZHOME/conf
ZDUMPDIR=/opt/zimbra/backup
ZMBOX=/opt/zimbra/bin/zmmailbox

### Log & Mail
ZLOG=~/log_backup.txt
TEMP=~/temp.txt
RECEP=yourmail@domain.fr
ATT=~/mail.txt

### OPTS
MAIL_ALERT=1
CIFS_BACKUP=1

#### Exec
SLAPCAT=/opt/zimbra/common/sbin/slapcat
MYSQLDUMP=/opt/zimbra/common/bin/mysqldump

### LDAP
LDAPCONFDIR="/opt/zimbra/data/ldap/config"
LDAPDUMPNAME="zimbra_ldap"

### Mysql
MYSQL_USER="root"
MYSQL_PASSWORD="mJClQWgfgfgfNTAg1YQo3a"
MYSQL_SOCKET="/opt/zimbra/data/tmp/mysql/mysql.sock"
MYSQLDUMPNAME="zimbra_mysql"

### CIFS Backup
USER_SHARE=username
PASS_SHARE="E9????????2"
SHARE_SERVER=0.0.0.0
SHARE_FOLDER=folder_name
MOUNT_POINT=/backup

##############
#SCRIPT USAGE#
##############

ARGS=$(getopt -o a:h -l "action:help" -n "$(basename $0)" -- "$@")

function usage()
{
        echo -e "${GREEN}Usage:\t$(basename $0) [-a mysql | ldap | mbox | all]${def}" >&2
}

#Bad arguments
if [[ $? -ne 0 ]];
then
        echo -e "${RED}Error: unparsable arguments${def}" >&2
        exit 255
fi

eval set -- "${ARGS}"

while true
 do
        case "$1" in
                -a|--action)
                        shift
                        if [ -z "${action}" ]
                        then
                                action="$1"
                        else
                                echo -e "${RED}Error: -a option cannot be used several times.${def}" >&2
                                exit 255
                        fi
                        shift
                        ;;
                -h|--help)
                        shift
                        usage
                        exit
                        ;;
                --)
                        shift
                        break
                        ;;
        esac
done

#####################
##### FUNCTIONS     #
#####################

function log_date()
{
 echo $(date +%d/%m/%Y-%H:%M:%S)
}

####################

function test_dir()
{
 if [ ! -d $1 ]; then mkdir -p $1; fi
}

###################

function lblank()
{
 echo ""  >> $TEMP ;
}

####################

function send_mail()
{
 if [ $MAIL_ALERT = 1 ]
  then
    sed -r "s/\x1B\[([0-9];)?([0-9]{1,2}(;[0-9]{1,2})?)?[m]//g" $TEMP > $ATT ;
    mail -s "Zimbra Backup Report for `hostname` `date +%d/%m/%Y-%H:%M:%S`" $RECEP < $ATT ;
    [ "$?" != 0 ] && exit ;
    rm -rf $ATT ;
 fi
}

####################

function time_computing()
{
 elapsed="$(expr $time_end - $time_start)"
 hours=$(($elapsed / 3600))
 elapsed=$(($elapsed - $hours * 3600))
 minutes=$(($elapsed / 60))
 seconds=$(($elapsed - $minutes * 60))

 echo -e "${cyan}The $1 backup lasted : $hours hours $minutes minutes $seconds seconds ${def}" >> $TEMP ;
 lblank
}
##########################

function mount_cifs()
{
        if [ $CIFS_BACKUP = 1 ]
                then
         echo -e "${BLUE}$(log_date) CIFS BACKUP Method Selected${def}" >> $TEMP ;
         test_dir $MOUNT_POINT
         mount -t cifs \\\\$SHARE_SERVER\\$SHARE_FOLDER $MOUNT_POINT  -o username=$USER_SHARE,password=$PASS_SHARE
         [ "$?" != 0 ] &&  echo -e "${red}CIFS MOUNT : FAILED : BACKUP ABORTED${def}" >> $TEMP && exit ;
    fi
}
#########################

function umount_cifs()
{
        if [ $CIFS_BACKUP = 1 ]
                then
                 cd
                 umount $MOUNT_POINT
                 [ "$?" = 0 ] &&  echo -e "$(log_date) ${green}CIFS Share sucessfully unmounted${def}" >> $TEMP || echo -e "$(log_date) ${red}CIFS Share unmounting : FAILED${def}" >> $TEMP ;
    fi
}
############################

function mailbox_1by1()
{
 lblank
 echo -e "$(log_date)${BLUE} Mbox backup activated${def}" >> $TEMP;

 test_dir $ZBACKUP
 test_dir $ZMBOXBACKUP
 test_dir $ZDUMPDIR

 for mbox in `su - zimbra -c "zmprov -l gaa"`
  do
           echo -ne "$(log_date)${blue} Generating files from backup $mbox ... ${def}" >> $TEMP ;
           su - zimbra -c "$ZMBOX -z -m $mbox getRestURL "//?fmt=zip" > $ZDUMPDIR/$mbox.zip" ;
           ([ "$?" = 0 ] &&  echo -e "${green}DONE${def}" || echo -e "${red}FAILED${def}") >> $TEMP ;

 done
 mv $ZDUMPDIR/*.zip $ZMBOXBACKUP
}
#########################

function backup_mysql()
{
 lblank
 test_dir $ZBACKUP
        echo -ne "$(log_date)${BLUE} Mysql Backup activated ... ${def}" >> $TEMP ;

        if [[ -z "${MYSQL_USER}" || -z "${MYSQL_PASSWORD}" ]]
        then
                echo -e "${red}Error: mysql credentials have to be specified${def}" >> $TEMP ;
                exit 255
        fi

        dump_options="--user=${MYSQL_USER} --password=${MYSQL_PASSWORD} --socket="${MYSQL_SOCKET}" --all-databases \
                                  --single-transaction --flush-logs --events --ignore-table=mysql.event"

        $MYSQLDUMP ${dump_options} | gzip > "${ZBACKUP}"/"${MYSQLDUMPNAME}_${FQDN}.sql.gz"
        ([ "$?" = 0 ] &&  echo -e "${green}DONE${def}" || echo -e "${red}FAILED${def}") >> $TEMP ;
}

############################

function backup_ldap()
{
lblank
test_dir $ZBACKUP
        echo -ne "$(log_date)${BLUE} LDAP Backup activated ... ${def}" >> $TEMP ;

        $SLAPCAT -F "${LDAPCONFDIR}" -b "" | gzip > "${ZBACKUP}"/"${LDAPDUMPNAME}_${FQDN}.ldif.gz"
        ([ "$?" = 0 ] &&  echo -e "${green}DONE${def}" || echo -e "${red}FAILED${def}") >> $TEMP ;
}

################
### MAIN  ######
################


case ${action} in
        mbox)
                time_start=`date +%s`
                mount_cifs
                mailbox_1by1
                umount_cifs
                time_end=`date +%s`
                time_computing mbox
                cat $TEMP >> $ZLOG
                send_mail
                rm -rf $TEMP
                ;;

        mysql)
                time_start=`date +%s`
                mount_cifs
                backup_mysql
                umount_cifs
                time_end=`date +%s`
                time_computing mysql
                cat $TEMP >> $ZLOG
                send_mail
                rm -rf $TEMP
                ;;

        ldap)
                time_start=`date +%s`
                mount_cifs
                backup_ldap
                umount_cifs
                time_end=`date +%s`
                time_computing ldap
                cat $TEMP >> $ZLOG
                send_mail
                rm -rf $TEMP
                ;;

        all)
                time_start=`date +%s`
                mount_cifs
                backup_mysql
                ret_mysql=$?

                backup_ldap
                ret_ldap=$?

                mailbox_1by1
                ret_mbox=$?
                umount_cifs
                time_end=`date +%s`
                time_computing full
                cat $TEMP >> $ZLOG
                send_mail
                rm -rf $TEMP
                ;;

        "")
                usage
                ;;

        *)
                echo -e "${red} Error: unknown ${action} action. ${def}" >&2
                exit 255
                ;;
esac

Script de backup

#!/bin/sh
## Autor : Infragate
## PS: color only for bash & Modify ssh/rsync cmd if u plan to use it with rsa-keys
## Binary needed : bc / mysqldump / tar / [cifs-utils] | [sshpass] | [rsync]
## apt-get install bc postfix mutt bc pigz
## apt-get install rsync sshpass cifs-utils

###########################
#### SCRIPT VARIABLES #####
###########################

### Runtime computing ###
 basetime=$(date +%s%N)

### Colors for local logfile ###
 red='\033[0;31m'
 RED='\033[1;31m'
 green='\033[0;32m'
 GREEN='\033[1;32m'
 blue='\033[0;34m'
 BLUE='\033[1;34m'
 purple='\033[0;35m'
 PURPLE='\033[1;35m'
 cyan='\033[1;36m'
 def='\033[0m'
###

### Timestamps ###
 date=`date +%Y%m%d`
 day=`date +%u`
 jour=`date +%A`
 week=`date +%Y%U`
###

###########################
##### USER VARIABLES ######
###########################

### Backup parameters ####
 folders="/etc/nginx /etc/php-fpm /home/www/sample1"
 exclude_files_pattern='*.mp3'
 bases="mysql cattle wp_client1"
 dest=/backup/`hostname`
 daily_backup=$dest/backup_$date'_'$jour
 retention_days=7
 retention_weeks_full=4
###

### OPTS ###
 activate_bckp_db=1
 activate_bckp_files=1
 activate_mail_alert=1
 activate_cifs_backup=0
 activate_sshrsync_backup=0
 activate_usb_backup=0
###

### Database credentials ###
 user=root
 pass="insert pass here"
 host=localhost
###

### CIFS Backup method parameters###
 user_share=username
 pass_share="pass_here"
 share_server=192.168.168.168
 share_folder=nom_du_partage
 cifs_mount_point=/backup
###

### SSH / Rsync Backup Method parameters###
 user_ssh=username
 pass_ssh='pass ssh here'
 remote_host=10.10.10.10
 remote_target=/home/$user_ssh/backup
###

### USB HD Backup Method parameters###
 usb_device=/dev/sdx
 usb_mount_point=/backup
###

### MAIL ###
recipient="yourmail@domain.com"
attachement=~/mail.txt
###

### LOG ###
 logfile=~/log_backup.txt
 temp=~/temp.txt
###

###########################
######## FUNCTIONS ########
###########################

log_date () {
 echo $(date +%d/%m/%Y-%H:%M:%S)
}

#################

clean_attachement () {
 sed -r "s/\x1B\[([0-9];)?([0-9]{1,2}(;[0-9]{1,2})?)?[m]//g" $temp > $attachement
}

##################

blank_log () {
 echo " "  >> $temp ;
}

##################

backup_type () {
 if [ $day -eq 7 ] || [ ! -d $dest/snap_files ]
    then
       backup_type='_FULL';
       bkp_kind="Full";
     else
       backup_type='_INC_part_'$day;
       bkp_kind="Incremental";
 fi
}

##################

backup_file () {
 echo "${GREEN}$(log_date) $bkp_kind Folders Backup : STARTED${def}"  >> $temp ;

 for folder in $folders
    do
        if [ ! -d $folder ]
            then
                echo "$(log_date) Folder ${blue}${folder} ${def}:${RED} Don't exist${def}" >> $temp;
            else
                bckp_list=$dest/snap_files/'files_'$(basename $folder).snap
                if [ $day -eq 7 ] ; then rm -rf $bckp_list ; fi
                tar -I pigz -cf $daily_backup/'files_'$date'_'$(basename $folder)$backup_type.tgz  -g $bckp_list $folder --exclude=$exclude_files_pattern
                [ "$?" = 0 ] &&  echo "$(log_date) Folder${blue} ${folder} ${def}Backup : ${green}DONE${def}" >> $temp ;
               [ "$?" != 0 ] &&  echo "$(log_date) Folder${blue} ${folder} ${def}Backup : ${RED}FAILED${def}" >> $temp ;
        fi
    done

 echo "${GREEN}$(log_date) $bkp_kind Folders Backup : ENDED ${def}"  >> $temp ;
 blank_log
}

##################

backup_db () {
 echo "${GREEN}$(log_date) Databases Backup : STARTED ${def}" >> $temp ;
 for base in $bases
    do
      mysqldump -l --user $user --password=$pass  --host $host --events --opt --databases $base  > /tmp/$base.sql
      [ "$?" = 0 ] &&  echo "$(log_date) Database ${purple}${base} ${def}Backup : ${green}DONE${def}" >> $temp ;
      [ "$?" != 0 ] &&  echo "$(log_date) Database ${purple}${base} ${def}Backup : ${RED}FAILED${def}" >> $temp ;
      tar -I pigz -cf $daily_backup/'database_'$date'_'$base.tgz /tmp/$base.sql
      rm -rf /tmp/$base.sql
    done
 mysqladmin -p$pass flush-tables

 echo "${GREEN}$(log_date) Databases Backup : ENDED ${def}" >> $temp ;
 blank_log
}

#################

retention () {
 if [ $day -eq 7 ]
    then
        weekly=$dest/arch_$week
        if [ ! -d $weekly ] ; then mkdir -p $weekly; fi
        cp -r -p $dest/backup_$date'_'$jour/*.tgz $weekly
 fi

 date=`date -d "$1 days ago" +%Y%m%d`
 jour=`date +%A`

 if [ -d $dest/backup_$date'_'$jour ]
        then
            blank_log
            echo "$(log_date) Folder${blue} $dest/backup_$date"_"$jour ${def} : ${green}Deleted : Obsolete${def} => Daily Retention policy" >> $temp ;
            rm -rf $dest/backup_$date'_'$jour
 fi

 date=`date -d "$2 week ago" +%Y%U`
 
 if [ -d $dest/arch_$date ]
              then
              echo "$(log_date) Folder${blue} $dest/arch_$date  ${def} : ${green}Deleted : Obsolete${def} => Full Archive Retention policy" >> $temp ;
              blank_log
              rm -rf $dest/arch_$date
 fi
}

#################

logging_trace () {
 touch $logfile
 size_log=`stat -c %s $logfile`
 size_max=1048576
 if [ $size_log -gt $size_max ]
   then
      tar czf $logfile_$date.tgz $logfile
      rm -rf  $logfile
 fi
 touch $logfile
}

##############################
######## SCRIPT START ########
##############################

### Root user testing ###

idnbr=`id -u`
if [ $idnbr != 0 ]; then echo "Must be r00t Assh0le!" >> $logfile && exit ; fi

### INIT LOG ###

logging_trace

### HEADER ###

blank_log
echo "\t\t\t ${cyan} Server : `hostname` ${def}"  >> $temp ;
echo "${BLUE}===================================================================${def}" >> $temp ;
echo "${BLUE}$(log_date) Backup Script Launched ${def}" >> $temp ;
echo "${BLUE}===================================================================${def}" >> $temp ;

#### CIFS MOUNT ######

if [ $activate_cifs_backup = 1 ]
    then
        echo "${BLUE}CIFS BACKUP Method Selected, Umounting after backup" >> $temp ;
        if [ ! -d $cifs_mount_point ]; then mkdir -p $cifs_mount_point ; fi
        mount -t cifs \\\\$share_server\\$share_folder $cifs_mount_point  -o username=$user_share,password=$pass_share
        [ "$?" != 0 ] &&  echo "${red}$(log_date)CIFS MOUNT : FAILED : BACKUP ABORTED${def} " >> $temp && exit ;
fi

##### USB MOUNT #####

if [ $activate_usb_backup = 1 ]
    then
        echo "${BLUE}USB BACKUP Method Selected, Umounting after backup" >> $temp ;
        if [ ! -d $usb_mount_point ]; then  mkdir -p $usb_mount_point; fi
        mount $usb_device $usb_mount_point
        [ "$?" != 0 ] &&  echo "${red}$(log_date)USB MOUNT : FAILED : BACKUP ABORTED${def} " >> $temp && exit ;
fi

###### RSYNC LOG #####

if [ $activate_sshrsync_backup = 1 ]; then echo "${BLUE}SSH/RSYNC BACKUP Method Selected, Local files will be keept after backup" >> $temp ; fi
blank_log

#### FOLDERS CREATION ####

if [ ! -d $daily_backup ] ; then mkdir -p $daily_backup; fi
backup_type
if [ ! -d $dest/snap_files ]; then mkdir -p $dest/snap_files ; fi

##
###### BACKUP FOLDERS ######
##

if [ $activate_bckp_files = 1 ]
    then
        backup_file
    else
        echo  "${RED}$(log_date) Files backup : DISABLED ${def}" >> $temp ;
fi

##
###### BACKUP DATABASES ######
##

if [ $activate_bckp_db = 1 ]
    then
       backup_db
    else
       echo "${RED}$(log_date) Database backup : DISABLED${def}" >> $temp ;
fi

##
###### RETENTION POLICY ######
##

retention $retention_days $retention_weeks_full

#######################
#####Backup Type#######
#######################

#### RSYNC w SSH ####

if [ $activate_sshrsync_backup = 1 ]
    then
        echo "$(log_date)${green} SSH/RSYNC Copy : STARTED${def}" >> $temp ;
        blank_log
        /usr/bin/rsync -avz --rsh="sshpass -p $pass_ssh  ssh -oUserKnownHostsFile=/dev/null  -oStrictHostKeyChecking=no" $dest/* $user_ssh@$remote_host:$remote_target 1>> $temp ;
        [ "$?" = 0 ] &&  echo "$(log_date)${green} SSH/RSYNC Copy : DONE${def}" >> $temp ;
        [ "$?" != 0 ] &&  echo "$(log_date)${red} SSH/RSYNC Copy : FAILED${def}" >> $temp ;
        blank_log
fi

#### UMOUNT CIFS ####

if [ $activate_cifs_backup = 1 ]
    then
        umount $cifs_mount_point
        [ "$?" = 0 ] &&  echo "$(log_date)${green} CIFS Share sucessfully unmounted${def}" >> $temp ;
        [ "$?" != 0 ] &&  echo "$(log_date)${red} CIFS Share unmounting : FAILED${def}" >> $temp ;
fi

#### UMOUNT USB ####

if [ $activate_usb_backup = 1 ]
    then
        umount $usb_mount_point
        [ "$?" = 0 ] &&  echo "$(log_date)${green} USB HD sucessfully unmounted${def}" >> $temp ;
        [ "$?" != 0 ] &&  echo "$(log_date)${red} USB HD  unmounting : FAILED${def}" >> $temp ;
fi

###### FOOTER #######

echo "${BLUE}===================================================================${def}" >> $temp ;
echo "${BLUE}$(log_date) Backup Script Ended  !${def}" >> $temp ;
echo "${cyan} \t \t \t runtime: $(echo "scale=3;($(date +%s%N) - ${basetime})/(1*10^09)" | bc) seconds"${def} >> $temp ;
echo "${BLUE}===================================================================${def}" >> $temp ;
blank_log

#### BACKUP CURRENT LOG ####

cat $temp >> $logfile

#### MAILING ####

if [ $activate_mail_alert = 1 ]
 then
    echo "set record=" "" > ~/.muttrc
    clean_attachement
    cat $attachement | mutt -s " $bkp_kind Backup Report for `hostname` $(log_date)" $recipient
    [ "$?" != 0 ] && exit ;
    rm -rf $attachement ;
fi

rm -rf $temp ;

Gestion Couleurs bash

Usage

 affiche  -green "[OK]";
 affiche -n -blue "Saisir la taille du boney: "; <=M
#!/bin/sh
#options pour la fonction affichage
isOption()
{
    param=$1
    r=${param%%-*}
    if [ "$r" ]; then
        return -1
    else
        return 0
    fi
}
 
#fonction affiche
affiche()
{
    couleur="0m"
    endl=1
    nopt=0
    until [ -z "$1" ]; do
        if [ $nopt != 1 ] &&  isOption "$1"  ; then
            case $1 in
                # Autres options
                -n)    endl=0 ;;  # Pas de retour a la ligne final
                -nopt) nopt=1 ;;
                # Les couleurs
                -white)   couleur="1;37m" ;; 
                -lgray)   couleur="37m"   ;;  
                -gray)    couleur="1;30m" ;;  
                -black)   couleur="30m"   ;;  
                -red)     couleur="31m"   ;;  
                -lred)    couleur="1;31m" ;;  
                -green)   couleur="32m"   ;;  
                -lgreen)  couleur="1;32m" ;;  
                -brown)   couleur="33m"   ;;  
                -yellow)  couleur="1;33m" ;;  
                -blue)    couleur="34m"   ;;  
                -lblue)   couleur="1;34m" ;;  
                -purple)  couleur="35m"   ;;  
                -pink)    couleur="1;35m" ;;  
                -cyan)    couleur="36m"   ;;  
                -lcyan)   couleur="1;36m" ;;  
                *)        couleur="0m" ;;
            esac
        else
            echo -en "\033[$couleur$1\033[0m"
            nopt=0
        fi
        shift
    done
    if test $endl == 1; then
        echo
    fi
    return 0
}