#!/bin/bash

INSTALLDIR=/root/script
PHPINI=/usr/local/lib/php.ini
MKDIR=/bin/mkdir
GREP=/bin/grep

#############################################################
## Desabilitando compilers           			
#############################################################
comp() {
   let i++
   echo
   echo "Desabilitando compilers"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	/scripts/compilers off

	
fi
}

#############################################################
## Desabilitar funcoes              			
#############################################################
funcoes() {
   let i++
   echo
   echo "Desabilitando coisas nao necessarias"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	/sbin/service cups stop
	/sbin/chkconfig cups off 
	/sbin/service nfslock stop
	/sbin/chkconfig nfslock off
	/sbin/service rpcidmapd stop 
	/sbin/chkconfig rpcidmapd off
	/sbin/service bluetooth stop
	/sbin/chkconfig bluetooth off
	/sbin/service anacron stop
	/sbin/chkconfig anacron off
	/sbin/service hidd stop
	/sbin/chkconfig hidd off
	/sbin/service pcscd stop
	/sbin/chkconfig pcscd off
	/sbin/service avahi-daemon stop
	/sbin/chkconfig avahi-daemon off
	
fi
}

#############################################################
## Criando Regras mod_sec              			
#############################################################
regras() {
   let i++
   echo
   echo "Renomeando Regras mod_sec"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	mv /usr/local/apache/conf/modsec2.user.conf.none /usr/local/apache/conf/modsec2.user3.conf
	mv /usr/local/apache/conf/modsec2.user.conf.default /usr/local/apache/conf/modsec2.user2.conf
	touch /usr/local/apache/conf/modsec2.romer.conf
fi
}


#############################################################
## Instalando logview              			
#############################################################
logview() {
   let i++
   echo
   echo "Instalando logview"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	cd ${INSTALLDIR}/src
	wget http://www.logview.org/logview-install 
	chmod +x logview-install 
	./logview-install
fi
}

#############################################################
## ModSecurity Control  				###
#############################################################
cmc() {
   let i++
   echo
   echo "Instalando ModSecurity Control"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	cd ${INSTALLDIR}/src
	wget http://www.configserver.com/free/cmc.tgz 
	tar -xzf cmc.tgz 
	cd cmc/ 
	sh install.sh 
fi
}
	
#############################################################
## Instalando Firewall 					###
#############################################################
firewall() {
   let i++
   echo
   echo "Instalando Firewall"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	cd ${INSTALLDIR}/src
	wget http://www.configserver.com/free/csf.tgz 
	tar -xzf csf.tgz 
	cd csf/ 
	sh install.sh 
fi
}	
############################################################
## Instalando Mail Queues 				###
#############################################################
queues() {
   let i++
   echo
   echo "Instalando Mail Queues"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	cd ${INSTALLDIR}/src
	wget http://www.configserver.com/free/cmq.tgz 
	tar -xzf cmq.tgz 
	cd cmq/ 
	sh install.sh 
fi
}

#############################################################
## Funcao para confirmacao
#############################################################
funcconfirma() {
   echo -n "Confirma? (y/n): "
   read CONFIRMA
   until [ "${CONFIRMA}" = "y" ] || [ "${CONFIRMA}" = "n" ]; do
      echo -n "Por favor, digite 'y' ou 'n': "
      read CONFIRMA
   done
}

#############################################################
## Funcao para alterar porta do ssh			###
#############################################################
dosshport() {
   if [ -f /etc/ssh/sshd_config ]; then
      echo
      if [ "`${GREP} -m1 -i 'port 22' /etc/ssh/sshd_config`" != "" ]; then
         echo "Changing SSH to use a non-default port helps prevent"
         echo "against Brute Force attacks and potential hackers."
         echo "If you choose to change the SSH port, ensure the port is"
         echo "not already in use by another program.  There is a chance"
         echo "of locking yourself out of SSH, so it is recommended to"
         echo "add your Desktop's IP address to /etc/apf/allow_hosts.rules."
         echo "ELS can now change your SSH port for you."
         funcconfirma
         if [ "${CONFIRMA}" = "y" ]; then
            echo "Which port would you like to use for the SSH Deamon?"
            read SSHTCPPORT
            echo "You chose '$SSHTCPPORT'.  Ensure this is correct before continuing."
            funcconfirma
            if [ "${CONFIRMA}" = "y" ]; then
               GREPPED="`${GREP} -i 'port 22' /etc/ssh/sshd_config`"
               perl -pi -e "s/${GREPPED}/Port $SSHTCPPORT/" /etc/ssh/sshd_config
               if [ -d /etc/apf ]; then
                  ${GREP} IG_TCP_CPORTS /etc/apf/conf.apf > ${INSTALLDIR}/apfsshport.tmp
                  GREPPED1="`${GREP} \"# IG_TCP_CPORTS\" ${INSTALLDIR}/apfsshport.tmp`"
                  GREPPED2="`${GREP} \"# IG_TCP_CPORTS\" ${INSTALLDIR}/apfsshport2.tmp`"
                  GREPPED3="`${GREP} IG_TCP_CPORTS ${INSTALLDIR}/apfsshport2.tmp`"
                  GREPPED4="`${GREP} IG_TCP_CPORTS ${INSTALLDIR}/apfsshport.tmp`"
                  GREPPED5="`${GREP} \"# EG_TCP_CPORTS\" ${INSTALLDIR}/apfsshport.tmp`"
                  GREPPED6="`${GREP} \"# EG_TCP_CPORTS\" ${INSTALLDIR}/apfsshport2.tmp`"
                  GREPPED7="`${GREP} EG_TCP_CPORTS ${INSTALLDIR}/apfsshport2.tmp`"
                  GREPPED8="`${GREP} EG_TCP_CPORTS ${INSTALLDIR}/apfsshport.tmp`"
                  perl -pi -e "s/${GREPPED1}//" ${INSTALLDIR}/apfsshport.tmp
                  ${GREP} IG_TCP_CPORTS /etc/apf/conf.apf > ${INSTALLDIR}/apfsshport2.tmp
                  perl -pi -e "s/${GREPPED2}//" ${INSTALLDIR}/apfsshport2.tmp
                  perl -pi -e "s/,22,/,${SSHTCPPORT},/" ${INSTALLDIR}/apfsshport.tmp
                  perl -pi -e "s/${GREPPED3}/${GREPPED4}/" /etc/apf/conf.apf
                  ${RM} -rf ${INSTALLDIR}/apfsshport*
                  ${GREP} EG_TCP_CPORTS /etc/apf/conf.apf > ${INSTALLDIR}/apfsshport.tmp
                  perl -pi -e "s/${GREPPED5}//" ${INSTALLDIR}/apfsshport.tmp
                  ${GREP} EG_TCP_CPORTS /etc/apf/conf.apf > ${INSTALLDIR}/apfsshport2.tmp
                  perl -pi -e "s/${GREPPED6}//" ${INSTALLDIR}/apfsshport2.tmp
                  perl -pi -e "s/22/${SSHTCPPORT}/" ${INSTALLDIR}/apfsshport.tmp
                  perl -pi -e "s/${GREPPED7}/${GREPPED8}/" /etc/apf/conf.apf
                  ${RM} -rf ${INSTALLDIR}/apfsshport*
                  /etc/init.d/apf restart
                  echo "Done."
               fi
               /etc/init.d/sshd restart
            else
               sshport
            fi
         else
            echo "Leaving SSH port as 22."
         fi
      else
         echo "SSH Port already changed."
      fi
   fi
}



############################################################
## desabilita o uso da enable_dl no php.ini		###
#############################################################
dodisabledl() {
    let i++
	echo
    echo "${i}. Desabilitando o uso da funcao enable_dl no php.ini."
    if [ "`${GREP} \"^enable_dl =\" ${PHPINI}`" = "enable_dl = Off" ]; then
      echo
      echo "enable_dl ja esta off."
    else
      echo "O seu php enable_dl esta habilitado (On)."         
      echo "Por seguranca eh recomendado desabilitar. "
      echo "Mas nao se preocupe, estou aqui para fazer isto para voce!"     
      funcconfirma
      if [ "${CONFIRMA}" = "y" ]; then
         echo "Fazendo o backup do seu php.ini..."   
         cp --force ${PHPINI} ${INSTALLDIR}/bakfiles/php.ini-enable-dl.bak
         if [ -f ${INSTALLDIR}/bakfiles/php.ini-enable-dl.bak ]; then
            echo "O backup foi salvo em ${INSTALLDIR}/bakfiles/php.ini-enable-dl.bak!"
         else
            echo "O backup falhou."
            echo "Abortando instalacao."
            exit
         fi                 
         echo "Alterando php.ini..."
         GREPPED="`${GREP} \"^enable_dl =\" ${PHPINI}`"
         perl -pi -e "s/${GREPPED}/enable_dl = Off/" ${PHPINI}         
         if [ "`${GREP} \"^enable_dl =\" ${PHPINI}`" = "enable_dl = Off" ]; then
            echo "Alterado com sucesso!"
            echo "Reiniciando o servico httpd ..."
            /etc/init.d/httpd restart
            echo "Pronto. enable_dl esta desabilitado agora."
         else
            echo "A operacao Falhou!"
            echo "Restaurando o backup..."
            mv --force ${INSTALLDIR}/bakfiles/php.ini-enable-dl.bak ${PHPINI}
            echo "Backup restaurado."
            echo "Nao fomos capazes de desabilitar o enable_dl no php."
         fi         
      else 
         echo "Tudo bem, por seguranca voce deveria  mudar de ideia"
         echo "mas, eu nao irei desabilitar o enable_dl." 
      fi
    fi
}

############################################################
## desabilita o uso de diversas funcoes perigosas do php
#############################################################
dodisablephpfunctions() {
    let i++
    echo
    echo "${i}. Desabilitando funcoes perigosas no php."
    COUNT=`${GREP} -c -e ^disable_functions ${PHPINI}`
    if [ "`${GREP} ^disable_functions ${PHPINI}`" = "disable_functions = dl, system, exec, shell_exec, chown, chgrp, escapeshellcmd, putenv, popen, pclose, passthru, proc_open, proc_get_status, proc_nice, proc_close, proc_terminate, posix_ctermid, posix_get_last_error, posix_getcwd, posix_getegid, posix_geteuid, posix_getgid, posix_getgrgid, posix_getgrnam, posix_getgroups, posix_getlogin, posix_getpgid, posix_getpgrp, posix_getpid, posix_getppid, posix_getpwnam, posix_getpwuid, posix_getrlimit, posix_getsid, posix_getuid, posix_isatty, posix_kill, posix_mkfifo, posix_setegid, posix_seteuid, posix_setgid, posix_setpgid, posix_setsid, posix_setuid, posix_strerror, posix_times, posix_ttyname, posix_uname, ini_set" ]; then
      echo
      echo "As funcoes consideradas perigosas ao sistema"
      echo "ja estao desabilitadas."
   else
      echo
      echo "Observei que voce tem funcoes perigosas habilitadas no php, por padrao."
      echo "Se me pedir, eu desabilito elas para voce. O seu sistema ficara mais seguro."
      funcconfirma
      if [ "${CONFIRMA}" = "y" ]; then
         echo "Fazendo um backup do arquivo de configuracao..."
         cp --force ${PHPINI} ${INSTALLDIR}/bakfiles/php.ini-disable-functions.bak
         if [ -f ${INSTALLDIR}/bakfiles/php.ini-disable-functions.bak ]; then
            echo "Backup feito em ${INSTALLDIR}/bakfiles/php.ini-disable-functions.bak!"
         else
            echo "O backup falhou."
            echo "Abortando configuracao."
            exit
         fi      
         if [ "$COUNT" = "0" ]; then
            echo "Nao encontrei a disable_function no arquivo de configuracao..."
            echo "Vou adicionar diretamente no arquivo  ${PHPINI}"
            echo "" >> ${PHPINI}
            echo ";Mofificado por (servidorgerenciado.com.br)" >> ${PHPINI}
            echo "disable_functions = dl, system, exec, shell_exec, chown, chgrp, escapeshellcmd, putenv, popen, pclose, passthru, proc_open, proc_get_status, proc_nice, proc_close, proc_terminate, posix_ctermid, posix_get_last_error, posix_getcwd, posix_getegid, posix_geteuid, posix_getgid, posix_getgrgid, posix_getgrnam, posix_getgroups, posix_getlogin, posix_getpgid, posix_getpgrp, posix_getpid, posix_getppid, posix_getpwnam, posix_getpwuid, posix_getrlimit, posix_getsid, posix_getuid, posix_isatty, posix_kill, posix_mkfifo, posix_setegid, posix_seteuid, posix_setgid, posix_setpgid, posix_setsid, posix_setuid, posix_strerror, posix_times, posix_ttyname, posix_uname, ini_set" >> ${PHPINI}
         else
            echo "Encontrei o disable_functions no arquivo. Irei configura-lo..."
            GREPPED="`${GREP} \"^disable_functions\" ${PHPINI}`"
            perl -pi -e "s/${GREPPED}/disable_functions = dl, system, exec, shell_exec, chown, chgrp, escapeshellcmd, putenv, popen, pclose, passthru, proc_open, proc_get_status, proc_nice, proc_close, proc_terminate, posix_ctermid, posix_get_last_error, posix_getcwd, posix_getegid, posix_geteuid, posix_getgid, posix_getgrgid, posix_getgrnam, posix_getgroups, posix_getlogin, posix_getpgid, posix_getpgrp, posix_getpid, posix_getppid, posix_getpwnam, posix_getpwuid, posix_getrlimit, posix_getsid, posix_getuid, posix_isatty, posix_kill, posix_mkfifo, posix_setegid, posix_seteuid, posix_setgid, posix_setpgid, posix_setsid, posix_setuid, posix_strerror, posix_times, posix_ttyname, posix_uname, ini_set/" ${PHPINI}
         fi  
         if [ "`${GREP} ^disable_functions ${PHPINI}`" = "disable_functions = dl, system, exec, shell_exec, chown, chgrp, escapeshellcmd, putenv, popen, pclose, passthru, proc_open, proc_get_status, proc_nice, proc_close, proc_terminate, posix_ctermid, posix_get_last_error, posix_getcwd, posix_getegid, posix_geteuid, posix_getgid, posix_getgrgid, posix_getgrnam, posix_getgroups, posix_getlogin, posix_getpgid, posix_getpgrp, posix_getpid, posix_getppid, posix_getpwnam, posix_getpwuid, posix_getrlimit, posix_getsid, posix_getuid, posix_isatty, posix_kill, posix_mkfifo, posix_setegid, posix_seteuid, posix_setgid, posix_setpgid, posix_setsid, posix_setuid, posix_strerror, posix_times, posix_ttyname, posix_uname, ini_set" ]; then
            echo "Alterado com sucesso!"
            echo "Reiniciando servico httpd..."
            /etc/init.d/httpd restart
            echo "Feito. Agora as funcoes perigosas do php estao desabilitadas."
         else
            echo "Falhou!"
            echo "Restaurando o backup..."
            mv --force ${INSTALLDIR}/bakfiles/php.ini-disable-functions.bak ${PHPINI}
            echo "Backup restaurado."
            echo "Nao fui capaz de desabilitar as funcoes perigosas do php."
         fi                
      else
         echo "Voce eh quem manda. Nao irei desabilitar nenhuma funcao."         
      fi #se confirma
      
   fi
}


#############################################################
## Altera permissao de arquivos perigosos para root somente.#
#############################################################
domudarpermissao() {
   let i++
   echo
   echo "${i}. Restringindo o acesso a arquivos de sistema."
   echo
   echo "Eu posso alterar a permissao de arquivos perigosos"
   echo "para serem executados somente pelo root."
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
     if [ -f /usr/bin/rcp ]; then
        chmod 750 /usr/bin/rcp
        echo "Permissao de /usr/bin/rcp alterada para 750."
     fi
     if [ -f /usr/bin/wget ]; then
        chmod 750 /usr/bin/wget
        echo "Permissao de /usr/bin/wget alterada para 750."
     fi
     if [ -f /usr/bin/lynx ]; then
        chmod 750 /usr/bin/lynx
        echo "Permissao de /usr/bin/lynx alterada para 750."
     fi
     if [ -f /usr/bin/links ]; then
        chmod 750 /usr/bin/links
        echo "Permissao de /usr/bin/links alterada para 750."
     fi
     if [ -f /usr/bin/scp ]; then
        chmod 750 /usr/bin/scp
        echo "Permissao de /usr/bin/scp alterada para 750."
     fi
     if [ -d /etc/httpd/proxy ]; then
        chmod 000 /etc/httpd/proxy/
        echo "Permissao de /etc/httpd/proxy/ alterada para 000."
     fi
     if [ -d /var/spool/samba ]; then
        chmod 000 /var/spool/samba/
        echo "Permissao de /var/spool/samba/ alterada para 000."
     fi
     if [ -d /var/mail/vbox ]; then
        chmod 000 /var/mail/vbox/
        echo "Permissao de /var/mail/vbox/ alterada para 000."
     fi
     echo "Alterei todas permissoes de arquivos perigosos."
   else
        echo "Ok, porem isto deixa seu sistema inseguro."

   fi
}

## Force SSH protocol 2
doforcessh2() {
   echo
   if [ -f /etc/ssh/sshd_config ]&& [ "`${GREP} Protocol /etc/ssh/sshd_config`" = "Protocol 2" ]; then
      echo "SSHd already forcing Protocol 2."
   else
      echo "This feature can make the SSH deamon force SSH Protocl 2"
      funcconfirma
      if [ "${CONFIRMA}" = "y" ]; then
         echo "Backing up current configuration file..."
         cp /etc/ssh/sshd_config ${INSTALLDIR}/bakfiles/sshd_config.bak
         if [ -f ${INSTALLDIR}/bakfiles/sshd_config.bak ]; then
            echo "Successfully backed up as ${INSTALLDIR}/bakfiles/sshd_config.bak!"
         else
            echo "Backup failed."
            echo "Aborting."
            exit
         fi
         echo "Modifying configuration file..."
         perl -pi -e "s/#Protocol 2,1/Protocol 2/" /etc/ssh/sshd_config
         if [ "`${GREP} Protocol /etc/ssh/sshd_config`" = "Protocol 2" ]; then
            echo "Edit successful!"
            echo "Restarting SSHd service..."
            /etc/init.d/sshd restart
            echo "Done. SSH now forces Protocol 2."
         else
            echo "Edit failed!"
            echo "Restoring backup..."
            mv --force ${INSTALLDIR}/bakfiles/sshd_config.bak /etc/ssh/sshd_config
            echo "Backup restored."
            echo "SSH is NOT forcing Protocol 2."
         fi
      else
         echo "Not forcing SSH Protocol 2"
      fi
   fi
}

## Add a wheel user and force no root login in the SSH deamon's configuration
dowheeluser() {
   echo
   if [ "`${GREP} -m1 -i 'permitrootlogin' /etc/ssh/sshd_config | ${AWK} '{print $2}'`" != "no" ] && [ "`${GREP} -m1 -i 'permitrootlogin' /etc/ssh/sshd_config | ${AWK} '{print $2}'`" != "No" ]; then
      echo "Disabling root login to SSH adds an extra layer of security"
      echo "to prevent hackers from gaining root access.  It requires"
      echo "you to login as a special user and then use the command"
      echo "'su -' to get prompted for root password and become root."
      echo "You should be careful and write the information necessary"
      echo "down incase you need it."
      funcconfirma
      if [ "${CONFIRMA}" = "y" ]; then
         echo "What username would you like for the wheel user?"
         read WHEELUSERNAME
         echo "You enetered '${WHEELUSERNAME}'.  Ensure this is correct before continuing."
         funcconfirma
         if [ "${CONFIRMA}" = "y" ]; then
            if [ -d /home/${WHEELUSERNAME} ]; then
               echo "User already exists.  Please select a different username."
               wheeluser
            fi
            adduser -G wheel -m -s /bin/bash -d /home/${WHEELUSERNAME} ${WHEELUSERNAME}
            echo "Please enter a password."
            passwd ${WHEELUSERNAME}
            if [ "`groups ${WHEELUSERNAME} | ${GREP} wheel`" != "" ]; then
               echo "User addition success!  Editing SSHd config and restarting service..."
               GREPPED="`${GREP} -m1 -i 'permitrootlogin' /etc/ssh/sshd_config`"
               perl -pi -e "s/${GREPPED}/PermitRootLogin no/" /etc/ssh/sshd_config
               /etc/init.d/sshd restart
               echo "Done."
            else
               echo "Operation failed."
               echo "SSH still allowing root login."
            fi
         else
            wheeluserask
         fi
      else
         echo "Allowing root login over SSH"
      fi
   else
      echo "SSH deamon already not allowing root login."
   fi
}


#############################################################
## Instalando DNS Check			
#############################################################
accountdnscheck() {
   let i++
   echo
   echo "Instalando DNS Check"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	cd ${INSTALLDIR}/src
	wget http://www.ndchost.com/cpanel-whm/plugins/accountdnscheck/download.php
	sh latest-accountdnscheck
fi
}

#############################################################
## Instalando SQL.txt			
#############################################################
sqltxt() {
   let i++
   echo
   echo "Instalando SQLtxt"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	cd /usr/local/apache/conf/
	wget http://www.servhost.com.br/rbl/sql.txt
fi
}

#############################################################
## Instalando Clear Backups			
#############################################################
cleanbackups() {
   let i++
   echo
   echo "Instalando Clear Backups"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	cd ${INSTALLDIR}/src
	wget http://www.ndchost.com/cpanel-whm/plugins/cleanbackups/download.php
	sh latest-cleanbackups
fi
}

#############################################################
## Adicionando Regras Firewall			
#############################################################
regrasadd() {
   let i++
   echo
   echo "Adicionando Regras Firewall"
   funcconfirma
   if [ "${CONFIRMA}" = "y" ]; then
	useradd csf -s /bin/false
	cd /etc/csf/messenger
	mv index.html index.html-bkp
	mv index.text index.text-bkp
	wget http://www.servhost.com.br/rbl/index.html
	wget http://www.servhost.com.br/rbl/index.text
	cd /etc/csf
	perl csf.pl --deny tcp:in:d=21:d=0.0.0.0/0
	perl csf.pl --deny tcp:in:d=22:d=0.0.0.0/0
	perl csf.pl --deny tcp:in:d=1865:d=0.0.0.0/0
	perl csf.pl --add tcp:in:d=21:s=187.0.0.0/8 
	perl csf.pl --add tcp:in:d=21:s=189.0.0.0/8 
	perl csf.pl --add tcp:in:d=21:s=200.0.0.0/8 
	perl csf.pl --add tcp:in:d=21:s=201.0.0.0/8
	perl csf.pl --add tcp:in:d=21:s=177.0.0.0/8 
	perl csf.pl --add tcp:in:d=21:s=186.0.0.0/8
        perl csf.pl --add 187.103.78.18
        perl csf.pl --add 186.215.202.39

fi
}

## Criando as pastas necessarias ao script
   if [ ! -d ${INSTALLDIR} ]; then
      echo "${INSTALLDIR} nao existe. Criando..."
      ${MKDIR} ${INSTALLDIR}
   fi
   if [ ! -d ${INSTALLDIR}/src ]; then
      echo "${INSTALLDIR}/src nao existe. Criando..."
      ${MKDIR} ${INSTALLDIR}/src
   fi
   if [ ! -d ${INSTALLDIR}/bakfiles ]; then
      echo "${INSTALLDIR}/bakfiles nao existe. Criando..."
      ${MKDIR} ${INSTALLDIR}/bakfiles
   fi

comp
funcoes
regras
logview
cmc
firewall
queues
sqltxt
dosshport
dodisabledl
dodisablephpfunctions
domudarpermissao
doforcessh2
dowheeluser
accountdnscheck
cleanbackups
regrasadd
exit 0;
