From 63a4f959f0062a618ee0f513f3f05964b9f054d0 Mon Sep 17 00:00:00 2001
From: Ramkumar Radhakrishnan <ramkumar@codeaurora.org>
Date: Thu, 20 Sep 2018 13:17:36 -0700
Subject: [PATCH] Gralloc: Validate buffer parameters during importBuffer call

Validate buffer parameters like numInts, numFds, version etc of buffer
handle while importing the buffer

Change-Id: Ia1cb1cf05d845b5ef5b2feb476c2c924fa3bbf17
CRs-Fixed: 2337383
---
 gralloc/gr_buf_mgr.cpp   |  6 +++++-
 gralloc/gr_priv_handle.h | 14 ++++++++------
 2 files changed, 13 insertions(+), 7 deletions(-)

diff --git a/gralloc/gr_buf_mgr.cpp b/gralloc/gr_buf_mgr.cpp
index af0018a93..f3c96c999 100644
--- a/gralloc/gr_buf_mgr.cpp
+++ b/gralloc/gr_buf_mgr.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2018 The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2019 The Linux Foundation. All rights reserved.
  * Not a Contribution
  *
  * Copyright (C) 2010 The Android Open Source Project
@@ -227,6 +227,10 @@ void BufferManager::RegisterHandleLocked(const private_handle_t *hnd,
 }
 
 gralloc1_error_t BufferManager::ImportHandleLocked(private_handle_t *hnd) {
+  if (private_handle_t::validate(hnd) != 0) {
+    ALOGE("ImportHandleLocked: Invalid handle: %p", hnd);
+    return GRALLOC1_ERROR_BAD_HANDLE;
+  }
   ALOGD_IF(DEBUG, "Importing handle:%p id: %" PRIu64, hnd, hnd->id);
   int ion_handle = allocator_->ImportBuffer(hnd->fd);
   if (ion_handle < 0) {
diff --git a/gralloc/gr_priv_handle.h b/gralloc/gr_priv_handle.h
index e4b521c95..2acb16cc4 100644
--- a/gralloc/gr_priv_handle.h
+++ b/gralloc/gr_priv_handle.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011-2018, The Linux Foundation. All rights reserved.
+ * Copyright (c) 2011-2019, The Linux Foundation. All rights reserved.
  * Not a Contribution
  *
  * Copyright (C) 2008 The Android Open Source Project
@@ -154,12 +154,14 @@ struct private_handle_t {
   static int validate(const native_handle *h) {
     const private_handle_t *hnd = (const private_handle_t *)h;
     if (!h || h->version != sizeof(native_handle) || h->numInts != NumInts() ||
-        h->numFds != kNumFds || hnd->magic != kMagic) {
-      ALOGE(
-          "Invalid gralloc handle (at %p): ver(%d/%zu) ints(%d/%d) fds(%d/%d) "
-          "magic(%c%c%c%c/%c%c%c%c)",
+        h->numFds != kNumFds) {
+      ALOGE("Invalid gralloc handle (at %p): ver(%d/%zu) ints(%d/%d) fds(%d/%d) ",
           h, h ? h->version : -1, sizeof(native_handle), h ? h->numInts : -1, NumInts(),
-          h ? h->numFds : -1, kNumFds,
+          h ? h->numFds : -1, kNumFds);
+      return -EINVAL;
+    }
+    if (hnd->magic != kMagic) {
+       ALOGE("magic(%c%c%c%c/%c%c%c%c)",
           hnd ? (((hnd->magic >> 24) & 0xFF) ? ((hnd->magic >> 24) & 0xFF) : '-') : '?',
           hnd ? (((hnd->magic >> 16) & 0xFF) ? ((hnd->magic >> 16) & 0xFF) : '-') : '?',
           hnd ? (((hnd->magic >> 8) & 0xFF) ? ((hnd->magic >> 8) & 0xFF) : '-') : '?',