2
0

generate-dhparam.sh 2.0 KB

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