#!/bin/sh
#
#    Copyright (c) 2006-2008 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    File name:   certvalidate
#    Module name: fabos/src/security/certvalidate.sh
#
#    This script validates the certificate against the private key of the switch
#
export PATH=/fabos/sbin:/fabos/bin:/bin:/usr/bin:/sbin:/fabos/cliexec

# commands
OPENSSL_CMD=/usr/bin/openssl

# File locations and suffixes
ROOT_DIR=/etc/fabos
CERT_DIR=$ROOT_DIR/certs/sw0
TMP_DIR=/tmp
CRT_SUFFIX=.crt
CER_SUFFIX=.cer
PEM_SUFFIX=.pem
PVT_KEY_FILE=$CERT_DIR/pvt_key
SSL_CERT=ssl.certfile
# usage /fabos/libexec/certValidate <certificate_name>
if [ $# -ne 2 ]; then
	exit 1
fi

certFile=$1
hashCheck=$2

cLen=`expr length $certFile`
let dotIndex="$cLen"-3
fileSuffix=`expr substr $certFile $dotIndex $cLen`
if [ ! -f $PVT_KEY_FILE ]; then
	exit 1
fi

if [ "$fileSuffix" == "$PEM_SUFFIX" ]; then
	$OPENSSL_CMD x509 -in $CERT_DIR/$certFile -inform PEM -outform DER -out $TMP_DIR/$certFile.der > /dev/null 2>&1
	if [ $? != 0 ]; then
		exit 1
	fi
	rm $TMP_DIR/$certFile.der
	certificate=$CERT_DIR/$certFile

elif [ "$fileSuffix" == "$CER_SUFFIX" ] || [ "$fileSuffix" == "$CRT_SUFFIX" ]; then

	$OPENSSL_CMD x509 -in $CERT_DIR/$certFile -inform DER -outform PEM -out $TMP_DIR/$certFile.pem > /dev/null 2>&1
	if [ $? != 0 ]; then
		exit 1
	fi
	certificate=$TMP_DIR/$certFile.pem
else
	# any other extension is not supported
	exit 1
fi


if [ "$hashCheck" == "$SSL_CERT" ]; then
pvtkeyhash=`$OPENSSL_CMD rsa -noout -modulus -in $PVT_KEY_FILE | $OPENSSL_CMD md5`
certkeyhash=`$OPENSSL_CMD x509 -noout -modulus -in $certificate | $OPENSSL_CMD md5`
	if [ "$pvtkeyhash" != "$certkeyhash" ]; then
		exit 1
	fi
fi
exit 0
