From f11c286bc6a987a3f1f838c061d65636b90e3aa8 Mon Sep 17 00:00:00 2001 From: Jakub Jelen Date: Wed, 13 Nov 2019 14:51:17 +0100 Subject: [PATCH] coolkey: Refactor the object listing to avoid invalid memory access Probably resolves some bad memory access from oss-fuzz such as https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=18907 --- src/libopensc/card-coolkey.c | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/libopensc/card-coolkey.c b/src/libopensc/card-coolkey.c index b7985741..07652fc2 100644 --- a/src/libopensc/card-coolkey.c +++ b/src/libopensc/card-coolkey.c @@ -2166,11 +2166,19 @@ static int coolkey_initialize(sc_card_t *card) priv->life_cycle = life_cycle.life_cycle; /* walk down the list of objects and read them off the token */ - for(r=coolkey_list_object(card, COOLKEY_LIST_RESET, &object_info); r >= 0; - r= coolkey_list_object(card, COOLKEY_LIST_NEXT, &object_info)) { - unsigned long object_id = bebytes2ulong(object_info.object_id); - unsigned short object_len = bebytes2ulong(object_info.object_length); - /* also look at the ACL... */ + r = coolkey_list_object(card, COOLKEY_LIST_RESET, &object_info); + while (r >= 0) { + unsigned long object_id; + unsigned short object_len; + + /* The card did not return what we expected: Lets try other objects */ + if ((size_t)r < (sizeof(object_info))) + break; + + /* TODO also look at the ACL... */ + + object_id = bebytes2ulong(object_info.object_id); + object_len = bebytes2ulong(object_info.object_length); /* the combined object is a single object that can store the other objects. @@ -2197,12 +2205,14 @@ static int coolkey_initialize(sc_card_t *card) break; } combined_processed = 1; - continue; + } else { + r = coolkey_add_object(priv, object_id, NULL, object_len, 0); + if (r != SC_SUCCESS) + sc_log(card->ctx, "coolkey_add_object() returned %d", r); } - r = coolkey_add_object(priv, object_id, NULL, object_len, 0); - if (r != SC_SUCCESS) - sc_log(card->ctx, "coolkey_add_object() returned %d", r); + /* Read next object: error is handled on the cycle condition and below after cycle */ + r = coolkey_list_object(card, COOLKEY_LIST_NEXT, &object_info); } if (r != SC_ERROR_FILE_END_REACHED) { goto cleanup;