summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authornobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2015-02-14 03:01:36 (GMT)
committernobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2015-02-14 03:01:36 (GMT)
commiteeeb7ae8c06164dfe445db35f08eea0255c2617a (patch)
tree71700764bda322951c03b0ed0d2dd6a538beb1d0
parent68c2c522fd0f694da9e3a068ee0eeb6abb253f79 (diff)
random.c: Random.raw_seed
* random.c (random_raw_seed): extract platform dependent random seed initialization function as a new method Random.raw_seed. * lib/securerandom.rb (SecureRandom): use Random.raw_seed. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@49593 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
-rw-r--r--ChangeLog7
-rw-r--r--lib/securerandom.rb83
-rw-r--r--random.c106
3 files changed, 92 insertions, 104 deletions
diff --git a/ChangeLog b/ChangeLog
index 4bcd254..feff938 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,10 @@
+Sat Feb 14 12:01:32 2015 Nobuyoshi Nakada <nobu@ruby-lang.org>
+
+ * random.c (random_raw_seed): extract platform dependent random
+ seed initialization function as a new method Random.raw_seed.
+
+ * lib/securerandom.rb (SecureRandom): use Random.raw_seed.
+
Sat Feb 14 00:49:37 2015 Aaron Patterson <aaron@tenderlovemaking.com>
* ext/coverage/coverage.c: Add Coverage.peek_result. Allows you to
diff --git a/lib/securerandom.rb b/lib/securerandom.rb
index 476f5e1..96117e6 100644
--- a/lib/securerandom.rb
+++ b/lib/securerandom.rb
@@ -47,56 +47,6 @@ end
#
module SecureRandom
- if /mswin|mingw/ =~ RUBY_PLATFORM
- require "fiddle/import"
-
- module AdvApi32 # :nodoc:
- extend Fiddle::Importer
- dlload "advapi32"
- extern "int CryptAcquireContext(void*, void*, void*, unsigned long, unsigned long)"
- extern "int CryptGenRandom(void*, unsigned long, void*)"
-
- def self.get_provider
- hProvStr = " " * Fiddle::SIZEOF_VOIDP
- prov_rsa_full = 1
- crypt_verifycontext = 0xF0000000
-
- if CryptAcquireContext(hProvStr, nil, nil, prov_rsa_full, crypt_verifycontext) == 0
- raise SystemCallError, "CryptAcquireContext failed: #{lastWin32ErrorMessage}"
- end
- type = Fiddle::SIZEOF_VOIDP == Fiddle::SIZEOF_LONG_LONG ? 'q' : 'l'
- hProv, = hProvStr.unpack(type)
- hProv
- end
-
- def self.gen_random(n)
- @hProv ||= get_provider
- bytes = " ".force_encoding("ASCII-8BIT") * n
- if CryptGenRandom(@hProv, bytes.size, bytes) == 0
- raise SystemCallError, "CryptGenRandom failed: #{Kernel32.last_error_message}"
- end
- bytes
- end
- end
-
- module Kernel32 # :nodoc:
- extend Fiddle::Importer
- dlload "kernel32"
- extern "unsigned long GetLastError()"
- extern "unsigned long FormatMessageA(unsigned long, void*, unsigned long, unsigned long, void*, unsigned long, void*)"
-
- # Following code is based on David Garamond's GUID library for Ruby.
- def self.last_error_message
- format_message_ignore_inserts = 0x00000200
- format_message_from_system = 0x00001000
-
- code = GetLastError()
- msg = "\0" * 1024
- len = FormatMessageA(format_message_ignore_inserts + format_message_from_system, 0, code, 0, msg, 1024, nil)
- msg[0, len].force_encoding("filesystem").tr("\r", '').chomp
- end
- end
- end
# SecureRandom.random_bytes generates a random binary string.
#
@@ -129,35 +79,16 @@ module SecureRandom
end
return OpenSSL::Random.random_bytes(n)
end
- elsif defined?(AdvApi32)
- def self.gen_random(n)
- return AdvApi32.gen_random(n)
- end
-
- def self.lastWin32ErrorMessage # :nodoc:
- # for compatibility
- return Kernel32.last_error_message
- end
else
def self.gen_random(n)
- flags = File::RDONLY
- flags |= File::NONBLOCK if defined? File::NONBLOCK
- flags |= File::NOCTTY if defined? File::NOCTTY
- begin
- File.open("/dev/urandom", flags) {|f|
- unless f.stat.chardev?
- break
- end
- ret = f.read(n)
- unless ret.length == n
- raise NotImplementedError, "Unexpected partial read from random device: only #{ret.length} for #{n} bytes"
- end
- return ret
- }
- rescue Errno::ENOENT
+ ret = Random.raw_seed(n)
+ unless ret
+ raise NotImplementedError, "No random device"
end
-
- raise NotImplementedError, "No random device"
+ unless ret.length == n
+ raise NotImplementedError, "Unexpected partial read from random device: only #{ret.length} for #{n} bytes"
+ end
+ ret
end
end
diff --git a/random.c b/random.c
index c03d613..a179790 100644
--- a/random.c
+++ b/random.c
@@ -84,6 +84,7 @@ The original copyright notice follows.
# undef __WINCRYPT_H__
# endif
#include <wincrypt.h>
+#include "ruby_atomic.h"
#endif
typedef int int_must_be_32bit_at_least[sizeof(int) * CHAR_BIT < 32 ? -1 : 1];
@@ -433,43 +434,75 @@ random_init(int argc, VALUE *argv, VALUE obj)
# define USE_DEV_URANDOM 0
#endif
+#if defined(_WIN32)
static void
-fill_random_seed(uint32_t seed[DEFAULT_SEED_CNT])
+release_crypt(void *p)
{
- static int n = 0;
- struct timeval tv;
-#if USE_DEV_URANDOM
- int fd;
- struct stat statbuf;
-#elif defined(_WIN32)
- HCRYPTPROV prov;
+ HCRYPTPROV prov = (HCRYPTPROV)ATOMIC_PTR_EXCHANGE(*(HCRYPTPROV *)p, INVALID_HANDLE_VALUE);
+ if (prov && prov != (HCRYPTPROV)INVALID_HANDLE_VALUE) {
+ CryptReleaseContext(prov, 0);
+ }
+}
#endif
- memset(seed, 0, DEFAULT_SEED_LEN);
-
+static int
+fill_random_bytes(void *seed, size_t size)
+{
#if USE_DEV_URANDOM
- if ((fd = rb_cloexec_open("/dev/urandom", O_RDONLY
-#ifdef O_NONBLOCK
- |O_NONBLOCK
-#endif
-#ifdef O_NOCTTY
- |O_NOCTTY
-#endif
- , 0)) >= 0) {
- rb_update_max_fd(fd);
- if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
- if (read(fd, seed, DEFAULT_SEED_LEN) < DEFAULT_SEED_LEN) {
- /* abandon */;
- }
- }
- close(fd);
+ int fd = rb_cloexec_open("/dev/urandom",
+# ifdef O_NONBLOCK
+ O_NONBLOCK|
+# endif
+# ifdef O_NOCTTY
+ O_NOCTTY|
+# endif
+ O_RDONLY, 0);
+ struct stat statbuf;
+ ssize_t ret = 0;
+
+ if (fd < 0) return -1;
+ rb_update_max_fd(fd);
+ if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
+ ret = read(fd, seed, size);
}
+ close(fd);
+ if (ret < 0 || (size_t)ret < size) return -1;
#elif defined(_WIN32)
- if (CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
- CryptGenRandom(prov, DEFAULT_SEED_LEN, (void *)seed);
- CryptReleaseContext(prov, 0);
+ static HCRYPTPROV perm_prov;
+ HCRYPTPROV prov = perm_prov, old_prov;
+ if (!prov) {
+ if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
+ prov = (HCRYPTPROV)INVALID_HANDLE_VALUE;
+ }
+ old_prov = (HCRYPTPROV)ATOMIC_PTR_CAS(perm_prov, 0, prov);
+ if (prov == (HCRYPTPROV)INVALID_HANDLE_VALUE) {
+ if (old_prov) prov = old_prov;
+ }
+ else {
+ if (!old_prov) {
+ rb_gc_register_mark_object(Data_Wrap_Struct(0, 0, release_crypt, &prov));
+ }
+ else {
+ CryptReleaseContext(prov, 0);
+ prov = old_prov;
+ }
+ }
}
+ if (prov == (HCRYPTPROV)INVALID_HANDLE_VALUE) return -1;
+ CryptGenRandom(prov, size, seed);
#endif
+ return 0;
+}
+
+static void
+fill_random_seed(uint32_t seed[DEFAULT_SEED_CNT])
+{
+ static int n = 0;
+ struct timeval tv;
+
+ memset(seed, 0, DEFAULT_SEED_LEN);
+
+ fill_random_bytes(seed, sizeof(*seed));
gettimeofday(&tv, 0);
seed[0] ^= tv.tv_usec;
@@ -525,6 +558,22 @@ random_seed(void)
}
/*
+ * call-seq: Random.raw_seed(size) -> string
+ *
+ * Returns a raw seed string, using platform providing features.
+ *
+ * Random.raw_seed(8) #=> "\x78\x41\xBA\xAF\x7D\xEA\xD8\xEA"
+ */
+static VALUE
+random_raw_seed(VALUE self, VALUE size)
+{
+ long n = NUM2ULONG(size);
+ VALUE buf = rb_str_new(0, n);
+ if (fill_random_bytes(RSTRING_PTR(buf), n)) return Qnil;
+ return buf;
+}
+
+/*
* call-seq: prng.seed -> integer
*
* Returns the seed value used to initialize the generator. This may be used to
@@ -1380,6 +1429,7 @@ InitVM_Random(void)
rb_define_singleton_method(rb_cRandom, "srand", rb_f_srand, -1);
rb_define_singleton_method(rb_cRandom, "rand", random_s_rand, -1);
rb_define_singleton_method(rb_cRandom, "new_seed", random_seed, 0);
+ rb_define_singleton_method(rb_cRandom, "raw_seed", random_raw_seed, 1);
rb_define_private_method(CLASS_OF(rb_cRandom), "state", random_s_state, 0);
rb_define_private_method(CLASS_OF(rb_cRandom), "left", random_s_left, 0);
}