# frozen_string_literal: true# Released under the MIT License.# Copyright, 2018-2025, by Samuel Williams.# Copyright, 2019, by Richard S. Leung.# Copyright, 2021, by Akshay Birajdar.# Copyright, 2021, by Ye Lin Aung.# Copyright, 2023, by Antonio Terceiro.# Copyright, 2023, by Yuuji Yaginuma.# Copyright, 2024, by Colin Shea.# Copyright, 2024, by Aurel Branzeanu.require"fileutils"require"openssl"require_relative"state"require_relative"issuer"moduleLocalhost# Represents a single public/private key pair for a given hostname.classAuthority# List all certificate authorities in the given directory:defself.list(path=State.path)returnto_enum(:list,path)unlessblock_given?Dir.glob("*.crt",base: path)do|certificate_path|hostname=File.basename(certificate_path,".crt")authority=self.new(hostname,path: path)ifauthority.loadyieldauthorityendendend# Fetch (load or create) a certificate with the given hostname.# See {#initialize} for the format of the arguments.defself.fetch(*arguments,**options)authority=self.new(*arguments,**options)unlessauthority.loadauthority.saveendreturnauthorityend# Create an authority forn the given hostname.# @parameter hostname [String] The common name to use for the certificate.# @parameter path [String] The path path for loading and saving the certificate.definitialize(hostname="localhost",path: State.path,issuer: Issuer.fetch)@path=path@hostname=hostname@issuer=issuer@subject=nil@key=nil@certificate=nil@store=nilendattr:issuer# The hostname of the certificate authority.attr:hostnameBITS=1024*2# @returns [OpenSSL::PKey::DH] A Diffie-Hellman key suitable for secure key exchange.defdh_key@dh_key||=OpenSSL::PKey::DH.new(BITS)end# @returns [String] The path to the private key.defkey_pathFile.join(@path,"#{@hostname}.key")end# @returns [String] The path to the public certificate.defcertificate_pathFile.join(@path,"#{@hostname}.crt")end# @returns [OpenSSL::PKey::RSA] The private key.defkey@key||=OpenSSL::PKey::RSA.new(BITS)end# Set the private key.## @parameter key [OpenSSL::PKey::RSA] The private key.defkey=key@key=keyend# @returns [OpenSSL::X509::Name] The subject name for the certificate.defsubject@subject||=OpenSSL::X509::Name.parse("/O=localhost.rb/CN=#{@hostname}")end# Set the subject name for the certificate.## @parameter subject [OpenSSL::X509::Name] The subject name.defsubject=subject@subject=subjectend# Generates a self-signed certificate if one does not already exist for the given hostname.# # @returns [OpenSSL::X509::Certificate] A self-signed certificate.defcertificateissuer=@issuer||self@certificate||=OpenSSL::X509::Certificate.new.tapdo|certificate|certificate.subject=self.subjectcertificate.issuer=issuer.subjectcertificate.public_key=self.key.public_keycertificate.serial=Time.now.to_icertificate.version=2certificate.not_before=Time.nowcertificate.not_after=Time.now+(3600*24*365)extension_factory=OpenSSL::X509::ExtensionFactory.newextension_factory.subject_certificate=certificateextension_factory.issuer_certificate=@issuer&.certificate||certificatecertificate.add_extensionextension_factory.create_extension("basicConstraints","CA:FALSE",true)certificate.add_extensionextension_factory.create_extension("subjectKeyIdentifier","hash")certificate.add_extensionextension_factory.create_extension("subjectAltName","DNS: #{@hostname}")certificate.add_extensionextension_factory.create_extension("authorityKeyIdentifier","keyid:always,issuer:always")certificate.signissuer.key,OpenSSL::Digest::SHA256.newendend# The certificate store which is used for validating the server certificate.## @returns [OpenSSL::X509::Store] The certificate store with the issuer certificate.defstore@store||=OpenSSL::X509::Store.new.tapdo|store|if@issuerstore.add_cert(@issuer.certificate)elsestore.add_cert(self.certificate)endendendSERVER_CIPHERS="EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5".freeze# @returns [OpenSSL::SSL::SSLContext] An context suitable for implementing a secure server.defserver_context(*arguments)OpenSSL::SSL::SSLContext.new(*arguments).tapdo|context|context.key=self.keycontext.cert=self.certificateif@issuercontext.extra_chain_cert=[@issuer.certificate]endcontext.session_id_context="localhost"ifcontext.respond_to?:tmp_dh_callback=context.tmp_dh_callback=proc{self.dh_key}endifcontext.respond_to?:ecdh_curves=context.ecdh_curves="P-256:P-384:P-521"endcontext.set_params(ciphers: SERVER_CIPHERS,verify_mode: OpenSSL::SSL::VERIFY_NONE,)endend# @returns [OpenSSL::SSL::SSLContext] An context suitable for connecting to a secure server using this authority.defclient_context(*args)OpenSSL::SSL::SSLContext.new(*args).tapdo|context|context.cert_store=self.storecontext.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER,)endend# Load the certificate and key from the given path.## @parameter path [String] The path to the certificate and key.# @returns [Boolean] Whether the certificate and key were successfully loaded.defload(path=@path)certificate_path=File.join(path,"#{@hostname}.crt")key_path=File.join(path,"#{@hostname}.key")returnfalseunlessFile.exist?(certificate_path)andFile.exist?(key_path)certificate=OpenSSL::X509::Certificate.new(File.read(certificate_path))key=OpenSSL::PKey::RSA.new(File.read(key_path))# Certificates with old version need to be regenerated.returnfalseifcertificate.version<2@certificate=certificate@key=keyreturntrueend# Save the certificate and key to the given path.## @parameter path [String] The path to save the certificate and key.defsave(path=@path)lockfile_path=File.join(path,"#{@hostname}.lock")File.open(lockfile_path,File::RDWR|File::CREAT,0644)do|lockfile|lockfile.flock(File::LOCK_EX)File.write(File.join(path,"#{@hostname}.crt"),self.certificate.to_pem)File.write(File.join(path,"#{@hostname}.key"),self.key.to_pem)endreturntrueendendend