Home | History | Annotate | Line # | Download | only in conf
      1 #!/bin/sh
      2 #	$NetBSD: postfix-tls-script,v 1.5 2023/12/23 20:30:42 christos Exp $
      3 #
      4 
      5 #++
      6 # NAME
      7 #	postfix-tls 1
      8 # SUMMARY
      9 #	Postfix TLS management
     10 # SYNOPSIS
     11 #	\fBpostfix tls\fR \fIsubcommand\fR
     12 # DESCRIPTION
     13 #	The "\fBpostfix tls \fIsubcommand\fR" feature enables
     14 #	opportunistic TLS in the Postfix SMTP client or server, and
     15 #	manages Postfix SMTP server private keys and certificates.
     16 #
     17 #	The following subcommands are available:
     18 # .IP "\fBenable-client\fR [\fB-r \fIrandsource\fR]"
     19 #	Enable opportunistic TLS in the Postfix SMTP client, if all
     20 #	SMTP client TLS settings are at their default values.
     21 #	Otherwise, suggest parameter settings without making any
     22 #	changes.
     23 # .sp
     24 #	Specify \fIrandsource\fR to update the value of the
     25 #	\fBtls_random_source\fR configuration parameter (typically,
     26 #	/dev/urandom).  Prepend \fBdev:\fR to device paths or
     27 #	\fBegd:\fR to EGD socket paths.
     28 # .sp
     29 #	See also the \fBall-default-client\fR subcommand.
     30 # .IP "\fBenable-server\fR [\fB-r \fIrandsource\fR] [\fB-a \fIalgorithm\fR] [\fB-b \fIbits\fR] [\fIhostname\fB...\fR]"
     31 #	Create a new private key and self-signed server certificate
     32 #	and enable opportunistic TLS in the Postfix SMTP server,
     33 #	if all SMTP server TLS settings are at their default values.
     34 #	Otherwise, suggest parameter settings without making any
     35 #	changes.
     36 # .sp
     37 #	The \fIrandsource\fR parameter is as with \fBenable-client\fR
     38 #	above, and the remaining options are as with \fBnew-server-key\fR
     39 #	below.
     40 # .sp
     41 #	See also the \fBall-default-server\fR subcommand.
     42 # .IP "\fBnew-server-key\fR [\fB-a \fIalgorithm\fR] [\fB-b \fIbits\fR] [\fIhostname\fB...\fR]"
     43 #	Create a new private key and self-signed server certificate,
     44 #	but do not deploy them. Log and display commands to deploy
     45 #	the new key and corresponding certificate.  Also log and
     46 #	display commands to output a corresponding CSR or TLSA
     47 #	records which may be needed to obtain a CA certificate or
     48 #	to update DNS before the new key can be deployed.
     49 # .sp
     50 #	The \fIalgorithm\fR defaults to \fBrsa\fR, and \fIbits\fR
     51 #	defaults to 2048.  If you choose the \fBecdsa\fR  \fIalgorithm\fR
     52 #	then \fIbits\fR will be an EC curve name (by default
     53 #	\fBsecp256r1\fR, also known as prime256v1).  Curves other
     54 #	than \fBsecp256r1\fR, \fBsecp384r1\fR or \fBsecp521r1\fR
     55 #	are unlikely to be widely interoperable.  When generating
     56 #	EC keys, use one of these three.  DSA keys are obsolete and
     57 #	are not supported.
     58 # .sp
     59 #	Note: ECDSA support requires OpenSSL 1.0.0 or later and may
     60 #	not be available on your system.  Not all client systems
     61 #	will support ECDSA, so you'll generally want to deploy both
     62 #	RSA and ECDSA certificates to make use of ECDSA with
     63 #	compatible clients and RSA with the rest. If you want to
     64 #	deploy certificate chains with intermediate CAs for both
     65 #	RSA and ECDSA, you'll want at least OpenSSL 1.0.2, as earlier
     66 #	versions may not handle multiple chain files correctly.
     67 # .sp
     68 #	The first \fIhostname\fR argument will be the \fBCommonName\fR
     69 #	of both the subject and issuer of the self-signed certificate.
     70 #	It, and any additional \fIhostname\fR arguments, will also
     71 #	be listed as DNS alternative names in the certificate.  If
     72 #	no \fIhostname\fR is provided the value of the \fBmyhostname\fR
     73 #	main.cf parameter will be used.
     74 # .sp
     75 #	For RSA, the generated private key and certificate files
     76 #	are named \fBkey-\fIyyyymmdd-hhmmss\fB.pem\fR and
     77 #	\fBcert-\fIyyyymmdd-hhmmss\fB.pem\fR, where \fIyyyymmdd\fR
     78 #	is the calendar date and \fIhhmmss\fR is the time of day
     79 #	in UTC.  For ECDSA, the file names start with \fBeckey-\fR
     80 #	and \fBeccert-\fR instead of \fBkey-\fR and \fBcert-\fR
     81 #	respectively.
     82 # .sp
     83 #	Before deploying the new key and certificate with DANE,
     84 #	update the DNS with new DANE TLSA records, then wait for
     85 #	secondary nameservers to update and then for stale records
     86 #	in remote DNS caches to expire.
     87 # .sp
     88 #	Before deploying a new CA certificate make sure to include
     89 #	all the required intermediate issuing CA certificates in
     90 #	the certificate chain file.  The server certificate must
     91 #	be the first certificate in the chain file.  Overwrite and
     92 #	deploy the file with the original self-signed certificate
     93 #	that was generated together with the key.
     94 # .IP "\fBnew-server-cert\fR [\fB-a \fIalgorithm\fR] [\fB-b \fIbits\fR] [\fIhostname\fB...\fR]"
     95 #	This is just like \fBnew-server-key\fR except that, rather
     96 #	than generating a new private key, any currently deployed
     97 #	private key is copied to the new key file.  Thus if you're
     98 #	publishing DANE TLSA "3 1 1" or "3 1 2" records, there is
     99 #	no need to update DNS records.  The \fIalgorithm\fR and
    100 #	\fIbits\fR arguments are used only if no key of the same
    101 #	algorithm is already configured.
    102 # .sp
    103 #	This command is rarely needed, because the self-signed
    104 #	certificates generated have a 100-year nominal expiration
    105 #	time.  The underlying public key algorithms may well be
    106 #	obsoleted by quantum computers long before then.
    107 # .sp
    108 #	The most plausible reason for using this command is when
    109 #	the system hostname changes, and you'd like the name in the
    110 #	certificate to match the new hostname (not required for
    111 #	DANE "3 1 1", but some needlessly picky non-DANE opportunistic
    112 #	TLS clients may log warnings or even refuse to communicate).
    113 # .IP "\fBdeploy-server-cert \fIcertfile\fB \fIkeyfile\fR"
    114 #	This subcommand deploys the certificates in \fIcertfile\fR
    115 #	and private key in \fIkeyfile\fR (which are typically
    116 #	generated by the commands above, which will also log and
    117 #	display the full command needed to deploy the generated key
    118 #	and certificate).  After the new certificate and key are
    119 #	deployed any obsolete keys and certificates may be removed
    120 #	by hand.   The \fIkeyfile\fR and \fIcertfile\fR filenames
    121 #	may be relative to the Postfix configuration directory.
    122 # .IP "\fBoutput-server-csr\fR [\fB-k \fIkeyfile\fR] [\fIhostname\fB...\fR]"
    123 #	Write to stdout a certificate signing request (CSR) for the
    124 #	specified \fIkeyfile\fR.
    125 # .sp
    126 #	Instead of an absolute pathname or a pathname relative to
    127 #	$config_directory, \fIkeyfile\fR may specify one of the
    128 #	supported key algorithm names (see "\fBpostconf -T
    129 #	public-key-algorithms\fR"). In that case, the corresponding
    130 #	setting from main.cf is used to locate the \fIkeyfile\fR.
    131 #	The default \fIkeyfile\fR value is \fBrsa\fR.
    132 # .sp
    133 #	Zero or more \fIhostname\fR values can be specified.  The
    134 #	default \fIhostname\fR is the value of \fBmyhostname\fR
    135 #	main.cf parameter.
    136 # .IP "\fBoutput-server-tlsa\fR [\fB-h \fIhostname\fR] [\fIkeyfile\fB...\fR]"
    137 #	Write to stdout a DANE TLSA RRset suitable for a port 25
    138 #	SMTP server on host \fIhostname\fR with keys from any of
    139 #	the specified \fIkeyfile\fR values.  The default \fIhostname\fR
    140 #	is the value of the \fBmyhostname\fR main.cf parameter.
    141 # .sp
    142 #	Instead of absolute pathnames or pathnames relative to
    143 #	$config_directory, the \fIkeyfile\fR list may specify
    144 #	names of supported public key algorithms (see "\fBpostconf
    145 #	-T public-key-algorithms\fR").  In that case, the actual
    146 #	\fIkeyfile\fR list uses the values of the corresponding
    147 #	Postfix server TLS key file parameters.  If a parameter
    148 #	value is empty or equal to \fBnone\fR, then no TLSA record
    149 #	is output for that algorithm.
    150 # .sp
    151 #	The default \fIkeyfile\fR list consists of the two supported
    152 #	algorithms \fBrsa\fR and \fBecdsa\fR.
    153 # AUXILIARY COMMANDS
    154 # .IP "\fBall-default-client\fR"
    155 #	Exit with status 0 (success) if all SMTP client TLS settings are
    156 #	at their default values.  Otherwise, exit with a non-zero status.
    157 #	This is typically used as follows:
    158 # .sp
    159 #	\fBpostfix tls all-default-client &&
    160 #		postfix tls enable-client\fR
    161 # .IP "\fBall-default-server\fR"
    162 #	Exit with status 0 (success) if all SMTP server TLS settings are
    163 #	at their default values.  Otherwise, exit with a non-zero status.
    164 #	This is typically used as follows:
    165 # .sp
    166 #	\fBpostfix tls all-default-server &&
    167 #		postfix tls enable-server\fR
    168 # CONFIGURATION PARAMETERS
    169 # .ad 
    170 # .fi
    171 #	The "\fBpostfix tls \fIsubcommand\fR" feature reads
    172 #	or updates the following configuration parameters.
    173 # .IP "\fBcommand_directory (see 'postconf -d' output)\fR"
    174 #	The location of all postfix administrative commands.
    175 # .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
    176 #	The default location of the Postfix main.cf and master.cf
    177 #	configuration files.
    178 # .IP "\fBopenssl_path (openssl)\fR"
    179 #	The location of the OpenSSL command line program \fBopenssl\fR(1).
    180 # .IP "\fBsmtp_tls_loglevel (0)\fR"
    181 #	Enable additional Postfix SMTP client logging of TLS activity.
    182 # .IP "\fBsmtp_tls_security_level (empty)\fR"
    183 #	The default SMTP TLS security level for the Postfix SMTP client.
    184 # .IP "\fBsmtp_tls_session_cache_database (empty)\fR"
    185 #	Name of the file containing the optional Postfix SMTP client
    186 #	TLS session cache.
    187 # .IP "\fBsmtpd_tls_cert_file (empty)\fR"
    188 #	File with the Postfix SMTP server RSA certificate in PEM format.
    189 # .IP "\fBsmtpd_tls_eccert_file (empty)\fR"
    190 #	File with the Postfix SMTP server ECDSA certificate in PEM format.
    191 # .IP "\fBsmtpd_tls_eckey_file ($smtpd_tls_eccert_file)\fR"
    192 #	File with the Postfix SMTP server ECDSA private key in PEM format.
    193 # .IP "\fBsmtpd_tls_key_file ($smtpd_tls_cert_file)\fR"
    194 #	File with the Postfix SMTP server RSA private key in PEM format.
    195 # .IP "\fBsmtpd_tls_loglevel (0)\fR"
    196 #	Enable additional Postfix SMTP server logging of TLS activity.
    197 # .IP "\fBsmtpd_tls_received_header (no)\fR"
    198 #	Request that the Postfix SMTP server produces Received:  message
    199 #	headers that include information about the protocol and cipher used,
    200 #	as well as the remote SMTP client CommonName and client certificate issuer
    201 #	CommonName.
    202 # .IP "\fBsmtpd_tls_security_level (empty)\fR"
    203 #	The SMTP TLS security level for the Postfix SMTP server; when
    204 #	a non-empty value is specified, this overrides the obsolete parameters
    205 #	smtpd_use_tls and smtpd_enforce_tls.
    206 # .IP "\fBtls_random_source (see 'postconf -d' output)\fR"
    207 #	The external entropy source for the in-memory \fBtlsmgr\fR(8) pseudo
    208 #	random number generator (PRNG) pool.
    209 # SEE ALSO
    210 #	master(8) Postfix master program
    211 #	postfix(1) Postfix administrative interface
    212 # README FILES
    213 # .ad
    214 # .fi
    215 #	Use "\fBpostconf readme_directory\fR" or
    216 #	"\fBpostconf html_directory\fR" to locate this information.
    217 # .na
    218 # .nf
    219 #	TLS_README, Postfix TLS configuration and operation
    220 # LICENSE
    221 # .ad
    222 # .fi
    223 #	The Secure Mailer license must be distributed with this software.
    224 # HISTORY
    225 #	The "\fBpostfix tls\fR" command was introduced with Postfix
    226 #	version 3.1.
    227 # AUTHOR(S)
    228 #	Viktor Dukhovni
    229 #--
    230 
    231 RSA_BITS=2048		# default
    232 EC_CURVE=secp256r1	# default
    233 
    234 case $daemon_directory in
    235 "") echo This script must be run by the postfix command. 1>&2
    236     echo Do not run directly. 1>&2
    237     exit 1;;
    238 esac
    239 
    240 umask 022
    241 SHELL=/bin/sh
    242 
    243 postconf=$command_directory/postconf
    244 LOGGER="$command_directory/postlog -t $MAIL_LOGTAG/postfix-tls-script"
    245 INFO="$LOGGER -p info"
    246 WARN="$LOGGER -p warn"
    247 ERROR="$LOGGER -p error"
    248 FATAL="$LOGGER -p fatal"
    249 
    250 # Overwrite SMTP client and server settings only when these are at defaults.
    251 client_settings="
    252     smtp_use_tls 
    253     smtp_enforce_tls 
    254     smtp_tls_enforce_peername 
    255     smtp_tls_security_level 
    256     smtp_tls_cert_file
    257     smtp_tls_dcert_file
    258     smtp_tls_eccert_file
    259 "
    260 
    261 server_settings="
    262     smtpd_use_tls 
    263     smtpd_enforce_tls 
    264     smtpd_tls_security_level 
    265     smtpd_tls_cert_file
    266     smtpd_tls_dcert_file
    267     smtpd_tls_eccert_file
    268 "
    269 
    270 #
    271 # Can't do much without these in place.
    272 #
    273 cd $command_directory || {
    274     # Let's hope there's a "postlog" somewhere else on the PATH
    275     FATAL="postlog -p fatal -t $MAIL_LOGTAG/postfix-tls-script"
    276     msg="no Postfix command directory '${command_directory}'"
    277     $FATAL "$msg" || { echo "$msg" >&2; sleep 1; }
    278     exit 1
    279 }
    280 
    281 check_getopt() {
    282     OPTIND=1
    283     a=
    284     b=
    285     c=
    286     set -- -a 1 -b 2 -c -- -pos
    287     while getopts :a:b:c o
    288     do
    289 	case $o in
    290 	a) a="${OPTARG}";;
    291 	b) b="${OPTARG}";;
    292 	c) c=3;;
    293 	*) return 1;;
    294 	esac
    295     done
    296     shift `expr ${OPTIND} - 1`
    297     if [ "${a}" != "1" -o "${b}" != 2 -o "${c}" != 3 \
    298 	 -o "${OPTIND}" -ne 7 -o "$1" != "-pos" ]; then
    299 	return 1
    300     fi
    301 }
    302 
    303 check_getopt || {
    304     $FATAL "/bin/sh does not implement a compatible 'getopts' built-in"
    305     exit 1
    306 }
    307 
    308 # ----- BEGIN OpenSSL-specific -----
    309 
    310 # No need to set the location of the OpenSSL command in each Postfix instance,
    311 # the value from the default instance is used for all instances.
    312 #
    313 default_config_directory=`$postconf -dh config_directory`
    314 openssl=`$postconf -c $default_config_directory -xh openssl_path`
    315 "$openssl" version >/dev/null 2>&1 || {
    316     $FATAL "No working openssl(1) command found with 'openssl_path = $openssl'"
    317     exit 1
    318 }
    319 
    320 # ----- END OpenSSL-specific -----
    321 
    322 test -n "$config_directory" -a -d "$config_directory" || {
    323     $FATAL no Postfix configuration directory $config_directory!
    324     exit 1
    325 }
    326 
    327 # Do we support TLS and if so which algorithms?
    328 #
    329 $postconf -T compile-version | grep . >/dev/null || {
    330     mail_version=`$postconf -dh mail_version`
    331     $FATAL "Postfix $mail_version is not compiled with TLS support"
    332     exit 1
    333 }
    334 rsa=
    335 ecdsa=
    336 for _algo in `$postconf -T public-key-algorithms | grep -E '^(rsa|ecdsa)$'`
    337 do
    338     eval $_algo=$_algo
    339 done
    340 
    341 # ----- BEGIN OpenSSL-specific -----
    342 
    343 if [ -n "${ecdsa}" ]; then
    344     $openssl ecparam -name secp256r1 >/dev/null 2>&1 || {
    345 	cat <<-EOM | $WARN
    346 	Postfix supports ECDSA, but the $openssl command does not. Consider
    347 	setting the openssl_path parameter to a more capable version of the
    348 	command-line utility than $openssl (with PATH=$PATH).
    349 	EOM
    350 	ecdsa=
    351     }
    352 fi
    353 if [ -n "${rsa}" ]; then
    354    DEFALG=rsa
    355 elif [ -n "${ecdsa}" ]; then
    356    DEFALG=ecdsa
    357 else
    358     mail_version=`$postconf -dh mail_version`
    359     $FATAL "Postfix $mail_version does not support either RSA or ECDSA"
    360     exit 1
    361 fi
    362 
    363 # Make sure stdin is open when testing
    364 if [ -r /dev/stdin ] < /dev/null; then
    365     stdin=/dev/stdin
    366 elif [ -r /dev/fd/0 ] </dev/null; then
    367     stdin=/dev/fd/0
    368 else
    369     $FATAL No /dev/fd/0 or /dev/stdin found
    370     exit 1
    371 fi
    372 
    373 hex_sha256() {
    374     $openssl dgst -binary -sha256 | od -An -vtx1 | tr -d ' \012'
    375 }
    376 
    377 # We require SHA2-256 support from openssl(1)
    378 #
    379 null256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
    380 tmp=`hex_sha256 </dev/null 2>/dev/null`
    381 if [ "${tmp}" != "${null256}" ]; then
    382     cat <<EOF >&2
    383 Your $openssl does not support the SHA2-256 digest algorithm. To enable
    384 'postfix tls', install an OpenSSL that does. Install its openssl(1) command
    385 at /usr/local/bin/openssl or other suitable location, and set the
    386 'openssl_path' parameter in $default_config_directory/main.cf accordingly.
    387 EOF
    388     $FATAL "No 'postfix tls' support when openssl(1) is obsolete"
    389     exit 1
    390 fi
    391 
    392 read_key() {
    393     [ -n "$1" -a -f "$1" ] || return 1
    394 
    395     # Old OpenSSL versions return success even for unsupported sub-commands!
    396     # So we inspect the output instead.	 Don't prompt if the key is password
    397     # protected.
    398     #
    399     while read cmd key_algo key_param cert_param; do
    400 	$openssl $cmd -passin "pass:umask 077" -in "$1" |
    401 	    grep . && return 0
    402     done 2>/dev/null <<-EOF
    403 	rsa rsa smtpd_tls_key_file smtpd_tls_cert_file
    404 	ec ecdsa smtpd_tls_eckey_file smtpd_tls_eccert_file
    405 	EOF
    406     return 1
    407 }
    408 
    409 pubkey_dgst() {
    410     [ -n "$1" -a -f "$1" ] || return 1
    411 
    412     # Old OpenSSL versions return success even for unsupported sub-commands!
    413     # So we inspect the output instead.
    414     #
    415     for cmd in ec rsa; do
    416 	$openssl $cmd -passin "pass:umask 077" -in "$1" -pubout |
    417 	$openssl $cmd -pubin -outform DER |
    418 	hex_sha256 | grep -E -v "${null256}" && return 0
    419     done 2>/dev/null
    420     return 1
    421 }
    422 
    423 cert_pubkey_dgst() {
    424     [ -n "$1" -a -f "$1" ] || return 1
    425 
    426     # Old OpenSSL versions return success even for unsupported sub-commands!
    427     # So we inspect the output instead.
    428     #
    429     for cmd in ec rsa; do
    430 	$openssl x509 -pubkey -noout -in "$1" |
    431 	$openssl $cmd -pubin -outform DER |
    432 	hex_sha256 | grep -E -v "${null256}" && return 0
    433     done 2>/dev/null
    434     return 1
    435 }
    436 
    437 copy_key() {
    438     _algo=$1; shift
    439     _bits=$1; shift
    440     _fold=$1; shift
    441     _fnew=$1; shift
    442     _umask=`umask`
    443 
    444     umask 077
    445     read_key "${_fold}" > "${_fnew}"	# sets key_algo of current key
    446     _ret=$?
    447     umask "${_umask}"
    448 
    449     if [ "${_ret}" -ne 0 ]; then
    450 	$FATAL "Error copying private key from '${_fold}' to '${_fnew}'"
    451 	return 1
    452     fi
    453     if [ "${key_algo}" != "${_algo}" ]; then
    454 	$FATAL "Key algorithm '$key_algo' of '${_fold}' is not '${_algo}'"
    455 	return 1
    456     fi
    457     # XXX: We'd need C-code in postconf to portably check for compatible "bits"
    458 }
    459 
    460 create_key() {
    461     _algo=$1
    462     _bits=$2
    463     _fnew=$3
    464     _umask=`umask`
    465 
    466     case $_algo in
    467         "") $FATAL "Internal error: empty algorithm"; return 1;;
    468       $rsa) set -- "${openssl}" genrsa -out "${_fnew}" "${_bits}";;
    469     $ecdsa) set -- "${openssl}" ecparam -param_enc named_curve -genkey \
    470 		-out "${_fnew}" -name "${_bits}";;
    471 	 *) $FATAL "Internal error: bad algorithm '${_algo}'"
    472 	    return 1;;
    473     esac
    474 
    475     umask 077
    476     _err=`"$@" 2>&1`
    477     _ret=$?
    478     umask "${_umask}"
    479 
    480     if [ "${_ret}" -ne 0 ]; then
    481 	echo "${_err}" | $WARN
    482 	$FATAL "error generating new ${_algo} ${_bits} private key"
    483 	return 1
    484     fi
    485 }
    486 
    487 create_cert() {
    488     _k=$1; shift
    489     _c=$1; shift
    490     set_fqdn "$1"
    491     if [ $# -gt 0 ]; then shift; fi
    492     set -- "$fqdn" "$@"
    493 
    494     if [ -r "${_c}" ]; then
    495 	$FATAL "New certificate file already exists: ${_c}"
    496 	return 1
    497     fi
    498 
    499     # Generate a new self-signed (~100 year) certificate
    500     #
    501     (
    502 	echo "default_md = sha256"
    503 	echo "x509_extensions = v3"
    504 	echo "prompt = yes"
    505 	echo "distinguished_name = dn"
    506 	echo "[dn]"
    507 	echo "[v3]"
    508 	echo "basicConstraints = CA:false"
    509 	echo "subjectKeyIdentifier = hash"
    510 	echo "extendedKeyUsage = serverAuth, clientAuth"
    511 	echo "subjectAltName = @alts"
    512 	echo "[alts]"
    513 	i=1; for dns in "$@"; do
    514 	    # XXX map empty to $myhostname
    515 	    echo "DNS.$i = $dns"
    516 	    i=`expr $i + 1`
    517 	done
    518     ) | $openssl req -x509 -config $stdin -new -key "${_k}" \
    519 	    -subj "/CN=$fqdn" -days 36525 -out "${_c}" || {
    520 	rm -f "${_c}" "${_k}"
    521 	$FATAL "error generating self-signed SSL certificate"
    522 	return 1
    523     }
    524 }
    525 
    526 output_server_csr() {
    527     set_keyfile "$1" || return 1
    528     shift
    529     set_fqdn "$1" || return 1
    530     shift
    531     set -- "$fqdn" "$@"
    532     (
    533 	echo "default_md = sha256"
    534 	echo "req_extensions = v3"
    535 	echo "prompt = yes"
    536 	echo "distinguished_name = dn"
    537 	echo "[dn]"
    538 	echo "[v3]"
    539 	echo "subjectKeyIdentifier = hash"
    540 	echo "extendedKeyUsage = serverAuth, clientAuth"
    541 	echo "subjectAltName = @alts"
    542 	echo "[alts]"
    543 	i=1; for dns in "$@"; do
    544 	    echo "DNS.$i = $dns"
    545 	    i=`expr $i + 1`
    546 	done
    547     ) | $openssl req -config $stdin -new -key "$keyfile" -subj /
    548 }
    549 
    550 # ----- END OpenSSL-specific -----
    551 
    552 info_enable_client() {
    553 	cat <<-EOM
    554 	*** Non-default SMTP client TLS settings detected, no changes made.
    555 	For opportunistic TLS in the Postfix SMTP client, the below settings
    556 	are typical:
    557 	  smtp_tls_security_level = may
    558 	  smtp_tls_loglevel = 1
    559 	EOM
    560 	if get_cache_db_type dbtype
    561 	then
    562 	    echo "  smtp_tls_session_cache_database = ${dbtype}:\${data_directory}/smtp_scache"
    563 	fi
    564 }
    565 
    566 info_client_deployed() {
    567 	cat <<-EOM
    568 	Enabled opportunistic TLS in the Postfix SMTP client.
    569 	Run the command:
    570 	  # postfix reload
    571 	if you want the new settings to take effect immediately.
    572 	EOM
    573 }
    574 
    575 info_enable_server() {
    576 	cat <<-EOM
    577 	*** Non-default SMTP server TLS settings detected, no changes made.
    578 	For opportunistic TLS in the Postfix SMTP server, the below settings
    579 	are typical:
    580 	  smtpd_tls_security_level = may
    581 	  smtpd_tls_loglevel = 1
    582 	You can use "postfix tls new-server-cert" to create a new certificate.
    583 	Or, "postfix tls new-server-key" to also force a new private key.
    584 	If you publish DANE TLSA records, see:
    585 	  https://tools.ietf.org/html/rfc7671#section-8
    586 	  https://tools.ietf.org/html/rfc7671#section-5.1
    587 	  https://tools.ietf.org/html/rfc7671#section-5.2
    588 	  https://community.letsencrypt.org/t/please-avoid-3-0-1-and-3-0-2-dane-tlsa-records-with-le-certificates/7022
    589 	EOM
    590 }
    591 
    592 # args: certfile keyfile deploy
    593 info_created() {
    594 	cat <<-EOM
    595 	New private key and self-signed certificate created. To deploy run:
    596 	  # postfix tls deploy-server-cert $1 $2
    597 	EOM
    598 }
    599 
    600 # args: certfile keyfile deploy
    601 info_server_deployed() {
    602 	if [ "$3" = "enable" ]; then
    603 	    echo "Enabled opportunistic TLS in the Postfix SMTP server"
    604 	fi
    605 	cat <<-EOM
    606 	New TLS private key and certificate deployed.
    607 	Run the command:
    608 	  # postfix reload
    609 	if you want the new settings to take effect immediately.
    610 	EOM
    611 }
    612 
    613 # args: certfile keyfile deploy
    614 info_csr() {
    615 	cat <<-EOM
    616 	To generate a CSR run:
    617 	  # postfix tls output-server-csr -k $2 [<hostname> ...]
    618 	EOM
    619 	if [ -z "$3" ]; then
    620 	    echo "Save the signed certificate chain in $1, and deploy as above."
    621 	else
    622 	    echo "Save the signed certificate chain in $1."
    623 	fi
    624 }
    625 
    626 # args: certfile keyfile deploy
    627 info_tlsa() {
    628 	# If already deployed, info for how to show all the deployed keys.
    629 	# Otherwise, just the new keys, so that TLSA records can be updated
    630 	# first.
    631 	if [ -n "$3" ]; then shift $#; fi
    632 	cat <<-EOM
    633 	To generate TLSA records run:
    634 	  # postfix tls output-server-tlsa [-h <hostname>] $2
    635 	EOM
    636 }
    637 
    638 # args: certfile keyfile deploy
    639 info_dane_dns() {
    640 	# If already deployed, too late to wait, otherwise advise updating TLSA
    641 	# RRs before deployment.
    642 	if [ -n "$3" ]; then
    643 	    cat <<-EOM
    644 	(If you have DANE TLSA RRs, update them as soon as possible to match
    645 	the newly deployed keys).
    646 	EOM
    647 	else
    648 	    cat <<-EOM
    649 	(deploy after updating the DNS and waiting for stale RRs to expire).
    650 	EOM
    651 	fi
    652 }
    653 
    654 set_fqdn() {
    655     if [ -n "$1" ]; then fqdn=$1; return 0; fi
    656     fqdn=`$postconf -xh myhostname` || return 1
    657     case $fqdn in /*) fqdn=`cat "${fqdn}"` || return 1;; esac
    658 }
    659 
    660 set_keyfile() {
    661     keyfile=$1
    662     case $keyfile in
    663        rsa) if [ -n "${rsa}" ]; then
    664 		keyfile=`$postconf -nxh smtpd_tls_key_file`
    665 	    else
    666 		keyfile=
    667 	    fi
    668 	    ;;
    669      ecdsa) if [ -n "${ecdsa}" ]; then
    670 		keyfile=`$postconf -nxh smtpd_tls_eckey_file`
    671 	    else
    672 		keyfile=
    673 	    fi
    674 	    ;;
    675         "") : empty ok;;
    676       none) : see below;;
    677         /*) ;;
    678          *) # User-specified key pathnames are relative to the configuration
    679 	    # directory
    680 	    keyfile="${config_directory}/${keyfile}";;
    681     esac
    682     if [ "${keyfile}" = "none" ]; then keyfile= ; fi
    683 }
    684 
    685 check_key() {
    686     read_key "$1" >/dev/null && return 0
    687     $FATAL "no private key found in file: $1"
    688     return 1
    689 }
    690 
    691 # Create new key or copy existing if specified.
    692 #
    693 ensure_key() {
    694     _algo=$1; shift
    695     _bits=$1; shift
    696     stamp=`TZ=UTC date +%Y%m%d-%H%M%S`
    697 
    698     case $_algo in
    699 	"") $FATAL "Internal error: empty algorithm "; return 1;;
    700       $rsa) keyfile="${config_directory}/key-${stamp}.pem"
    701 	    certfile="${config_directory}/cert-${stamp}.pem";;
    702     $ecdsa) keyfile="${config_directory}/eckey-${stamp}.pem"
    703 	    certfile="${config_directory}/eccert-${stamp}.pem";;
    704 	 *) $FATAL "Internal error: bad algorithm '${_algo}'"
    705 	    return 1;;
    706     esac
    707 
    708     if [ -r "${keyfile}" ]; then
    709 	$FATAL "New private key file already exists: ${keyfile}"
    710 	return 1
    711     fi
    712     if [ -r "${certfile}" ]; then
    713 	$FATAL "New certificate file already exists: ${certfile}"
    714 	return 1
    715     fi
    716 
    717     if [ -n "$1" ]; then
    718 	copy_key "${_algo}" "${_bits}" "$1" "${keyfile}" && return 0
    719     else
    720 	create_key "${_algo}" "${_bits}" "${keyfile}" && return 0
    721     fi
    722     rm -f "${keyfile}"
    723     return 1
    724 }
    725 
    726 init_random_source() {
    727     tls_random_source=$1
    728 
    729     if [ -z "${tls_random_source}" ]; then
    730 	tls_random_source=`$postconf -xh tls_random_source`
    731     fi
    732     if [ -n "${tls_random_source}" ]; then
    733 	return 0
    734     fi
    735     if [ -r /dev/urandom ]
    736     then
    737 	tls_random_source=dev:/dev/urandom
    738     else
    739 	$FATAL no default TLS random source defined and no /dev/urandom
    740 	return 1
    741     fi
    742 }
    743 
    744 # Don't be too clever by half.
    745 all_default() {
    746     for var in "$@"
    747     do
    748 	val=`$postconf -nh "${var}"`
    749 	if [ -n "$val" ]; then return 1; fi
    750     done
    751     return 0
    752 }
    753 
    754 # Select read-write database type for TLS session caches.
    755 #
    756 get_cache_db_type() {
    757     var=$1; shift
    758     prio=0
    759     ret=1
    760     for _dbtype in `$postconf -m`
    761     do
    762 	_prio=0
    763 	case $_dbtype in
    764 	 lmdb) _prio=2;;
    765 	btree) _prio=1;;
    766 	esac
    767 	if [ "$_prio" -gt "$prio" ]
    768 	then
    769 	    eval "$var=\$_dbtype"
    770 	    prio=$_prio
    771 	    ret=0
    772 	fi
    773     done
    774     return $ret
    775 }
    776 
    777 deploy_server_cert() {
    778     certfile=$1; shift
    779     keyfile=$1; shift
    780     case $# in 0) deploy=;; *) deploy=$1; shift;; esac
    781 
    782     # Sets key_algo, key_param and cert_param
    783     check_key "$keyfile" || return 1
    784 
    785     cd=`cert_pubkey_dgst "${certfile}"` || {
    786 	$FATAL "error computing certificate public key digest"
    787 	return 1
    788     }
    789     kd=`pubkey_dgst "$keyfile"` || {
    790 	$FATAL "error computing public key digest"
    791 	return 1
    792     }
    793 
    794     if [ "$cd" != "$kd" ]; then
    795 	$FATAL "Certificate in ${certfile} does not match key in ${keyfile}"
    796 	return 1
    797     fi
    798 
    799     set -- \
    800 	"${key_param} = ${keyfile}" \
    801 	"${cert_param} = ${certfile}"
    802 
    803     if [ "${deploy}" = "enable" ]; then
    804 	set -- "$@" \
    805 	    "smtpd_tls_security_level = may" \
    806 	    "smtpd_tls_received_header = yes" \
    807 	    "smtpd_tls_loglevel = 1"
    808     fi
    809 
    810     if [ -n "${tls_random_source}" ]; then
    811 	set -- "$@" "tls_random_source = ${tls_random_source}"
    812     fi
    813 
    814     # All in one shot, since postconf delays modifying "hot" main.cf files.
    815     $postconf -e "$@" || return 1
    816 }
    817 
    818 # Prepare a new cert and perhaps re-use any existing private key.
    819 #
    820 new_server_cert() {
    821     algo=$1; shift
    822     bits=$1; shift
    823     oldkey=$1; shift
    824     deploy=$1; shift
    825 
    826     # resets keyfile (copy or else new) and new certfile
    827     ensure_key "$algo" "$bits" "${oldkey}" || return 1
    828     create_cert "${keyfile}" "${certfile}" "$@" || return 1
    829     if [ -n "${deploy}" ]; then
    830 	deploy_server_cert "${certfile}" "${keyfile}" "${deploy}" || return 1
    831     fi
    832 
    833     (
    834 	if [ -z "${deploy}" ]; then
    835 	    info_created "${certfile}" "${keyfile}" "${deploy}"
    836 	else
    837 	    info_server_deployed "${certfile}" "${keyfile}" "${deploy}"
    838 	fi
    839 	info_csr "${certfile}" "${keyfile}" "${deploy}"
    840 	info_tlsa "${certfile}" "${keyfile}" "${deploy}"
    841 	if [ -z "${oldkey}" ]; then
    842 	    info_dane_dns "${certfile}" "${keyfile}" "${deploy}"
    843 	fi
    844     ) | $INFO
    845 }
    846 
    847 enable_client() {
    848     if all_default ${client_settings}
    849     then
    850 	set -- \
    851 	    "smtp_tls_security_level = may" \
    852 	    "smtp_tls_loglevel = 1"
    853 
    854 	if get_cache_db_type dbtype
    855 	then
    856 	    set -- "$@" \
    857 		"smtp_tls_session_cache_database = ${dbtype}:${data_directory}/smtp_scache"
    858 	fi
    859 
    860 	if [ -n "${tls_random_source}" ]; then
    861 	    set -- "$@" "tls_random_source = ${tls_random_source}"
    862 	fi
    863 
    864 	# All in one shot, since postconf delays modifying "hot" main.cf files.
    865 	$postconf -e "$@" || return 1
    866 	info_client_deployed
    867     else
    868 	info_enable_client
    869     fi | $INFO
    870 }
    871 
    872 enable_server() {
    873     algo=$1; shift
    874     bits=$1; shift
    875 
    876     if all_default ${server_settings}
    877     then
    878 	# algo bits keyfile deploy [hostnames ...]
    879 	new_server_cert "${algo}" "${bits}" "" "enable" "$@" || return 1
    880     else
    881 	info_enable_server | $INFO
    882     fi
    883 }
    884 
    885 output_server_tlsa() {
    886     hostname=$1
    887     check_key "$2" || return 1
    888     data=`pubkey_dgst "$2"` || return 1
    889     if [ -z "$data" ]
    890     then
    891 	$FATAL error computing SHA2-256 SPKI digest of "$key"
    892 	return 1
    893     fi
    894     echo "_25._tcp.$hostname. IN TLSA 3 1 1 $data"
    895 }
    896 
    897 #
    898 # Parse JCL
    899 #
    900 case $1 in
    901 enable-client)
    902 	cmd=$1; shift; OPTIND=1
    903 	rand=
    904 	while getopts :r: _opt
    905 	do
    906 	    case $_opt in
    907 	    r) rand="${OPTARG}";;
    908 	    *) $FATAL "usage: postfix tls $cmd [-r devrandom]"
    909 	       exit 1;;
    910 	    esac
    911 	done
    912 
    913 	# No positional arguments supported with enable-client
    914 	if [ $# -ge "${OPTIND}" ]; then
    915 	    $FATAL "usage: postfix tls $cmd [-r devrandom]"
    916 	    exit 1
    917 	fi
    918 	# But, shift anyway
    919 	shift `expr $OPTIND - 1`
    920 
    921 	init_random_source "${rand}" || exit 1
    922 	enable_client || exit 1
    923 	;;
    924 
    925 enable-server)
    926 	cmd=$1; shift; OPTIND=1
    927 	algo=$DEFALG
    928 	bits=
    929 	rand=
    930 	while getopts :a:b:r: _opt
    931 	do
    932 	    case $_opt in
    933 	    a) algo="${OPTARG}";;
    934 	    b) bits="${OPTARG}";;
    935 	    r) rand="${OPTARG}";;
    936 	    *) $FATAL "usage: postfix tls $cmd [-a algorithm] [-b bits ] [-r devrandom] [hostname ...]"
    937 	       exit 1;;
    938 	    esac
    939 	done
    940 
    941 	# Here positional arguments are hostnames for the new certificate, as
    942 	# many as the user wants
    943 	shift `expr $OPTIND - 1`
    944 
    945 	case $algo in
    946 	    "") $FATAL "Internal error: empty algorithm "; return 1;;
    947 	  $rsa) : ${bits:=${RSA_BITS}};;
    948 	$ecdsa) : ${bits:=${EC_CURVE}};;
    949 	     *) $FATAL "Unsupported private key algorithm: $algo"
    950 		exit 1;;
    951 	esac
    952 
    953 	init_random_source "${rand}" || exit 1
    954 	enable_server "${algo}" "${bits}" "$@" || exit 1
    955 	;;
    956 
    957 new-server-key)
    958 	cmd=$1; shift; OPTIND=1
    959 	algo=$DEFALG
    960 	while getopts :a:b: _opt
    961 	do
    962 	    case $_opt in
    963 	    a) algo="${OPTARG}";;
    964 	    b) bits="${OPTARG}";;
    965 	    *) $FATAL "usage: postfix tls $cmd [-a algorithm] [-b bits ] [hostname ...]"
    966 	       exit 1;;
    967 	    esac
    968 	done
    969 
    970 	# Here positional arguments are hostnames for the new certificate, as
    971 	# many as the user wants
    972 	shift `expr $OPTIND - 1`
    973 
    974 	case $algo in
    975 	    "") $FATAL "Internal error: empty algorithm "; return 1;;
    976 	  $rsa) : ${bits:=${RSA_BITS}};;
    977 	$ecdsa) : ${bits:=${EC_CURVE}};;
    978 	     *) $FATAL "Unsupported public key algorithm: $algo"
    979 		exit 1;;
    980 	esac
    981 
    982 	# Force new key
    983 	new_server_cert "${algo}" "${bits}" "" "" "$@" || exit 1
    984 	;;
    985 
    986 new-server-cert)
    987 	cmd=$1; shift; OPTIND=1
    988 	algo=$DEFALG
    989 	while getopts :a:b: _opt
    990 	do
    991 	    case $_opt in
    992 	    a) algo="${OPTARG}";;
    993 	    b) bits="${OPTARG}";;
    994 	    *) $FATAL "usage: postfix tls $cmd [-a algorithm] [-b bits ] [hostname ...]"
    995 	       exit 1;;
    996 	    esac
    997 	done
    998 
    999 	# Here positional arguments are hostnames for the new certificate, as
   1000 	# many as the user wants
   1001 	shift `expr $OPTIND - 1`
   1002 
   1003 	case $algo in
   1004 	    "") $FATAL "Invalid empty key algorithm"; exit 1;;
   1005 	  $rsa) : ${bits:=${RSA_BITS}};;
   1006 	$ecdsa) : ${bits:=${EC_CURVE}};;
   1007 	     *) $FATAL "Unsupported private key algorithm: $algo"
   1008 		exit 1;;
   1009 	esac
   1010 
   1011 	# Existing keyfile or empty
   1012 	set_keyfile "${algo}"
   1013 
   1014 	if [ -n "${keyfile}" -a ! -f "${keyfile}" ]; then
   1015 	    echo "Key file: ${keyfile} not found, creating new keys" | $WARN
   1016 	    keyfile=
   1017 	fi
   1018 
   1019 	# Try to re-use (copy) existing key.
   1020 	new_server_cert "${algo}" "${bits}" "${keyfile}" "" "$@" || exit 1
   1021 	;;
   1022 
   1023 deploy-server-cert)
   1024 	if [ $# -ne 3 ]; then
   1025 	    $FATAL "usage: postfix tls $1 certfile keyfile"
   1026 	    exit 1
   1027 	fi
   1028 	shift
   1029 
   1030 	# User-specified key and cert pathnames are relative to the
   1031 	# configuration directory
   1032 	#
   1033 	case "${1}" in
   1034 	/*) certfile="${1}" ;;
   1035 	 *) certfile="${config_directory}/${1}" ;;
   1036 	esac
   1037 	case "${2}" in
   1038 	/*) keyfile="${2}" ;;
   1039 	 *) keyfile="${config_directory}/${2}" ;;
   1040 	esac
   1041 
   1042 	deploy_server_cert "${certfile}" "${keyfile}" || exit 1
   1043 	info_server_deployed "${certfile}" "${keyfile}" "deploy" | $INFO
   1044 	;;
   1045 
   1046 output-server-csr)
   1047 	cmd=$1; shift; OPTIND=1
   1048 	k=
   1049 	while getopts :k: _opt
   1050 	do
   1051 	    case $_opt in
   1052 	    k) k="${OPTARG}";;
   1053 	    *) $FATAL "usage: postfix tls $cmd [-k keyfile] [hostname ...]"
   1054 	       exit 1;;
   1055 	    esac
   1056 	done
   1057 
   1058 	# Here positional arguments are hostnames for the new certificate, as
   1059 	# many as the user wants
   1060 	shift `expr $OPTIND - 1`
   1061 
   1062 	if [ -n "${k}" ]; then
   1063 	    set_keyfile "${k}"
   1064 	else
   1065 	    for _algo in $rsa $ecdsa
   1066 	    do
   1067 		set_keyfile "${_algo}"
   1068 		if [ -n "${keyfile}" ]; then
   1069 		    break
   1070 		fi
   1071 	    done
   1072 	fi
   1073 
   1074 	if [ -z "${keyfile}" -o ! -r "${keyfile}" ]; then
   1075 	    $FATAL "No usable keyfile specified or configured"
   1076 	    exit 1
   1077 	fi
   1078 
   1079 	# Default <hostname> from $myhostname
   1080 	if [ $# -eq 0 ]; then
   1081 	    set_fqdn
   1082 	    set -- "$fqdn"
   1083 	fi
   1084 
   1085 	# Output a CSR for the requested names
   1086 	output_server_csr "$keyfile" "$@" || exit 1
   1087 	;;
   1088 
   1089 output-server-tlsa)
   1090 	cmd=$1; shift; OPTIND=1
   1091 	hostname=
   1092 	while getopts :h: _opt
   1093 	do
   1094 	    case $_opt in
   1095 	    h) hostname="${OPTARG}";;
   1096 	    *) $FATAL "usage: postfix tls $cmd [-h hostname] [keyfile ...]"
   1097 	       exit 1;;
   1098 	    esac
   1099 	done
   1100 	set_fqdn "${hostname}"
   1101 
   1102 	# Here positional arguments are keyfiles for which we output "3 1 1"
   1103 	# TLSA RRs, as many keyfiles as the user wants.  By default the live
   1104 	# RSA and/or ECDSA keys.
   1105 	shift `expr $OPTIND - 1`
   1106 
   1107 	if [ $# -eq 0 ]; then set -- $rsa $ecdsa; fi
   1108 
   1109 	found=
   1110 	for _k in "$@"
   1111 	do
   1112 	    set_keyfile "${_k}"
   1113 	    if [ -z "${keyfile}" ]; then continue; fi
   1114 	    echo "; ${keyfile}"
   1115 	    output_server_tlsa "${fqdn}" "${keyfile}" || exit 1
   1116 	    found=1
   1117 	done
   1118 	if [ -z "${found}" ]; then
   1119 	    $FATAL "No usable keyfiles specified or configured"
   1120 	    exit 1
   1121 	fi
   1122 	;;
   1123 
   1124 all-default-client)
   1125 	cmd=$1; shift; OPTIND=1
   1126 
   1127 	# No arguments for all-default-client
   1128 	if [ $# -ge "${OPTIND}" ]; then
   1129 	    $FATAL "usage: postfix tls $cmd"
   1130 	    exit 1
   1131 	fi
   1132 
   1133 	all_default ${client_settings} || exit 1
   1134 	;;
   1135 
   1136 all-default-server)
   1137 	cmd=$1; shift; OPTIND=1
   1138 
   1139 	# No arguments for all-default-server
   1140 	if [ $# -ge "${OPTIND}" ]; then
   1141 	    $FATAL "usage: postfix tls $cmd"
   1142 	    exit 1
   1143 	fi
   1144 
   1145 	all_default ${server_settings} || exit 1
   1146 	;;
   1147 
   1148 *)
   1149 	$ERROR "unknown tls command: '$1'"
   1150 	$FATAL "usage: postfix tls enable-client (or enable-server, new-server-key, new-server-cert, deploy-server-cert, output-server-csr, output-server-tlsa, all-default-client, all-default-server)"
   1151 	exit 1
   1152 	;;
   1153 
   1154 esac
   1155