2
0

generate-dhparam.sh 1.9 KB

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