generate-dhparam.sh 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. exit 0
  16. fi
  17. if [[ -f $GEN_LOCKFILE ]]; then
  18. # Generation is already in progress
  19. exit 0
  20. fi
  21. fi
  22. cat >&2 <<-EOT
  23. WARNING: $DHPARAM_FILE was not found. A pre-generated dhparam.pem will be used for now while a new one
  24. is being generated in the background. Once the new dhparam.pem is in place, nginx will be reloaded.
  25. EOT
  26. # Put the default dhparam file in place so we can start immediately
  27. cp $PREGEN_DHPARAM_FILE $DHPARAM_FILE
  28. touch $GEN_LOCKFILE
  29. # Generate a new dhparam in the background in a low priority and reload nginx when finished (grep removes the progress indicator).
  30. (
  31. (
  32. nice -n +5 openssl dhparam -out $DHPARAM_FILE $DHPARAM_BITS 2>&1 \
  33. && echo "dhparam generation complete, reloading nginx" \
  34. && nginx -s reload
  35. ) | grep -vE '^[\.+]+'
  36. rm $GEN_LOCKFILE
  37. ) &disown