generate-dhparam.sh 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/bin/bash -e
  2. # The first argument is the bit depth of the dhparam, or 2048 if unspecified
  3. DHPARAM_BITS=${1:-2048}
  4. # If a dhparam file is not available, use the pre-generated one and generate a new one in the background.
  5. # Note that /etc/nginx/dhparam is a volume, so this dhparam will persist restarts.
  6. PREGEN_DHPARAM_FILE="/app/dhparam.pem.default"
  7. DHPARAM_FILE="/etc/nginx/dhparam/dhparam.pem"
  8. GEN_LOCKFILE="/tmp/dhparam_generating.lock"
  9. # The hash of the pregenerated dhparam file is used to check if the pregen dhparam is already in use
  10. PREGEN_HASH=$(md5sum $PREGEN_DHPARAM_FILE | cut -d" " -f1)
  11. if [[ -f $DHPARAM_FILE ]]; then
  12. CURRENT_HASH=$(md5sum $DHPARAM_FILE | cut -d" " -f1)
  13. if [[ $PREGEN_HASH != $CURRENT_HASH ]]; then
  14. # There is already a dhparam, and it's not the default
  15. echo "Custom dhparam.pem file found, generation skipped"
  16. exit 0
  17. fi
  18. if [[ -f $GEN_LOCKFILE ]]; then
  19. # Generation is already in progress
  20. exit 0
  21. fi
  22. fi
  23. cat >&2 <<-EOT
  24. WARNING: $DHPARAM_FILE was not found. A pre-generated dhparam.pem will be used for now while a new one
  25. is being generated in the background. Once the new dhparam.pem is in place, nginx will be reloaded.
  26. EOT
  27. # Put the default dhparam file in place so we can start immediately
  28. cp $PREGEN_DHPARAM_FILE $DHPARAM_FILE
  29. touch $GEN_LOCKFILE
  30. # Generate a new dhparam in the background in a low priority and reload nginx when finished (grep removes the progress indicator).
  31. (
  32. (
  33. nice -n +5 openssl dhparam -out $DHPARAM_FILE $DHPARAM_BITS 2>&1 \
  34. && echo "dhparam generation complete, reloading nginx" \
  35. && nginx -s reload
  36. ) | grep -vE '^[\.+]+'
  37. rm $GEN_LOCKFILE
  38. ) &disown