From 53509eaf2253e23bfb552e9386fd0877abe592b4 Mon Sep 17 00:00:00 2001
From: Jian J Wang <jian.j.wang@intel.com>
Date: Thu, 25 Apr 2019 23:42:16 +0800
Subject: [PATCH] CryptoPkg/BaseCryptLib: fix NULL dereference

AuthenticodeVerify() calls OpenSSLs d2i_PKCS7() API to parse asn encoded
signed authenticode pkcs#7 data. when this successfully returns, a type
check is done by calling PKCS7_type_is_signed() and then
Pkcs7->d.sign->contents->type is used. It is possible to construct an asn1
blob that successfully decodes and have d2i_PKCS7() return a valid pointer
and have PKCS7_type_is_signed() also return success  but have Pkcs7->d.sign
be a NULL pointer.

Looking at how PKCS7_verify() [inside of OpenSSL] implements checking for
pkcs7 structs it does the following:
- call PKCS7_type_is_signed()
- call PKCS7_get_detached()
Looking into how PKCS7_get_detatched() is implemented, it checks to see if
p7->d.sign is NULL or if p7->d.sign->contents->d.ptr is NULL.

As such, the fix is to do the same as OpenSSL after calling d2i_PKCS7().
- Add call to PKS7_get_detached() to existing error handling

Cc: Chao Zhang <chao.b.zhang@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Signed-off-by: Jian J Wang <jian.j.wang@intel.com>
Cherry-picked-from: https://github.com/tianocore/edk2/commit/26442d11e620a9e81c019a24a4ff38441c64ba10
---
 Cryptlib/Pk/CryptAuthenticode.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/Cryptlib/Pk/CryptAuthenticode.c b/Cryptlib/Pk/CryptAuthenticode.c
index 74e50a2..f6f988b 100644
--- a/Cryptlib/Pk/CryptAuthenticode.c
+++ b/Cryptlib/Pk/CryptAuthenticode.c
@@ -9,7 +9,7 @@
   AuthenticodeVerify() will get PE/COFF Authenticode and will do basic check for
   data structure.
 
-Copyright (c) 2011 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2011 - 2019, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -106,7 +106,7 @@ AuthenticodeVerify (
   //
   // Check if it's PKCS#7 Signed Data (for Authenticode Scenario)
   //
-  if (!PKCS7_type_is_signed (Pkcs7)) {
+  if (!PKCS7_type_is_signed (Pkcs7) || PKCS7_get_detached (Pkcs7)) {
     goto _Exit;
   }
 
-- 
2.27.0

