Fix range check bugs

This is a patch hunting for fuzzing failures and adding
appropriate range checks.


Change-Id: Ieae02b7e461b9a6c5e25de6c663a768f7a0d5e10
Signed-off-by: Ed Tanous <etanous@nvidia.com>
diff --git a/sections/cper-section-cxl-component.c b/sections/cper-section-cxl-component.c
index f1db9ad..cae152b 100644
--- a/sections/cper-section-cxl-component.c
+++ b/sections/cper-section-cxl-component.c
@@ -12,10 +12,20 @@
 #include <libcper/sections/cper-section-cxl-component.h>
 
 //Converts a single CXL component error CPER section into JSON IR.
-json_object *cper_section_cxl_component_to_ir(const void *section)
+json_object *cper_section_cxl_component_to_ir(const UINT8 *section, UINT32 size)
 {
+	if (size < sizeof(EFI_CXL_COMPONENT_EVENT_HEADER)) {
+		return NULL;
+	}
+
 	EFI_CXL_COMPONENT_EVENT_HEADER *cxl_error =
 		(EFI_CXL_COMPONENT_EVENT_HEADER *)section;
+	if (cxl_error->Length < sizeof(EFI_CXL_COMPONENT_EVENT_HEADER)) {
+		return NULL;
+	}
+	if (size < cxl_error->Length) {
+		return NULL;
+	}
 	json_object *section_ir = json_object_new_object();
 
 	//Length (bytes) for the entire structure.
@@ -63,20 +73,21 @@
 
 	//The specification for this is defined within the CXL Specification Section 8.2.9.1.
 	if (isvalid_prop_to_ir(&ui64Type, 2)) {
-		const char *cur_pos = (const char *)(cxl_error + 1);
+		const UINT8 *cur_pos = (const UINT8 *)(cxl_error + 1);
 		int remaining_len = cxl_error->Length -
 				    sizeof(EFI_CXL_COMPONENT_EVENT_HEADER);
 		if (remaining_len > 0) {
-			json_object *event_log = json_object_new_object();
-
 			int32_t encoded_len = 0;
 
-			char *encoded = base64_encode(
-				(UINT8 *)cur_pos, remaining_len, &encoded_len);
+			char *encoded = base64_encode(cur_pos, remaining_len,
+						      &encoded_len);
 			if (encoded == NULL) {
 				printf("Failed to allocate encode output buffer. \n");
+				json_object_put(section_ir);
 				return NULL;
 			}
+			json_object *event_log = json_object_new_object();
+
 			json_object_object_add(event_log, "data",
 					       json_object_new_string_len(
 						       encoded, encoded_len));