Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

openssl read cert template

Here's a post that combines all my favorite technologies! This is so fun.

If you want to use openssl to read the template name of a Microsoft Certificate Services certificate, you have to look up the OID that is stored on the cert and find it in the directory.

files/2024/listings/read-cert-template.sh (Source)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env sh
# File: read-cert-template.sh
# Location: blog exclusive
# Author: bgstack15
# SPDX-License-Identifier: GPL-3.0-only
# Startdate: 2024-05-16-5 10:23
# Title: Read cert template
# Purpose: read certificate and print cert tempalte name if discoverable
# History:
# Usage:
# Reference: see blog post
# Improve:
# Dependencies:
#    openssl, ldapsearch, ldap credential in read-cert-template.conf

# Load conf, RCT_LDAPSERVER RCT_LDAPBASE RCT_LDAPAUTH1 RCT_LDAPAUTH2
RCT_CONF="${RCT_CONF:-${HOME}/.config/read-cert-template.conf}"
test -f "${RCT_CONF}" && . "${RCT_CONF}"

# use RCT_IN env var or first parameter, or else standard input
RCT_IN="${RCT_IN:-${1}}"
RCT_IN="${RCT_IN:-/dev/stdin}"

if echo "${RCT_IN}" | grep -qE -e '^-$|^stdin$' ;
then
   _input="$( cat )"
else
   _input="$( cat "${RCT_IN}" )"
fi

oid="$( echo "${_input}" | openssl x509 -in /dev/stdin -noout -text -certopt no_header,no_version,no_serial,no_signame,no_validity,no_subject,no_issuer,no_pubkey,ext_parse | sed -n -r -e '/1.3.6.1.4.1.311.21.7/,+2p' | awk '/OBJECT/{print $NF}' | sed -r -e 's/^://;' )"
test -n "${VERBOSE}" && printf 'oid=%s\n' "${oid}" 1>&2
LDAPTLS_REQCERT=never ldapsearch -LLL -o ldif-wrap=9000 -H "${RCT_LDAPSERVER}" ${RCT_LDAPAUTHUNQUOTED} "${RCT_LDAPAUTHQUOTED}" -b "CN=Certificate Templates,CN=Public Key,CN=Services,CN=Configuration,${RCT_LDAPBASE}" "(msPKI-Cert-Template-OID=${oid})" CN | awk '$1~/cn:/{$1="";print;}' | sed -r -e 's/^ +| +$//g;'

files/2024/listings/read-cert-template.conf (Source)

1
2
3
4
5
6
# File: ~/.config/read-cert-template.conf
RCT_LDAPSERVER=ldaps://example.corp
# The "CN=Certificate Templates,CN=Public Key,CN=Services,CN=Configuration," will be prepended to this:
RCT_LDAPBASE="DC=example,DC=corp"
RCT_LDAPAUTHUNQUOTED="-x -w see#keepass"
RCT_LDAPAUTHQUOTED="-D CN=Service Account 319 (sa319),OU=Accounts,DC=example,DC=corp"

References

man openssl man x509

Comments