generate-dhparam.sh 1.5 KB

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