From a01daab656a3d32b52bd236503e3d9aebaf39483 Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Wed, 19 May 2021 17:58:18 +0900 Subject: [ruby/openssl] x509, ssl, pkcs7: try to parse as DER-encoding first Methods that take both PEM-encoding and DER-encoding have not been consistent in the order in which encoding to attempt to parse. A DER-encoding may contain a valid PEM block ("\n-----BEGIN ..-----" to "-----END ...-----") embedded within it. Also, the PEM-encoding parser allows arbitrary data around the PEM block and silently skips it. As a result, attempting to parse data in DER-encoding as PEM-encoding first can incorrectly finds the embedded PEM block instead. This commit ensures that DER encoding will always be attempted before PEM encoding. OpenSSL::X509::Certificate is one of the updated classes. With this, the following will always be true: # obj is an OpenSSL::X509::Certificate obj == OpenSSL::X509::Certificate.new(obj.to_der) obj == OpenSSL::X509::Certificate.new(obj.to_pem) https://github.com/ruby/openssl/commit/b280eb1fd0 --- ext/openssl/ossl_x509req.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) (limited to 'ext/openssl/ossl_x509req.c') diff --git a/ext/openssl/ossl_x509req.c b/ext/openssl/ossl_x509req.c index 2c20042a92..6eb91e9c2f 100644 --- a/ext/openssl/ossl_x509req.c +++ b/ext/openssl/ossl_x509req.c @@ -79,23 +79,26 @@ static VALUE ossl_x509req_initialize(int argc, VALUE *argv, VALUE self) { BIO *in; - X509_REQ *req, *x = DATA_PTR(self); + X509_REQ *req, *req_orig = RTYPEDDATA_DATA(self); VALUE arg; + rb_check_frozen(self); if (rb_scan_args(argc, argv, "01", &arg) == 0) { return self; } arg = ossl_to_der_if_possible(arg); in = ossl_obj2bio(&arg); - req = PEM_read_bio_X509_REQ(in, &x, NULL, NULL); - DATA_PTR(self) = x; + req = d2i_X509_REQ_bio(in, NULL); if (!req) { - OSSL_BIO_reset(in); - req = d2i_X509_REQ_bio(in, &x); - DATA_PTR(self) = x; + OSSL_BIO_reset(in); + req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL); } BIO_free(in); - if (!req) ossl_raise(eX509ReqError, NULL); + if (!req) + ossl_raise(eX509ReqError, "PEM_read_bio_X509_REQ"); + + RTYPEDDATA_DATA(self) = req; + X509_REQ_free(req_orig); return self; } -- cgit v1.2.3