#!/bin/bash
#
## OS: openSuSE - tested with 10.3-11.1
#
## This script will build the SSL server keys, csr and crt, install them, and 
## copy vhosts-ssl.conf to the appropriate directory in /etc/apache2 to provide
## basic https:// functionality on opensuse 10.3-11.1

#
## General Functions and Colors
#
green='\e[0;32m'
red='\e[0;31m'
lightred='\e[1;31m'
lightblue='\e[1;34m'
lightgray='\e[0;37m'
nc='\e[0m'

check_root () {

ROOT_UID=0
E_NOTROOT=67

if [ "$UID" -ne "$ROOT_UID" ]; then
	echo -e "\n${lightblue}You must be ${lightred}root${lightblue} to run this script.\nUser: ${lightgray}$USER${lightblue}, UID: ${lightgray}$UID${lightblue} can't!${nc}\n"
	exit $E_NOTROOT
else
	return $ROOT_UID
fi
}

showvhost () {
echo '
#
## Virtual Host Configuration (/etc/apache2/vhosts.d/vhost-ssl.conf)
#
<IfDefine SSL>
<IfDefine !NOSSL>
<VirtualHost _default_:443>
        DocumentRoot "/srv/www/htdocs"
fix ->  #ServerName www.yourhost.com:443
    ->  #ServerAdmin youremail@yourhost.com
        ErrorLog /var/log/apache2/error_log
        TransferLog /var/log/apache2/access_log
        SSLEngine on
        SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
        SSLCertificateFile /etc/apache2/ssl.crt/server.crt
        SSLCertificateKeyFile /etc/apache2/ssl.key/server.key
        SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
        <Files ~ "\.(cgi|shtml|phtml|php3?)$">
            SSLOptions +StdEnvVars
        </Files>
        <Directory "/srv/www/cgi-bin">
            SSLOptions +StdEnvVars
        </Directory>
        SetEnvIf User-Agent ".*MSIE.*" \
                 nokeepalive ssl-unclean-shutdown \
                 downgrade-1.0 force-response-1.0
        CustomLog /var/log/apache2/ssl_request_log   ssl_combined
</VirtualHost>
</IfDefine>
</IfDefine>'
}

testyn() {
INPUT=$1
while [[ 0 ]]; do
	case "$INPUT" in
		"y"|"Y"|"yes"|"Yes"|"YES" ) return 0;;
		"n"|"N"|"no"|"No"|"NO" ) return 1;;
		* ) read -p "Invalid Input, Enter 'yes' or 'no':  " INPUT;;
	esac
done
}

usage () {
echo -e "\n\tThis will create apache2 SSL server.key, .csr and .crt and install them for basic \nhttps:// functionality on openSuSE 10.3-11.1. It will also set the apache2 SSL sysconfig flag.\nIn your key, your common name (CN) must be a FQDN. You must edit vhost-ssl.conf when done.\n"
echo -e "\tThis script has a fully-automated mode and a manual mode. If use the \nautomated mode, you need to EDIT the variables in this script or you will end up \nwith a certificate issued to the Rankin Law Firm, PLLC. Just change what is needed, \nsave and re-run the script.  To run the script fully automated, you need to provide \nthe common name as an argument in the form of hostname.domain.tld\n"
echo -e "\tIf you run the script with the manual option, the script will walk you through \nall required settings.\n"
echo -e "\tUsage:    ${0##*/} [option] [common-name-for-server]\n\n\t-m | --manual\tPrompts for all information\n"

read -p "Continue  (y/n)? " key

if testyn $key; then
	echo -e "${green}\n\tInitializing Server Key Generation${nc}\n"
else
	echo -e "\n\t${lightblue}Apache2 SSL Config - ${red}Canceled, exiting....${nc}\n"
	exit 1
fi
}

setvars() {
echo -e "\n\tThe folling information is needed for your server certificate:\n"
read -p "        Country Name (2 letter code) [AU]: " COUNTRY
read -p "        State or Province Name (full name) [Some-State]: " STATE
read -p "        Locality Name (eg, city) []: " LOCAL
read -p "        Organization Name (eg, company) [Internet Widgits Pty Ltd]: " ON
read -p "        Organizational Unit Name (eg, section) []: " OU
read -p "        Enter the common name (CN) of the server: " CN
read -p "        Email Address []: " EMAIL
}
#
## Pre-set Variables for Automated Script Operation
#
TPHRASE=serverkey
COUNTRY=US
STATE=Texas
LOCAL=Nacogdoches
ON="Rankin Law Firm, PLLC"
OU=Attorneys
EMAIL=dell@3111skyline.com
#
## Show usage for help, check if manual or set CN if auto
#
case $1 in
	-m | --manual) setvars;;
	*.* | *.*.* ) CN=$1; AUTO=1;;
	* ) usage;;
esac
#
#check for root
#
check_root
#
## test common name and prompt if needed
#
if [[ $1 =~ [.] ]]; then
	CN=$1
	else
		while [[ -z $CN ]] || [[ ! $CN =~ [.] ]]; do
			echo -e "\n\tYou must provide a common name for the server\n"
			echo -en "\t"
			read -p "Enter the common name (CN) of the server: " CN
		done
fi
#
## Set SSL Flag
#
if a2enflag SSL; then
	echo -e "\n\t${lightblue}Server SSL Flag Successfully Set\n${nc}"
else
	echo -e "\n\t${lightblue}Server SSL Flag ${red}NOT ${lightblue}Set\nEdit /etc/sysconfig/apache2 manually\n${nc}"
fi
#
## Create Directory
#
echo -en "\n\t${lightblue}Creating Directory for New SSL KeySet"

if mkdir -p new_sslkeyset && cd new_sslkeyset; then
	echo -e " - ${green}OK${nc}\n"	
else
	echo -e " - ${red}FAILED. Exiting...${nc}\n"
	exit 1
fi
#
## Generate Private Server Key
#
echo -e "\n\t${lightblue}Generating Private Server Key\n${nc}"
openssl genrsa -passout pass:$TPHRASE -des3 -out server.key 1024
#  <<GENPSK
# $TPHRASE
# $TPHRASE
# GENPSK
#
## Generate Certificate Signing Request (CSR)
#
echo -e "\n\t${lightblue}Generating Certificate Signing Request (CSR)\n${nc}"
openssl req -new -key server.key -out server.csr -passin pass:$TPHRASE <<GENCSR
$COUNTRY
$STATE
$LOCAL
$ON
$OU
$CN
$EMAIL


GENCSR
#
## Remove Passphrase from Key
#
echo -e "\n\t${lightblue}Removing Passphrase From Key To Eliminate PW Request On Server Start\n${nc}"
cp server.key server.key.protected
openssl rsa -in server.key.protected -out server.key -passin pass:$TPHRASE
# <<REMPW
# $TPHRASE
# REMPW
#
## Generating a Self-Signed Certificate
#
echo -e "\n\t${lightblue}Generating Self-Signed Certificate\n${nc}"
openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt
#
## Installing the Private Key and Certificate
#
echo -e "\n\t${lightblue}Installing server.crt, server.key and server.csr in /etc/apache2/<dir>${nc}\n"
if cp server.crt /etc/apache2/ssl.crt && cp server.key /etc/apache2/ssl.key && cp server.csr /etc/apache2/ssl.csr; then
	echo -e "\n\t${lightblue}Key, CSR and Certificate install ${green}Succeeded${nc}\n"
else
	echo -e "\n\t${lightblue}Key, CSR and Certificate install ${red}Failed${nc}\n"
fi
#
## Config Reminder
#
if [[ $AUTO != "1" ]]; then
	echo -e "${green}\n\tDon't forget to create /etc/apache2/vhosts.d/vhost-ssl.conf by copying \n/etc/apache2/vhosts.d/vhost-ssl.template to /etc/apache2/vhosts.d/vhost-ssl.conf and editing as \nnecessary. You can check this script for the comments that contain a working example of a \nvhost-ssl.conf${lightblue}\n"
	read -p "        Would you like to copy /etc/apache2/vhosts.d/vhost-ssl.template to vhost-ssl.conf now (y/n)? " key
	
	if testyn $key; then
		cp /etc/apache2/vhosts.d/vhost-ssl.template /etc/apache2/vhosts.d/vhost-ssl.conf
	fi

	echo -e "\n\t${green}All Done!\n\n\t${lightblue}Remember to edit ${red}vhost-ssl.conf ${lightblue}as required and restart apache2\n\n"
	read -p "        Would you like to see the example vhost-ssl.conf (y/n)? " key
	echo -e "${nc}"
	
	if testyn $key; then
		showvhost
	fi
else
		cp /etc/apache2/vhosts.d/vhost-ssl.template /etc/apache2/vhosts.d/vhost-ssl.conf
echo ""
fi

exit 0
