Skip to content

Instantly share code, notes, and snippets.

@reagent
Last active June 5, 2024 17:31
Show Gist options
  • Save reagent/cd9abf8984548b055a0adf8cbae68b9b to your computer and use it in GitHub Desktop.
Save reagent/cd9abf8984548b055a0adf8cbae68b9b to your computer and use it in GitHub Desktop.
Automate SSL Certificate Generation for Your Rails Applications
namespace :cert do
desc 'Generate certificate and keys for the provided hostname'
task :generate, [:hostname] => [:environment] do |_t, args|
hostname = args.fetch(:hostname) { raise 'Missing `hostname`, invoke as cert:generate[<hostname>]' }
cert_path = Rails.root.join('config', 'certs')
FileUtils.mkdir_p(cert_path)
root_key = cert_path.join('root-ca.key')
root_certificate = cert_path.join('root-ca.crt')
server_key = cert_path.join("#{hostname}.key")
server_certificate = cert_path.join("#{hostname}.crt")
extfile = cert_path.join("#{hostname}.ss.cnf")
unless root_certificate.exist?
system <<~CMD
openssl req -x509 -nodes \
-newkey RSA:2048 \
-keyout #{root_key} \
-days 365 \
-out #{root_certificate} \
-subj '/C=US/ST=Denial/L=Earth/O=Private Certificate Authority/CN=Root CA for Local Certificates'
CMD
end
system <<~CMD
openssl req -nodes \
-newkey rsa:2048 \
-keyout #{server_key} \
-out #{cert_path.join([hostname, 'csr'].join('.'))} \
-subj '/C=US/ST=Denial/L=Earth/O=Dis/CN=#{hostname}'
CMD
extfile.write <<~CONF
subjectAltName = DNS:#{hostname}
authorityKeyIdentifier = keyid,issuer
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage=serverAuth
CONF
system <<~CMD
openssl x509 -req \
-CA #{root_certificate} \
-CAkey #{root_key} \
-in #{cert_path.join([hostname, 'csr'].join('.'))} \
-out #{server_certificate} \
-days 365 \
-CAcreateserial \
-extfile #{extfile}
CMD
puts 'Completed'
puts <<~OUT
Files needed for configuration:
Root CA: #{root_certificate} (add to your browser certs)
Server Certificate: #{server_certificate}
Server Key: #{server_key}
Run your server in SSL mode:
sudo rails server -b 'ssl://#{hostname}:443?key=#{server_key}&cert=#{server_certificate}'
OUT
ensure
extfile.unlink if extfile.exist?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment