#!/bin/sh
#
# nessus-mkcert
#
# Written by Renaud Deraison <deraison@cvs.nessus.org> 
# and Michel Arboi <arboi@alussinan.org>
#
# This script is distributed under the Gnu General Public License (GPL)
#

case `echo -n` in
\-n)	Xn=   ; Xc='\c' ;;
*)	Xn=-n ; Xc=
esac



test "$1" = "-q" && QUIET=y


echo_no_nl ()
{
    echo $Xn "$*$Xc"
}


header()
{
clear
echo "-------------------------------------------------------------------------------"
echo "			Creation of the Nessus SSL Certificate"
echo "-------------------------------------------------------------------------------"
echo
}
#
umask 022

prefix=/usr/local
datadir=${prefix}/share
sysconfdir=/etc
localstatedir=/var
sharedstatedir=/var
sbindir=${prefix}/sbin
bindir=${prefix}/bin
egdpath=
is_cygwin=

RANDFLAG=""
test -n "$egdpath" && 
{
 RANDFLAG="-rand $egdpath"
}





PATH=$PATH:$sbindir:$bindir:/usr/ssl/bin:/usr/local/ssl/bin:/opt/ssl/bin





if [ -z "$is_cygwin" ];
then
#
# We need root priv
#
case `id 2>/dev/null` in 
uid=0*) 
    $sbindir/nessusd -g || {
	echo "Executing nessusd failed. Make sure your library loader is configured properly"
	echo "and that nessusd is in your \$PATH"
	exit 1
	}
    ;; 
*)
    echo "Only root can use nessus-mkcert"
    exit 1
esac
fi

#
# We need openssl
#
case `openssl version` in 
 OpenSSL*)
     ;;
 *)
   echo "OpenSSL is not properly installed (the 'openssl' command line utility could not"
   echo "be found (is your \$PATH set properly ?)"
   exit 1
esac
     
NESSUSPRIV="$localstatedir/nessus/CA"
NESSUSPUB="$sharedstatedir/nessus/CA"
if [ ! -d "$NESSUSPRIV" ]; then
    mkdir -p "$NESSUSPRIV"
    chmod 0700 "$NESSUSPRIV"
    echo "$NESSUSPRIV created"
fi

if [ ! -d "$NESSUSPUB" ]; then
    mkdir -p "$NESSUSPUB"
    chmod a+rx "$NESSUSPUB"
    echo "$NESSUSPUB created"
fi


# Check environment
if [ -z "$HOME" ]; then
    echo "HOME should be defined" 1>&2; exit 1
fi


#
# If EGD is not installed, we have to rely on other sources
# of entropy
# 
test -z "$RANDFLAG" -a -z "$RANDFILE" &&
{
 if [ ! -r /dev/random -a ! -r /dev/urandom -a ! -r $HOME/.rnd ];
  then
   header
   echo "You do not have any suitable random source"
   echo "You will be asked to type a few random keys on your keyboard"
   echo "to generate random bytes"
   nessus-mkrand $HOME/.rnd 1024 
   echo "Press [ENTER] to continue..."
  fi
}



umask 077

# Set environment
BASEDIR=${TMPDIR-/tmp}/nessus-mkcert.$$
mkdir $BASEDIR || exit 1


CAKEY=$NESSUSPRIV/cakey.pem
CACERT=$NESSUSPUB/cacert.pem
#
SRVKEY=$NESSUSPRIV/serverkey.pem
SRVREQ=$BASEDIR/serverreq.pem
SRVCERT=$NESSUSPUB/servercert.pem
#

# The client part will be implemented later on...
#cln CLNKEY=$BASEDIR/clientkey.pem
#cln CLNREQ=$BASEDIR/clientreq.pem
#cln CLNCERT=$BASEDIR/clientcert.pem


if [ -z "$QUIET" ];
then
header
echo "This script will now ask you the relevant information to create the SSL"
echo "certificate of Nessus. Note that this information will *NOT* be sent to"
echo "anybody (everything stays local), but anyone with the ability to connect to your"
echo "Nessus daemon will be able to retrieve this information."
echo
echo
#
echo_no_nl "CA certificate life time in days [1460]: "; read x
CACERT_LIFETIME=${x:-1460}
echo_no_nl "Server certificate life time in days [365]: "; read x
SRVCERT_LIFETIME=${x:-365}
#cln echo_no_nl "Client certificate life time in days [365]:"; read x
#cln CLNCERT_LIFETIME=${x:-365}

if [ ! -z "$LANG" ]; then
    DC=`echo $LANG | sed -n 's/^..*_\(..\)$/\1/p'`
fi

# Default country = France
# Too bad for you, but quicker for my tests!
echo_no_nl "Your country (two letter code) [${DC:=FR}]: "; read x
COUNTRY=${x:-$DC}
#
echo_no_nl "Your state or province name [none]: "; read x
PROVINCE=${x:-.}
X=Paris; echo_no_nl "Your location (e.g. town) [$X]: "; read x
LOCATION=${x:-$X}
X="Nessus Users United"; echo_no_nl "Your organization [$X]: "; read x
ORGANIZATION=${x:-$X}
# X="Test unit"; echo_no_nl "Your organization unit [$X]:"; read x
# ORGUNIT=${x:-$X}

####
else 
CACERT_LIFETIME="1460"
SRVCERT_LIFETIME="365"
COUNTRY="FR"
PROVINCE="none"
LOCATION="Paris"
ORGANIZATION="Nessus Users United"
fi


cat <<EOF>$BASEDIR/std000.cnf
RANDFILE		= $HOME/.rnd
#
[ ca ]
default_ca = NessusCA

[ NessusCA ]
dir		= $BASEDIR		# Where everything is kept
certs		= \$dir			# Where the issued certs are kept
crl_dir		= \$dir			# Where the issued crl are kept
database	= \$dir/index.txt	# database index file.
new_certs_dir	= \$dir			# default place for new certs.

certificate	= $CACERT	 	# The CA certificate
serial		= \$dir/serial 		# The current serial number
crl		= \$dir/crl.pem 	# The current CRL
private_key	= $CAKEY		# The private key

x509_extensions	= usr_cert		# The extentions to add to the cert
crl_extensions	= crl_ext

default_days	= 365		# how long to certify for
default_crl_days= 30			# how long before next CRL
default_md	= md5			# which md to use.
preserve	= no			# keep passed DN ordering

policy		= policy_anything

[ policy_anything ]
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ req ]
default_bits		= 1024
distinguished_name	= req_distinguished_name
# attributes		= req_attributes
x509_extensions	= v3_ca	# The extentions to add to the self signed cert

[ req_distinguished_name ]
countryName			= Country Name (2 letter code)
countryName_default		= FR
countryName_min			= 2
countryName_max			= 2

stateOrProvinceName		= State or Province Name (full name)
stateOrProvinceName_default	= Some-State

localityName			= Locality Name (eg, city)

0.organizationName		= Organization Name (eg, company)
0.organizationName_default	= Internet Widgits Pty Ltd

# we can do this but it is not needed normally :-)
#1.organizationName		= Second Organization Name (eg, company)
#1.organizationName_default	= World Wide Web Pty Ltd

organizationalUnitName		= Organizational Unit Name (eg, section)
#organizationalUnitName_default	=

commonName			= Common Name (eg, your name or your server\'s hostname)
commonName_max			= 255

emailAddress			= Email Address
emailAddress_max		= 255

# SET-ex3			= SET extension number 3

[ usr_cert ]
# These extensions are added when 'ca' signs a request.
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
#basicConstraints=CA:FALSE

# Here are some examples of the usage of nsCertType. If it is omitted
# the certificate can be used for anything *except* object signing.

# This is OK for an SSL server.
# nsCertType			= nsCertType
# For normal client use this is typical
# nsCertType = client, email
nsCertType			= NSCERTTYPE

keyUsage = nonRepudiation, digitalSignature, keyEncipherment

# This will be displayed in Netscape's comment listbox.
nsComment			= "OpenSSL Generated Certificate"

# PKIX recommendations harmless if included in all certificates.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer:always

# This stuff is for subjectAltName and issuerAltname.
# Import the email address.
subjectAltName=email:copy

# Copy subject details
issuerAltName=issuer:copy

#nsCaRevocationUrl		= http://www.domain.dom/ca-crl.pem
#nsBaseUrl
#nsRevocationUrl
#nsRenewalUrl
#nsCaPolicyUrl
#nsSslServerName

[ v3_ca ]
# PKIX recommendation.
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always

# This is what PKIX recommends but some broken software chokes on critical
# extensions.
basicConstraints = critical,CA:true
# So we do this instead.
#basicConstraints = CA:true

# Key usage: this is typical for a CA certificate. However since it will
# prevent it being used as an test self-signed certificate it is best
# left out by default.
keyUsage = cRLSign, keyCertSign
nsCertType = sslCA
EOF

#####

sed 's/NSCERTTYPE/server/g' < $BASEDIR/std000.cnf > $BASEDIR/std.cnf
sed 's/NSCERTTYPE/client/g' < $BASEDIR/std000.cnf > $BASEDIR/stdC.cnf
hostname=`hostname`
if [ -z "$hostname" ];
then
 echo "An error occured while trying to determine hostname !"
 exit 1
fi
# The value for organizationalUnitName must be 64 chars or less;
#   thus, hostname must be 36 chars or less. If it's too big,
#   try removing domain.

hostname_len=`echo $hostname| wc -c`

if [ $hostname_len -gt 36 ];
then
  hostname=`echo $hostname | cut -d '.' -f 1`
fi

CAMAIL=ca@$hostname
#cln CLNMAIL=nessus@$hostname
SRVMAIL=nessusd@$hostname
#
# Create the root CA
#


echo 01 > $BASEDIR/serial
touch $BASEDIR/index.txt
openssl genrsa $RANDFLAG -out $CAKEY  1024 2> $BASEDIR/openssl-log


echo "$COUNTRY
$PROVINCE
$LOCATION
$ORGANIZATION
Certification Authority for $hostname
$hostname
$CAMAIL" | 
openssl req -config $BASEDIR/std.cnf -new -x509 -days $CACERT_LIFETIME -key $CAKEY -out $CACERT 2>> $BASEDIR/openssl-log

# Server key
openssl genrsa $RANDFLAG -out $SRVKEY 1024 2>> $BASEDIR/openssl-log

# Server certificate "request"
echo "$COUNTRY
$PROVINCE
$LOCATION
$ORGANIZATION
Server certificate for $hostname
$hostname
$SRVMAIL" | 
openssl req -config $BASEDIR/std.cnf -new -key $SRVKEY -out $SRVREQ 2>> $BASEDIR/openssl-log

# Sign the server certificate
openssl ca -config $BASEDIR/std.cnf -name NessusCA -batch -days $SRVCERT_LIFETIME -in $SRVREQ -out $SRVCERT 2>> $BASEDIR/openssl-log

#cln # Client key
#cln openssl genrsa -out $CLNKEY 1024

#cln # Client certificate "request"
#cln echo "$COUNTRY
#cln $PROVINCE
#cln $LOCATION
#cln $ORGANIZATION
#cln Client certificate for $hostname
#cln $hostname
#cln $CLNMAIL" | 
#cln openssl req -config $BASEDIR/stdC.cnf -new -key $CLNKEY -out $CLNREQ

#cln # Sign the client certificate
#cln openssl ca -config $BASEDIR/stdC.cnf -name NessusCA -batch -days $CLNCERT_LIFETIME -in $CLNREQ -out $CLNCERT

####


chmod a+r $CACERT $SRVCERT #cln $CLNCERT


CF=/etc/nessus/nessusd.conf
egrep -v '^ *(pem_password|cert_file|key_file|ca_file|force_pubkey_auth) *=' "$CF" > "$CF.tmp"
echo "#
# Added by nessus-mkcert
#
cert_file=$SRVCERT
key_file=$SRVKEY
ca_file=$CACERT
# If you decide to protect your private key with a password, 
# uncomment and change next line
# pem_password=password
# If you want to force the use of a client certificate, uncomment next line
# force_pubkey_auth = yes" >> "$CF.tmp"




test -z "$QUIET" && header

if [ -s "$CACERT" -a -s "$CAKEY" -a -s "$SRVCERT" -a -s "$SRVKEY" ];
 then
 test -z "$QUIET" && echo "Congratulations. Your server certificate was properly created."
 
 mv -f "$CF.tmp" "$CF"
 test -z "$QUIET" && { 
 echo
 echo "$CF updated
 "

 #cln echo "Your client certificates are in $BASEDIR
 #cln You will have to copy them by hand

 echo "The following files were created : "
 echo
 echo ". Certification authority : "
 echo "   Certificate = $CACERT"
 echo "   Private key = $CAKEY"
 echo
 echo ". Nessus Server : "
 echo "    Certificate = $SRVCERT"
 echo "    Private key = $SRVKEY"
 #cln ***** Nessus client *****
 #cln Certificate = $CLNCERT
 #cln Private key = $CLNKEY
 }
else
 echo "An error occured while generating the certificates and/or keys !"
 echo
 echo_no_nl "Do you want to save openssl output in a file for further analysis ? (y/n) [y] " $Xc
 read n < /dev/tty
 test -z "$n" -o "$n" = "y" && {
  echo_no_nl "Where should I save this file ? [$HOME/openssl-output] "
  read n < /dev/tty
  test -z "$n" && n="$HOME/openssl-output"
  cp "$BASEDIR"/openssl-log "$n"
}
fi




test -z "$QUIET" &&
{
 echo
 echo "Press [ENTER] to exit"; read x
}
rm -rf "$BASEDIR"


if [ -s "$CACERT" -a -s "$CAKEY" -a -s "$SRVCERT" -a -s "$SRVKEY" ];
then
 exit 0
else
 exit 1
fi
