summaryrefslogtreecommitdiff
path: root/read-cert-template.sh
blob: 902a4de6402d8212183571bf61c496692fbe0ae9 (plain)
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/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:
#    2024-07-23 added to support RCT_LDAPSERVER_1234567 values in the conf file for domain-specific connection info
# 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="${RTC_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|Microsoft certificate template/,+2p' | awk '/OBJECT/{print $NF}' | sed -r -e 's/^://;' )"
# domain oid segment
_d="$( echo "${oid}" | awk -F'.' '$0~/1\.3\.6\.1\.4\.1\.311\.21\.8/{print $10}' )"
# Load RCT_ALIAS_1234567 where 1234567=domain oid segment
for word in ALIAS LDAPSERVER LDAPBASE LDAPAUTH1 LDAPAUTH2 ;
do
   eval test -n \"\${RCT_${word}_${_d}}\" && eval RCT_${word}=\"\${RCT_${word}_${_d}}\"
done
test -n "${VERBOSE}" && {
   printf 'oid=%s\n' "${oid}"
   printf 'domain=%s\n' "${RCT_ALIAS}"
} 1>&2

# look up template
LDAPTLS_REQCERT=never ldapsearch -LLL -o ldif-wrap=9000 -H "${RCT_LDAPSERVER}" ${RCT_LDAPAUTH1} "${RCT_LDAPAUTH2}" -b "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,${RCT_LDAPBASE}" "(msPKI-Cert-Template-OID=${oid})" CN | awk '$1~/cn:/{$1="";print;}' | sed -r -e 's/^ +| +$//g;' | {
   if test -n "${RCT_ALIAS}" ;
   then
      # append alias on end
      sed -r -e "s/ *$/ (${RCT_ALIAS})/g;"
   else
      cat
   fi
}
bgstack15