diff options
author | Bob Beck <beck@cvs.openbsd.org> | 2023-05-02 14:13:06 +0000 |
---|---|---|
committer | Bob Beck <beck@cvs.openbsd.org> | 2023-05-02 14:13:06 +0000 |
commit | a286f3a7d454a86fb7ece313880acf17eab0e254 (patch) | |
tree | d2ee90278166d501c89eaa0b85bb39a977891d05 /lib/libcrypto/x509 | |
parent | bdd59976deeceb45e5a797175d7a2dcbf6c1a604 (diff) |
Change X509_NAME_get_index_by[NID|OBJ] to be safer.
Currently these functions return raw ASN1_STRING bytes as
a C string and ignore the encoding in a "hold my beer I am
a toolkit not a functioning API surely it's just for testing
and you'd never send nasty bytes" kind of way.
Sadly some callers seem to use them to fetch things liks
subject name components for comparisons, and often just
use the result as a C string.
Instead, encode the resulting bytes as UTF-8 so it is
something like "text",
Add a failure case if the length provided is inadequate
or if the resulting text would contain an nul byte.
based on boringssl.
nits by dlg@
ok tb@
Diffstat (limited to 'lib/libcrypto/x509')
-rw-r--r-- | lib/libcrypto/x509/x509name.c | 37 |
1 files changed, 27 insertions, 10 deletions
diff --git a/lib/libcrypto/x509/x509name.c b/lib/libcrypto/x509/x509name.c index a6e4dbef89b..3c9e224c1b0 100644 --- a/lib/libcrypto/x509/x509name.c +++ b/lib/libcrypto/x509/x509name.c @@ -1,4 +1,4 @@ -/* $OpenBSD: x509name.c,v 1.31 2023/02/16 08:38:17 tb Exp $ */ +/* $OpenBSD: x509name.c,v 1.32 2023/05/02 14:13:05 beck Exp $ */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -66,6 +66,7 @@ #include <openssl/stack.h> #include <openssl/x509.h> +#include "bytestring.h" #include "x509_local.h" int @@ -84,21 +85,37 @@ int X509_NAME_get_text_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, char *buf, int len) { - int i; + unsigned char *text = NULL; ASN1_STRING *data; + int i, text_len; + int ret = -1; + CBS cbs; i = X509_NAME_get_index_by_OBJ(name, obj, -1); if (i < 0) - return (-1); + goto err; data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i)); - i = (data->length > (len - 1)) ? (len - 1) : data->length; - if (buf == NULL) - return (data->length); - if (i >= 0) { - memcpy(buf, data->data, i); - buf[i] = '\0'; + /* + * Fail if we cannot encode as UTF-8, or if the UTF-8 encoding of the + * string contains a 0 byte, because mortal callers seldom handle the + * length difference correctly + */ + if ((text_len = ASN1_STRING_to_UTF8(&text, data)) < 0) + goto err; + CBS_init(&cbs, text, text_len); + if (CBS_contains_zero_byte(&cbs)) + goto err; + /* We still support the "pass NULL to find out how much" API */ + if (buf != NULL) { + if (!CBS_write_bytes(&cbs, buf, len - 1, NULL)) + goto err; + /* It must be a C string */ + buf[text_len] = '\0'; } - return (i); + ret = text_len; + err: + free(text); + return (ret); } LCRYPTO_ALIAS(X509_NAME_get_text_by_OBJ); |