ClusterLabs/hawk-apiserver

View on GitHub
tools/generate-ssl-cert

Summary

Maintainability
Test Coverage
#!/usr/bin/env bash
# Copyright (c) 2009-2015 Tim Serong <tserong@suse.com>
# Copyright (c) 2017 Kristoffer Gronlund <kgronlund@suse.com>
# See COPYING for license.

#
# Generate a self-signed SSL certificate if necessary. Will not
# generate certificate if one already exists, so administrator can
# install a "real" certificate by simply replacing the generated
# one at /etc/ssl/certs/hawk.pem
#
# NOTE: This is essentially a heavily stripped-back shell version
# of the more generic check-create-certificate.pl script from WebYaST.
# If this latter script becomes generally available, we should prefer
# using it over this.
#

openssl_bin=/usr/bin/openssl
c_rehash_bin=/usr/bin/c_rehash

cert_key_file=sslgen.key
[ -n "$SSLGEN_KEY" ] && cert_key_file=$SSLGEN_KEY

cert_file=sslgen.pem
[ -n "$SSLGEN_CERT" ] && cert_file=$SSLGEN_CERT

log_file=$(dirname "$0")/certificate.log

# Hawk had a strange pair of bugs: generate-ssl-cert will sometimes
# generate the key in the .pem file and the certificate in the .key
# file. The service file would also look for the key in the .pem file
# and vice versa. To work around this, we check and swap the files
# both before and after generation. (bsc#954159)
swap_key_certificate() {
  if [ -e "$cert_key_file" ] && [ -e "$cert_file" ]; then
    if head -1 <"$cert_key_file" | grep "CERTIFICATE" >/dev/null; then
      if head -1 <"$cert_file" | grep "PRIVATE KEY" >/dev/null; then
        mv -f -- "$cert_key_file" "$cert_file.$$"
        mv -f -- "$cert_file" "$cert_key_file.$$"
        mv -f -- "$cert_key_file.$$" "$cert_key_file"
        mv -f -- "$cert_file.$$" "$cert_file"
      fi
    fi
  fi
}

swap_key_certificate

[ -e "$cert_key_file" ] && [ -e "$cert_file" ] && exit 0

echo "No SSL certificate found. Creating one now."
mkdir -p "$(dirname "$cert_key_file")"
mkdir -p "$(dirname "$cert_file")"

old_mask=$(umask)
umask 137

CN=$(hostname -f)

[ -z "$CN" ] && CN=$(hostname)
[ -z "$CN" ] && CN=localhost

$openssl_bin req -x509 -sha256 -nodes -days 1095 -newkey rsa:2048 -batch -config /dev/fd/0 -keyout "$cert_key_file" -out "$cert_file" >"$log_file" 2>&1 <<CONF
[req]
distinguished_name = user_dn
prompt = no

[user_dn]
commonName=$CN
emailAddress=root@$CN
organizationName=SUSE
organizationalUnitName=Automatically Generated Certificate
CONF

rc=$?

if [ $rc -eq 0 ]; then
  swap_key_certificate
  [ -x "$c_rehash_bin" ] && $c_rehash_bin "$(dirname "$cert_file")" >/dev/null 2>&1
else
  echo "Could not generate certificate. Please see $log_file for details"
fi

umask "$old_mask"
exit $rc