summaryrefslogtreecommitdiffstats
path: root/bin/deploy_cert.slapd.sh
blob: e40060d78a8def6aba5c9508e024df1a51a2a38e (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/bin/sh

set -e

#CA_FROM_INTERNET="TRUE"
CA_LINK_FILE_NAME="ca"
CA_CHAIN_NAME="cachain"
CERT_PATH="$(dirname ${CHAINFILE})"
CA_LINK_FILE="${CERT_PATH}/${CA_LINK_FILE_NAME}.pem"

Ca_from_internet ()
{
	echo "Downloading CA file from internet!"

	ISSUER_URL="$(openssl  x509 -in "${CHAINFILE}" -noout -text | grep 'CA Issuers' | cut -d ':' -f 2-)"
	TEMPDIR="$(mktemp -d /tmp/dehydrated-hook.XXXX)"

	wget --quiet "${ISSUER_URL}" -O "${TEMPDIR}/${CA_LINK_FILE_NAME}"

	if openssl x509 -in "${TEMPDIR}/${CA_LINK_FILE_NAME}" -text > /dev/null 2>&1
	then
		echo "Root certificate format is text PEM"
		/usr/bin/mv "${TEMPDIR}/${CA_LINK_FILE_NAME}" "${CA_LINK_FILE}.new"
	elif openssl x509 -inform DER -in "${TEMPDIR}/${CA_LINK_FILE_NAME}" -text > /dev/null 2>&1
	then
		echo "Root certificate format is binary DER"
		openssl x509 -in "${TEMPDIR}/${CA_LINK_FILE_NAME}" -inform DER -out "${CA_LINK_FILE}.new"
	elif openssl pkcs7 -inform der -in "${TEMPDIR}/${CA_LINK_FILE_NAME}" > /dev/null 2>&1
	then
		echo "Root certificate format is binary pkcs7"
		openssl pkcs7 -print_certs -inform der -in "${TEMPDIR}/${CA_LINK_FILE_NAME}" -out "${CA_LINK_FILE}.new"
	elif openssl pkcs12 -in "${TEMPDIR}/${CA_LINK_FILE_NAME}" -info > /dev/null 2>&1
	then
		echo "${0}: root certificate format is binary pkcs12"
		echo "Error, root certificate is in unhandled format." >&2
		exit 1
	else
		echo "${0}: error, root certificate is in unhandled format." >&2
		exit 1
	fi

	openssl verify -trusted "${CA_LINK_FILE}.new" -untrusted "${CHAINFILE}" "${CERTFILE}" 1> /dev/null

	CA_COMMON_NAME="$(openssl x509 -noout -subject -nameopt multiline -in "${CA_LINK_FILE}.new" | grep commonName | sed -n 's/ *commonName *= //p')"
	CA_FILE="${CERT_PATH}/${CA_COMMON_NAME}.pem"

	mv "${CA_LINK_FILE}.new" "${CA_FILE}"
	rm -rf "${TEMPDIR}"
}

unset CA_FILE

for FILE in $(find /etc/ssl/certs -not -name "????????.?" -not -name ca-certificates.crt)
do
	if openssl verify -no-CApath -CAfile "${FILE}"  "${CHAINFILE}" > /dev/null 2>&1
	then
		CA_FILE="${FILE}"
		break
	fi
done

if [ -z "${CA_FILE}" ]
then
	echo "Could not find root CA on this system."

	if [ "${CA_FROM_INTERNET}" = "TRUE" ]
	then
		Ca_from_internet
	else
		exit 1
	fi
fi

echo "Found trusted root CA file: ${CA_FILE}"
ln -sf "${CA_FILE}" "${CA_LINK_FILE}"
#cp "${CA_FILE}" "${CA_LINK_FILE}"
openssl verify -trusted "${CA_LINK_FILE}" -untrusted "${CHAINFILE}" "${CERTFILE}" 1> /dev/null
cat "${CA_LINK_FILE}" "${CHAINFILE}" "${CERTFILE}" > "${CERT_PATH}/${CA_CHAIN_NAME}.pem"