This script is designed to remove expired computer and user certificates from the device. When a SCEP (Simple Certificate Enrollment Protocol) certificate is issued, any previously issued certificates are not automatically removed. As a result, expired certificates can accumulate on the machine, causing users to be presented with these expired certificates, for example, when connecting to a wireless network. This script addresses this issue by cleaning up expired certificates.
#!/bin/bash
# Variables
SYSTEM_KEYCHAIN="/Library/Keychains/System.keychain"
function MAIN() {
CERT_LIST=$(security find-certificate -p -a)
CERT_LIST=$(echo "$CERT_LIST" | sed 's/ //g' | sed 's/-----ENDCERTIFICATE-----/-----ENDCERTIFICATE----- /g')
OIFS="$IFS"
IFS=' '
declare -a CERT_ARRAY=($CERT_LIST)
IFS="$OIFS"
i=-1
for CERT_ELEMENT in "${CERT_ARRAY[@]}"; do
let "i++"
# Parse certificates
CERT_ELEMENT=$(echo "$CERT_ELEMENT" | sed 's/-----BEGINCERTIFICATE-----/-----BEGIN CERTIFICATE-----/g' | sed 's/-----ENDCERTIFICATE-----/-----END CERTIFICATE-----/g')
CERT_MD5=$(echo "$CERT_ELEMENT" | openssl x509 -noout -fingerprint -sha1 -inform pem | cut -d "=" -f 2 | sed 's/://g')
CERT_EXPIRATION_DATE_FULL=$(echo "$CERT_ELEMENT" | openssl x509 -text | grep 'Not After' | sed -E 's|.*Not After : ||')
CERT_ISSUED_BY=$(echo "$CERT_ELEMENT" | openssl x509 -text | grep 'Issuer:' | sed -E 's|.*Issuer: ||')
# Evaluate certificates issued by the Company CA.
if [[ $CERT_ISSUED_BY = "DC=nl, DC=company, CN=Company Issuing Certificate Authority" ]]
then
CERT_EXPIRATION_DATE_FORMATTED=$(date -jf "%b %d %T %Y %Z" "${CERT_EXPIRATION_DATE_FULL}" +%Y%m%d)
NOW=$(date +'%Y%m%d')
if [[ $NOW -gt "$CERT_EXPIRATION_DATE_FORMATTED" ]]
then
echo "certificate is expired, deleting..."
/usr/bin/security delete-certificate -Z "${CERT_MD5}" "${SYSTEM_KEYCHAIN}"
else
echo "certificate is valid"
fi
fi
done
}
MAIN