Skip to content

Commit 96211a3

Browse files
committed
ossl_pem_passwd_cb: handle nil from the block explicitly
There is code that returns nil in the passphrase block on purpose (to prevent OpenSSL from prompting on stdin): OpenSSL::PKey.read(File.read("file.pem")) { nil } This is working just by chance because the TypeError from StringValue() is silently ignored. Let's short circuit in that case and save raising a needless exception, as this pattern has become too common.
1 parent 2a5ae3c commit 96211a3

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

ext/openssl/ossl.c

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -148,11 +148,10 @@ ossl_pem_passwd_value(VALUE pass)
148148
static VALUE
149149
ossl_pem_passwd_cb0(VALUE flag)
150150
{
151-
VALUE pass;
152-
153-
pass = rb_yield(flag);
151+
VALUE pass = rb_yield(flag);
152+
if (NIL_P(pass))
153+
return Qnil;
154154
StringValue(pass);
155-
156155
return pass;
157156
}
158157

@@ -195,6 +194,8 @@ ossl_pem_passwd_cb(char *buf, int max_len, int flag, void *pwd_)
195194
rb_set_errinfo(Qnil);
196195
return -1;
197196
}
197+
if (NIL_P(pass))
198+
return -1;
198199
len = RSTRING_LEN(pass);
199200
if (len > max_len) {
200201
rb_warning("password must not be longer than %d bytes", max_len);

test/test_pkey_rsa.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,9 @@ def test_pem_passwd
248248
assert_match (/ENCRYPTED/), pem3c
249249
assert_equal key.to_der, OpenSSL::PKey.read(pem3c, "key").to_der
250250
assert_equal key.to_der, OpenSSL::PKey.read(pem3c) { "key" }.to_der
251+
assert_raise(OpenSSL::PKey::PKeyError) {
252+
OpenSSL::PKey.read(pem3c) { nil }
253+
}
251254
end
252255

253256
def test_dup

0 commit comments

Comments
 (0)