Skip to content

Commit

Permalink
Add X509::Certificate#tbs_bytes
Browse files Browse the repository at this point in the history
Ref ruby#519

This makes verifying embedded certificate transparency signatures significantly easier, as otherwise the alternative was manipulating the ASN1 sequence, as in segiddins/sigstore-ruby@656d992
  • Loading branch information
segiddins committed Apr 30, 2024
1 parent 5a52368 commit f1b591f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
29 changes: 29 additions & 0 deletions ext/openssl/ossl_x509cert.c
Expand Up @@ -707,6 +707,34 @@ ossl_x509_eq(VALUE self, VALUE other)
return !X509_cmp(a, b) ? Qtrue : Qfalse;
}

/*
* call-seq:
* cert.tbs_bytes => string
*
* Returns the DER-encoded bytes of the certificate's to be signed certificate.
* This is mainly useful for validating embedded certificate transparency signatures.
*/
static VALUE
ossl_x509_tbs_bytes(VALUE self)
{
X509 *x509;
int len;
unsigned char *p0, *p1;
VALUE str;

GetX509(self, x509);
len = i2d_re_X509_tbs(x509, NULL);
if (len <= 0) {
ossl_raise(eX509CertError, NULL);
}
str = rb_str_new(NULL, len);
p0 = p1 = (unsigned char *)RSTRING_PTR(str);
i2d_re_X509_tbs(x509, &p0);
assert(p0 - p1 == len);

return str;
}

struct load_chained_certificates_arguments {
VALUE certificates;
X509 *certificate;
Expand Down Expand Up @@ -999,4 +1027,5 @@ Init_ossl_x509cert(void)
rb_define_method(cX509Cert, "add_extension", ossl_x509_add_extension, 1);
rb_define_method(cX509Cert, "inspect", ossl_x509_inspect, 0);
rb_define_method(cX509Cert, "==", ossl_x509_eq, 1);
rb_define_method(cX509Cert, "tbs_bytes", ossl_x509_tbs_bytes, 0);
}
7 changes: 7 additions & 0 deletions test/openssl/test_x509cert.rb
Expand Up @@ -322,6 +322,13 @@ def test_load_file_fullchain_garbage
end
end

def test_tbs_precert_bytes
cert = issue_cert(@ca, @rsa2048, 1, [], nil, nil)
seq = OpenSSL::ASN1.decode(cert.tbs_bytes)

assert_equal 7, seq.value.size
end

private

def certificate_error_returns_false
Expand Down

0 comments on commit f1b591f

Please sign in to comment.