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 printf "WARNING: Skipping duplicate file ${1}\n" >&2
113 SUFFIX=$(( ${SUFFIX} + 1 ))
114 LINKFILE=${HASH}.${TAG}${SUFFIX}
117 printf "${1} => ${LINKFILE}\n"
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
130 printf "Doing ${1}\n"
136 # no files in directory at all, no point in continuing
142 if echo ${FILE} | grep -q -E '^[[:xdigit:]]{8}\.r?[[:digit:]]+$' \
151 # no pem files so FILE gets set to the unexpanded *.pem
161 if [ $(( ${FILE_TYPE} & ${IS_CERT} )) -ne 0 ]
164 elif [ $(( ${FILE_TYPE} & ${IS_CRL} )) -ne 0 ]
168 printf "WARNING: ${FILE} does not contain a certificate or CRL: skipping\n" >&2
172 link_hash ${FILE} ${TYPE_STR}
177 # choose the name of an ssl application
178 if [ -n "${OPENSSL}" ]
188 PATH=${PATH}:${DIR}/bin
191 # confirm existance/executability of ssl command
192 if ! [ -x $( which ${SSL_CMD} ) ]
194 printf "${0}: rehashing skipped ('openssl' program not available)\n" >&2
198 # determine which directories to process
204 elif [ -n "${SSL_CERT_DIR}" ]
206 DIRLIST=$SSL_CERT_DIR
213 # process directories
214 for CERT_DIR in ${DIRLIST}
216 if [ -d ${CERT_DIR} -a -w ${CERT_DIR} ]