From 0e29988b9694f622fdc146dcb9c148e092d2fb02 Mon Sep 17 00:00:00 2001 From: Bart Date: Fri, 7 Feb 2020 17:30:56 +0100 Subject: [PATCH] Simplify Configuration.random_token and remove insecure fallback (#2102) The original implementation is 8 years old from commit 47f76712. I'm guessing it partially reimplemented Ruby's SecureRandom from that time to provide the fallback to using Kernel#rand in case the CSPRNG is unavailable. I'm removing it since I don't believe this is very common and I don't think it is Puma's job to fix a broken system. --- History.md | 1 + lib/puma/configuration.rb | 24 ++---------------------- 2 files changed, 3 insertions(+), 22 deletions(-) diff --git a/History.md b/History.md index 566ef9c5..3d06bb00 100644 --- a/History.md +++ b/History.md @@ -12,6 +12,7 @@ * Refactor * Remove unused loader argument from Plugin initializer (#2095) + * Simplify `Configuration.random_token` and remove insecure fallback (#2102) ## 4.3.1 and 3.12.2 / 2019-12-05 diff --git a/lib/puma/configuration.rb b/lib/puma/configuration.rb index 5c40adf0..e8e546d6 100644 --- a/lib/puma/configuration.rb +++ b/lib/puma/configuration.rb @@ -332,29 +332,9 @@ module Puma end def self.random_token - begin - require 'openssl' - rescue LoadError - end + require 'securerandom' unless defined?(SecureRandom) - count = 16 - - bytes = nil - - if defined? OpenSSL::Random - bytes = OpenSSL::Random.random_bytes(count) - elsif File.exist?("/dev/urandom") - File.open('/dev/urandom') { |f| bytes = f.read(count) } - end - - if bytes - token = "".dup - bytes.each_byte { |b| token << b.to_s(16) } - else - token = (0..count).to_a.map { rand(255).to_s(16) }.join - end - - return token + SecureRandom.hex(16) end end end