From 1be9811ad91c8d2113130e7274bd532a9c784c81 Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Tue, 23 Apr 2024 09:19:54 +0200 Subject: [PATCH] Add sanity check that prevents to much memory consumption with corrupted files With this change ordinal numbers in imports are limited to 65535, larger ordinal numbers are ignored because they are sign of file corruption. --- libyara/modules/pe/pe.c | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/libyara/modules/pe/pe.c b/libyara/modules/pe/pe.c index cc0181d1e4..7b060c8c24 100644 --- a/libyara/modules/pe/pe.c +++ b/libyara/modules/pe/pe.c @@ -871,11 +871,15 @@ static IMPORT_FUNCTION* pe_parse_import_descriptor( } else { - // If imported by ordinal. Lookup the ordinal. - name = ord_lookup(dll_name, yr_le64toh(thunks64->u1.Ordinal) & 0xFFFF); - // Also store the ordinal. - ordinal = yr_le64toh(thunks64->u1.Ordinal) & 0xFFFF; - has_ordinal = 1; + // The maximum possible value for the ordinal is when the high + // bit is set (indicating import by ordinal) and the low bits + // are FFFF. The maximum number of ordinal exports is 65536. + if (yr_le64toh(thunks64->u1.Ordinal) <= 0x800000000000ffff) + { + ordinal = yr_le64toh(thunks64->u1.Ordinal) & 0xFFFF; + name = ord_lookup(dll_name, ordinal); + has_ordinal = 1; + } } rva_address = yr_le32toh(import_descriptor->FirstThunk) + @@ -957,11 +961,15 @@ static IMPORT_FUNCTION* pe_parse_import_descriptor( } else { - // If imported by ordinal. Lookup the ordinal. - name = ord_lookup(dll_name, yr_le32toh(thunks32->u1.Ordinal) & 0xFFFF); - // Also store the ordinal. - ordinal = yr_le32toh(thunks32->u1.Ordinal) & 0xFFFF; - has_ordinal = 1; + // The maximum possible value for the ordinal is when the high + // bit is set (indicating import by ordinal) and the low bits + // are FFFF. The maximum number of ordinal exports is 65536. + if (yr_le32toh(thunks32->u1.Ordinal) <= 0x8000ffff) + { + ordinal = yr_le32toh(thunks32->u1.Ordinal) & 0xFFFF; + name = ord_lookup(dll_name, ordinal); + has_ordinal = 1; + } } rva_address = yr_le32toh(import_descriptor->FirstThunk) +