3 # Ben Secrest <blsecres@gmail.com>
5 # sh c_rehash script, scan all files in a directory
6 # and add symbolic links to their hash values.
8 # based on the c_rehash perl script distributed with openssl
10 # LICENSE: See OpenSSL license
14 # default certificate location
17 # for filetype bitfield
22 # check to see if a file is a certificate file or a CRL file
24 # 1. the filename to be scanned
26 # bitfield of file type; uses ${IS_CERT} and ${IS_CRL}
32 # make IFS a newline so we can process grep output line by line
36 # XXX: could be more efficient to have two 'grep -m' but is -m portable?
37 for LINE in $( grep '^-----BEGIN .*-----' ${1} )
40 | grep -q -E '^-----BEGIN (X509 |TRUSTED )?CERTIFICATE-----'
42 IS_TYPE=$(( ${IS_TYPE} | ${IS_CERT} ))
44 if [ $(( ${IS_TYPE} & ${IS_CRL} )) -ne 0 ]
48 elif echo ${LINE} | grep -q '^-----BEGIN X509 CRL-----'
50 IS_TYPE=$(( ${IS_TYPE} | ${IS_CRL} ))
52 if [ $(( ${IS_TYPE} & ${IS_CERT} )) -ne 0 ]
67 # use openssl to fingerprint a file
69 # 1. the filename to fingerprint
70 # 2. the method to use (x509, crl)
74 # user will capture output from last stage of pipeline
78 ${SSL_CMD} ${2} -fingerprint -noout -in ${1} | sed 's/^.*=//' | tr -d ':'
83 # link_hash - create links to certificate files
85 # 1. the filename to create a link for
86 # 2. the type of certificate being linked (x509, crl)
88 # 0 on success, 1 otherwise
92 local FINGERPRINT=$( fingerprint ${1} ${2} )
93 local HASH=$( ${SSL_CMD} ${2} -hash -noout -in ${1} )
103 LINKFILE=${HASH}.${TAG}${SUFFIX}
105 while [ -f ${LINKFILE} ]
107 if [ ${FINGERPRINT} = $( fingerprint ${LINKFILE} ${2} ) ]
109 echo "WARNING: Skipping duplicate file ${1}" >&2
113 SUFFIX=$(( ${SUFFIX} + 1 ))
114 LINKFILE=${HASH}.${TAG}${SUFFIX}
117 echo "${1} => ${LINKFILE}"
119 # assume any system with a POSIX shell will either support symlinks or
120 # do something to handle this gracefully
121 ln -s ${1} ${LINKFILE}
127 # hash_dir create hash links in a given directory
134 ls -1 * 2>/dev/null | while read FILE
136 if echo ${FILE} | grep -q -E '^[[:xdigit:]]{8}\.r?[[:digit:]]+$' \
143 ls -1 *.pem 2>/dev/null | while read FILE
149 if [ $(( ${FILE_TYPE} & ${IS_CERT} )) -ne 0 ]
152 elif [ $(( ${FILE_TYPE} & ${IS_CRL} )) -ne 0 ]
156 echo "WARNING: ${FILE} does not contain a certificate or CRL: skipping" >&2
160 link_hash ${FILE} ${TYPE_STR}
165 # choose the name of an ssl application
166 if [ -n "${OPENSSL}" ]
168 SSL_CMD=$(which ${OPENSSL} 2>/dev/null)
170 SSL_CMD=/usr/bin/openssl
176 PATH=${PATH}:${DIR}/bin
179 # confirm existance/executability of ssl command
180 if ! [ -x ${SSL_CMD} ]
182 echo "${0}: rehashing skipped ('openssl' program not available)" >&2
186 # determine which directories to process
192 elif [ -n "${SSL_CERT_DIR}" ]
194 DIRLIST=$SSL_CERT_DIR
201 # process directories
202 for CERT_DIR in ${DIRLIST}
204 if [ -d ${CERT_DIR} -a -w ${CERT_DIR} ]