#!/bin/sh
#
# cisco_verify_file - Verify that a file is a valid Cisco signed file using
#  its associated signature file. It is assumed that the signature file is
#  in the same location as the file being verified and has the same name but
#  with a .sig extension. It defaults to using a signing certifcate with the
#  path /etc/ssl/cisco-img-sign-sha2.cert, but can be overridden by supplying
#  a certificate path on the command line.
#
# Apr. 2016, Scott Boswell
#
# Copyright (c) 2016 by cisco Systems, Inc.
# All rights reserved.
#
#
# Usage: ./cisco_verify_file <input_file> [other_cert]
#

# Example: ./cisco_verify_file phy.tgz
#
# Return value:
#               0 - File passed verification
#               1 - File failed verification

usage(){
	echo "Usage: $0 <input_file> [other_cert]"
	exit 1
}

SIGNING_CERT="/etc/ssl/cisco-img-sign-sha2.cert"

if test "$#" -ne 1; then
  if test "$#" -ne 2; then
    usage
  else
    SIGNING_CERT=$2
  fi
fi

FILE_NAME=$1
SIG_FILE=${FILE_NAME}.sig
SIG_SHA_FILE=${FILE_NAME}.sig.sha512
SHA_SUM_FILE=${FILE_NAME}.sha512

rm -f ${SIG_SHA_FILE}
rm -f ${SHA_SUM_FILE}

#echo "Signing certifcate: ${SIGNING_CERT}"

openssl rsautl -verify -in ${SIG_FILE} -certin -inkey ${SIGNING_CERT} -out ${SIG_SHA_FILE}
openssl dgst -sha512 -binary -out ${SHA_SUM_FILE} ${FILE_NAME}

cmp ${SHA_SUM_FILE} ${SIG_SHA_FILE} > /dev/null 2>&1

if [ $? -eq 0 ]; then
  #echo "Verification passed for ${FILE_NAME}"
  RES=0
else
  #echo "Verification failed for ${FILE_NAME}"
  RES=1
fi

rm -f ${SIG_SHA_FILE}
rm -f ${SHA_SUM_FILE}

exit ${RES}

