#!/bin/sh
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# $Id: dhparams.sh 144933 2017-02-08 09:50:25Z justin.carveley@oracle.com $
#
# Generate the required Diffie-Hellman parameters for SGD.

TTABINDIR="${instdir}/bin"
. "${TTABINDIR}/scripts/common.sh"

GetPrivUsrGrp()
{
    cat $instdir/var/serverconfig/global/array.properties 2>/dev/null | awk -F= \
	'BEGIN { u="ttasys"; wu="ttaserv"; g="ttaserv" }
	$1 == "tarantella.config.array.privilegeduser" { u = $2 }
	$1 == "tarantella.config.array.webserveruser" { wu = $2 }
	$1 == "tarantella.config.array.privilegedgroup" { g = $2 }
	END { print u " " wu " " g }'
}
_privusrgrp=`GetPrivUsrGrp`
privusr=`expr "$_privusrgrp" : '\([^ ]*\) .*'`
webservusr=`expr "$_privusrgrp" : '.* \([^ ]*\) .*'`
privgrp=`expr "$_privusrgrp" : '.* \([^ ]*\)$'`


case "$trace" in
x) set -x
esac

DH_PARAMS_LENGTH='2048'
DH_PARAMS_FORMAT='PEM'
DH_PARAMS_FILE="${instdir}/var/tsp/dhparams.pem"

if [ -n "$USE_EXISTING_DHPARAMS" -a -f "$DH_PARAMS_FILE" ]
then
    echo
    echo "WARNING: Using the existing Diffie-Hellman parameters file \"$DH_PARAMS_FILE\""
    echo "This may reduce the security of your TLS connections."
else
    echo

    OPENSSL_CONF="${instdir}/etc/data/openssl.cnf"
    export OPENSSL_CONF

    # Find a system OpenSSL command to use.
    sys_ssl=''
    old_ifs=$IFS
    IFS=':'
    openssl_path='/usr/bin:/usr/sfw/bin:/opt/csw/bin'
    for path in $openssl_path
    do
        if [ -x "${path}/openssl" ]
        then
            sys_ssl="${path}/openssl"
            break
        fi
    done
    IFS="$old_ifs"

    param_regen_reqd=1
    if [ -n "$sys_ssl" ]
    then
        # Use the system OpenSSL command to generate the DH parameters.
        "$sys_ssl" dhparam -outform "$DH_PARAMS_FORMAT" -out "$DH_PARAMS_FILE" \
            "$DH_PARAMS_LENGTH" >/dev/null
        exitCode=$?
        if [ $exitCode -eq 0 ]
        then
            # Check params file is valid.
            openssl dhparam -check -inform \
                "$DH_PARAMS_FORMAT" -in "$DH_PARAMS_FILE" -noout >/dev/null 2>&1
            exitCode=$?
            if [ $exitCode -eq 0 ]
            then
                param_regen_reqd=0
            fi
        fi
    fi
 
    # If we don't have a valid set of parameters use SGD's OpenSSL binary to
    # generate some.
    if [ $param_regen_reqd -ne 0 ]
    then
        openssl dhparam -outform "$DH_PARAMS_FORMAT" \
            -out "$DH_PARAMS_FILE" "$DH_PARAMS_LENGTH" >/dev/null
        exit_on_error "Failed to generate DH parameters." $?
    fi

    chmod 600 "$DH_PARAMS_FILE"
    exit_on_error "Could not set the permissions of ${DH_PARAMS_FILE}" $?
    
    chown "${privusr}:${privgrp}" "$DH_PARAMS_FILE"
    exit_on_error "Could not set the ownership of ${DH_PARAMS_FILE}" $?
fi
