Skip to content

Instantly share code, notes, and snippets.

@bgstack15
Created December 19, 2017 20:54
Show Gist options
  • Save bgstack15/46ed24a4c05440f8b4f7c4a6ff16c7ad to your computer and use it in GitHub Desktop.
Save bgstack15/46ed24a4c05440f8b4f7c4a6ff16c7ad to your computer and use it in GitHub Desktop.
Hash certificate directory in another directory
#!/bin/sh
# File: hash-cert-dir.sh
# Location: /etc/ansible/roles/general_conf/files/hash-cert-dir.sh
# Author: bgstack15@gmail.com
# Startdate: 2017-12-18
# Title: Script that Makes Symlinks for Certs in a Directory
# Purpose: Make a directory suitable for openldap to use as TLS_CACERTDIR
# History:
# Usage:
# HCD_SOURCEDIR=/etc/pki/ca-trust/source/anchors HCD_LINKDIR=/etc/openldap/cacerts hash-cert-dir.sh
# Reference:
# Improve:
# # Ansible task
# - name: hash trusted certs for ldap to trust
# script: hash-cert-dir.sh
# environment:
# HCD_SOURCEDIR: /etc/pki/ca-trust/source/anchors
# HCD_LINKDIR: /etc/openldap/cacerts
# register: hcd
# changed_when: '"changed" in hcd.stdout'
# Declare variables
test -z "${HCD_SOURCEDIR}" && export HCD_SOURCEDIR=/etc/pki/ca-trust/source/anchors
test -z "${HCD_LINKDIR}" && export HCD_LINKDIR=/etc/openldap/cacerts
# Check dependencies
OPENSSL="$( which openssl 2>/dev/null )" ; test ! -x "${OPENSSL}" && { echo "${0} needs openssl. Aborted." 1>&2 ; exit 1; }
# Make directory
mkdir -p "${HCD_LINKDIR}"
# Loop over ca certificates
__changed=0
for infile in $( find "${HCD_SOURCEDIR}" -type f 2>/dev/null ) ;
do
# Get hash of certificate
hash="$( ${OPENSSL} x509 -hash -noout -in "${infile}" 2>/dev/null )"
# Get new filename
count="$( find "${HCD_LINKDIR}" -type l -regex "${HCD_LINKDIR}/${hash}.*" 2>/dev/null | wc -l )"
__used=0
# Check if any symlinks exist for this target cert
for outfile in $( find "${HCD_LINKDIR}" -type l -regex "${HCD_LINKDIR}/${hash}.*" 2>/dev/null ) ;
do
test "$( readlink -f "${outfile}" )" = "${infile}" && __used=1
done
# If no symlinks point to this target cert, make the symlink
test ${__used} -eq 0 && { ln -s "${infile}" "${HCD_LINKDIR}/${hash}.${count}" ; __changed=$(( __changed + 1 )) ; }
done
# Report to ansible if any changes occurred
test ${__changed} -gt 0 && echo "changed"
# Exit cleanly
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment