From ac641bf4d68a8bfd1f6e36630c40239b73c56aee Mon Sep 17 00:00:00 2001 From: Daniel Barlow Date: Wed, 25 Sep 2024 20:49:56 +0100 Subject: [PATCH] src/openssl.c: Add getAttributes method on x509.csr returns a table of attribute name as string => [val1 val2 .... valn] --- src/openssl.c | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/src/openssl.c b/src/openssl.c index db64d03..f868330 100644 --- a/src/openssl.c +++ b/src/openssl.c @@ -7818,6 +7818,76 @@ static int xr_modifyRequestedExtension(X509_REQ *csr, int target_nid, int crit, return 1; } /* xr_modifyRequestedExtension() */ +static int xr_getAttributes(lua_State *L) { + X509_REQ *csr = checksimple(L, 1, X509_CSR_CLASS); + + int buf_len = 80; + char * buf = 0; + char * err = 0; + int attr_count = X509_REQ_get_attr_count(csr); + + buf = malloc(buf_len); + + lua_createtable(L, attr_count, 0); + int table = lua_gettop(L); + + for (int i = 0; i < attr_count; i++) { + X509_ATTRIBUTE *a; + ASN1_BIT_STRING *bs = NULL; + ASN1_OBJECT *aobj; + int name_len, val_count = 1; + + a = X509_REQ_get_attr(csr, i); + aobj = X509_ATTRIBUTE_get0_object(a); + + name_len = OBJ_obj2txt(buf, buf_len, aobj, 0); + if(name_len <= 0) continue; + if(name_len >= buf_len) { + buf_len = name_len; + buf = realloc(buf, buf_len); + OBJ_obj2txt(buf, buf_len, aobj, 0); + } + lua_pushlstring(L, buf, name_len); + + val_count = X509_ATTRIBUTE_count(a); + if (val_count == 0) { + err = "x509_r_invalid_attributes"; goto failed; + } + + lua_createtable(L, val_count, 0); + + for(int ii=0; ii < val_count; ii++) { + ASN1_TYPE *at = X509_ATTRIBUTE_get0_type(a, ii); + int type = at->type; + bs = at->value.asn1_string; + + switch (type) { + case V_ASN1_PRINTABLESTRING: + case V_ASN1_T61STRING: + case V_ASN1_NUMERICSTRING: + case V_ASN1_UTF8STRING: + case V_ASN1_IA5STRING: + lua_pushlstring(L, (char *)bs->data, bs->length); + break; + default: + lua_pushnil(L); + break; + } + lua_seti(L, -2, ii + 1); + } + lua_settable(L, table); + } + if(buf) free(buf); + return 1; + + failed: + if(buf) free(buf); + lua_pushnil(L); + lua_pushstring(L, err); + return 2; +} + + static int xr_setSubjectAlt(lua_State *L) { X509_REQ *csr = checksimple(L, 1, X509_CSR_CLASS); @@ -8023,6 +8093,7 @@ static const auxL_Reg xr_methods[] = { { "setSubject", &xr_setSubject }, { "getPublicKey", &xr_getPublicKey }, { "setPublicKey", &xr_setPublicKey }, + { "getAttributes", &xr_getAttributes }, { "getSubjectAlt", &xr_getSubjectAlt }, { "setSubjectAlt", &xr_setSubjectAlt }, { "getRequestedExtension", &xr_getRequestedExtension },