public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [Patch 0/3] BaseTools: Add the support for FMP capsule generate auth info
@ 2016-08-15  8:17 Yonghong Zhu
  2016-08-15  8:17 ` [Patch 1/3] BaseTools: Add the PKCS7 tool Yonghong Zhu
                   ` (2 more replies)
  0 siblings, 3 replies; 8+ messages in thread
From: Yonghong Zhu @ 2016-08-15  8:17 UTC (permalink / raw)
  To: edk2-devel; +Cc: Liming Gao

Current BaseTools cannot support the EFI_FIRMWARE_IMAGE_AUTHENTICATION struct for 
FMP capsule.
# typedef struct {
#   UINT64                    MonotonicCount;
#   WIN_CERTIFICATE_UEFI_GUID AuthInfo;
# } EFI_FIRMWARE_IMAGE_AUTHENTICATION;
Patch 1: add the PKCS7 Tool to support CertType - EFI_CERT_TYPE_PKCS7_GUID
Patch 2: update the Rsa2048Sha256Sign tool to support Monotonic count
Patch 3: update the FMP capsule generation, call the tool by CERTIFICATE_GUID 
defined in the FDF file to generate the certdata and fill the header info.

Cc: Liming Gao <liming.gao@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Yonghong Zhu <yonghong.zhu@intel.com>

Yonghong Zhu (3):
  BaseTools: Add the PKCS7 tool
  BaseTools: Rsa2048Sha256Sign add new option to support Monotonic count
  BaseTools: FMP capsule add the support to generate auth info

 BaseTools/Conf/tools_def.template                  |   6 +
 BaseTools/Source/Python/GenFds/Capsule.py          |  80 +++++-
 BaseTools/Source/Python/GenFds/CapsuleData.py      |   4 +-
 BaseTools/Source/Python/GenFds/FdfParser.py        |  64 ++++-
 BaseTools/Source/Python/GenFds/GenFds.py           |  59 ++++-
 BaseTools/Source/Python/GenFds/GuidSection.py      |  59 +----
 BaseTools/Source/Python/Makefile                   |  27 +-
 .../Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py  | 285 +++++++++++++++++++++
 BaseTools/Source/Python/Pkcs7Sign/TestCert.pem     |  57 +++++
 BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem |  19 ++
 BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem     |  56 ++++
 BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem |  18 ++
 BaseTools/Source/Python/Pkcs7Sign/TestSub.pem      |  57 +++++
 BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem  |  19 ++
 .../Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py  |  31 ++-
 15 files changed, 760 insertions(+), 81 deletions(-)
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem

-- 
2.6.1.windows.1



^ permalink raw reply	[flat|nested] 8+ messages in thread

* [Patch 1/3] BaseTools: Add the PKCS7 tool
  2016-08-15  8:17 [Patch 0/3] BaseTools: Add the support for FMP capsule generate auth info Yonghong Zhu
@ 2016-08-15  8:17 ` Yonghong Zhu
  2016-08-15  8:32   ` Yao, Jiewen
  2016-08-15  8:17 ` [Patch 2/3] BaseTools: Rsa2048Sha256Sign add new option to support Monotonic count Yonghong Zhu
  2016-08-15  8:17 ` [Patch 3/3] BaseTools: FMP capsule add the support to generate auth info Yonghong Zhu
  2 siblings, 1 reply; 8+ messages in thread
From: Yonghong Zhu @ 2016-08-15  8:17 UTC (permalink / raw)
  To: edk2-devel; +Cc: Liming Gao, Jiewen Yao

Provide the PKCS7 Tool to support the CertType - EFI_CERT_TYPE_PKCS7_GUID,
then user can use this tool to add EFI_FIRMWARE_IMAGE_AUTHENTICATION
for a binary.

Cc: Liming Gao <liming.gao@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Jiewen Yao <jiewen.yao@intel.com>
---
 BaseTools/Conf/tools_def.template                  |   6 +
 BaseTools/Source/Python/Makefile                   |  27 +-
 .../Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py  | 285 +++++++++++++++++++++
 BaseTools/Source/Python/Pkcs7Sign/TestCert.pem     |  57 +++++
 BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem |  19 ++
 BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem     |  56 ++++
 BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem |  18 ++
 BaseTools/Source/Python/Pkcs7Sign/TestSub.pem      |  57 +++++
 BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem  |  19 ++
 9 files changed, 541 insertions(+), 3 deletions(-)
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
 create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem

diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template
index 974656c..a78ea77 100755
--- a/BaseTools/Conf/tools_def.template
+++ b/BaseTools/Conf/tools_def.template
@@ -7669,10 +7669,16 @@ RELEASE_RVCTCYGWIN_ARM_CC_FLAGS  = "$(CCPATH_FLAG)" $(ARCHCC_FLAGS) $(PLATFORM_F
 ##################
 *_*_*_VPDTOOL_PATH         = BPDG
 *_*_*_VPDTOOL_GUID         = 8C3D856A-9BE6-468E-850A-24F7A8D38E08
 
 ##################
+# Firmware Image Auth PKCS7 tool definitions
+##################
+*_*_*_PKCS7_PATH           = GenFirmwareImageAuthPkcs7
+*_*_*_PKCS7_GUID           = 4AAFD29D-68DF-49EE-8AA9-347D375665A7
+
+##################
 # NASM tool definitions
 ##################
 *_*_*_NASM_PATH                = ENV(NASM_PREFIX)nasm
 # NASMB uses NASM produce a .bin from a .nasmb NASM source file
 *_*_*_NASMB_FLAGS              = -f bin
diff --git a/BaseTools/Source/Python/Makefile b/BaseTools/Source/Python/Makefile
index 8bc213b..8d6a386 100644
--- a/BaseTools/Source/Python/Makefile
+++ b/BaseTools/Source/Python/Makefile
@@ -1,9 +1,9 @@
 ## @file
 # Windows makefile for Python tools build.
 #
-# Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2010 - 2016, 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
 # http://opensource.org/licenses/bsd-license.php
 #
@@ -29,11 +29,11 @@ MODULES=encodings.cp437,encodings.gbk,encodings.utf_16,encodings.utf_8,encodings
 BASE_TOOLS_PATH = $(BASE_TOOLS_PATH::\\=:\)
 EDK_TOOLS_PATH  = $(EDK_TOOLS_PATH::\\=:\)
 
 BIN_DIR=$(EDK_TOOLS_PATH)\Bin\Win32
 
-APPLICATIONS=$(BIN_DIR)\build.exe $(BIN_DIR)\GenFds.exe $(BIN_DIR)\Trim.exe $(BIN_DIR)\TargetTool.exe $(BIN_DIR)\GenDepex.exe $(BIN_DIR)\GenPatchPcdTable.exe $(BIN_DIR)\PatchPcdValue.exe $(BIN_DIR)\BPDG.exe $(BIN_DIR)\UPT.exe $(BIN_DIR)\Rsa2048Sha256Sign.exe $(BIN_DIR)\Rsa2048Sha256GenerateKeys.exe $(BIN_DIR)\Ecc.exe
+APPLICATIONS=$(BIN_DIR)\build.exe $(BIN_DIR)\GenFds.exe $(BIN_DIR)\Trim.exe $(BIN_DIR)\TargetTool.exe $(BIN_DIR)\GenDepex.exe $(BIN_DIR)\GenPatchPcdTable.exe $(BIN_DIR)\PatchPcdValue.exe $(BIN_DIR)\BPDG.exe $(BIN_DIR)\UPT.exe $(BIN_DIR)\Rsa2048Sha256Sign.exe $(BIN_DIR)\Rsa2048Sha256GenerateKeys.exe $(BIN_DIR)\GenFirmwareImageAuthPkcs7.exe $(BIN_DIR)\Ecc.exe
 
 COMMON_PYTHON=$(BASE_TOOLS_PATH)\Source\Python\Common\BuildToolError.py \
               $(BASE_TOOLS_PATH)\Source\Python\Common\Database.py \
               $(BASE_TOOLS_PATH)\Source\Python\Common\DataType.py \
               $(BASE_TOOLS_PATH)\Source\Python\Common\DecClassObject.py \
@@ -283,11 +283,32 @@ $(BIN_DIR)\Ecc.exe: $(BASE_TOOLS_PATH)\Source\Python\Ecc\Ecc.py $(CMD_ECC) $(BIN
 $(BIN_DIR)\config.ini: $(BASE_TOOLS_PATH)\Source\Python\Ecc\config.ini
   @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Ecc\config.ini $(BIN_DIR)\config.ini
 
 $(BIN_DIR)\exception.xml: $(BASE_TOOLS_PATH)\Source\Python\Ecc\exception.xml
   @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Ecc\exception.xml $(BIN_DIR)\exception.xml
-  
+
+$(BIN_DIR)\GenFirmwareImageAuthPkcs7.exe: $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\GenFirmwareImageAuthPkcs7.py $(BIN_DIR)\TestCert.pem $(BIN_DIR)\TestCert.pub.pem $(BIN_DIR)\TestRoot.pem $(BIN_DIR)\TestRoot.pub.pem $(BIN_DIR)\TestSub.pem $(BIN_DIR)\TestSub.pub.pem
+  @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR) Pkcs7Sign\GenFirmwareImageAuthPkcs7.py
+
+$(BIN_DIR)\TestCert.pem: $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pem
+  @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pem $(BIN_DIR)\TestCert.pem
+
+$(BIN_DIR)\TestCert.pub.pem: $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pub.pem
+  @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pub.pem $(BIN_DIR)\TestCert.pub.pem
+
+$(BIN_DIR)\TestSub.pem: $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pem
+  @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pem $(BIN_DIR)\TestSub.pem
+
+$(BIN_DIR)\TestSub.pub.pem: $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pub.pem
+  @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pub.pem $(BIN_DIR)\TestSub.pub.pem
+
+$(BIN_DIR)\TestRoot.pem: $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pem
+  @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pem $(BIN_DIR)\TestRoot.pem
+
+$(BIN_DIR)\TestRoot.pub.pem: $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pub.pem
+  @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pub.pem $(BIN_DIR)\TestRoot.pub.pem
+
 clean:
 cleanall:  
   @del /f /q $(BIN_DIR)\*.pyd $(BIN_DIR)\*.dll
   @for %%i in ($(APPLICATIONS)) do @del /f /q %%i
 
diff --git a/BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py b/BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
new file mode 100644
index 0000000..ccbb1c2
--- /dev/null
+++ b/BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
@@ -0,0 +1,285 @@
+## @file
+# This tool adds EFI_FIRMWARE_IMAGE_AUTHENTICATION for a binary.
+#
+# This tool only support CertType - EFI_CERT_TYPE_PKCS7_GUID
+#   {0x4aafd29d, 0x68df, 0x49ee, {0x8a, 0xa9, 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7}}
+#
+# This tool has been tested with OpenSSL.
+#
+# Copyright (c) 2016, 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
+# http://opensource.org/licenses/bsd-license.php
+#
+# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
+# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
+#
+
+'''
+GenFirmwareImageAuth
+'''
+
+import os
+import sys
+import argparse 
+import subprocess
+import uuid
+import struct
+import collections
+from Common.BuildVersion import gBUILD_VERSION
+
+#
+# Globals for help information
+#
+__prog__      = 'GenFirmwareImageAuthPkcs7'
+__version__   = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)
+__copyright__ = 'Copyright (c) 2016, Intel Corporation. All rights reserved.'
+__usage__     = '%s -e|-d [options] <input_file>' % (__prog__)
+
+#
+# GUID for PKCS7 from UEFI Specification
+#
+WIN_CERT_REVISION      = 0x0200
+WIN_CERT_TYPE_EFI_GUID = 0x0EF1
+EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}')
+
+#
+# typedef struct _WIN_CERTIFICATE {
+#   UINT32 dwLength;
+#   UINT16 wRevision;
+#   UINT16 wCertificateType;
+# //UINT8 bCertificate[ANYSIZE_ARRAY];
+# } WIN_CERTIFICATE;
+#
+# typedef struct _WIN_CERTIFICATE_UEFI_GUID {
+#   WIN_CERTIFICATE Hdr;
+#   EFI_GUID        CertType;
+# //UINT8 CertData[ANYSIZE_ARRAY];
+# } WIN_CERTIFICATE_UEFI_GUID;
+#
+# typedef struct {
+#   UINT64                    MonotonicCount;
+#   WIN_CERTIFICATE_UEFI_GUID AuthInfo;
+# } EFI_FIRMWARE_IMAGE_AUTHENTICATION;
+#
+
+EFI_FIRMWARE_IMAGE_AUTHENTICATION        = collections.namedtuple('EFI_FIRMWARE_IMAGE_AUTHENTICATION', ['MonotonicCount','dwLength','wRevision','wCertificateType','CertType'])
+EFI_FIRMWARE_IMAGE_AUTHENTICATION_STRUCT = struct.Struct('QIHH16s')
+
+#
+# Filename of test signing private cert that is stored in same directory as this tool
+#
+TEST_SIGNER_PRIVATE_CERT_FILENAME = 'TestCert.pem'
+TEST_OTHER_PUBLIC_CERT_FILENAME = 'TestSub.pub.pem'
+TEST_TRUSTED_PUBLIC_CERT_FILENAME = 'TestRoot.pub.pem'
+
+if __name__ == '__main__':
+  #
+  # Create command line argument parser object
+  #  
+  parser = argparse.ArgumentParser(prog=__prog__, version=__version__, usage=__usage__, description=__copyright__, conflict_handler='resolve')
+  group = parser.add_mutually_exclusive_group(required=True)
+  group.add_argument("-e", action="store_true", dest='Encode', help='encode file')
+  group.add_argument("-d", action="store_true", dest='Decode', help='decode file')
+  parser.add_argument("-o", "--output", dest='OutputFile', type=str, metavar='filename', help="specify the output filename", required=True)
+  parser.add_argument("--signer-private-cert", dest='SignerPrivateCertFile', type=argparse.FileType('rb'), help="specify the signer private cert filename.  If not specified, a test signer private cert is used.")
+  parser.add_argument("--other-public-cert", dest='OtherPublicCertFile', type=argparse.FileType('rb'), help="specify the other public cert filename.  If not specified, a test other public cert is used.")
+  parser.add_argument("--trusted-public-cert", dest='TrustedPublicCertFile', type=argparse.FileType('rb'), help="specify the trusted public cert filename.  If not specified, a test trusted public cert is used.")
+  parser.add_argument("--monotonic-count", dest='MonotonicCountStr', type=str, help="specify the MonotonicCount in FMP capsule.  If not specified, 0 is used.")
+  parser.add_argument("--signature-size", dest='SignatureSizeStr', type=str, help="specify the signature size for decode process.")
+  parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages")
+  parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages")
+  parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0,10), default=0, help="set debug level")
+  parser.add_argument(metavar="input_file", dest='InputFile', type=argparse.FileType('rb'), help="specify the input filename")
+
+  #
+  # Parse command line arguments
+  #  
+  args = parser.parse_args()
+
+  #
+  # Generate file path to Open SSL command
+  #
+  OpenSslCommand = 'openssl'
+  try:
+    OpenSslPath = os.environ['OPENSSL_PATH']
+    OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand)
+  except:
+    pass
+
+  #
+  # Verify that Open SSL command is available
+  #
+  try:
+    Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+  except:  
+    print 'ERROR: Open SSL command not available.  Please verify PATH or set OPENSSL_PATH'
+    sys.exit(1)
+
+  Version = Process.communicate()
+  if Process.returncode <> 0:
+    print 'ERROR: Open SSL command not available.  Please verify PATH or set OPENSSL_PATH'
+    sys.exit(Process.returncode)
+  print Version[0]
+
+  #
+  # Read input file into a buffer and save input filename
+  #  
+  args.InputFileName   = args.InputFile.name
+  args.InputFileBuffer = args.InputFile.read()
+  args.InputFile.close()
+
+  #
+  # Save output filename and check if path exists
+  #
+  OutputDir = os.path.dirname(args.OutputFile)
+  if not os.path.exists(OutputDir):
+    print 'ERROR: The output path does not exist: %s' % OutputDir
+    sys.exit(1)
+  args.OutputFileName = args.OutputFile
+
+  try:
+    if args.MonotonicCountStr.upper().startswith('0X'):
+      args.MonotonicCountValue = (long)(args.MonotonicCountStr, 16)
+    else:
+      args.MonotonicCountValue = (long)(args.MonotonicCountStr)
+  except:
+    args.MonotonicCountValue = (long)(0)
+
+  if args.Encode:
+    #
+    # Save signer private cert filename and close private cert file
+    #
+    try:
+      args.SignerPrivateCertFileName = args.SignerPrivateCertFile.name
+      args.SignerPrivateCertFile.close()
+    except:
+      try:
+        #
+        # Get path to currently executing script or executable
+        #
+        if hasattr(sys, 'frozen'):
+            Pkcs7ToolPath = sys.executable
+        else:
+            Pkcs7ToolPath = sys.argv[0]
+        if Pkcs7ToolPath.startswith('"'):
+            Pkcs7ToolPath = Pkcs7ToolPath[1:]
+        if Pkcs7ToolPath.endswith('"'):
+            Pkcs7ToolPath = RsaToolPath[:-1]
+        args.SignerPrivateCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_SIGNER_PRIVATE_CERT_FILENAME)
+        args.SignerPrivateCertFile = open(args.SignerPrivateCertFileName, 'rb')
+        args.SignerPrivateCertFile.close()
+      except:
+        print 'ERROR: test signer private cert file %s missing' % (args.SignerPrivateCertFileName)
+        sys.exit(1)
+
+    #
+    # Save other public cert filename and close public cert file
+    #
+    try:
+      args.OtherPublicCertFileName = args.OtherPublicCertFile.name
+      args.OtherPublicCertFile.close()
+    except:
+      try:
+        #
+        # Get path to currently executing script or executable
+        #
+        if hasattr(sys, 'frozen'):
+            Pkcs7ToolPath = sys.executable
+        else:
+            Pkcs7ToolPath = sys.argv[0]
+        if Pkcs7ToolPath.startswith('"'):
+            Pkcs7ToolPath = Pkcs7ToolPath[1:]
+        if Pkcs7ToolPath.endswith('"'):
+            Pkcs7ToolPath = RsaToolPath[:-1]
+        args.OtherPublicCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_OTHER_PUBLIC_CERT_FILENAME)
+        args.OtherPublicCertFile = open(args.OtherPublicCertFileName, 'rb')
+        args.OtherPublicCertFile.close()
+      except:
+        print 'ERROR: test other public cert file %s missing' % (args.OtherPublicCertFileName)
+        sys.exit(1)
+
+    format = "Q%ds" % len(args.InputFileBuffer)
+    FullInputFileBuffer = struct.pack(format,args.MonotonicCountValue, args.InputFileBuffer)
+
+    # 
+    # Sign the input file using the specified private key and capture signature from STDOUT
+    #
+    Process = subprocess.Popen('%s smime -sign -binary -signer "%s" -outform DER -md sha256 -certfile "%s"' % (OpenSslCommand, args.SignerPrivateCertFileName, args.OtherPublicCertFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    Signature = Process.communicate(input=FullInputFileBuffer)[0]
+    if Process.returncode <> 0:
+      sys.exit(Process.returncode)
+
+    #
+    # Write output file that contains Signature, and Input data
+    #    
+    args.OutputFile = open(args.OutputFileName, 'wb')
+    args.OutputFile.write(Signature)
+    args.OutputFile.write(args.InputFileBuffer)
+    args.OutputFile.close()
+
+  if args.Decode:
+    #
+    # Save trusted public cert filename and close public cert file
+    #
+    try:
+      args.TrustedPublicCertFileName = args.TrustedPublicCertFile.name
+      args.TrustedPublicCertFile.close()
+    except:
+      try:
+        #
+        # Get path to currently executing script or executable
+        #
+        if hasattr(sys, 'frozen'):
+            Pkcs7ToolPath = sys.executable
+        else:
+            Pkcs7ToolPath = sys.argv[0]
+        if Pkcs7ToolPath.startswith('"'):
+            Pkcs7ToolPath = Pkcs7ToolPath[1:]
+        if Pkcs7ToolPath.endswith('"'):
+            Pkcs7ToolPath = RsaToolPath[:-1]
+        args.TrustedPublicCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_TRUSTED_PUBLIC_CERT_FILENAME)
+        args.TrustedPublicCertFile = open(args.TrustedPublicCertFileName, 'rb')
+        args.TrustedPublicCertFile.close()
+      except:
+        print 'ERROR: test trusted public cert file %s missing' % (args.TrustedPublicCertFileName)
+        sys.exit(1)
+
+    if not args.SignatureSizeStr:
+      print "ERROR: please use the option --signature-size to specify the size of the signature data!"
+      sys.exit(1)
+    else:
+      if args.SignatureSizeStr.upper().startswith('0X'):
+        SignatureSize = (long)(args.SignatureSizeStr, 16)
+      else:
+        SignatureSize = (long)(args.SignatureSizeStr)
+    if SignatureSize < 0:
+        print "ERROR: The value of option --signature-size can't be set to negative value!"
+        sys.exit(1)
+    elif SignatureSize > len(args.InputFileBuffer):
+        print "ERROR: The value of option --signature-size is exceed the size of the input file !"
+        sys.exit(1)
+
+    args.SignatureBuffer = args.InputFileBuffer[0:SignatureSize]
+    args.InputFileBuffer = args.InputFileBuffer[SignatureSize:]
+
+    format = "Q%ds" % len(args.InputFileBuffer)
+    FullInputFileBuffer = struct.pack(format,args.MonotonicCountValue, args.InputFileBuffer)
+
+    #
+    # Save output file contents from input file 
+    #
+    open(args.OutputFileName, 'wb').write(FullInputFileBuffer)
+
+    #
+    # Verify signature
+    #
+    Process = subprocess.Popen('%s smime -verify -inform DER -content %s -CAfile %s' % (OpenSslCommand, args.OutputFileName, args.TrustedPublicCertFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    Process.communicate(input=args.SignatureBuffer)[0]
+    if Process.returncode <> 0:
+      print 'ERROR: Verification failed'
+      os.remove (args.OutputFileName)
+      sys.exit(Process.returncode)
+
+    open(args.OutputFileName, 'wb').write(args.InputFileBuffer)
diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestCert.pem b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
new file mode 100644
index 0000000..7e10358
--- /dev/null
+++ b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
@@ -0,0 +1,57 @@
+Bag Attributes
+    localKeyID: 01 00 00 00 
+    Microsoft CSP Name: Microsoft Strong Cryptographic Provider
+    friendlyName: PvkTmp:133cc061-112c-467a-b8cf-dc0a56d7830e
+Key Attributes
+    X509v3 Key Usage: 80 
+-----BEGIN PRIVATE KEY-----
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCSPHYSohF+fim4
+89iNx8CcCG/fPb7KLu9Dsq+pB4Pc/UJtaaA+D7RK3PhqNCrWbb+gCNgm7lxiOCrH
+mm0tPal71UV8VFUiTM7Zf1y8VBFCHJ92ykmS7MDwqV25oMGGocz4jdcPl3r2yFFq
+d9jaBAPjUsHRbs8AC8CKHexOACfeydgQoj9KPWH9DUFQyXcbtMyGXAvFCktnSNRQ
+f01UdNJebeD6+wlQn0sUaojn1lu570OdZ3AkJlm6bTEKvfHeOB21GaHnQ1O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Ah0FAAOCAQEAK7YgK6iiTo07d3CSY4xG
+9N0QS2m4LsBPrF8pFmk5h6R81MFEdBZrA+zggbUujQ2IGB7k6F7WvP3F3B3AXZtx
+DW1FYrQheQhTT5wx85LxFdLy+q6uwUtJi/VyErPmZOcds3QaBXPvG/UykFbu24JV
+K2ScLpQVyzmkTN7GWSXrIO6eHHMQgeRX3XjRutbR8CKP1pWTOY+MO4G6YZqrzLdp
+opYFPgvdZpTL3IKSSkp31Amu5oidkvzLgallC3SOYdLZirWEIAAXW2LVYXwiiL6L
+HEIV/G9u85jhKhv/z9l8F/1Eg4HHGSYba8pf1HQA+WsQwi4BVp4x4MBoeHOolyVT
+/A==
+-----END CERTIFICATE-----
diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
new file mode 100644
index 0000000..f5b0cec
--- /dev/null
+++ b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIC/TCCAemgAwIBAgIQ0+nLBVt+jbJMSfzhFpRJrDAJBgUrDgMCHQUAMBIxEDAO
+BgNVBAMTB1Rlc3RTdWIwHhcNMTYwODA0MTUwMjMwWhcNMzkxMjMxMjM1OTU5WjAT
+MREwDwYDVQQDEwhUZXN0Q2VydDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
+ggEBAJI8dhKiEX5+Kbjz2I3HwJwIb989vsou70Oyr6kHg9z9Qm1poD4PtErc+Go0
+KtZtv6AI2CbuXGI4KseabS09qXvVRXxUVSJMztl/XLxUEUIcn3bKSZLswPCpXbmg
+wYahzPiN1w+XevbIUWp32NoEA+NSwdFuzwALwIod7E4AJ97J2BCiP0o9Yf0NQVDJ
+dxu0zIZcC8UKS2dI1FB/TVR00l5t4Pr7CVCfSxRqiOfWW7nvQ51ncCQmWbptMQq9
+8d44HbUZoedDU7VFW2q938qMUeHFJLDyZ5OzKo39Ohr/zQXJQoSZMhol0Rqr8LZc
+ppQAJ7Oxiq9HEOr6mWKTKIim3psCAwEAAaNWMFQwDAYDVR0TAQH/BAIwADBEBgNV
+HQEEPTA7gBAeQOcW6KCBdWSbrvKQrBrfoRUwEzERMA8GA1UEAxMIVGVzdFJvb3SC
+ELOMZKZtPz2BS8i5NTXdHNMwCQYFKw4DAh0FAAOCAQEAK7YgK6iiTo07d3CSY4xG
+9N0QS2m4LsBPrF8pFmk5h6R81MFEdBZrA+zggbUujQ2IGB7k6F7WvP3F3B3AXZtx
+DW1FYrQheQhTT5wx85LxFdLy+q6uwUtJi/VyErPmZOcds3QaBXPvG/UykFbu24JV
+K2ScLpQVyzmkTN7GWSXrIO6eHHMQgeRX3XjRutbR8CKP1pWTOY+MO4G6YZqrzLdp
+opYFPgvdZpTL3IKSSkp31Amu5oidkvzLgallC3SOYdLZirWEIAAXW2LVYXwiiL6L
+HEIV/G9u85jhKhv/z9l8F/1Eg4HHGSYba8pf1HQA+WsQwi4BVp4x4MBoeHOolyVT
+/A==
+-----END CERTIFICATE-----
diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
new file mode 100644
index 0000000..3ca5149
--- /dev/null
+++ b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
@@ -0,0 +1,56 @@
+Bag Attributes
+    localKeyID: 01 00 00 00 
+    Microsoft CSP Name: Microsoft Strong Cryptographic Provider
+    friendlyName: PvkTmp:76c92422-d6f3-4763-9b80-b423fd921d00
+Key Attributes
+    X509v3 Key Usage: 80 
+-----BEGIN PRIVATE KEY-----
+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCU5jNPVsMHoNCZ
+V8PhVkIBcFkcL0pmjzSek7227JKkkFFdxo+1w4YV32CAvrh4WVub/SeSaczKjj6e
+gUdbhO9cm7NKQ1uNCzEEALaKwKn1IdA/zbBnfVAzLvsbLBYu7lYBh/bI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jWOpbhF0dlZc49AgMBAAGjSDBGMEQGA1UdAQQ9MDuAEM61es/l
+Icdr8+yS1L9lKjWhFTATMREwDwYDVQQDEwhUZXN0Um9vdIIQNDAnfwU9lYVDoKT1
+DJrnyjAJBgUrDgMCHQUAA4IBAQBrDeAK0O5bP7ZzSGLo9Fvh7dkAxeUOaPtTMzBq
+YLruOFtRY3DVfgX+5EUqFWIb/Nh1k1b25gaFIfcIRya5/gVOkCJU9DkJTFyOzXw7
+r0stGAb0XCQqZPdZdSiXqZAsukYCamRmSTLLXTT+JOREsMKtFxsFfdNYiC6+Dtcr
+yly/KCU92Ls8OFLmJ/rSuEVrX39LsCMF6K9n6OJsL5/4c3/DF7yyalsq82vT3H/f
+L9CrBgz+A+eNguyEPch97ctqWzVIVQf7qngaAbuYRYvaiuMhV4YVIxdQG5y8Glmo
+Kq06fgEkg/ewYea9T9mRkKcquQw7q5UgHPB0zgK6FF3xkSVK
+-----END CERTIFICATE-----
diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
new file mode 100644
index 0000000..14b6418
--- /dev/null
+++ b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIC8DCCAdygAwIBAgIQNDAnfwU9lYVDoKT1DJrnyjAJBgUrDgMCHQUAMBMxETAP
+BgNVBAMTCFRlc3RSb290MB4XDTE2MDgwNDE1MDE0OFoXDTM5MTIzMTIzNTk1OVow
+EzERMA8GA1UEAxMIVGVzdFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
+AoIBAQCU5jNPVsMHoNCZV8PhVkIBcFkcL0pmjzSek7227JKkkFFdxo+1w4YV32CA
+vrh4WVub/SeSaczKjj6egUdbhO9cm7NKQ1uNCzEEALaKwKn1IdA/zbBnfVAzLvsb
+LBYu7lYBh/bI1FMHZ5kLRr8dkMbbf21iDEqsqKI8eQ+tj/7B6OUnPfmmmh3sml9i
+US6YHSm6a4r7Qw5oKfW+Z0hEKEX+HTtQcmrAuwyfAmGtY6eH9jKfPhZc7swFvRfo
+RlKvUIqmfhZpg2lbbk3Hz4C4zfZmP75soOicJmC6qQXdcUq9AKgM91CrRNY+hyE8
+LeYzJ14hJ7ncOEjWOpbhF0dlZc49AgMBAAGjSDBGMEQGA1UdAQQ9MDuAEM61es/l
+Icdr8+yS1L9lKjWhFTATMREwDwYDVQQDEwhUZXN0Um9vdIIQNDAnfwU9lYVDoKT1
+DJrnyjAJBgUrDgMCHQUAA4IBAQBrDeAK0O5bP7ZzSGLo9Fvh7dkAxeUOaPtTMzBq
+YLruOFtRY3DVfgX+5EUqFWIb/Nh1k1b25gaFIfcIRya5/gVOkCJU9DkJTFyOzXw7
+r0stGAb0XCQqZPdZdSiXqZAsukYCamRmSTLLXTT+JOREsMKtFxsFfdNYiC6+Dtcr
+yly/KCU92Ls8OFLmJ/rSuEVrX39LsCMF6K9n6OJsL5/4c3/DF7yyalsq82vT3H/f
+L9CrBgz+A+eNguyEPch97ctqWzVIVQf7qngaAbuYRYvaiuMhV4YVIxdQG5y8Glmo
+Kq06fgEkg/ewYea9T9mRkKcquQw7q5UgHPB0zgK6FF3xkSVK
+-----END CERTIFICATE-----
diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestSub.pem b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
new file mode 100644
index 0000000..67f9d25
--- /dev/null
+++ b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
@@ -0,0 +1,57 @@
+Bag Attributes
+    localKeyID: 01 00 00 00 
+    Microsoft CSP Name: Microsoft Strong Cryptographic Provider
+    friendlyName: PvkTmp:11e8b08d-46fb-45a2-90c4-d458be4a1276
+Key Attributes
+    X509v3 Key Usage: 80 
+-----BEGIN PRIVATE KEY-----
+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCfNn3oUo5iCBXg
+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ycZ57o
+xh8/EtBF7ikgiWHJcApmLEGcCVm+J+jclHBMpdEfOSPpWnkqEOyL/fVjniIslAeJ
+638WXKYgeu2QWkLjvGKd0XqM2l8CAwEAAaNZMFcwDwYDVR0TAQH/BAUwAwEB/zBE
+BgNVHQEEPTA7gBDOtXrP5SHHa/PsktS/ZSo1oRUwEzERMA8GA1UEAxMIVGVzdFJv
+b3SCEDQwJ38FPZWFQ6Ck9Qya58owCQYFKw4DAh0FAAOCAQEAFT8uXdMSHCmatVNg
+LMKsyVA/jJgXGncHmAy59Vjo2+KCIooEuY3NaK527LxB1yi9+UyMe2+Ia4KWcEGY
++mb+PDTDrlsYtjIU3aRzDpyXUrkYV/D6vZaw+zsgAquQkCi+WwEYZ4uCSUznlcyt
+U3p2Rd/+tvQqq5UerPfRBIs6JTUerwRGUQurTNpzqCGClo3zi58yuOEbNIrOzW1D
+MtQFKUtKkMx4rg6NT9kq/ICXt8k3UIsXh52NTYchkLlsnCgaoKzW2DFqSMFL3KC0
+NmQtmKaPo3mBIYJT0WDofYzas2TQO8cBiQHGrSqXNFAfI5eUo3qLtsRE+7Z9F2Mw
+HgNmsA==
+-----END CERTIFICATE-----
diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem
new file mode 100644
index 0000000..a12d837
--- /dev/null
+++ b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIDADCCAeygAwIBAgIQs4xkpm0/PYFLyLk1Nd0c0zAJBgUrDgMCHQUAMBMxETAP
+BgNVBAMTCFRlc3RSb290MB4XDTE2MDgwNDE1MDIwOVoXDTM5MTIzMTIzNTk1OVow
+EjEQMA4GA1UEAxMHVGVzdFN1YjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
+ggEBAJ82fehSjmIIFeDHUBTGAcb+Hbf9bJOGBiPY0BOgbdLnWLQwZqbKMY/wZsGm
+FFzQ5GkiFATxVr40+NZx2iHixcs6uhbcSzbqxH5zF1HA0XT9jEr/4luhgOZ1R5yB
+zCqKki/v3ltVCNEsLJP/4uMtez8Hdcz+NziMdruCz4CbAfYNfP1VOwgeZeub8oZn
+rhVDMVslgmX4q8UCaWYtwv63T32XKIlgv7ctjZqOifOQCJ1VDKUh+yaECVycZ57o
+xh8/EtBF7ikgiWHJcApmLEGcCVm+J+jclHBMpdEfOSPpWnkqEOyL/fVjniIslAeJ
+638WXKYgeu2QWkLjvGKd0XqM2l8CAwEAAaNZMFcwDwYDVR0TAQH/BAUwAwEB/zBE
+BgNVHQEEPTA7gBDOtXrP5SHHa/PsktS/ZSo1oRUwEzERMA8GA1UEAxMIVGVzdFJv
+b3SCEDQwJ38FPZWFQ6Ck9Qya58owCQYFKw4DAh0FAAOCAQEAFT8uXdMSHCmatVNg
+LMKsyVA/jJgXGncHmAy59Vjo2+KCIooEuY3NaK527LxB1yi9+UyMe2+Ia4KWcEGY
++mb+PDTDrlsYtjIU3aRzDpyXUrkYV/D6vZaw+zsgAquQkCi+WwEYZ4uCSUznlcyt
+U3p2Rd/+tvQqq5UerPfRBIs6JTUerwRGUQurTNpzqCGClo3zi58yuOEbNIrOzW1D
+MtQFKUtKkMx4rg6NT9kq/ICXt8k3UIsXh52NTYchkLlsnCgaoKzW2DFqSMFL3KC0
+NmQtmKaPo3mBIYJT0WDofYzas2TQO8cBiQHGrSqXNFAfI5eUo3qLtsRE+7Z9F2Mw
+HgNmsA==
+-----END CERTIFICATE-----
-- 
2.6.1.windows.1



^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [Patch 2/3] BaseTools: Rsa2048Sha256Sign add new option to support Monotonic count
  2016-08-15  8:17 [Patch 0/3] BaseTools: Add the support for FMP capsule generate auth info Yonghong Zhu
  2016-08-15  8:17 ` [Patch 1/3] BaseTools: Add the PKCS7 tool Yonghong Zhu
@ 2016-08-15  8:17 ` Yonghong Zhu
  2016-08-19  5:41   ` Gao, Liming
  2016-08-15  8:17 ` [Patch 3/3] BaseTools: FMP capsule add the support to generate auth info Yonghong Zhu
  2 siblings, 1 reply; 8+ messages in thread
From: Yonghong Zhu @ 2016-08-15  8:17 UTC (permalink / raw)
  To: edk2-devel; +Cc: Liming Gao

the EFI_FIRMWARE_IMAGE_AUTHENTICATION struct require the AuthInfo which
is a signature across the image data and the Monotonic Count value, so we
add the new option to support Monotonic count.

Cc: Liming Gao <liming.gao@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Yonghong Zhu <yonghong.zhu@intel.com>
---
 .../Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py  | 31 +++++++++++++++++-----
 1 file changed, 25 insertions(+), 6 deletions(-)

diff --git a/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py
index b3254d8..3410668 100644
--- a/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py
+++ b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py
@@ -1,12 +1,12 @@
 ## @file
-# This tool encodes and decodes GUIDed FFS sections for a GUID type of
+# This tool encodes and decodes GUIDed FFS sections or FMP capsule for a GUID type of
 # EFI_CERT_TYPE_RSA2048_SHA256_GUID defined in the UEFI 2.4 Specification as
 #   {0xa7717414, 0xc616, 0x4977, {0x94, 0x20, 0x84, 0x47, 0x12, 0xa7, 0x35, 0xbf}}
 # This tool has been tested with OpenSSL 1.0.1e 11 Feb 2013
 #
-# Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.<BR>
+# Copyright (c) 2013 - 2016, 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
 # http://opensource.org/licenses/bsd-license.php
 #
@@ -30,11 +30,11 @@ from Common.BuildVersion import gBUILD_VERSION
 #
 # Globals for help information
 #
 __prog__      = 'Rsa2048Sha256Sign'
 __version__   = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)
-__copyright__ = 'Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.'
+__copyright__ = 'Copyright (c) 2013 - 2016, Intel Corporation. All rights reserved.'
 __usage__     = '%s -e|-d [options] <input_file>' % (__prog__)
 
 #
 # GUID for SHA 256 Hash Algorithm from UEFI Specification
 #
@@ -64,10 +64,11 @@ if __name__ == '__main__':
   parser = argparse.ArgumentParser(prog=__prog__, version=__version__, usage=__usage__, description=__copyright__, conflict_handler='resolve')
   group = parser.add_mutually_exclusive_group(required=True)
   group.add_argument("-e", action="store_true", dest='Encode', help='encode file')
   group.add_argument("-d", action="store_true", dest='Decode', help='decode file')
   parser.add_argument("-o", "--output", dest='OutputFile', type=str, metavar='filename', help="specify the output filename", required=True)
+  parser.add_argument("--monotonic-count", dest='MonotonicCountStr', type=str, help="specify the MonotonicCount in FMP capsule.")
   parser.add_argument("--private-key", dest='PrivateKeyFile', type=argparse.FileType('rb'), help="specify the private key filename.  If not specified, a test signing key is used.")
   parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages")
   parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages")
   parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0,10), default=0, help="set debug level")
   parser.add_argument(metavar="input_file", dest='InputFile', type=argparse.FileType('rb'), help="specify the input filename")
@@ -153,17 +154,30 @@ if __name__ == '__main__':
   while len(PublicKeyHexString) > 0:
     PublicKey = PublicKey + chr(int(PublicKeyHexString[0:2],16))
     PublicKeyHexString=PublicKeyHexString[2:]
   if Process.returncode <> 0:
     sys.exit(Process.returncode)
-  
+
+  if args.MonotonicCountStr:
+    try:
+      if args.MonotonicCountStr.upper().startswith('0X'):
+        args.MonotonicCountValue = (long)(args.MonotonicCountStr, 16)
+      else:
+        args.MonotonicCountValue = (long)(args.MonotonicCountStr)
+    except:
+        pass
+
   if args.Encode:
+    FullInputFileBuffer = args.InputFileBuffer
+    if args.MonotonicCountStr:
+      format = "Q%ds" % len(args.InputFileBuffer)
+      FullInputFileBuffer = struct.pack(format,args.MonotonicCountValue, args.InputFileBuffer)
     # 
     # Sign the input file using the specified private key and capture signature from STDOUT
     #
     Process = subprocess.Popen('%s sha256 -sign "%s"' % (OpenSslCommand, args.PrivateKeyFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-    Signature = Process.communicate(input=args.InputFileBuffer)[0]
+    Signature = Process.communicate(input=FullInputFileBuffer)[0]
     if Process.returncode <> 0:
       sys.exit(Process.returncode)
       
     #
     # Write output file that contains hash GUID, Public Key, Signature, and Input data
@@ -194,20 +208,25 @@ if __name__ == '__main__':
     #
     if Header.PublicKey <> PublicKey:
       print 'ERROR: Public key in input file does not match public key from private key file'
       sys.exit(1)
 
+    FullInputFileBuffer = args.InputFileBuffer
+    if args.MonotonicCountStr:
+      format = "Q%ds" % len(args.InputFileBuffer)
+      FullInputFileBuffer = struct.pack(format,args.MonotonicCountValue, args.InputFileBuffer)
+
     #
     # Write Signature to output file
     #
     open(args.OutputFileName, 'wb').write(Header.Signature)
       
     #
     # Verify signature
     #    
     Process = subprocess.Popen('%s sha256 -prverify "%s" -signature %s' % (OpenSslCommand, args.PrivateKeyFileName, args.OutputFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-    Process.communicate(args.InputFileBuffer)
+    Process.communicate(input=FullInputFileBuffer)
     if Process.returncode <> 0:
       print 'ERROR: Verification failed'
       os.remove (args.OutputFileName)
       sys.exit(Process.returncode)
 
-- 
2.6.1.windows.1



^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [Patch 3/3] BaseTools: FMP capsule add the support to generate auth info
  2016-08-15  8:17 [Patch 0/3] BaseTools: Add the support for FMP capsule generate auth info Yonghong Zhu
  2016-08-15  8:17 ` [Patch 1/3] BaseTools: Add the PKCS7 tool Yonghong Zhu
  2016-08-15  8:17 ` [Patch 2/3] BaseTools: Rsa2048Sha256Sign add new option to support Monotonic count Yonghong Zhu
@ 2016-08-15  8:17 ` Yonghong Zhu
  2016-08-19  5:41   ` Gao, Liming
  2 siblings, 1 reply; 8+ messages in thread
From: Yonghong Zhu @ 2016-08-15  8:17 UTC (permalink / raw)
  To: edk2-devel; +Cc: Liming Gao

Current BaseTools cannot generate EFI_FIRMWARE_IMAGE_AUTHENTICATION
for FMP capsule. this patch fix it by FDF spec's update to add the
definition for CERTIFICATE_GUID and  MONOTONIC_COUNT. BaseTools call
the tool by CERTIFICATE_GUID to generate the certdata and fill the header
info.

Cc: Liming Gao <liming.gao@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Yonghong Zhu <yonghong.zhu@intel.com>
---
 BaseTools/Source/Python/GenFds/Capsule.py     | 80 +++++++++++++++++++++++++--
 BaseTools/Source/Python/GenFds/CapsuleData.py |  4 +-
 BaseTools/Source/Python/GenFds/FdfParser.py   | 64 ++++++++++++++++++---
 BaseTools/Source/Python/GenFds/GenFds.py      | 59 +++++++++++++++++++-
 BaseTools/Source/Python/GenFds/GuidSection.py | 59 +-------------------
 5 files changed, 194 insertions(+), 72 deletions(-)

diff --git a/BaseTools/Source/Python/GenFds/Capsule.py b/BaseTools/Source/Python/GenFds/Capsule.py
index 1683433..f8af12a 100644
--- a/BaseTools/Source/Python/GenFds/Capsule.py
+++ b/BaseTools/Source/Python/GenFds/Capsule.py
@@ -1,9 +1,9 @@
 ## @file
 # generate capsule
 #
-#  Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR>
+#  Copyright (c) 2007 - 2016, 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
 #  http://opensource.org/licenses/bsd-license.php
@@ -23,13 +23,20 @@ import StringIO
 from Common.Misc import SaveFileOnChange
 from GenFds import GenFds
 from Common.Misc import PackRegistryFormatGuid
 import uuid
 from struct import pack
+from GenFds import FindExtendTool
+from Common import EdkLogger
+from Common.BuildToolError import *
 
 
 T_CHAR_LF = '\n'
+WIN_CERT_REVISION      = 0x0200
+WIN_CERT_TYPE_EFI_GUID = 0x0EF1
+EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}')
+EFI_CERT_TYPE_RSA2048_SHA256_GUID = uuid.UUID('{a7717414-c616-4977-9420-844712a735bf}')
 
 ## create inf file describes what goes into capsule and call GenFv to generate capsule
 #
 #
 class Capsule (CapsuleClassObject) :
@@ -96,24 +103,87 @@ class Capsule (CapsuleClassObject) :
         else:
             FwMgrHdr.write(pack('=I', 0x00000001))
         FwMgrHdr.write(pack('=HH', len(self.CapsuleDataList), len(self.FmpPayloadList)))
         FwMgrHdrSize = 4+2+2+8*(len(self.CapsuleDataList)+len(self.FmpPayloadList))
 
+        #
+        # typedef struct _WIN_CERTIFICATE {
+        #   UINT32 dwLength;
+        #   UINT16 wRevision;
+        #   UINT16 wCertificateType;
+        # //UINT8 bCertificate[ANYSIZE_ARRAY];
+        # } WIN_CERTIFICATE;
+        #
+        # typedef struct _WIN_CERTIFICATE_UEFI_GUID {
+        #   WIN_CERTIFICATE Hdr;
+        #   EFI_GUID        CertType;
+        # //UINT8 CertData[ANYSIZE_ARRAY];
+        # } WIN_CERTIFICATE_UEFI_GUID;
+        #
+        # typedef struct {
+        #   UINT64                    MonotonicCount;
+        #   WIN_CERTIFICATE_UEFI_GUID AuthInfo;
+        # } EFI_FIRMWARE_IMAGE_AUTHENTICATION;
+        #
+        # typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 {
+        #   EFI_GUID HashType;
+        #   UINT8 PublicKey[256];
+        #   UINT8 Signature[256];
+        # } EFI_CERT_BLOCK_RSA_2048_SHA256;
+        #
+
         PreSize = FwMgrHdrSize
         Content = StringIO.StringIO()
         for driver in self.CapsuleDataList:
             FileName = driver.GenCapsuleSubItem()
             FwMgrHdr.write(pack('=Q', PreSize))
             PreSize += os.path.getsize(FileName)
             File = open(FileName, 'rb')
             Content.write(File.read())
             File.close()
         for fmp in self.FmpPayloadList:
-            payload = fmp.GenCapsuleSubItem()
-            FwMgrHdr.write(pack('=Q', PreSize))
-            PreSize += len(payload)
-            Content.write(payload)
+            if fmp.Certificate_Guid:
+                ExternalTool, ExternalOption = FindExtendTool([], GenFdsGlobalVariable.ArchList, fmp.Certificate_Guid)
+                CmdOption = ''
+                CapInputFile = fmp.ImageFile
+                if not os.path.isabs(fmp.ImageFile):
+                    CapInputFile = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, fmp.ImageFile)
+                CapOutputTmp = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) + '.tmp'
+                if ExternalTool == None:
+                    EdkLogger.error("GenFds", GENFDS_ERROR, "No tool found with GUID %s" % fmp.Certificate_Guid)
+                else:
+                    CmdOption += ExternalTool
+                if ExternalOption:
+                    CmdOption = CmdOption + ' ' + ExternalOption
+                CmdOption += ' -e ' + ' --monotonic-count ' + str(fmp.MonotonicCount) + ' -o ' + CapOutputTmp + ' ' + CapInputFile
+                CmdList = CmdOption.split()
+                GenFdsGlobalVariable.CallExternalTool(CmdList, "Failed to generate FMP auth capsule")
+                if uuid.UUID(fmp.Certificate_Guid) == EFI_CERT_TYPE_PKCS7_GUID:
+                    dwLength = 4 + 2 + 2 + 16 + os.path.getsize(CapOutputTmp) - os.path.getsize(CapInputFile)
+                else:
+                    dwLength = 4 + 2 + 2 + 16 + 16 + 256 + 256
+                Buffer  = pack('Q', fmp.MonotonicCount)
+                Buffer += pack('I', dwLength)
+                Buffer += pack('H', WIN_CERT_REVISION)
+                Buffer += pack('H', WIN_CERT_TYPE_EFI_GUID)
+                Buffer += uuid.UUID(fmp.Certificate_Guid).get_bytes_le()
+                if os.path.exists(CapOutputTmp):
+                    TmpFile = open(CapOutputTmp, 'rb')
+                    Buffer += TmpFile.read()
+                    TmpFile.close()
+                    if fmp.VendorCodeFile:
+                        VendorFile = open(fmp.VendorCodeFile, 'rb')
+                        Buffer += VendorFile.read()
+                        VendorFile.close()
+                    FwMgrHdr.write(pack('=Q', PreSize))
+                    PreSize += len(Buffer)
+                    Content.write(Buffer)
+            else:
+                payload = fmp.GenCapsuleSubItem()
+                FwMgrHdr.write(pack('=Q', PreSize))
+                PreSize += len(payload)
+                Content.write(payload)
         BodySize = len(FwMgrHdr.getvalue()) + len(Content.getvalue())
         Header.write(pack('=I', HdrSize + BodySize))
         #
         # The real capsule header structure is 28 bytes
         #
diff --git a/BaseTools/Source/Python/GenFds/CapsuleData.py b/BaseTools/Source/Python/GenFds/CapsuleData.py
index efc2812..2a5c454 100644
--- a/BaseTools/Source/Python/GenFds/CapsuleData.py
+++ b/BaseTools/Source/Python/GenFds/CapsuleData.py
@@ -1,9 +1,9 @@
 ## @file
 # generate capsule
 #
-#  Copyright (c) 2007-2013, Intel Corporation. All rights reserved.<BR>
+#  Copyright (c) 2007-2016, 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
 #  http://opensource.org/licenses/bsd-license.php
@@ -178,10 +178,12 @@ class CapsulePayload(CapsuleData):
         self.ImageTypeId = None
         self.ImageIndex = None
         self.HardwareInstance = None
         self.ImageFile = None
         self.VendorCodeFile = None
+        self.Certificate_Guid = None
+        self.MonotonicCount = None
 
     def GenCapsuleSubItem(self):
         if not self.Version:
             self.Version = 0x00000002
         ImageFileSize = os.path.getsize(self.ImageFile)
diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py b/BaseTools/Source/Python/GenFds/FdfParser.py
index 8709cfc..02ae7c9 100644
--- a/BaseTools/Source/Python/GenFds/FdfParser.py
+++ b/BaseTools/Source/Python/GenFds/FdfParser.py
@@ -50,15 +50,17 @@ from Common.Misc import PathClass
 from Common.String import NormPath
 import Common.GlobalData as GlobalData
 from Common.Expression import *
 from Common import GlobalData
 from Common.String import ReplaceMacro
-
+import uuid
 from Common.Misc import tdict
 
 import Common.LongFilePathOs as os
 from Common.LongFilePathSupport import OpenLongFilePath as open
+from Capsule import EFI_CERT_TYPE_PKCS7_GUID
+from Capsule import EFI_CERT_TYPE_RSA2048_SHA256_GUID
 
 ##define T_CHAR_SPACE                ' '
 ##define T_CHAR_NULL                 '\0'
 ##define T_CHAR_CR                   '\r'
 ##define T_CHAR_TAB                  '\t'
@@ -1122,10 +1124,30 @@ class FdfParser:
             return True
         else:
             self.__UndoToken()
             return False
 
+    def __Verify(self, Name, Value, Scope):
+        if Scope in ['UINT64', 'UINT8']:
+            ValueNumber = 0
+            try:
+                if Value.upper().startswith('0X'):
+                    ValueNumber = int (Value, 16)
+                else:
+                    ValueNumber = int (Value)
+            except:
+                EdkLogger.error("FdfParser", FORMAT_INVALID, "The value is not valid dec or hex number for %s." % Name)
+            if ValueNumber < 0:
+                EdkLogger.error("FdfParser", FORMAT_INVALID, "The value can't be set to negative value for %s." % Name)
+            if Scope == 'UINT64':
+                if ValueNumber >= 0x10000000000000000:
+                    EdkLogger.error("FdfParser", FORMAT_INVALID, "Too large value for %s." % Name)
+            if Scope == 'UINT8':
+                if ValueNumber >= 0x100:
+                    EdkLogger.error("FdfParser", FORMAT_INVALID, "Too large value for %s." % Name)
+            return True
+
     ## __UndoToken() method
     #
     #   Go back one token unit in file buffer
     #
     #   @param  self        The object pointer
@@ -3185,44 +3207,70 @@ class FdfParser:
         if not self.__IsToken( "]"):
             raise Warning("expected ']'", self.FileName, self.CurrentLineNumber)
 
         if not self.__GetNextToken():
             raise Warning("The FMP payload section is empty!", self.FileName, self.CurrentLineNumber)
-        FmpKeyList = ['IMAGE_HEADER_INIT_VERSION', 'IMAGE_TYPE_ID', 'IMAGE_INDEX', 'HARDWARE_INSTANCE']
+        FmpKeyList = ['IMAGE_HEADER_INIT_VERSION', 'IMAGE_TYPE_ID', 'IMAGE_INDEX', 'HARDWARE_INSTANCE', 'CERTIFICATE_GUID', 'MONOTONIC_COUNT']
         while self.__Token in FmpKeyList:
             Name = self.__Token
             FmpKeyList.remove(Name)
             if not self.__IsToken("="):
                 raise Warning("expected '='", self.FileName, self.CurrentLineNumber)
             if Name == 'IMAGE_TYPE_ID':
                 if not self.__GetNextGuid():
-                    raise Warning("expected GUID value for IMAGE_TYPE_ID", self.FileName, self.CurrentLineNumber)
+                    raise Warning("expected GUID value for IMAGE_TYPE_ID.", self.FileName, self.CurrentLineNumber)
                 FmpData.ImageTypeId = self.__Token
+            elif Name == 'CERTIFICATE_GUID':
+                if not self.__GetNextGuid():
+                    raise Warning("expected GUID value for CERTIFICATE_GUID.", self.FileName, self.CurrentLineNumber)
+                FmpData.Certificate_Guid = self.__Token
+                if uuid.UUID(FmpData.Certificate_Guid) != EFI_CERT_TYPE_RSA2048_SHA256_GUID and uuid.UUID(FmpData.Certificate_Guid) != EFI_CERT_TYPE_PKCS7_GUID:
+                    raise Warning("Only support EFI_CERT_TYPE_RSA2048_SHA256_GUID or EFI_CERT_TYPE_PKCS7_GUID for CERTIFICATE_GUID.", self.FileName, self.CurrentLineNumber)
             else:
                 if not self.__GetNextToken():
                     raise Warning("expected value of %s" % Name, self.FileName, self.CurrentLineNumber)
                 Value = self.__Token
                 if Name == 'IMAGE_HEADER_INIT_VERSION':
-                    FmpData.Version = Value
+                    if self.__Verify(Name, Value, 'UINT8'):
+                        FmpData.Version = Value
                 elif Name == 'IMAGE_INDEX':
-                    FmpData.ImageIndex = Value
+                    if self.__Verify(Name, Value, 'UINT8'):
+                        FmpData.ImageIndex = Value
                 elif Name == 'HARDWARE_INSTANCE':
-                    FmpData.HardwareInstance = Value
+                    if self.__Verify(Name, Value, 'UINT8'):
+                        FmpData.HardwareInstance = Value
+                elif Name == 'MONOTONIC_COUNT':
+                    if self.__Verify(Name, Value, 'UINT64'):
+                        FmpData.MonotonicCount = Value
+                        if FmpData.MonotonicCount.upper().startswith('0X'):
+                            FmpData.MonotonicCount = (long)(FmpData.MonotonicCount, 16)
+                        else:
+                            FmpData.MonotonicCount = (long)(FmpData.MonotonicCount)
             if not self.__GetNextToken():
                 break
         else:
             self.__UndoToken()
 
+        if (FmpData.MonotonicCount and not FmpData.Certificate_Guid) or (not FmpData.MonotonicCount and FmpData.Certificate_Guid):
+            EdkLogger.error("FdfParser", FORMAT_INVALID, "CERTIFICATE_GUID and MONOTONIC_COUNT must be work as a pair.")
+        # remove CERTIFICATE_GUID and MONOTONIC_COUNT from FmpKeyList, since these keys are optional
+        if 'CERTIFICATE_GUID' in FmpKeyList:
+            FmpKeyList.remove('CERTIFICATE_GUID')
+        if 'MONOTONIC_COUNT' in FmpKeyList:
+            FmpKeyList.remove('MONOTONIC_COUNT')
         if FmpKeyList:
-            raise Warning("Missing keywords %s in FMP payload section" % ', '.join(FmpKeyList), self.FileName, self.CurrentLineNumber)
+            raise Warning("Missing keywords %s in FMP payload section." % ', '.join(FmpKeyList), self.FileName, self.CurrentLineNumber)
         ImageFile = self.__ParseRawFileStatement()
         if not ImageFile:
-            raise Warning("Missing image file in FMP payload section", self.FileName, self.CurrentLineNumber)
+            raise Warning("Missing image file in FMP payload section.", self.FileName, self.CurrentLineNumber)
         FmpData.ImageFile = ImageFile
         VendorCodeFile = self.__ParseRawFileStatement()
         if VendorCodeFile:
             FmpData.VendorCodeFile = VendorCodeFile
+        AdditionalFile = self.__ParseRawFileStatement()
+        if AdditionalFile:
+            raise Warning("At most one Image file and one Vendor code file are allowed in FMP payload section.", self.FileName, self.CurrentLineNumber)
         self.Profile.FmpPayloadDict[FmpUiName] = FmpData
         return True
 
     ## __GetCapsule() method
     #
diff --git a/BaseTools/Source/Python/GenFds/GenFds.py b/BaseTools/Source/Python/GenFds/GenFds.py
index 68232c5..1a0ec7a 100644
--- a/BaseTools/Source/Python/GenFds/GenFds.py
+++ b/BaseTools/Source/Python/GenFds/GenFds.py
@@ -410,11 +410,68 @@ def BuildOptionPcdValueFormat(TokenSpaceGuidCName, TokenCName, PcdDatumType, Val
             Value = '1'
         elif Value == 'FALSE' or Value == '0':
             Value = '0'
     return  Value
 
-        
+## FindExtendTool()
+#
+#  Find location of tools to process data
+#
+#  @param  KeyStringList    Filter for inputs of section generation
+#  @param  CurrentArchList  Arch list
+#  @param  NameGuid         The Guid name
+#
+def FindExtendTool(KeyStringList, CurrentArchList, NameGuid):
+    # if user not specify filter, try to deduce it from global data.
+    if KeyStringList == None or KeyStringList == []:
+        Target = GenFdsGlobalVariable.TargetName
+        ToolChain = GenFdsGlobalVariable.ToolChainTag
+        ToolDb = ToolDefClassObject.ToolDefDict(GenFdsGlobalVariable.ConfDir).ToolsDefTxtDatabase
+        if ToolChain not in ToolDb['TOOL_CHAIN_TAG']:
+            EdkLogger.error("GenFds", GENFDS_ERROR, "Can not find external tool because tool tag %s is not defined in tools_def.txt!" % ToolChain)
+        KeyStringList = [Target + '_' + ToolChain + '_' + CurrentArchList[0]]
+        for Arch in CurrentArchList:
+            if Target + '_' + ToolChain + '_' + Arch not in KeyStringList:
+                KeyStringList.append(Target + '_' + ToolChain + '_' + Arch)
+
+    if GenFdsGlobalVariable.GuidToolDefinition:
+        if NameGuid in GenFdsGlobalVariable.GuidToolDefinition.keys():
+            return GenFdsGlobalVariable.GuidToolDefinition[NameGuid]
+
+    ToolDefinition = ToolDefClassObject.ToolDefDict(GenFdsGlobalVariable.ConfDir).ToolsDefTxtDictionary
+    ToolPathTmp = None
+    ToolOption = None
+    for ToolDef in ToolDefinition.items():
+        if NameGuid == ToolDef[1]:
+            KeyList = ToolDef[0].split('_')
+            Key = KeyList[0] + \
+                  '_' + \
+                  KeyList[1] + \
+                  '_' + \
+                  KeyList[2]
+            if Key in KeyStringList and KeyList[4] == 'GUID':
+
+                ToolPath = ToolDefinition.get(Key + \
+                                               '_' + \
+                                               KeyList[3] + \
+                                               '_' + \
+                                               'PATH')
+
+                ToolOption = ToolDefinition.get(Key + \
+                                                '_' + \
+                                                KeyList[3] + \
+                                                '_' + \
+                                                'FLAGS')
+                if ToolPathTmp == None:
+                    ToolPathTmp = ToolPath
+                else:
+                    if ToolPathTmp != ToolPath:
+                        EdkLogger.error("GenFds", GENFDS_ERROR, "Don't know which tool to use, %s or %s ?" % (ToolPathTmp, ToolPath))
+
+    GenFdsGlobalVariable.GuidToolDefinition[NameGuid] = (ToolPathTmp, ToolOption)
+    return ToolPathTmp, ToolOption
+
 ## Parse command line options
 #
 # Using standard Python module optparse to parse command line option of this tool.
 #
 #   @retval Opt   A optparse.Values object containing the parsed options
diff --git a/BaseTools/Source/Python/GenFds/GuidSection.py b/BaseTools/Source/Python/GenFds/GuidSection.py
index ac5ae58..f199dcd 100644
--- a/BaseTools/Source/Python/GenFds/GuidSection.py
+++ b/BaseTools/Source/Python/GenFds/GuidSection.py
@@ -25,10 +25,11 @@ from Common import ToolDefClassObject
 import sys
 from Common import EdkLogger
 from Common.BuildToolError import *
 from FvImageSection import FvImageSection
 from Common.LongFilePathSupport import OpenLongFilePath as open
+from GenFds import FindExtendTool
 
 ## generate GUIDed section
 #
 #
 class GuidSection(GuidSectionClassObject) :
@@ -126,11 +127,11 @@ class GuidSection(GuidSectionClassObject) :
         OutputFile = os.path.normpath(OutputFile)
 
         ExternalTool = None
         ExternalOption = None
         if self.NameGuid != None:
-            ExternalTool, ExternalOption = self.__FindExtendTool__()
+            ExternalTool, ExternalOption = FindExtendTool(self.KeyStringList, self.CurrentArchList, self.NameGuid)
 
         #
         # If not have GUID , call default
         # GENCRC32 section
         #
@@ -247,63 +248,7 @@ class GuidSection(GuidSectionClassObject) :
                 self.Alignment = None
                 self.IncludeFvSection = False
                 self.ProcessRequired = "TRUE"
             return OutputFileList, self.Alignment
 
-    ## __FindExtendTool()
-    #
-    #    Find location of tools to process section data
-    #
-    #   @param  self        The object pointer
-    #
-    def __FindExtendTool__(self):
-        # if user not specify filter, try to deduce it from global data.
-        if self.KeyStringList == None or self.KeyStringList == []:
-            Target = GenFdsGlobalVariable.TargetName
-            ToolChain = GenFdsGlobalVariable.ToolChainTag
-            ToolDb = ToolDefClassObject.ToolDefDict(GenFdsGlobalVariable.ConfDir).ToolsDefTxtDatabase
-            if ToolChain not in ToolDb['TOOL_CHAIN_TAG']:
-                EdkLogger.error("GenFds", GENFDS_ERROR, "Can not find external tool because tool tag %s is not defined in tools_def.txt!" % ToolChain)
-            self.KeyStringList = [Target + '_' + ToolChain + '_' + self.CurrentArchList[0]]
-            for Arch in self.CurrentArchList:
-                if Target + '_' + ToolChain + '_' + Arch not in self.KeyStringList:
-                    self.KeyStringList.append(Target + '_' + ToolChain + '_' + Arch)
-
-        if GenFdsGlobalVariable.GuidToolDefinition:
-            if self.NameGuid in GenFdsGlobalVariable.GuidToolDefinition.keys():
-                return GenFdsGlobalVariable.GuidToolDefinition[self.NameGuid]
-
-        ToolDefinition = ToolDefClassObject.ToolDefDict(GenFdsGlobalVariable.ConfDir).ToolsDefTxtDictionary
-        ToolPathTmp = None
-        ToolOption = None
-        for ToolDef in ToolDefinition.items():
-            if self.NameGuid == ToolDef[1]:
-                KeyList = ToolDef[0].split('_')
-                Key = KeyList[0] + \
-                      '_' + \
-                      KeyList[1] + \
-                      '_' + \
-                      KeyList[2]
-                if Key in self.KeyStringList and KeyList[4] == 'GUID':
-
-                    ToolPath = ToolDefinition.get(Key + \
-                                                   '_' + \
-                                                   KeyList[3] + \
-                                                   '_' + \
-                                                   'PATH')
-
-                    ToolOption = ToolDefinition.get(Key + \
-                                                    '_' + \
-                                                    KeyList[3] + \
-                                                    '_' + \
-                                                    'FLAGS')
-                    if ToolPathTmp == None:
-                        ToolPathTmp = ToolPath
-                    else:
-                        if ToolPathTmp != ToolPath:
-                            EdkLogger.error("GenFds", GENFDS_ERROR, "Don't know which tool to use, %s or %s ?" % (ToolPathTmp, ToolPath))
-
-        GenFdsGlobalVariable.GuidToolDefinition[self.NameGuid] = (ToolPathTmp, ToolOption)
-        return ToolPathTmp, ToolOption
-
 
 
-- 
2.6.1.windows.1



^ permalink raw reply related	[flat|nested] 8+ messages in thread

* Re: [Patch 1/3] BaseTools: Add the PKCS7 tool
  2016-08-15  8:17 ` [Patch 1/3] BaseTools: Add the PKCS7 tool Yonghong Zhu
@ 2016-08-15  8:32   ` Yao, Jiewen
  2016-08-15  8:34     ` Zhu, Yonghong
  0 siblings, 1 reply; 8+ messages in thread
From: Yao, Jiewen @ 2016-08-15  8:32 UTC (permalink / raw)
  To: Zhu, Yonghong, edk2-devel@lists.01.org; +Cc: Gao, Liming

Hello
In order to make PKCS7 tool be consistent with RSA2048SHA256, I suggest we use "Pkcs7Sign.py" instead of GenFirmwareImageAuthPkcs7.py.



> -----Original Message-----
> From: Zhu, Yonghong
> Sent: Monday, August 15, 2016 4:18 PM
> To: edk2-devel@lists.01.org
> Cc: Gao, Liming <liming.gao@intel.com>; Yao, Jiewen
> <jiewen.yao@intel.com>
> Subject: [Patch 1/3] BaseTools: Add the PKCS7 tool
> 
> Provide the PKCS7 Tool to support the CertType -
> EFI_CERT_TYPE_PKCS7_GUID,
> then user can use this tool to add EFI_FIRMWARE_IMAGE_AUTHENTICATION
> for a binary.
> 
> Cc: Liming Gao <liming.gao@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Jiewen Yao <jiewen.yao@intel.com>
> ---
>  BaseTools/Conf/tools_def.template                  |   6 +
>  BaseTools/Source/Python/Makefile                   |  27 +-
>  .../Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py  | 285
> +++++++++++++++++++++
>  BaseTools/Source/Python/Pkcs7Sign/TestCert.pem     |  57 +++++
>  BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem |  19 ++
>  BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem     |  56 ++++
>  BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem |  18 ++
>  BaseTools/Source/Python/Pkcs7Sign/TestSub.pem      |  57 +++++
>  BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem  |  19 ++
>  9 files changed, 541 insertions(+), 3 deletions(-)
>  create mode 100644
> BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
>  create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
>  create mode 100644
> BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
>  create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
>  create mode 100644
> BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
>  create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
>  create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem
> 
> diff --git a/BaseTools/Conf/tools_def.template
> b/BaseTools/Conf/tools_def.template
> index 974656c..a78ea77 100755
> --- a/BaseTools/Conf/tools_def.template
> +++ b/BaseTools/Conf/tools_def.template
> @@ -7669,10 +7669,16 @@ RELEASE_RVCTCYGWIN_ARM_CC_FLAGS  =
> "$(CCPATH_FLAG)" $(ARCHCC_FLAGS) $(PLATFORM_F
>  ##################
>  *_*_*_VPDTOOL_PATH         = BPDG
>  *_*_*_VPDTOOL_GUID         =
> 8C3D856A-9BE6-468E-850A-24F7A8D38E08
> 
>  ##################
> +# Firmware Image Auth PKCS7 tool definitions
> +##################
> +*_*_*_PKCS7_PATH           = GenFirmwareImageAuthPkcs7
> +*_*_*_PKCS7_GUID           =
> 4AAFD29D-68DF-49EE-8AA9-347D375665A7
> +
> +##################
>  # NASM tool definitions
>  ##################
>  *_*_*_NASM_PATH                = ENV(NASM_PREFIX)nasm
>  # NASMB uses NASM produce a .bin from a .nasmb NASM source file
>  *_*_*_NASMB_FLAGS              = -f bin
> diff --git a/BaseTools/Source/Python/Makefile
> b/BaseTools/Source/Python/Makefile
> index 8bc213b..8d6a386 100644
> --- a/BaseTools/Source/Python/Makefile
> +++ b/BaseTools/Source/Python/Makefile
> @@ -1,9 +1,9 @@
>  ## @file
>  # Windows makefile for Python tools build.
>  #
> -# Copyright (c) 2010 - 2015, Intel Corporation. All rights reserved.<BR>
> +# Copyright (c) 2010 - 2016, 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
>  # http://opensource.org/licenses/bsd-license.php
>  #
> @@ -29,11 +29,11 @@
> MODULES=encodings.cp437,encodings.gbk,encodings.utf_16,encodings.utf
> _8,encodings
>  BASE_TOOLS_PATH = $(BASE_TOOLS_PATH::\\=:\)
>  EDK_TOOLS_PATH  = $(EDK_TOOLS_PATH::\\=:\)
> 
>  BIN_DIR=$(EDK_TOOLS_PATH)\Bin\Win32
> 
> -APPLICATIONS=$(BIN_DIR)\build.exe $(BIN_DIR)\GenFds.exe
> $(BIN_DIR)\Trim.exe $(BIN_DIR)\TargetTool.exe $(BIN_DIR)\GenDepex.exe
> $(BIN_DIR)\GenPatchPcdTable.exe $(BIN_DIR)\PatchPcdValue.exe
> $(BIN_DIR)\BPDG.exe $(BIN_DIR)\UPT.exe
> $(BIN_DIR)\Rsa2048Sha256Sign.exe
> $(BIN_DIR)\Rsa2048Sha256GenerateKeys.exe $(BIN_DIR)\Ecc.exe
> +APPLICATIONS=$(BIN_DIR)\build.exe $(BIN_DIR)\GenFds.exe
> $(BIN_DIR)\Trim.exe $(BIN_DIR)\TargetTool.exe $(BIN_DIR)\GenDepex.exe
> $(BIN_DIR)\GenPatchPcdTable.exe $(BIN_DIR)\PatchPcdValue.exe
> $(BIN_DIR)\BPDG.exe $(BIN_DIR)\UPT.exe
> $(BIN_DIR)\Rsa2048Sha256Sign.exe
> $(BIN_DIR)\Rsa2048Sha256GenerateKeys.exe
> $(BIN_DIR)\GenFirmwareImageAuthPkcs7.exe $(BIN_DIR)\Ecc.exe
> 
> 
> COMMON_PYTHON=$(BASE_TOOLS_PATH)\Source\Python\Common\BuildT
> oolError.py \
> 
> $(BASE_TOOLS_PATH)\Source\Python\Common\Database.py \
> 
> $(BASE_TOOLS_PATH)\Source\Python\Common\DataType.py \
> 
> $(BASE_TOOLS_PATH)\Source\Python\Common\DecClassObject.py \
> @@ -283,11 +283,32 @@ $(BIN_DIR)\Ecc.exe:
> $(BASE_TOOLS_PATH)\Source\Python\Ecc\Ecc.py $(CMD_ECC) $(BIN
>  $(BIN_DIR)\config.ini: $(BASE_TOOLS_PATH)\Source\Python\Ecc\config.ini
>    @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Ecc\config.ini
> $(BIN_DIR)\config.ini
> 
>  $(BIN_DIR)\exception.xml:
> $(BASE_TOOLS_PATH)\Source\Python\Ecc\exception.xml
>    @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Ecc\exception.xml
> $(BIN_DIR)\exception.xml
> -
> +
> +$(BIN_DIR)\GenFirmwareImageAuthPkcs7.exe:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\GenFirmwareImageAuthPk
> cs7.py $(BIN_DIR)\TestCert.pem $(BIN_DIR)\TestCert.pub.pem
> $(BIN_DIR)\TestRoot.pem $(BIN_DIR)\TestRoot.pub.pem
> $(BIN_DIR)\TestSub.pem $(BIN_DIR)\TestSub.pub.pem
> +  @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR)
> Pkcs7Sign\GenFirmwareImageAuthPkcs7.py
> +
> +$(BIN_DIR)\TestCert.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pem
> $(BIN_DIR)\TestCert.pem
> +
> +$(BIN_DIR)\TestCert.pub.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pub.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pub.pem
> $(BIN_DIR)\TestCert.pub.pem
> +
> +$(BIN_DIR)\TestSub.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pem
> $(BIN_DIR)\TestSub.pem
> +
> +$(BIN_DIR)\TestSub.pub.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pub.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pub.pem
> $(BIN_DIR)\TestSub.pub.pem
> +
> +$(BIN_DIR)\TestRoot.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pem
> $(BIN_DIR)\TestRoot.pem
> +
> +$(BIN_DIR)\TestRoot.pub.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pub.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pub.pem
> $(BIN_DIR)\TestRoot.pub.pem
> +
>  clean:
>  cleanall:
>    @del /f /q $(BIN_DIR)\*.pyd $(BIN_DIR)\*.dll
>    @for %%i in ($(APPLICATIONS)) do @del /f /q %%i
> 
> diff --git
> a/BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
> b/BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
> new file mode 100644
> index 0000000..ccbb1c2
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
> @@ -0,0 +1,285 @@
> +## @file
> +# This tool adds EFI_FIRMWARE_IMAGE_AUTHENTICATION for a binary.
> +#
> +# This tool only support CertType - EFI_CERT_TYPE_PKCS7_GUID
> +#   {0x4aafd29d, 0x68df, 0x49ee, {0x8a, 0xa9, 0x34, 0x7d, 0x37, 0x56,
> 0x65, 0xa7}}
> +#
> +# This tool has been tested with OpenSSL.
> +#
> +# Copyright (c) 2016, 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
> +# http://opensource.org/licenses/bsd-license.php
> +#
> +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS"
> BASIS,
> +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER
> EXPRESS OR IMPLIED.
> +#
> +
> +'''
> +GenFirmwareImageAuth
> +'''
> +
> +import os
> +import sys
> +import argparse
> +import subprocess
> +import uuid
> +import struct
> +import collections
> +from Common.BuildVersion import gBUILD_VERSION
> +
> +#
> +# Globals for help information
> +#
> +__prog__      = 'GenFirmwareImageAuthPkcs7'
> +__version__   = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)
> +__copyright__ = 'Copyright (c) 2016, Intel Corporation. All rights reserved.'
> +__usage__     = '%s -e|-d [options] <input_file>' % (__prog__)
> +
> +#
> +# GUID for PKCS7 from UEFI Specification
> +#
> +WIN_CERT_REVISION      = 0x0200
> +WIN_CERT_TYPE_EFI_GUID = 0x0EF1
> +EFI_CERT_TYPE_PKCS7_GUID =
> uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}')
> +
> +#
> +# typedef struct _WIN_CERTIFICATE {
> +#   UINT32 dwLength;
> +#   UINT16 wRevision;
> +#   UINT16 wCertificateType;
> +# //UINT8 bCertificate[ANYSIZE_ARRAY];
> +# } WIN_CERTIFICATE;
> +#
> +# typedef struct _WIN_CERTIFICATE_UEFI_GUID {
> +#   WIN_CERTIFICATE Hdr;
> +#   EFI_GUID        CertType;
> +# //UINT8 CertData[ANYSIZE_ARRAY];
> +# } WIN_CERTIFICATE_UEFI_GUID;
> +#
> +# typedef struct {
> +#   UINT64                    MonotonicCount;
> +#   WIN_CERTIFICATE_UEFI_GUID AuthInfo;
> +# } EFI_FIRMWARE_IMAGE_AUTHENTICATION;
> +#
> +
> +EFI_FIRMWARE_IMAGE_AUTHENTICATION        =
> collections.namedtuple('EFI_FIRMWARE_IMAGE_AUTHENTICATION',
> ['MonotonicCount','dwLength','wRevision','wCertificateType','CertType'])
> +EFI_FIRMWARE_IMAGE_AUTHENTICATION_STRUCT =
> struct.Struct('QIHH16s')
> +
> +#
> +# Filename of test signing private cert that is stored in same directory as
> this tool
> +#
> +TEST_SIGNER_PRIVATE_CERT_FILENAME = 'TestCert.pem'
> +TEST_OTHER_PUBLIC_CERT_FILENAME = 'TestSub.pub.pem'
> +TEST_TRUSTED_PUBLIC_CERT_FILENAME = 'TestRoot.pub.pem'
> +
> +if __name__ == '__main__':
> +  #
> +  # Create command line argument parser object
> +  #
> +  parser = argparse.ArgumentParser(prog=__prog__, version=__version__,
> usage=__usage__, description=__copyright__, conflict_handler='resolve')
> +  group = parser.add_mutually_exclusive_group(required=True)
> +  group.add_argument("-e", action="store_true", dest='Encode',
> help='encode file')
> +  group.add_argument("-d", action="store_true", dest='Decode',
> help='decode file')
> +  parser.add_argument("-o", "--output", dest='OutputFile', type=str,
> metavar='filename', help="specify the output filename", required=True)
> +  parser.add_argument("--signer-private-cert", dest='SignerPrivateCertFile',
> type=argparse.FileType('rb'), help="specify the signer private cert filename.
> If not specified, a test signer private cert is used.")
> +  parser.add_argument("--other-public-cert", dest='OtherPublicCertFile',
> type=argparse.FileType('rb'), help="specify the other public cert filename.
> If not specified, a test other public cert is used.")
> +  parser.add_argument("--trusted-public-cert", dest='TrustedPublicCertFile',
> type=argparse.FileType('rb'), help="specify the trusted public cert filename.
> If not specified, a test trusted public cert is used.")
> +  parser.add_argument("--monotonic-count", dest='MonotonicCountStr',
> type=str, help="specify the MonotonicCount in FMP capsule.  If not
> specified, 0 is used.")
> +  parser.add_argument("--signature-size", dest='SignatureSizeStr', type=str,
> help="specify the signature size for decode process.")
> +  parser.add_argument("-v", "--verbose", dest='Verbose',
> action="store_true", help="increase output messages")
> +  parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true",
> help="reduce output messages")
> +  parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]',
> choices=range(0,10), default=0, help="set debug level")
> +  parser.add_argument(metavar="input_file", dest='InputFile',
> type=argparse.FileType('rb'), help="specify the input filename")
> +
> +  #
> +  # Parse command line arguments
> +  #
> +  args = parser.parse_args()
> +
> +  #
> +  # Generate file path to Open SSL command
> +  #
> +  OpenSslCommand = 'openssl'
> +  try:
> +    OpenSslPath = os.environ['OPENSSL_PATH']
> +    OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand)
> +  except:
> +    pass
> +
> +  #
> +  # Verify that Open SSL command is available
> +  #
> +  try:
> +    Process = subprocess.Popen('%s version' % (OpenSslCommand),
> stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> +  except:
> +    print 'ERROR: Open SSL command not available.  Please verify PATH
> or set OPENSSL_PATH'
> +    sys.exit(1)
> +
> +  Version = Process.communicate()
> +  if Process.returncode <> 0:
> +    print 'ERROR: Open SSL command not available.  Please verify PATH
> or set OPENSSL_PATH'
> +    sys.exit(Process.returncode)
> +  print Version[0]
> +
> +  #
> +  # Read input file into a buffer and save input filename
> +  #
> +  args.InputFileName   = args.InputFile.name
> +  args.InputFileBuffer = args.InputFile.read()
> +  args.InputFile.close()
> +
> +  #
> +  # Save output filename and check if path exists
> +  #
> +  OutputDir = os.path.dirname(args.OutputFile)
> +  if not os.path.exists(OutputDir):
> +    print 'ERROR: The output path does not exist: %s' % OutputDir
> +    sys.exit(1)
> +  args.OutputFileName = args.OutputFile
> +
> +  try:
> +    if args.MonotonicCountStr.upper().startswith('0X'):
> +      args.MonotonicCountValue = (long)(args.MonotonicCountStr, 16)
> +    else:
> +      args.MonotonicCountValue = (long)(args.MonotonicCountStr)
> +  except:
> +    args.MonotonicCountValue = (long)(0)
> +
> +  if args.Encode:
> +    #
> +    # Save signer private cert filename and close private cert file
> +    #
> +    try:
> +      args.SignerPrivateCertFileName = args.SignerPrivateCertFile.name
> +      args.SignerPrivateCertFile.close()
> +    except:
> +      try:
> +        #
> +        # Get path to currently executing script or executable
> +        #
> +        if hasattr(sys, 'frozen'):
> +            Pkcs7ToolPath = sys.executable
> +        else:
> +            Pkcs7ToolPath = sys.argv[0]
> +        if Pkcs7ToolPath.startswith('"'):
> +            Pkcs7ToolPath = Pkcs7ToolPath[1:]
> +        if Pkcs7ToolPath.endswith('"'):
> +            Pkcs7ToolPath = RsaToolPath[:-1]
> +        args.SignerPrivateCertFileName =
> os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)),
> TEST_SIGNER_PRIVATE_CERT_FILENAME)
> +        args.SignerPrivateCertFile = open(args.SignerPrivateCertFileName,
> 'rb')
> +        args.SignerPrivateCertFile.close()
> +      except:
> +        print 'ERROR: test signer private cert file %s missing' %
> (args.SignerPrivateCertFileName)
> +        sys.exit(1)
> +
> +    #
> +    # Save other public cert filename and close public cert file
> +    #
> +    try:
> +      args.OtherPublicCertFileName = args.OtherPublicCertFile.name
> +      args.OtherPublicCertFile.close()
> +    except:
> +      try:
> +        #
> +        # Get path to currently executing script or executable
> +        #
> +        if hasattr(sys, 'frozen'):
> +            Pkcs7ToolPath = sys.executable
> +        else:
> +            Pkcs7ToolPath = sys.argv[0]
> +        if Pkcs7ToolPath.startswith('"'):
> +            Pkcs7ToolPath = Pkcs7ToolPath[1:]
> +        if Pkcs7ToolPath.endswith('"'):
> +            Pkcs7ToolPath = RsaToolPath[:-1]
> +        args.OtherPublicCertFileName =
> os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)),
> TEST_OTHER_PUBLIC_CERT_FILENAME)
> +        args.OtherPublicCertFile = open(args.OtherPublicCertFileName,
> 'rb')
> +        args.OtherPublicCertFile.close()
> +      except:
> +        print 'ERROR: test other public cert file %s missing' %
> (args.OtherPublicCertFileName)
> +        sys.exit(1)
> +
> +    format = "Q%ds" % len(args.InputFileBuffer)
> +    FullInputFileBuffer = struct.pack(format,args.MonotonicCountValue,
> args.InputFileBuffer)
> +
> +    #
> +    # Sign the input file using the specified private key and capture
> signature from STDOUT
> +    #
> +    Process = subprocess.Popen('%s smime -sign -binary -signer "%s"
> -outform DER -md sha256 -certfile "%s"' % (OpenSslCommand,
> args.SignerPrivateCertFileName, args.OtherPublicCertFileName),
> stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> +    Signature = Process.communicate(input=FullInputFileBuffer)[0]
> +    if Process.returncode <> 0:
> +      sys.exit(Process.returncode)
> +
> +    #
> +    # Write output file that contains Signature, and Input data
> +    #
> +    args.OutputFile = open(args.OutputFileName, 'wb')
> +    args.OutputFile.write(Signature)
> +    args.OutputFile.write(args.InputFileBuffer)
> +    args.OutputFile.close()
> +
> +  if args.Decode:
> +    #
> +    # Save trusted public cert filename and close public cert file
> +    #
> +    try:
> +      args.TrustedPublicCertFileName = args.TrustedPublicCertFile.name
> +      args.TrustedPublicCertFile.close()
> +    except:
> +      try:
> +        #
> +        # Get path to currently executing script or executable
> +        #
> +        if hasattr(sys, 'frozen'):
> +            Pkcs7ToolPath = sys.executable
> +        else:
> +            Pkcs7ToolPath = sys.argv[0]
> +        if Pkcs7ToolPath.startswith('"'):
> +            Pkcs7ToolPath = Pkcs7ToolPath[1:]
> +        if Pkcs7ToolPath.endswith('"'):
> +            Pkcs7ToolPath = RsaToolPath[:-1]
> +        args.TrustedPublicCertFileName =
> os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)),
> TEST_TRUSTED_PUBLIC_CERT_FILENAME)
> +        args.TrustedPublicCertFile = open(args.TrustedPublicCertFileName,
> 'rb')
> +        args.TrustedPublicCertFile.close()
> +      except:
> +        print 'ERROR: test trusted public cert file %s missing' %
> (args.TrustedPublicCertFileName)
> +        sys.exit(1)
> +
> +    if not args.SignatureSizeStr:
> +      print "ERROR: please use the option --signature-size to specify the
> size of the signature data!"
> +      sys.exit(1)
> +    else:
> +      if args.SignatureSizeStr.upper().startswith('0X'):
> +        SignatureSize = (long)(args.SignatureSizeStr, 16)
> +      else:
> +        SignatureSize = (long)(args.SignatureSizeStr)
> +    if SignatureSize < 0:
> +        print "ERROR: The value of option --signature-size can't be set to
> negative value!"
> +        sys.exit(1)
> +    elif SignatureSize > len(args.InputFileBuffer):
> +        print "ERROR: The value of option --signature-size is exceed the
> size of the input file !"
> +        sys.exit(1)
> +
> +    args.SignatureBuffer = args.InputFileBuffer[0:SignatureSize]
> +    args.InputFileBuffer = args.InputFileBuffer[SignatureSize:]
> +
> +    format = "Q%ds" % len(args.InputFileBuffer)
> +    FullInputFileBuffer = struct.pack(format,args.MonotonicCountValue,
> args.InputFileBuffer)
> +
> +    #
> +    # Save output file contents from input file
> +    #
> +    open(args.OutputFileName, 'wb').write(FullInputFileBuffer)
> +
> +    #
> +    # Verify signature
> +    #
> +    Process = subprocess.Popen('%s smime -verify -inform DER
> -content %s -CAfile %s' % (OpenSslCommand, args.OutputFileName,
> args.TrustedPublicCertFileName), stdin=subprocess.PIPE,
> stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> +    Process.communicate(input=args.SignatureBuffer)[0]
> +    if Process.returncode <> 0:
> +      print 'ERROR: Verification failed'
> +      os.remove (args.OutputFileName)
> +      sys.exit(Process.returncode)
> +
> +    open(args.OutputFileName, 'wb').write(args.InputFileBuffer)
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
> new file mode 100644
> index 0000000..7e10358
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
> @@ -0,0 +1,57 @@
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +    Microsoft CSP Name: Microsoft Strong Cryptographic Provider
> +    friendlyName: PvkTmp:133cc061-112c-467a-b8cf-dc0a56d7830e
> +Key Attributes
> +    X509v3 Key Usage: 80
> +-----BEGIN PRIVATE KEY-----
> +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCSPHYSohF
> +fim4
> +89iNx8CcCG/fPb7KLu9Dsq+pB4Pc/UJtaaA+D7RK3PhqNCrWbb+gCNgm7lxiO
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/mw0euWN2cdGnid3W9J4uUJMH8n0MpMU4ar+2
> /xVNUAO
> +YTBXmirusGbKO8SPocwsMXQ8bGMrrc19yeREUpr22XdB6408L9WfnyW9hsu
> WlGhm
> +LclLT4I4cf/9GNbIJedcvvRckEozvmFdIplMP0tpeiDEdfYwZNSkiuktAoGBAL5m
> +gTXYDSFO/VUiFFOsOElyPV174LOsuQyVoGZjOjOtI1rVInTqkAD1p1/hf+aahSy
> D
> +qYzrvv8s+RVWKg9u10JDNgVg0kupHLr98RfPiWJg8vHhXFYwtb6tlNMS9+9yvc
> zm
> +O4jzY/4zW7+qQoYKxkyq2pVn7uVOnmPNcQIHEGqBAoGBAJMfZV2vpxY6kti8
> SXzb
> +PscYI3ZbbKyJLq4+KHGcKCqqbLiY4ao8vflDyDwBm+TJg4xq9wjJAN2riE9nuuds
> +99mYW/8R30BIfiH/4oBHjggb0NC5K3vHR4KGDKcUiIKZPv1r7mNeYw227N4n
> /dPM
> +NXjlZVuS6mqc2T+GPzAJj/Uf
> +-----END PRIVATE KEY-----
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +subject=/CN=TestCert
> +issuer=/CN=TestSub
> +-----BEGIN CERTIFICATE-----
> +MIIC/TCCAemgAwIBAgIQ0+nLBVt+jbJMSfzhFpRJrDAJBgUrDgMCHQUAMBIx
> EDAO
> +BgNVBAMTB1Rlc3RTdWIwHhcNMTYwODA0MTUwMjMwWhcNMzkxMjMx
> MjM1OTU5WjAT
> +MREwDwYDVQQDEwhUZXN0Q2VydDCCASIwDQYJKoZIhvcNAQEBBQADggE
> PADCCAQoC
> +ggEBAJI8dhKiEX5+Kbjz2I3HwJwIb989vsou70Oyr6kHg9z9Qm1poD4PtErc+Go
> 0
> +KtZtv6AI2CbuXGI4KseabS09qXvVRXxUVSJMztl/XLxUEUIcn3bKSZLswPCpXbm
> g
> +wYahzPiN1w+XevbIUWp32NoEA+NSwdFuzwALwIod7E4AJ97J2BCiP0o9Yf0N
> QVDJ
> +dxu0zIZcC8UKS2dI1FB/TVR00l5t4Pr7CVCfSxRqiOfWW7nvQ51ncCQmWbpt
> MQq9
> +8d44HbUZoedDU7VFW2q938qMUeHFJLDyZ5OzKo39Ohr/zQXJQoSZMhol0R
> qr8LZc
> +ppQAJ7Oxiq9HEOr6mWKTKIim3psCAwEAAaNWMFQwDAYDVR0TAQH/BAIw
> ADBEBgNV
> +HQEEPTA7gBAeQOcW6KCBdWSbrvKQrBrfoRUwEzERMA8GA1UEAxMIVGVz
> dFJvb3SC
> +ELOMZKZtPz2BS8i5NTXdHNMwCQYFKw4DAh0FAAOCAQEAK7YgK6iiTo07d3C
> SY4xG
> +9N0QS2m4LsBPrF8pFmk5h6R81MFEdBZrA+zggbUujQ2IGB7k6F7WvP3F3B3
> AXZtx
> +DW1FYrQheQhTT5wx85LxFdLy+q6uwUtJi/VyErPmZOcds3QaBXPvG/UykFbu
> 24JV
> +K2ScLpQVyzmkTN7GWSXrIO6eHHMQgeRX3XjRutbR8CKP1pWTOY+MO4G6Y
> ZqrzLdp
> +opYFPgvdZpTL3IKSSkp31Amu5oidkvzLgallC3SOYdLZirWEIAAXW2LVYXwiiL6L
> +HEIV/G9u85jhKhv/z9l8F/1Eg4HHGSYba8pf1HQA+WsQwi4BVp4x4MBoeHOol
> yVT
> +/A==
> +-----END CERTIFICATE-----
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
> new file mode 100644
> index 0000000..f5b0cec
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
> @@ -0,0 +1,19 @@
> +-----BEGIN CERTIFICATE-----
> +MIIC/TCCAemgAwIBAgIQ0+nLBVt+jbJMSfzhFpRJrDAJBgUrDgMCHQUAMBIx
> EDAO
> +BgNVBAMTB1Rlc3RTdWIwHhcNMTYwODA0MTUwMjMwWhcNMzkxMjMx
> MjM1OTU5WjAT
> +MREwDwYDVQQDEwhUZXN0Q2VydDCCASIwDQYJKoZIhvcNAQEBBQADggE
> PADCCAQoC
> +ggEBAJI8dhKiEX5+Kbjz2I3HwJwIb989vsou70Oyr6kHg9z9Qm1poD4PtErc+Go
> 0
> +KtZtv6AI2CbuXGI4KseabS09qXvVRXxUVSJMztl/XLxUEUIcn3bKSZLswPCpXbm
> g
> +wYahzPiN1w+XevbIUWp32NoEA+NSwdFuzwALwIod7E4AJ97J2BCiP0o9Yf0N
> QVDJ
> +dxu0zIZcC8UKS2dI1FB/TVR00l5t4Pr7CVCfSxRqiOfWW7nvQ51ncCQmWbpt
> MQq9
> +8d44HbUZoedDU7VFW2q938qMUeHFJLDyZ5OzKo39Ohr/zQXJQoSZMhol0R
> qr8LZc
> +ppQAJ7Oxiq9HEOr6mWKTKIim3psCAwEAAaNWMFQwDAYDVR0TAQH/BAIw
> ADBEBgNV
> +HQEEPTA7gBAeQOcW6KCBdWSbrvKQrBrfoRUwEzERMA8GA1UEAxMIVGVz
> dFJvb3SC
> +ELOMZKZtPz2BS8i5NTXdHNMwCQYFKw4DAh0FAAOCAQEAK7YgK6iiTo07d3C
> SY4xG
> +9N0QS2m4LsBPrF8pFmk5h6R81MFEdBZrA+zggbUujQ2IGB7k6F7WvP3F3B3
> AXZtx
> +DW1FYrQheQhTT5wx85LxFdLy+q6uwUtJi/VyErPmZOcds3QaBXPvG/UykFbu
> 24JV
> +K2ScLpQVyzmkTN7GWSXrIO6eHHMQgeRX3XjRutbR8CKP1pWTOY+MO4G6Y
> ZqrzLdp
> +opYFPgvdZpTL3IKSSkp31Amu5oidkvzLgallC3SOYdLZirWEIAAXW2LVYXwiiL6L
> +HEIV/G9u85jhKhv/z9l8F/1Eg4HHGSYba8pf1HQA+WsQwi4BVp4x4MBoeHOol
> yVT
> +/A==
> +-----END CERTIFICATE-----
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
> new file mode 100644
> index 0000000..3ca5149
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
> @@ -0,0 +1,56 @@
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +    Microsoft CSP Name: Microsoft Strong Cryptographic Provider
> +    friendlyName: PvkTmp:76c92422-d6f3-4763-9b80-b423fd921d00
> +Key Attributes
> +    X509v3 Key Usage: 80
> +-----BEGIN PRIVATE KEY-----
> +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCU5jNPVsM
> HoNCZ
> +V8PhVkIBcFkcL0pmjzSek7227JKkkFFdxo+1w4YV32CAvrh4WVub/SeSaczKjj6e
> +gUdbhO9cm7NKQ1uNCzEEALaKwKn1IdA/zbBnfVAzLvsbLBYu7lYBh/bI1FMHZ
> 5kL
> +Rr8dkMbbf21iDEqsqKI8eQ+tj/7B6OUnPfmmmh3sml9iUS6YHSm6a4r7Qw5o
> KfW+
> +Z0hEKEX+HTtQcmrAuwyfAmGtY6eH9jKfPhZc7swFvRfoRlKvUIqmfhZpg2lbbk
> 3H
> +z4C4zfZmP75soOicJmC6qQXdcUq9AKgM91CrRNY+hyE8LeYzJ14hJ7ncOEjW
> Opbh
> +F0dlZc49AgMBAAECgf8dY26Sej8u15Xiri/l3zXgy7aR7uAAbFGoM8fv2exQgID
> k
> +FrdxTDtqzqTSxGAkfUWs4Ip2DUEeZDwF/qjW4FCzb3mI/QmNt70Yd9KsEDAm
> DkZ2
> +wylcYC2l7IqVEl6HZMpNyiu5hfXdTn/tlkkUIiKr6POYmFR6IyPiS61Tm4LQXyhv
> +iW+Lx0GqFQcH82CsbNRNgJGJk/BIiHn7kNDi5rRrKsmTuKEQB9iwF/rKp+lnJN0
> g
> +4qTv2bbZVxj39QWdOovU5LCL+1WJdkA2mpFpZjBEsTdF+UEGCbixdiftfovnZa
> 64
> +rofw3pIxr97XS42D3OmdPmSokpwqcQtjTXfScCECgYEAvxBMHcEFMZX644hh
> ZtH7
> +t0/PCka9DUBZfe58r+lmgSvlbMCka9OvKGtr86+j0IdWqmGWxRHAuk3KR3NI
> C3EU
> +mD0rYSWiStW0I/cmHidS/a9OdWWHtWi1LcXX7KBn9AjKjPzghqAfDAkRxYfZK
> LIo
> +PRL44O/RM6nJ1j7az5CgWR0CgYEAx4FW/xVVL1Z0kn/VyNVYLdlhV4zMNn6
> Cu0ko
> +jebQydDBh4Tsne2A4dPonZQSsEiJ6jhzaUZr7l5OAEp+0aX0M/h6JbxTcA4CK3X
> r
> +X2TAaOCkPc1r0I79ZduKymyMNrWfXHenvFVl57klp9eFRQJ6o+pZB9ysFzPHXb
> ci
> +4VCsX6ECgYBMqAdB8M1apafxXihmDl2FoJmar+LtzCGbqvGPyn772FbGGUxe
> jqG5
> +/89iB9gbtBELbvgEvSisFsXPgOso3Ae9RN2Aro68o50QyPocIv7jFVDPPRsDp6z
> 5
> +XmVRZNIQUO6jPln+6YNLWuAsdmKkN0Z5qoD8DnvK1JZMRQ+ZM5eB6QKBg
> QCuvz+w
> +VsMyn4uj9o0PSK/gGRQGV7FX2iAwY7g98vrWix+40FlhS3MkWzTZMaXc+uyy
> V5ff
> +kmtfcwLnhljm0XHBQ9fZzcdX0y1bXAI6oElYk8vIxnG1UEnsOgyrmcCG+zcHC1f
> E
> +wxhri+TLyx9UfwNlKBOrq0KhYB00nQDUUpFpgQKBgQCPWpNeNQ8hCARnay
> hzu2fE
> +HEPG1P/resOp0u+c4jy4TeHVa9806wqZlkYNRKNn09Ub5Ajpp05dwdb+JvUSk
> Wwr
> +vOmE94WeLg5FuNzPAQjwAe+Eq54Vk8TdAhdLSu1m2xdBKFtEOk6TQTmRBCi
> knwhg
> +19TgHd8hEFnz6ZICAeWGbQ==
> +-----END PRIVATE KEY-----
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +subject=/CN=TestRoot
> +issuer=/CN=TestRoot
> +-----BEGIN CERTIFICATE-----
> +MIIC8DCCAdygAwIBAgIQNDAnfwU9lYVDoKT1DJrnyjAJBgUrDgM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a/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
> new file mode 100644
> index 0000000..14b6418
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
> @@ -0,0 +1,18 @@
> +-----BEGIN CERTIFICATE-----
> +MIIC8DCCAdygAwIBAgIQNDAnfwU9lYVDoKT1DJrnyjAJBgUrDgMCHQUAMB
> MxETAP
> +BgNVBAMTCFRlc3RSb290MB4XDTE2MDgwNDE1MDE0OFoXDTM5MTIzMTI
> zNTk1OVow
> +EzERMA8GA1UEAxMIVGVzdFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBD
> wAwggEK
> +AoIBAQCU5jNPVsMHoNCZV8PhVkIBcFkcL0pmjzSek7227JKkkFFdxo+1w4YV3
> 2CA
> +vrh4WVub/SeSaczKjj6egUdbhO9cm7NKQ1uNCzEEALaKwKn1IdA/zbBnfVAzLv
> sb
> +LBYu7lYBh/bI1FMHZ5kLRr8dkMbbf21iDEqsqKI8eQ+tj/7B6OUnPfmmmh3sml
> 9i
> +US6YHSm6a4r7Qw5oKfW+Z0hEKEX+HTtQcmrAuwyfAmGtY6eH9jKfPhZc7sw
> FvRfo
> +RlKvUIqmfhZpg2lbbk3Hz4C4zfZmP75soOicJmC6qQXdcUq9AKgM91CrRNY+h
> yE8
> +LeYzJ14hJ7ncOEjWOpbhF0dlZc49AgMBAAGjSDBGMEQGA1UdAQQ9MDuAE
> M61es/l
> +Icdr8+yS1L9lKjWhFTATMREwDwYDVQQDEwhUZXN0Um9vdIIQNDAnfwU9lY
> VDoKT1
> +DJrnyjAJBgUrDgMCHQUAA4IBAQBrDeAK0O5bP7ZzSGLo9Fvh7dkAxeUOaPtT
> MzBq
> +YLruOFtRY3DVfgX+5EUqFWIb/Nh1k1b25gaFIfcIRya5/gVOkCJU9DkJTFyOzX
> w7
> +r0stGAb0XCQqZPdZdSiXqZAsukYCamRmSTLLXTT+JOREsMKtFxsFfdNYiC6+Dt
> cr
> +yly/KCU92Ls8OFLmJ/rSuEVrX39LsCMF6K9n6OJsL5/4c3/DF7yyalsq82vT3H/f
> +L9CrBgz+A+eNguyEPch97ctqWzVIVQf7qngaAbuYRYvaiuMhV4YVIxdQG5y8G
> lmo
> +Kq06fgEkg/ewYea9T9mRkKcquQw7q5UgHPB0zgK6FF3xkSVK
> +-----END CERTIFICATE-----
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
> new file mode 100644
> index 0000000..67f9d25
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
> @@ -0,0 +1,57 @@
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +    Microsoft CSP Name: Microsoft Strong Cryptographic Provider
> +    friendlyName: PvkTmp:11e8b08d-46fb-45a2-90c4-d458be4a1276
> +Key Attributes
> +    X509v3 Key Usage: 80
> +-----BEGIN PRIVATE KEY-----
> +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCfNn3oUo5
> iCBXg
> +x1AUxgHG/h23/WyThgYj2NAToG3S51i0MGamyjGP8GbBphRc0ORpIhQE8Va
> +NPjW
> +cdoh4sXLOroW3Es26sR+cxdRwNF0/YxK/+JboYDmdUecgcwqipIv795bVQjRL
> CyT
> +/+LjLXs/B3XM/jc4jHa7gs+AmwH2DXz9VTsIHmXrm/KGZ64VQzFbJYJl+KvFAml
> m
> +LcL+t099lyiJYL+3LY2ajonzkAidVQylIfsmhAlcnGee6MYfPxLQRe4pIIlhyXAK
> +ZixBnAlZvifo3JRwTKXRHzkj6Vp5KhDsi/31Y54iLJQHiet/FlymIHrtkFpC47xi
> +ndF6jNpfAgMBAAECggEAD4owC9xS+A/gosnmxRWhLXJhet3fb8llvAX4zpGau
> +Uc
> +wVRKu1OCNucOAISx+W/iJhN6GhQRlWByO+wXkGB5UcwaRwpFb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RXbb1rdE6WoLkSk4Dz4u/B9E7YVzTZggYhPisChu6wZP
> tK
> +IiXBGu8h3GygUGI/WdNRKHW5nst9IZWrtVJ06c87jWqOktbgBnrbqXUG1rgRZ
> r+i
> +n3sJLF+GGwzdp/gCxLMH66M=
> +-----END PRIVATE KEY-----
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +subject=/CN=TestSub
> +issuer=/CN=TestRoot
> +-----BEGIN CERTIFICATE-----
> +MIIDADCCAeygAwIBAgIQs4xkpm0/PYFLyLk1Nd0c0zAJBgUrDgMCHQUAMB
> MxETAP
> +BgNVBAMTCFRlc3RSb290MB4XDTE2MDgwNDE1MDIwOVoXDTM5MTIzMTI
> zNTk1OVow
> +EjEQMA4GA1UEAxMHVGVzdFN1YjCCASIwDQYJKoZIhvcNAQEBBQADggEPA
> DCCAQoC
> +ggEBAJ82fehSjmIIFeDHUBTGAcb+Hbf9bJOGBiPY0BOgbdLnWLQwZqbKMY/
> wZsGm
> +FFzQ5GkiFATxVr40+NZx2iHixcs6uhbcSzbqxH5zF1HA0XT9jEr/4luhgOZ1R5yB
> +zCqKki/v3ltVCNEsLJP/4uMtez8Hdcz+NziMdruCz4CbAfYNfP1VOwgeZeub8oZ
> n
> +rhVDMVslgmX4q8UCaWYtwv63T32XKIlgv7ctjZqOifOQCJ1VDKUh+yaECVycZ
> 57o
> +xh8/EtBF7ikgiWHJcApmLEGcCVm+J+jclHBMpdEfOSPpWnkqEOyL/fVjniIslAeJ
> +638WXKYgeu2QWkLjvGKd0XqM2l8CAwEAAaNZMFcwDwYDVR0TAQH/BAU
> wAwEB/zBE
> +BgNVHQEEPTA7gBDOtXrP5SHHa/PsktS/ZSo1oRUwEzERMA8GA1UEAxMIVG
> VzdFJv
> +b3SCEDQwJ38FPZWFQ6Ck9Qya58owCQYFKw4DAh0FAAOCAQEAFT8uXdMS
> HCmatVNg
> +LMKsyVA/jJgXGncHmAy59Vjo2+KCIooEuY3NaK527LxB1yi9+UyMe2+Ia4KWc
> EGY
> ++mb+PDTDrlsYtjIU3aRzDpyXUrkYV/D6vZaw+zsgAquQkCi+WwEYZ4uCSUznlc
> yt
> +U3p2Rd/+tvQqq5UerPfRBIs6JTUerwRGUQurTNpzqCGClo3zi58yuOEbNIrOz
> W1D
> +MtQFKUtKkMx4rg6NT9kq/ICXt8k3UIsXh52NTYchkLlsnCgaoKzW2DFqSMFL3
> KC0
> +NmQtmKaPo3mBIYJT0WDofYzas2TQO8cBiQHGrSqXNFAfI5eUo3qLtsRE+7Z9
> F2Mw
> +HgNmsA==
> +-----END CERTIFICATE-----
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem
> new file mode 100644
> index 0000000..a12d837
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem
> @@ -0,0 +1,19 @@
> +-----BEGIN CERTIFICATE-----
> +MIIDADCCAeygAwIBAgIQs4xkpm0/PYFLyLk1Nd0c0zAJBgUrDgMCHQUAMB
> MxETAP
> +BgNVBAMTCFRlc3RSb290MB4XDTE2MDgwNDE1MDIwOVoXDTM5MTIzMTI
> zNTk1OVow
> +EjEQMA4GA1UEAxMHVGVzdFN1YjCCASIwDQYJKoZIhvcNAQEBBQADggEPA
> DCCAQoC
> +ggEBAJ82fehSjmIIFeDHUBTGAcb+Hbf9bJOGBiPY0BOgbdLnWLQwZqbKMY/
> wZsGm
> +FFzQ5GkiFATxVr40+NZx2iHixcs6uhbcSzbqxH5zF1HA0XT9jEr/4luhgOZ1R5yB
> +zCqKki/v3ltVCNEsLJP/4uMtez8Hdcz+NziMdruCz4CbAfYNfP1VOwgeZeub8oZ
> n
> +rhVDMVslgmX4q8UCaWYtwv63T32XKIlgv7ctjZqOifOQCJ1VDKUh+yaECVycZ
> 57o
> +xh8/EtBF7ikgiWHJcApmLEGcCVm+J+jclHBMpdEfOSPpWnkqEOyL/fVjniIslAeJ
> +638WXKYgeu2QWkLjvGKd0XqM2l8CAwEAAaNZMFcwDwYDVR0TAQH/BAU
> wAwEB/zBE
> +BgNVHQEEPTA7gBDOtXrP5SHHa/PsktS/ZSo1oRUwEzERMA8GA1UEAxMIVG
> VzdFJv
> +b3SCEDQwJ38FPZWFQ6Ck9Qya58owCQYFKw4DAh0FAAOCAQEAFT8uXdMS
> HCmatVNg
> +LMKsyVA/jJgXGncHmAy59Vjo2+KCIooEuY3NaK527LxB1yi9+UyMe2+Ia4KWc
> EGY
> ++mb+PDTDrlsYtjIU3aRzDpyXUrkYV/D6vZaw+zsgAquQkCi+WwEYZ4uCSUznlc
> yt
> +U3p2Rd/+tvQqq5UerPfRBIs6JTUerwRGUQurTNpzqCGClo3zi58yuOEbNIrOz
> W1D
> +MtQFKUtKkMx4rg6NT9kq/ICXt8k3UIsXh52NTYchkLlsnCgaoKzW2DFqSMFL3
> KC0
> +NmQtmKaPo3mBIYJT0WDofYzas2TQO8cBiQHGrSqXNFAfI5eUo3qLtsRE+7Z9
> F2Mw
> +HgNmsA==
> +-----END CERTIFICATE-----
> --
> 2.6.1.windows.1



^ permalink raw reply	[flat|nested] 8+ messages in thread

* Re: [Patch 1/3] BaseTools: Add the PKCS7 tool
  2016-08-15  8:32   ` Yao, Jiewen
@ 2016-08-15  8:34     ` Zhu, Yonghong
  0 siblings, 0 replies; 8+ messages in thread
From: Zhu, Yonghong @ 2016-08-15  8:34 UTC (permalink / raw)
  To: Yao, Jiewen, edk2-devel@lists.01.org; +Cc: Gao, Liming, Zhu, Yonghong

Thanks. I will update it and send a new version.

Best Regards,
Zhu Yonghong


-----Original Message-----
From: Yao, Jiewen 
Sent: Monday, August 15, 2016 4:32 PM
To: Zhu, Yonghong <yonghong.zhu@intel.com>; edk2-devel@lists.01.org
Cc: Gao, Liming <liming.gao@intel.com>
Subject: RE: [Patch 1/3] BaseTools: Add the PKCS7 tool

Hello
In order to make PKCS7 tool be consistent with RSA2048SHA256, I suggest we use "Pkcs7Sign.py" instead of GenFirmwareImageAuthPkcs7.py.



> -----Original Message-----
> From: Zhu, Yonghong
> Sent: Monday, August 15, 2016 4:18 PM
> To: edk2-devel@lists.01.org
> Cc: Gao, Liming <liming.gao@intel.com>; Yao, Jiewen 
> <jiewen.yao@intel.com>
> Subject: [Patch 1/3] BaseTools: Add the PKCS7 tool
> 
> Provide the PKCS7 Tool to support the CertType - 
> EFI_CERT_TYPE_PKCS7_GUID, then user can use this tool to add 
> EFI_FIRMWARE_IMAGE_AUTHENTICATION for a binary.
> 
> Cc: Liming Gao <liming.gao@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Jiewen Yao <jiewen.yao@intel.com>
> ---
>  BaseTools/Conf/tools_def.template                  |   6 +
>  BaseTools/Source/Python/Makefile                   |  27 +-
>  .../Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py  | 285
> +++++++++++++++++++++
>  BaseTools/Source/Python/Pkcs7Sign/TestCert.pem     |  57 +++++
>  BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem |  19 ++
>  BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem     |  56 ++++
>  BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem |  18 ++
>  BaseTools/Source/Python/Pkcs7Sign/TestSub.pem      |  57 +++++
>  BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem  |  19 ++
>  9 files changed, 541 insertions(+), 3 deletions(-)  create mode 
> 100644 BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
>  create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
>  create mode 100644
> BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
>  create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
>  create mode 100644
> BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
>  create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
>  create mode 100644 BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem
> 
> diff --git a/BaseTools/Conf/tools_def.template
> b/BaseTools/Conf/tools_def.template
> index 974656c..a78ea77 100755
> --- a/BaseTools/Conf/tools_def.template
> +++ b/BaseTools/Conf/tools_def.template
> @@ -7669,10 +7669,16 @@ RELEASE_RVCTCYGWIN_ARM_CC_FLAGS  = 
> "$(CCPATH_FLAG)" $(ARCHCC_FLAGS) $(PLATFORM_F  ##################
>  *_*_*_VPDTOOL_PATH         = BPDG
>  *_*_*_VPDTOOL_GUID         =
> 8C3D856A-9BE6-468E-850A-24F7A8D38E08
> 
>  ##################
> +# Firmware Image Auth PKCS7 tool definitions ##################
> +*_*_*_PKCS7_PATH           = GenFirmwareImageAuthPkcs7
> +*_*_*_PKCS7_GUID           =
> 4AAFD29D-68DF-49EE-8AA9-347D375665A7
> +
> +##################
>  # NASM tool definitions
>  ##################
>  *_*_*_NASM_PATH                = ENV(NASM_PREFIX)nasm
>  # NASMB uses NASM produce a .bin from a .nasmb NASM source file
>  *_*_*_NASMB_FLAGS              = -f bin
> diff --git a/BaseTools/Source/Python/Makefile
> b/BaseTools/Source/Python/Makefile
> index 8bc213b..8d6a386 100644
> --- a/BaseTools/Source/Python/Makefile
> +++ b/BaseTools/Source/Python/Makefile
> @@ -1,9 +1,9 @@
>  ## @file
>  # Windows makefile for Python tools build.
>  #
> -# Copyright (c) 2010 - 2015, Intel Corporation. All rights 
> reserved.<BR>
> +# Copyright (c) 2010 - 2016, 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  # http://opensource.org/licenses/bsd-license.php
>  #
> @@ -29,11 +29,11 @@
> MODULES=encodings.cp437,encodings.gbk,encodings.utf_16,encodings.utf
> _8,encodings
>  BASE_TOOLS_PATH = $(BASE_TOOLS_PATH::\\=:\)  EDK_TOOLS_PATH  = 
> $(EDK_TOOLS_PATH::\\=:\)
> 
>  BIN_DIR=$(EDK_TOOLS_PATH)\Bin\Win32
> 
> -APPLICATIONS=$(BIN_DIR)\build.exe $(BIN_DIR)\GenFds.exe 
> $(BIN_DIR)\Trim.exe $(BIN_DIR)\TargetTool.exe $(BIN_DIR)\GenDepex.exe 
> $(BIN_DIR)\GenPatchPcdTable.exe $(BIN_DIR)\PatchPcdValue.exe 
> $(BIN_DIR)\BPDG.exe $(BIN_DIR)\UPT.exe 
> $(BIN_DIR)\Rsa2048Sha256Sign.exe 
> $(BIN_DIR)\Rsa2048Sha256GenerateKeys.exe $(BIN_DIR)\Ecc.exe
> +APPLICATIONS=$(BIN_DIR)\build.exe $(BIN_DIR)\GenFds.exe
> $(BIN_DIR)\Trim.exe $(BIN_DIR)\TargetTool.exe $(BIN_DIR)\GenDepex.exe 
> $(BIN_DIR)\GenPatchPcdTable.exe $(BIN_DIR)\PatchPcdValue.exe 
> $(BIN_DIR)\BPDG.exe $(BIN_DIR)\UPT.exe 
> $(BIN_DIR)\Rsa2048Sha256Sign.exe 
> $(BIN_DIR)\Rsa2048Sha256GenerateKeys.exe
> $(BIN_DIR)\GenFirmwareImageAuthPkcs7.exe $(BIN_DIR)\Ecc.exe
> 
> 
> COMMON_PYTHON=$(BASE_TOOLS_PATH)\Source\Python\Common\BuildT
> oolError.py \
> 
> $(BASE_TOOLS_PATH)\Source\Python\Common\Database.py \
> 
> $(BASE_TOOLS_PATH)\Source\Python\Common\DataType.py \
> 
> $(BASE_TOOLS_PATH)\Source\Python\Common\DecClassObject.py \ @@ -283,11 
> +283,32 @@ $(BIN_DIR)\Ecc.exe:
> $(BASE_TOOLS_PATH)\Source\Python\Ecc\Ecc.py $(CMD_ECC) $(BIN
>  $(BIN_DIR)\config.ini: $(BASE_TOOLS_PATH)\Source\Python\Ecc\config.ini
>    @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Ecc\config.ini
> $(BIN_DIR)\config.ini
> 
>  $(BIN_DIR)\exception.xml:
> $(BASE_TOOLS_PATH)\Source\Python\Ecc\exception.xml
>    @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Ecc\exception.xml
> $(BIN_DIR)\exception.xml
> -
> +
> +$(BIN_DIR)\GenFirmwareImageAuthPkcs7.exe:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\GenFirmwareImageAuthPk
> cs7.py $(BIN_DIR)\TestCert.pem $(BIN_DIR)\TestCert.pub.pem 
> $(BIN_DIR)\TestRoot.pem $(BIN_DIR)\TestRoot.pub.pem 
> $(BIN_DIR)\TestSub.pem $(BIN_DIR)\TestSub.pub.pem
> +  @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR)
> Pkcs7Sign\GenFirmwareImageAuthPkcs7.py
> +
> +$(BIN_DIR)\TestCert.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pem
> $(BIN_DIR)\TestCert.pem
> +
> +$(BIN_DIR)\TestCert.pub.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pub.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestCert.pub.pem
> $(BIN_DIR)\TestCert.pub.pem
> +
> +$(BIN_DIR)\TestSub.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pem
> $(BIN_DIR)\TestSub.pem
> +
> +$(BIN_DIR)\TestSub.pub.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pub.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestSub.pub.pem
> $(BIN_DIR)\TestSub.pub.pem
> +
> +$(BIN_DIR)\TestRoot.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pem
> $(BIN_DIR)\TestRoot.pem
> +
> +$(BIN_DIR)\TestRoot.pub.pem:
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pub.pem
> +  @copy /Y /B
> $(BASE_TOOLS_PATH)\Source\Python\Pkcs7Sign\TestRoot.pub.pem
> $(BIN_DIR)\TestRoot.pub.pem
> +
>  clean:
>  cleanall:
>    @del /f /q $(BIN_DIR)\*.pyd $(BIN_DIR)\*.dll
>    @for %%i in ($(APPLICATIONS)) do @del /f /q %%i
> 
> diff --git
> a/BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
> b/BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
> new file mode 100644
> index 0000000..ccbb1c2
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/GenFirmwareImageAuthPkcs7.py
> @@ -0,0 +1,285 @@
> +## @file
> +# This tool adds EFI_FIRMWARE_IMAGE_AUTHENTICATION for a binary.
> +#
> +# This tool only support CertType - EFI_CERT_TYPE_PKCS7_GUID
> +#   {0x4aafd29d, 0x68df, 0x49ee, {0x8a, 0xa9, 0x34, 0x7d, 0x37, 0x56,
> 0x65, 0xa7}}
> +#
> +# This tool has been tested with OpenSSL.
> +#
> +# Copyright (c) 2016, 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
> +# http://opensource.org/licenses/bsd-license.php
> +#
> +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS"
> BASIS,
> +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER
> EXPRESS OR IMPLIED.
> +#
> +
> +'''
> +GenFirmwareImageAuth
> +'''
> +
> +import os
> +import sys
> +import argparse
> +import subprocess
> +import uuid
> +import struct
> +import collections
> +from Common.BuildVersion import gBUILD_VERSION
> +
> +#
> +# Globals for help information
> +#
> +__prog__      = 'GenFirmwareImageAuthPkcs7'
> +__version__   = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)
> +__copyright__ = 'Copyright (c) 2016, Intel Corporation. All rights reserved.'
> +__usage__     = '%s -e|-d [options] <input_file>' % (__prog__)
> +
> +#
> +# GUID for PKCS7 from UEFI Specification #
> +WIN_CERT_REVISION      = 0x0200
> +WIN_CERT_TYPE_EFI_GUID = 0x0EF1
> +EFI_CERT_TYPE_PKCS7_GUID =
> uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}')
> +
> +#
> +# typedef struct _WIN_CERTIFICATE {
> +#   UINT32 dwLength;
> +#   UINT16 wRevision;
> +#   UINT16 wCertificateType;
> +# //UINT8 bCertificate[ANYSIZE_ARRAY]; # } WIN_CERTIFICATE; # # 
> +typedef struct _WIN_CERTIFICATE_UEFI_GUID {
> +#   WIN_CERTIFICATE Hdr;
> +#   EFI_GUID        CertType;
> +# //UINT8 CertData[ANYSIZE_ARRAY];
> +# } WIN_CERTIFICATE_UEFI_GUID;
> +#
> +# typedef struct {
> +#   UINT64                    MonotonicCount;
> +#   WIN_CERTIFICATE_UEFI_GUID AuthInfo;
> +# } EFI_FIRMWARE_IMAGE_AUTHENTICATION;
> +#
> +
> +EFI_FIRMWARE_IMAGE_AUTHENTICATION        =
> collections.namedtuple('EFI_FIRMWARE_IMAGE_AUTHENTICATION',
> ['MonotonicCount','dwLength','wRevision','wCertificateType','CertType'
> ])
> +EFI_FIRMWARE_IMAGE_AUTHENTICATION_STRUCT =
> struct.Struct('QIHH16s')
> +
> +#
> +# Filename of test signing private cert that is stored in same 
> +directory as
> this tool
> +#
> +TEST_SIGNER_PRIVATE_CERT_FILENAME = 'TestCert.pem'
> +TEST_OTHER_PUBLIC_CERT_FILENAME = 'TestSub.pub.pem'
> +TEST_TRUSTED_PUBLIC_CERT_FILENAME = 'TestRoot.pub.pem'
> +
> +if __name__ == '__main__':
> +  #
> +  # Create command line argument parser object
> +  #
> +  parser = argparse.ArgumentParser(prog=__prog__, 
> +version=__version__,
> usage=__usage__, description=__copyright__, 
> conflict_handler='resolve')
> +  group = parser.add_mutually_exclusive_group(required=True)
> +  group.add_argument("-e", action="store_true", dest='Encode',
> help='encode file')
> +  group.add_argument("-d", action="store_true", dest='Decode',
> help='decode file')
> +  parser.add_argument("-o", "--output", dest='OutputFile', type=str,
> metavar='filename', help="specify the output filename", required=True)
> +  parser.add_argument("--signer-private-cert", 
> + dest='SignerPrivateCertFile',
> type=argparse.FileType('rb'), help="specify the signer private cert filename.
> If not specified, a test signer private cert is used.")
> +  parser.add_argument("--other-public-cert", 
> + dest='OtherPublicCertFile',
> type=argparse.FileType('rb'), help="specify the other public cert filename.
> If not specified, a test other public cert is used.")
> +  parser.add_argument("--trusted-public-cert", 
> + dest='TrustedPublicCertFile',
> type=argparse.FileType('rb'), help="specify the trusted public cert filename.
> If not specified, a test trusted public cert is used.")
> +  parser.add_argument("--monotonic-count", dest='MonotonicCountStr',
> type=str, help="specify the MonotonicCount in FMP capsule.  If not 
> specified, 0 is used.")
> +  parser.add_argument("--signature-size", dest='SignatureSizeStr', 
> + type=str,
> help="specify the signature size for decode process.")
> +  parser.add_argument("-v", "--verbose", dest='Verbose',
> action="store_true", help="increase output messages")
> +  parser.add_argument("-q", "--quiet", dest='Quiet', 
> + action="store_true",
> help="reduce output messages")
> +  parser.add_argument("--debug", dest='Debug', type=int, 
> + metavar='[0-9]',
> choices=range(0,10), default=0, help="set debug level")
> +  parser.add_argument(metavar="input_file", dest='InputFile',
> type=argparse.FileType('rb'), help="specify the input filename")
> +
> +  #
> +  # Parse command line arguments
> +  #
> +  args = parser.parse_args()
> +
> +  #
> +  # Generate file path to Open SSL command  #  OpenSslCommand = 
> + 'openssl'
> +  try:
> +    OpenSslPath = os.environ['OPENSSL_PATH']
> +    OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand)
> +  except:
> +    pass
> +
> +  #
> +  # Verify that Open SSL command is available  #
> +  try:
> +    Process = subprocess.Popen('%s version' % (OpenSslCommand),
> stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> +  except:
> +    print 'ERROR: Open SSL command not available.  Please verify PATH
> or set OPENSSL_PATH'
> +    sys.exit(1)
> +
> +  Version = Process.communicate()
> +  if Process.returncode <> 0:
> +    print 'ERROR: Open SSL command not available.  Please verify PATH
> or set OPENSSL_PATH'
> +    sys.exit(Process.returncode)
> +  print Version[0]
> +
> +  #
> +  # Read input file into a buffer and save input filename  #
> +  args.InputFileName   = args.InputFile.name
> +  args.InputFileBuffer = args.InputFile.read()
> +  args.InputFile.close()
> +
> +  #
> +  # Save output filename and check if path exists  #  OutputDir = 
> + os.path.dirname(args.OutputFile)  if not os.path.exists(OutputDir):
> +    print 'ERROR: The output path does not exist: %s' % OutputDir
> +    sys.exit(1)
> +  args.OutputFileName = args.OutputFile
> +
> +  try:
> +    if args.MonotonicCountStr.upper().startswith('0X'):
> +      args.MonotonicCountValue = (long)(args.MonotonicCountStr, 16)
> +    else:
> +      args.MonotonicCountValue = (long)(args.MonotonicCountStr)
> +  except:
> +    args.MonotonicCountValue = (long)(0)
> +
> +  if args.Encode:
> +    #
> +    # Save signer private cert filename and close private cert file
> +    #
> +    try:
> +      args.SignerPrivateCertFileName = args.SignerPrivateCertFile.name
> +      args.SignerPrivateCertFile.close()
> +    except:
> +      try:
> +        #
> +        # Get path to currently executing script or executable
> +        #
> +        if hasattr(sys, 'frozen'):
> +            Pkcs7ToolPath = sys.executable
> +        else:
> +            Pkcs7ToolPath = sys.argv[0]
> +        if Pkcs7ToolPath.startswith('"'):
> +            Pkcs7ToolPath = Pkcs7ToolPath[1:]
> +        if Pkcs7ToolPath.endswith('"'):
> +            Pkcs7ToolPath = RsaToolPath[:-1]
> +        args.SignerPrivateCertFileName =
> os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)),
> TEST_SIGNER_PRIVATE_CERT_FILENAME)
> +        args.SignerPrivateCertFile = 
> + open(args.SignerPrivateCertFileName,
> 'rb')
> +        args.SignerPrivateCertFile.close()
> +      except:
> +        print 'ERROR: test signer private cert file %s missing' %
> (args.SignerPrivateCertFileName)
> +        sys.exit(1)
> +
> +    #
> +    # Save other public cert filename and close public cert file
> +    #
> +    try:
> +      args.OtherPublicCertFileName = args.OtherPublicCertFile.name
> +      args.OtherPublicCertFile.close()
> +    except:
> +      try:
> +        #
> +        # Get path to currently executing script or executable
> +        #
> +        if hasattr(sys, 'frozen'):
> +            Pkcs7ToolPath = sys.executable
> +        else:
> +            Pkcs7ToolPath = sys.argv[0]
> +        if Pkcs7ToolPath.startswith('"'):
> +            Pkcs7ToolPath = Pkcs7ToolPath[1:]
> +        if Pkcs7ToolPath.endswith('"'):
> +            Pkcs7ToolPath = RsaToolPath[:-1]
> +        args.OtherPublicCertFileName =
> os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)),
> TEST_OTHER_PUBLIC_CERT_FILENAME)
> +        args.OtherPublicCertFile = open(args.OtherPublicCertFileName,
> 'rb')
> +        args.OtherPublicCertFile.close()
> +      except:
> +        print 'ERROR: test other public cert file %s missing' %
> (args.OtherPublicCertFileName)
> +        sys.exit(1)
> +
> +    format = "Q%ds" % len(args.InputFileBuffer)
> +    FullInputFileBuffer = 
> + struct.pack(format,args.MonotonicCountValue,
> args.InputFileBuffer)
> +
> +    #
> +    # Sign the input file using the specified private key and capture
> signature from STDOUT
> +    #
> +    Process = subprocess.Popen('%s smime -sign -binary -signer "%s"
> -outform DER -md sha256 -certfile "%s"' % (OpenSslCommand, 
> args.SignerPrivateCertFileName, args.OtherPublicCertFileName), 
> stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> +    Signature = Process.communicate(input=FullInputFileBuffer)[0]
> +    if Process.returncode <> 0:
> +      sys.exit(Process.returncode)
> +
> +    #
> +    # Write output file that contains Signature, and Input data
> +    #
> +    args.OutputFile = open(args.OutputFileName, 'wb')
> +    args.OutputFile.write(Signature)
> +    args.OutputFile.write(args.InputFileBuffer)
> +    args.OutputFile.close()
> +
> +  if args.Decode:
> +    #
> +    # Save trusted public cert filename and close public cert file
> +    #
> +    try:
> +      args.TrustedPublicCertFileName = args.TrustedPublicCertFile.name
> +      args.TrustedPublicCertFile.close()
> +    except:
> +      try:
> +        #
> +        # Get path to currently executing script or executable
> +        #
> +        if hasattr(sys, 'frozen'):
> +            Pkcs7ToolPath = sys.executable
> +        else:
> +            Pkcs7ToolPath = sys.argv[0]
> +        if Pkcs7ToolPath.startswith('"'):
> +            Pkcs7ToolPath = Pkcs7ToolPath[1:]
> +        if Pkcs7ToolPath.endswith('"'):
> +            Pkcs7ToolPath = RsaToolPath[:-1]
> +        args.TrustedPublicCertFileName =
> os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)),
> TEST_TRUSTED_PUBLIC_CERT_FILENAME)
> +        args.TrustedPublicCertFile = 
> + open(args.TrustedPublicCertFileName,
> 'rb')
> +        args.TrustedPublicCertFile.close()
> +      except:
> +        print 'ERROR: test trusted public cert file %s missing' %
> (args.TrustedPublicCertFileName)
> +        sys.exit(1)
> +
> +    if not args.SignatureSizeStr:
> +      print "ERROR: please use the option --signature-size to specify 
> + the
> size of the signature data!"
> +      sys.exit(1)
> +    else:
> +      if args.SignatureSizeStr.upper().startswith('0X'):
> +        SignatureSize = (long)(args.SignatureSizeStr, 16)
> +      else:
> +        SignatureSize = (long)(args.SignatureSizeStr)
> +    if SignatureSize < 0:
> +        print "ERROR: The value of option --signature-size can't be 
> + set to
> negative value!"
> +        sys.exit(1)
> +    elif SignatureSize > len(args.InputFileBuffer):
> +        print "ERROR: The value of option --signature-size is exceed 
> + the
> size of the input file !"
> +        sys.exit(1)
> +
> +    args.SignatureBuffer = args.InputFileBuffer[0:SignatureSize]
> +    args.InputFileBuffer = args.InputFileBuffer[SignatureSize:]
> +
> +    format = "Q%ds" % len(args.InputFileBuffer)
> +    FullInputFileBuffer = 
> + struct.pack(format,args.MonotonicCountValue,
> args.InputFileBuffer)
> +
> +    #
> +    # Save output file contents from input file
> +    #
> +    open(args.OutputFileName, 'wb').write(FullInputFileBuffer)
> +
> +    #
> +    # Verify signature
> +    #
> +    Process = subprocess.Popen('%s smime -verify -inform DER
> -content %s -CAfile %s' % (OpenSslCommand, args.OutputFileName, 
> args.TrustedPublicCertFileName), stdin=subprocess.PIPE, 
> stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> +    Process.communicate(input=args.SignatureBuffer)[0]
> +    if Process.returncode <> 0:
> +      print 'ERROR: Verification failed'
> +      os.remove (args.OutputFileName)
> +      sys.exit(Process.returncode)
> +
> +    open(args.OutputFileName, 'wb').write(args.InputFileBuffer)
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
> new file mode 100644
> index 0000000..7e10358
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pem
> @@ -0,0 +1,57 @@
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +    Microsoft CSP Name: Microsoft Strong Cryptographic Provider
> +    friendlyName: PvkTmp:133cc061-112c-467a-b8cf-dc0a56d7830e
> +Key Attributes
> +    X509v3 Key Usage: 80
> +-----BEGIN PRIVATE KEY-----
> +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCSPHYSohF
> +fim4
> +89iNx8CcCG/fPb7KLu9Dsq+pB4Pc/UJtaaA+D7RK3PhqNCrWbb+gCNgm7lxiO
> CrH
> +mm0tPal71UV8VFUiTM7Zf1y8VBFCHJ92ykmS7MDwqV25oMGGocz4jdcPl3r
> 2yFFq
> +d9jaBAPjUsHRbs8AC8CKHexOACfeydgQoj9KPWH9DUFQyXcbtMyGXAvFCktn
> SNRQ
> +f01UdNJebeD6+wlQn0sUaojn1lu570OdZ3AkJlm6bTEKvfHeOB21GaHnQ1O1
> RVtq
> +vd/KjFHhxSSw8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p1/hf+aahSy
> D
> +qYzrvv8s+RVWKg9u10JDNgVg0kupHLr98RfPiWJg8vHhXFYwtb6tlNMS9+9yvc
> zm
> +O4jzY/4zW7+qQoYKxkyq2pVn7uVOnmPNcQIHEGqBAoGBAJMfZV2vpxY6kti8
> SXzb
> +PscYI3ZbbKyJLq4+KHGcKCqqbLiY4ao8vflDyDwBm+TJg4xq9wjJAN2riE9nuuds
> +99mYW/8R30BIfiH/4oBHjggb0NC5K3vHR4KGDKcUiIKZPv1r7mNeYw227N4n
> /dPM
> +NXjlZVuS6mqc2T+GPzAJj/Uf
> +-----END PRIVATE KEY-----
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +subject=/CN=TestCert
> +issuer=/CN=TestSub
> +-----BEGIN CERTIFICATE-----
> +MIIC/TCCAemgAwIBAgIQ0+nLBVt+jbJMSfzhFpRJrDAJBgUrDgMCHQUAMBIx
> EDAO
> +BgNVBAMTB1Rlc3RTdWIwHhcNMTYwODA0MTUwMjMwWhcNMzkxMjMx
> MjM1OTU5WjAT
> +MREwDwYDVQQDEwhUZXN0Q2VydDCCASIwDQYJKoZIhvcNAQEBBQADggE
> PADCCAQoC
> +ggEBAJI8dhKiEX5+Kbjz2I3HwJwIb989vsou70Oyr6kHg9z9Qm1poD4PtErc+Go
> 0
> +KtZtv6AI2CbuXGI4KseabS09qXvVRXxUVSJMztl/XLxUEUIcn3bKSZLswPCpXbm
> g
> +wYahzPiN1w+XevbIUWp32NoEA+NSwdFuzwALwIod7E4AJ97J2BCiP0o9Yf0N
> QVDJ
> +dxu0zIZcC8UKS2dI1FB/TVR00l5t4Pr7CVCfSxRqiOfWW7nvQ51ncCQmWbpt
> MQq9
> +8d44HbUZoedDU7VFW2q938qMUeHFJLDyZ5OzKo39Ohr/zQXJQoSZMhol0R
> qr8LZc
> +ppQAJ7Oxiq9HEOr6mWKTKIim3psCAwEAAaNWMFQwDAYDVR0TAQH/BAIw
> ADBEBgNV
> +HQEEPTA7gBAeQOcW6KCBdWSbrvKQrBrfoRUwEzERMA8GA1UEAxMIVGVz
> dFJvb3SC
> +ELOMZKZtPz2BS8i5NTXdHNMwCQYFKw4DAh0FAAOCAQEAK7YgK6iiTo07d3C
> SY4xG
> +9N0QS2m4LsBPrF8pFmk5h6R81MFEdBZrA+zggbUujQ2IGB7k6F7WvP3F3B3
> AXZtx
> +DW1FYrQheQhTT5wx85LxFdLy+q6uwUtJi/VyErPmZOcds3QaBXPvG/UykFbu
> 24JV
> +K2ScLpQVyzmkTN7GWSXrIO6eHHMQgeRX3XjRutbR8CKP1pWTOY+MO4G6Y
> ZqrzLdp
> +opYFPgvdZpTL3IKSSkp31Amu5oidkvzLgallC3SOYdLZirWEIAAXW2LVYXwiiL6L
> +HEIV/G9u85jhKhv/z9l8F/1Eg4HHGSYba8pf1HQA+WsQwi4BVp4x4MBoeHOol
> yVT
> +/A==
> +-----END CERTIFICATE-----
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
> new file mode 100644
> index 0000000..f5b0cec
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestCert.pub.pem
> @@ -0,0 +1,19 @@
> +-----BEGIN CERTIFICATE-----
> +MIIC/TCCAemgAwIBAgIQ0+nLBVt+jbJMSfzhFpRJrDAJBgUrDgMCHQUAMBIx
> EDAO
> +BgNVBAMTB1Rlc3RTdWIwHhcNMTYwODA0MTUwMjMwWhcNMzkxMjMx
> MjM1OTU5WjAT
> +MREwDwYDVQQDEwhUZXN0Q2VydDCCASIwDQYJKoZIhvcNAQEBBQADggE
> PADCCAQoC
> +ggEBAJI8dhKiEX5+Kbjz2I3HwJwIb989vsou70Oyr6kHg9z9Qm1poD4PtErc+Go
> 0
> +KtZtv6AI2CbuXGI4KseabS09qXvVRXxUVSJMztl/XLxUEUIcn3bKSZLswPCpXbm
> g
> +wYahzPiN1w+XevbIUWp32NoEA+NSwdFuzwALwIod7E4AJ97J2BCiP0o9Yf0N
> QVDJ
> +dxu0zIZcC8UKS2dI1FB/TVR00l5t4Pr7CVCfSxRqiOfWW7nvQ51ncCQmWbpt
> MQq9
> +8d44HbUZoedDU7VFW2q938qMUeHFJLDyZ5OzKo39Ohr/zQXJQoSZMhol0R
> qr8LZc
> +ppQAJ7Oxiq9HEOr6mWKTKIim3psCAwEAAaNWMFQwDAYDVR0TAQH/BAIw
> ADBEBgNV
> +HQEEPTA7gBAeQOcW6KCBdWSbrvKQrBrfoRUwEzERMA8GA1UEAxMIVGVz
> dFJvb3SC
> +ELOMZKZtPz2BS8i5NTXdHNMwCQYFKw4DAh0FAAOCAQEAK7YgK6iiTo07d3C
> SY4xG
> +9N0QS2m4LsBPrF8pFmk5h6R81MFEdBZrA+zggbUujQ2IGB7k6F7WvP3F3B3
> AXZtx
> +DW1FYrQheQhTT5wx85LxFdLy+q6uwUtJi/VyErPmZOcds3QaBXPvG/UykFbu
> 24JV
> +K2ScLpQVyzmkTN7GWSXrIO6eHHMQgeRX3XjRutbR8CKP1pWTOY+MO4G6Y
> ZqrzLdp
> +opYFPgvdZpTL3IKSSkp31Amu5oidkvzLgallC3SOYdLZirWEIAAXW2LVYXwiiL6L
> +HEIV/G9u85jhKhv/z9l8F/1Eg4HHGSYba8pf1HQA+WsQwi4BVp4x4MBoeHOol
> yVT
> +/A==
> +-----END CERTIFICATE-----
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
> new file mode 100644
> index 0000000..3ca5149
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pem
> @@ -0,0 +1,56 @@
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +    Microsoft CSP Name: Microsoft Strong Cryptographic Provider
> +    friendlyName: PvkTmp:76c92422-d6f3-4763-9b80-b423fd921d00
> +Key Attributes
> +    X509v3 Key Usage: 80
> +-----BEGIN PRIVATE KEY-----
> +MIIEv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aUZr7l5OAEp+0aX0M/h6JbxTcA4CK3X
> r
> +X2TAaOCkPc1r0I79ZduKymyMNrWfXHenvFVl57klp9eFRQJ6o+pZB9ysFzPHXb
> ci
> +4VCsX6ECgYBMqAdB8M1apafxXihmDl2FoJmar+LtzCGbqvGPyn772FbGGUxe
> jqG5
> +/89iB9gbtBELbvgEvSisFsXPgOso3Ae9RN2Aro68o50QyPocIv7jFVDPPRsDp6z
> 5
> +XmVRZNIQUO6jPln+6YNLWuAsdmKkN0Z5qoD8DnvK1JZMRQ+ZM5eB6QKBg
> QCuvz+w
> +VsMyn4uj9o0PSK/gGRQGV7FX2iAwY7g98vrWix+40FlhS3MkWzTZMaXc+uyy
> V5ff
> +kmtfcwLnhljm0XHBQ9fZzcdX0y1bXAI6oElYk8vIxnG1UEnsOgyrmcCG+zcHC1f
> E
> +wxhri+TLyx9UfwNlKBOrq0KhYB00nQDUUpFpgQKBgQCPWpNeNQ8hCARnay
> hzu2fE
> +HEPG1P/resOp0u+c4jy4TeHVa9806wqZlkYNRKNn09Ub5Ajpp05dwdb+JvUSk
> Wwr
> +vOmE94WeLg5FuNzPAQjwAe+Eq54Vk8TdAhdLSu1m2xdBKFtEOk6TQTmRBCi
> knwhg
> +19TgHd8hEFnz6ZICAeWGbQ==
> +-----END PRIVATE KEY-----
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +subject=/CN=TestRoot
> +issuer=/CN=TestRoot
> +-----BEGIN CERTIFICATE-----
> +MIIC8DCCAdygAwIBAgIQNDAnfwU9lYVDoKT1DJrnyjAJBgUrDgMCHQUAMB
> MxETAP
> +BgNVBAMTCFRlc3RSb290MB4XDTE2MDgwNDE1MDE0OFoXDTM5MTIzMTI
> zNTk1OVow
> +EzERMA8GA1UEAxMIVGVzdFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBD
> wAwggEK
> +AoIBAQCU5jNPVsMHoNCZV8PhVkIBcFkcL0pmjzSek7227JKkkFFdxo+1w4YV3
> 2CA
> +vrh4WVub/SeSaczKjj6egUdbhO9cm7NKQ1uNCzEEALaKwKn1IdA/zbBnfVAzLv
> sb
> +LBYu7lYBh/bI1FMHZ5kLRr8dkMbbf21iDEqsqKI8eQ+tj/7B6OUnPfmmmh3sml
> 9i
> +US6YHSm6a4r7Qw5oKfW+Z0hEKEX+HTtQcmrAuwyfAmGtY6eH9jKfPhZc7sw
> FvRfo
> +RlKvUIqmfhZpg2lbbk3Hz4C4zfZmP75soOicJmC6qQXdcUq9AKgM91CrRNY+h
> yE8
> +LeYzJ14hJ7ncOEjWOpbhF0dlZc49AgMBAAGjSDBGMEQGA1UdAQQ9MDuAE
> M61es/l
> +Icdr8+yS1L9lKjWhFTATMREwDwYDVQQDEwhUZXN0Um9vdIIQNDAnfwU9lY
> VDoKT1
> +DJrnyjAJBgUrDgMCHQUAA4IBAQBrDeAK0O5bP7ZzSGLo9Fvh7dkAxeUOaPtT
> MzBq
> +YLruOFtRY3DVfgX+5EUqFWIb/Nh1k1b25gaFIfcIRya5/gVOkCJU9DkJTFyOzX
> w7
> +r0stGAb0XCQqZPdZdSiXqZAsukYCamRmSTLLXTT+JOREsMKtFxsFfdNYiC6+Dt
> cr
> +yly/KCU92Ls8OFLmJ/rSuEVrX39LsCMF6K9n6OJsL5/4c3/DF7yyalsq82vT3H/f
> +L9CrBgz+A+eNguyEPch97ctqWzVIVQf7qngaAbuYRYvaiuMhV4YVIxdQG5y8G
> lmo
> +Kq06fgEkg/ewYea9T9mRkKcquQw7q5UgHPB0zgK6FF3xkSVK
> +-----END CERTIFICATE-----
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
> new file mode 100644
> index 0000000..14b6418
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestRoot.pub.pem
> @@ -0,0 +1,18 @@
> +-----BEGIN CERTIFICATE-----
> +MIIC8DCCAdygAwIBAgIQNDAnfwU9lYVDoKT1D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TIFICATE-----
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
> new file mode 100644
> index 0000000..67f9d25
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pem
> @@ -0,0 +1,57 @@
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +    Microsoft CSP Name: Microsoft Strong Cryptographic Provider
> +    friendlyName: PvkTmp:11e8b08d-46fb-45a2-90c4-d458be4a1276
> +Key Attributes
> +    X509v3 Key Usage: 80
> +-----BEGIN PRIVATE KEY-----
> +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCfNn3oUo5
> iCBXg
> +x1AUxgHG/h23/WyThgYj2NAToG3S51i0MGamyjGP8GbBphRc0ORpIhQE8Va
> +NPjW
> +cdoh4sXLOroW3Es26sR+cxdRwNF0/YxK/+JboYDmdUecgcwqipIv795bVQjRL
> CyT
> +/+LjLXs/B3XM/jc4jHa7gs+AmwH2DXz9VTsIHmXrm/KGZ64VQzFbJYJl+KvFAml
> m
> +LcL+t099lyiJYL+3LY2ajonzkAidVQylIfsmhAlcnGee6MYfPxLQRe4pIIlhyXAK
> +ZixBnAlZvifo3JRwTKXRHzkj6Vp5KhDsi/31Y54iLJQHiet/FlymIHrtkFpC47xi
> +ndF6jNpfAgMBAAECggEAD4owC9xS+A/gosnmxRWhLXJhet3fb8llvAX4zpGau
> +Uc
> +wVRKu1OCNucOAISx+W/iJhN6GhQRlWByO+wXkGB5UcwaRwpFb8dxBQPo
> GMYAgQdm
> +XsOkV7E8dZdTirEYjmZsElsP5vY2dW7MWGhiFYO7mHv6ltbmk5G83Qci3biYyR
> KB
> +4Qb+q/1yl9tdqRvMnLshgSNSa2onGiJ8k9NniSnfnKCc4S0pliy2Z5HOPQCi2QA
> k
> +eVWORHz5jL8lzlVCflOL7VZiS13YORMDIj0S9LyMhXO4bAtsgWfldqOupNgNW
> 0qI
> +FwzrNvIXhQxeUiqylzfKNCzuBA11CFBnPt/+agv10QKBgQDH82PHMC3GH8Te
> q0lw
> +J5G+zYQol1ikRU7O116cAcV04P8HAiAmZ2lrP4DSJWD3y3sOjnnK54KmXkHVc
> NJI
> +IDjb8d/BZjuYqdylfKhoKNgAdI1WcNKOz7KOK6Le8/ZK1uh1ZHMA6M+L9mTtQ
> jhW
> +DyoMvEGsQmNHnYF5n3zPQWUMFQKBgQDL17jZMLOORK2U+Iqu0cTVttGU
> jg/agP+r
> +D4RWwA6BKI0vW3fFOka9MsjBpRZkZdXucq1TusDl8/J30FD/Cjp/gt9RwCQAv
> k44
> +Zp6HU3TFEsBdXU+3XeJqTtyJqFuPkRQWrd0UeudSiEJammAlzyF7pPZioF1muc
> OA
> +nCcDecLFowKBgBv1gKI9rmjh0FmCggZYwhx4CF7UquRtfJOXsfcGmGG7hG2q
> cmxs
> +UWVZv92itGhx34ctjQI+VRqGW5ZI7F6BgvHeZHdaoEK8ncnWIIZQD8QgiBLq
> O8cU
> +a9dNarzaSDo2ytJ/dUVPSJY9oec7Nz1xaWPWfyhjMBa3g39KOd2RO1vxAoGB
> AMRD
> +Q9r6JSeJwId6diy0FAyhJVEfJux+36tYGVddO5nn7Wf3bW4cGhf4WYr45IJt+njH
> +OVMwsKG3K3FoxVOKCaDT5SjVEtUUZkOvqlspY3iMAWLjgOlQH7uzimuQCfh
> E+06K
> +wB4D581zHFAX6xL8R4TA4+k59jP+D9o4fue9yGZ5AoGAMn+TsY1IZFSY1fw6T
> THq
> +sp9PiYQQqTMjRkzE7GRXbb1rdE6WoLkSk4Dz4u/B9E7YVzTZggYhPisChu6wZP
> tK
> +IiXBGu8h3GygUGI/WdNRKHW5nst9IZWrtVJ06c87jWqOktbgBnrbqXUG1rgRZ
> r+i
> +n3sJLF+GGwzdp/gCxLMH66M=
> +-----END PRIVATE KEY-----
> +Bag Attributes
> +    localKeyID: 01 00 00 00
> +subject=/CN=TestSub
> +issuer=/CN=TestRoot
> +-----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3mBIYJT0WDofYzas2TQO8cBiQHGrSqXNFAfI5eUo3qLtsRE+7Z9
> F2Mw
> +HgNmsA==
> +-----END CERTIFICATE-----
> diff --git a/BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem
> b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem
> new file mode 100644
> index 0000000..a12d837
> --- /dev/null
> +++ b/BaseTools/Source/Python/Pkcs7Sign/TestSub.pub.pem
> @@ -0,0 +1,19 @@
> +-----BEGIN CERTIFICATE-----
> +MIIDADCCAeygAwIBAgIQs4xkpm0/PYFLyLk1Nd0c0zAJBgUrDgMCHQUAMB
> MxETAP
> +BgNVBAMTCFRlc3RSb290MB4XDTE2MDgwNDE1MDIwOVoXDTM5MTIzMTI
> zNTk1OVow
> +EjEQMA4GA1UEAxMHVGVzdFN1YjCCASIwDQYJKoZIhvcNAQEBBQADggEPA
> DCCAQoC
> +ggEBAJ82fehSjmIIFeDHUBTGAcb+Hbf9bJOGBiPY0BOgbdLnWLQwZqbKMY/
> wZsGm
> +FFzQ5GkiFATxVr40+NZx2iHixcs6uhbcSzbqxH5zF1HA0XT9jEr/4luhgOZ1R5yB
> +zCqKki/v3ltVCNEsLJP/4uMtez8Hdcz+NziMdruCz4CbAfYNfP1VOwgeZeub8oZ
> n
> +rhVDMVslgmX4q8UCaWYtwv63T32XKIlgv7ctjZqOifOQCJ1VDKUh+yaECVycZ
> 57o
> +xh8/EtBF7ikgiWHJcApmLEGcCVm+J+jclHBMpdEfOSPpWnkqEOyL/fVjniIslAeJ
> +638WXKYgeu2QWkLjvGKd0XqM2l8CAwEAAaNZMFcwDwYDVR0TAQH/BAU
> wAwEB/zBE
> +BgNVHQEEPTA7gBDOtXrP5SHHa/PsktS/ZSo1oRUwEzERMA8GA1UEAxMIVG
> VzdFJv
> +b3SCEDQwJ38FPZWFQ6Ck9Qya58owCQYFKw4DAh0FAAOCAQEAFT8uXdMS
> HCmatVNg
> +LMKsyVA/jJgXGncHmAy59Vjo2+KCIooEuY3NaK527LxB1yi9+UyMe2+Ia4KWc
> EGY
> ++mb+PDTDrlsYtjIU3aRzDpyXUrkYV/D6vZaw+zsgAquQkCi+WwEYZ4uCSUznlc
> yt
> +U3p2Rd/+tvQqq5UerPfRBIs6JTUerwRGUQurTNpzqCGClo3zi58yuOEbNIrOz
> W1D
> +MtQFKUtKkMx4rg6NT9kq/ICXt8k3UIsXh52NTYchkLlsnCgaoKzW2DFqSMFL3
> KC0
> +NmQtmKaPo3mBIYJT0WDofYzas2TQO8cBiQHGrSqXNFAfI5eUo3qLtsRE+7Z9
> F2Mw
> +HgNmsA==
> +-----END CERTIFICATE-----
> --
> 2.6.1.windows.1



^ permalink raw reply	[flat|nested] 8+ messages in thread

* Re: [Patch 3/3] BaseTools: FMP capsule add the support to generate auth info
  2016-08-15  8:17 ` [Patch 3/3] BaseTools: FMP capsule add the support to generate auth info Yonghong Zhu
@ 2016-08-19  5:41   ` Gao, Liming
  0 siblings, 0 replies; 8+ messages in thread
From: Gao, Liming @ 2016-08-19  5:41 UTC (permalink / raw)
  To: Zhu, Yonghong, edk2-devel@lists.01.org

Reviewed-by: Liming Gao <liming.gao@intel.com>

> -----Original Message-----
> From: Zhu, Yonghong
> Sent: Monday, August 15, 2016 4:18 PM
> To: edk2-devel@lists.01.org
> Cc: Gao, Liming <liming.gao@intel.com>
> Subject: [Patch 3/3] BaseTools: FMP capsule add the support to generate
> auth info
> 
> Current BaseTools cannot generate
> EFI_FIRMWARE_IMAGE_AUTHENTICATION
> for FMP capsule. this patch fix it by FDF spec's update to add the
> definition for CERTIFICATE_GUID and  MONOTONIC_COUNT. BaseTools call
> the tool by CERTIFICATE_GUID to generate the certdata and fill the header
> info.
> 
> Cc: Liming Gao <liming.gao@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Yonghong Zhu <yonghong.zhu@intel.com>
> ---
>  BaseTools/Source/Python/GenFds/Capsule.py     | 80
> +++++++++++++++++++++++++--
>  BaseTools/Source/Python/GenFds/CapsuleData.py |  4 +-
>  BaseTools/Source/Python/GenFds/FdfParser.py   | 64
> ++++++++++++++++++---
>  BaseTools/Source/Python/GenFds/GenFds.py      | 59
> +++++++++++++++++++-
>  BaseTools/Source/Python/GenFds/GuidSection.py | 59 +-------------------
>  5 files changed, 194 insertions(+), 72 deletions(-)
> 
> diff --git a/BaseTools/Source/Python/GenFds/Capsule.py
> b/BaseTools/Source/Python/GenFds/Capsule.py
> index 1683433..f8af12a 100644
> --- a/BaseTools/Source/Python/GenFds/Capsule.py
> +++ b/BaseTools/Source/Python/GenFds/Capsule.py
> @@ -1,9 +1,9 @@
>  ## @file
>  # generate capsule
>  #
> -#  Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR>
> +#  Copyright (c) 2007 - 2016, 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
>  #  http://opensource.org/licenses/bsd-license.php
> @@ -23,13 +23,20 @@ import StringIO
>  from Common.Misc import SaveFileOnChange
>  from GenFds import GenFds
>  from Common.Misc import PackRegistryFormatGuid
>  import uuid
>  from struct import pack
> +from GenFds import FindExtendTool
> +from Common import EdkLogger
> +from Common.BuildToolError import *
> 
> 
>  T_CHAR_LF = '\n'
> +WIN_CERT_REVISION      = 0x0200
> +WIN_CERT_TYPE_EFI_GUID = 0x0EF1
> +EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-
> 347d375665a7}')
> +EFI_CERT_TYPE_RSA2048_SHA256_GUID = uuid.UUID('{a7717414-c616-
> 4977-9420-844712a735bf}')
> 
>  ## create inf file describes what goes into capsule and call GenFv to
> generate capsule
>  #
>  #
>  class Capsule (CapsuleClassObject) :
> @@ -96,24 +103,87 @@ class Capsule (CapsuleClassObject) :
>          else:
>              FwMgrHdr.write(pack('=I', 0x00000001))
>          FwMgrHdr.write(pack('=HH', len(self.CapsuleDataList),
> len(self.FmpPayloadList)))
>          FwMgrHdrSize =
> 4+2+2+8*(len(self.CapsuleDataList)+len(self.FmpPayloadList))
> 
> +        #
> +        # typedef struct _WIN_CERTIFICATE {
> +        #   UINT32 dwLength;
> +        #   UINT16 wRevision;
> +        #   UINT16 wCertificateType;
> +        # //UINT8 bCertificate[ANYSIZE_ARRAY];
> +        # } WIN_CERTIFICATE;
> +        #
> +        # typedef struct _WIN_CERTIFICATE_UEFI_GUID {
> +        #   WIN_CERTIFICATE Hdr;
> +        #   EFI_GUID        CertType;
> +        # //UINT8 CertData[ANYSIZE_ARRAY];
> +        # } WIN_CERTIFICATE_UEFI_GUID;
> +        #
> +        # typedef struct {
> +        #   UINT64                    MonotonicCount;
> +        #   WIN_CERTIFICATE_UEFI_GUID AuthInfo;
> +        # } EFI_FIRMWARE_IMAGE_AUTHENTICATION;
> +        #
> +        # typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 {
> +        #   EFI_GUID HashType;
> +        #   UINT8 PublicKey[256];
> +        #   UINT8 Signature[256];
> +        # } EFI_CERT_BLOCK_RSA_2048_SHA256;
> +        #
> +
>          PreSize = FwMgrHdrSize
>          Content = StringIO.StringIO()
>          for driver in self.CapsuleDataList:
>              FileName = driver.GenCapsuleSubItem()
>              FwMgrHdr.write(pack('=Q', PreSize))
>              PreSize += os.path.getsize(FileName)
>              File = open(FileName, 'rb')
>              Content.write(File.read())
>              File.close()
>          for fmp in self.FmpPayloadList:
> -            payload = fmp.GenCapsuleSubItem()
> -            FwMgrHdr.write(pack('=Q', PreSize))
> -            PreSize += len(payload)
> -            Content.write(payload)
> +            if fmp.Certificate_Guid:
> +                ExternalTool, ExternalOption = FindExtendTool([],
> GenFdsGlobalVariable.ArchList, fmp.Certificate_Guid)
> +                CmdOption = ''
> +                CapInputFile = fmp.ImageFile
> +                if not os.path.isabs(fmp.ImageFile):
> +                    CapInputFile = os.path.join(GenFdsGlobalVariable.WorkSpaceDir,
> fmp.ImageFile)
> +                CapOutputTmp = os.path.join(GenFdsGlobalVariable.FvDir,
> self.UiCapsuleName) + '.tmp'
> +                if ExternalTool == None:
> +                    EdkLogger.error("GenFds", GENFDS_ERROR, "No tool found with
> GUID %s" % fmp.Certificate_Guid)
> +                else:
> +                    CmdOption += ExternalTool
> +                if ExternalOption:
> +                    CmdOption = CmdOption + ' ' + ExternalOption
> +                CmdOption += ' -e ' + ' --monotonic-count ' +
> str(fmp.MonotonicCount) + ' -o ' + CapOutputTmp + ' ' + CapInputFile
> +                CmdList = CmdOption.split()
> +                GenFdsGlobalVariable.CallExternalTool(CmdList, "Failed to generate
> FMP auth capsule")
> +                if uuid.UUID(fmp.Certificate_Guid) ==
> EFI_CERT_TYPE_PKCS7_GUID:
> +                    dwLength = 4 + 2 + 2 + 16 + os.path.getsize(CapOutputTmp) -
> os.path.getsize(CapInputFile)
> +                else:
> +                    dwLength = 4 + 2 + 2 + 16 + 16 + 256 + 256
> +                Buffer  = pack('Q', fmp.MonotonicCount)
> +                Buffer += pack('I', dwLength)
> +                Buffer += pack('H', WIN_CERT_REVISION)
> +                Buffer += pack('H', WIN_CERT_TYPE_EFI_GUID)
> +                Buffer += uuid.UUID(fmp.Certificate_Guid).get_bytes_le()
> +                if os.path.exists(CapOutputTmp):
> +                    TmpFile = open(CapOutputTmp, 'rb')
> +                    Buffer += TmpFile.read()
> +                    TmpFile.close()
> +                    if fmp.VendorCodeFile:
> +                        VendorFile = open(fmp.VendorCodeFile, 'rb')
> +                        Buffer += VendorFile.read()
> +                        VendorFile.close()
> +                    FwMgrHdr.write(pack('=Q', PreSize))
> +                    PreSize += len(Buffer)
> +                    Content.write(Buffer)
> +            else:
> +                payload = fmp.GenCapsuleSubItem()
> +                FwMgrHdr.write(pack('=Q', PreSize))
> +                PreSize += len(payload)
> +                Content.write(payload)
>          BodySize = len(FwMgrHdr.getvalue()) + len(Content.getvalue())
>          Header.write(pack('=I', HdrSize + BodySize))
>          #
>          # The real capsule header structure is 28 bytes
>          #
> diff --git a/BaseTools/Source/Python/GenFds/CapsuleData.py
> b/BaseTools/Source/Python/GenFds/CapsuleData.py
> index efc2812..2a5c454 100644
> --- a/BaseTools/Source/Python/GenFds/CapsuleData.py
> +++ b/BaseTools/Source/Python/GenFds/CapsuleData.py
> @@ -1,9 +1,9 @@
>  ## @file
>  # generate capsule
>  #
> -#  Copyright (c) 2007-2013, Intel Corporation. All rights reserved.<BR>
> +#  Copyright (c) 2007-2016, 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
>  #  http://opensource.org/licenses/bsd-license.php
> @@ -178,10 +178,12 @@ class CapsulePayload(CapsuleData):
>          self.ImageTypeId = None
>          self.ImageIndex = None
>          self.HardwareInstance = None
>          self.ImageFile = None
>          self.VendorCodeFile = None
> +        self.Certificate_Guid = None
> +        self.MonotonicCount = None
> 
>      def GenCapsuleSubItem(self):
>          if not self.Version:
>              self.Version = 0x00000002
>          ImageFileSize = os.path.getsize(self.ImageFile)
> diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py
> b/BaseTools/Source/Python/GenFds/FdfParser.py
> index 8709cfc..02ae7c9 100644
> --- a/BaseTools/Source/Python/GenFds/FdfParser.py
> +++ b/BaseTools/Source/Python/GenFds/FdfParser.py
> @@ -50,15 +50,17 @@ from Common.Misc import PathClass
>  from Common.String import NormPath
>  import Common.GlobalData as GlobalData
>  from Common.Expression import *
>  from Common import GlobalData
>  from Common.String import ReplaceMacro
> -
> +import uuid
>  from Common.Misc import tdict
> 
>  import Common.LongFilePathOs as os
>  from Common.LongFilePathSupport import OpenLongFilePath as open
> +from Capsule import EFI_CERT_TYPE_PKCS7_GUID
> +from Capsule import EFI_CERT_TYPE_RSA2048_SHA256_GUID
> 
>  ##define T_CHAR_SPACE                ' '
>  ##define T_CHAR_NULL                 '\0'
>  ##define T_CHAR_CR                   '\r'
>  ##define T_CHAR_TAB                  '\t'
> @@ -1122,10 +1124,30 @@ class FdfParser:
>              return True
>          else:
>              self.__UndoToken()
>              return False
> 
> +    def __Verify(self, Name, Value, Scope):
> +        if Scope in ['UINT64', 'UINT8']:
> +            ValueNumber = 0
> +            try:
> +                if Value.upper().startswith('0X'):
> +                    ValueNumber = int (Value, 16)
> +                else:
> +                    ValueNumber = int (Value)
> +            except:
> +                EdkLogger.error("FdfParser", FORMAT_INVALID, "The value is not
> valid dec or hex number for %s." % Name)
> +            if ValueNumber < 0:
> +                EdkLogger.error("FdfParser", FORMAT_INVALID, "The value can't
> be set to negative value for %s." % Name)
> +            if Scope == 'UINT64':
> +                if ValueNumber >= 0x10000000000000000:
> +                    EdkLogger.error("FdfParser", FORMAT_INVALID, "Too large value
> for %s." % Name)
> +            if Scope == 'UINT8':
> +                if ValueNumber >= 0x100:
> +                    EdkLogger.error("FdfParser", FORMAT_INVALID, "Too large value
> for %s." % Name)
> +            return True
> +
>      ## __UndoToken() method
>      #
>      #   Go back one token unit in file buffer
>      #
>      #   @param  self        The object pointer
> @@ -3185,44 +3207,70 @@ class FdfParser:
>          if not self.__IsToken( "]"):
>              raise Warning("expected ']'", self.FileName, self.CurrentLineNumber)
> 
>          if not self.__GetNextToken():
>              raise Warning("The FMP payload section is empty!", self.FileName,
> self.CurrentLineNumber)
> -        FmpKeyList = ['IMAGE_HEADER_INIT_VERSION', 'IMAGE_TYPE_ID',
> 'IMAGE_INDEX', 'HARDWARE_INSTANCE']
> +        FmpKeyList = ['IMAGE_HEADER_INIT_VERSION', 'IMAGE_TYPE_ID',
> 'IMAGE_INDEX', 'HARDWARE_INSTANCE', 'CERTIFICATE_GUID',
> 'MONOTONIC_COUNT']
>          while self.__Token in FmpKeyList:
>              Name = self.__Token
>              FmpKeyList.remove(Name)
>              if not self.__IsToken("="):
>                  raise Warning("expected '='", self.FileName,
> self.CurrentLineNumber)
>              if Name == 'IMAGE_TYPE_ID':
>                  if not self.__GetNextGuid():
> -                    raise Warning("expected GUID value for IMAGE_TYPE_ID",
> self.FileName, self.CurrentLineNumber)
> +                    raise Warning("expected GUID value for IMAGE_TYPE_ID.",
> self.FileName, self.CurrentLineNumber)
>                  FmpData.ImageTypeId = self.__Token
> +            elif Name == 'CERTIFICATE_GUID':
> +                if not self.__GetNextGuid():
> +                    raise Warning("expected GUID value for CERTIFICATE_GUID.",
> self.FileName, self.CurrentLineNumber)
> +                FmpData.Certificate_Guid = self.__Token
> +                if uuid.UUID(FmpData.Certificate_Guid) !=
> EFI_CERT_TYPE_RSA2048_SHA256_GUID and
> uuid.UUID(FmpData.Certificate_Guid) != EFI_CERT_TYPE_PKCS7_GUID:
> +                    raise Warning("Only support
> EFI_CERT_TYPE_RSA2048_SHA256_GUID or EFI_CERT_TYPE_PKCS7_GUID for
> CERTIFICATE_GUID.", self.FileName, self.CurrentLineNumber)
>              else:
>                  if not self.__GetNextToken():
>                      raise Warning("expected value of %s" % Name, self.FileName,
> self.CurrentLineNumber)
>                  Value = self.__Token
>                  if Name == 'IMAGE_HEADER_INIT_VERSION':
> -                    FmpData.Version = Value
> +                    if self.__Verify(Name, Value, 'UINT8'):
> +                        FmpData.Version = Value
>                  elif Name == 'IMAGE_INDEX':
> -                    FmpData.ImageIndex = Value
> +                    if self.__Verify(Name, Value, 'UINT8'):
> +                        FmpData.ImageIndex = Value
>                  elif Name == 'HARDWARE_INSTANCE':
> -                    FmpData.HardwareInstance = Value
> +                    if self.__Verify(Name, Value, 'UINT8'):
> +                        FmpData.HardwareInstance = Value
> +                elif Name == 'MONOTONIC_COUNT':
> +                    if self.__Verify(Name, Value, 'UINT64'):
> +                        FmpData.MonotonicCount = Value
> +                        if FmpData.MonotonicCount.upper().startswith('0X'):
> +                            FmpData.MonotonicCount =
> (long)(FmpData.MonotonicCount, 16)
> +                        else:
> +                            FmpData.MonotonicCount =
> (long)(FmpData.MonotonicCount)
>              if not self.__GetNextToken():
>                  break
>          else:
>              self.__UndoToken()
> 
> +        if (FmpData.MonotonicCount and not FmpData.Certificate_Guid) or
> (not FmpData.MonotonicCount and FmpData.Certificate_Guid):
> +            EdkLogger.error("FdfParser", FORMAT_INVALID, "CERTIFICATE_GUID
> and MONOTONIC_COUNT must be work as a pair.")
> +        # remove CERTIFICATE_GUID and MONOTONIC_COUNT from
> FmpKeyList, since these keys are optional
> +        if 'CERTIFICATE_GUID' in FmpKeyList:
> +            FmpKeyList.remove('CERTIFICATE_GUID')
> +        if 'MONOTONIC_COUNT' in FmpKeyList:
> +            FmpKeyList.remove('MONOTONIC_COUNT')
>          if FmpKeyList:
> -            raise Warning("Missing keywords %s in FMP payload section" % ',
> '.join(FmpKeyList), self.FileName, self.CurrentLineNumber)
> +            raise Warning("Missing keywords %s in FMP payload section." % ',
> '.join(FmpKeyList), self.FileName, self.CurrentLineNumber)
>          ImageFile = self.__ParseRawFileStatement()
>          if not ImageFile:
> -            raise Warning("Missing image file in FMP payload section",
> self.FileName, self.CurrentLineNumber)
> +            raise Warning("Missing image file in FMP payload section.",
> self.FileName, self.CurrentLineNumber)
>          FmpData.ImageFile = ImageFile
>          VendorCodeFile = self.__ParseRawFileStatement()
>          if VendorCodeFile:
>              FmpData.VendorCodeFile = VendorCodeFile
> +        AdditionalFile = self.__ParseRawFileStatement()
> +        if AdditionalFile:
> +            raise Warning("At most one Image file and one Vendor code file are
> allowed in FMP payload section.", self.FileName, self.CurrentLineNumber)
>          self.Profile.FmpPayloadDict[FmpUiName] = FmpData
>          return True
> 
>      ## __GetCapsule() method
>      #
> diff --git a/BaseTools/Source/Python/GenFds/GenFds.py
> b/BaseTools/Source/Python/GenFds/GenFds.py
> index 68232c5..1a0ec7a 100644
> --- a/BaseTools/Source/Python/GenFds/GenFds.py
> +++ b/BaseTools/Source/Python/GenFds/GenFds.py
> @@ -410,11 +410,68 @@ def
> BuildOptionPcdValueFormat(TokenSpaceGuidCName, TokenCName,
> PcdDatumType, Val
>              Value = '1'
>          elif Value == 'FALSE' or Value == '0':
>              Value = '0'
>      return  Value
> 
> -
> +## FindExtendTool()
> +#
> +#  Find location of tools to process data
> +#
> +#  @param  KeyStringList    Filter for inputs of section generation
> +#  @param  CurrentArchList  Arch list
> +#  @param  NameGuid         The Guid name
> +#
> +def FindExtendTool(KeyStringList, CurrentArchList, NameGuid):
> +    # if user not specify filter, try to deduce it from global data.
> +    if KeyStringList == None or KeyStringList == []:
> +        Target = GenFdsGlobalVariable.TargetName
> +        ToolChain = GenFdsGlobalVariable.ToolChainTag
> +        ToolDb =
> ToolDefClassObject.ToolDefDict(GenFdsGlobalVariable.ConfDir).ToolsDefTxt
> Database
> +        if ToolChain not in ToolDb['TOOL_CHAIN_TAG']:
> +            EdkLogger.error("GenFds", GENFDS_ERROR, "Can not find external
> tool because tool tag %s is not defined in tools_def.txt!" % ToolChain)
> +        KeyStringList = [Target + '_' + ToolChain + '_' + CurrentArchList[0]]
> +        for Arch in CurrentArchList:
> +            if Target + '_' + ToolChain + '_' + Arch not in KeyStringList:
> +                KeyStringList.append(Target + '_' + ToolChain + '_' + Arch)
> +
> +    if GenFdsGlobalVariable.GuidToolDefinition:
> +        if NameGuid in GenFdsGlobalVariable.GuidToolDefinition.keys():
> +            return GenFdsGlobalVariable.GuidToolDefinition[NameGuid]
> +
> +    ToolDefinition =
> ToolDefClassObject.ToolDefDict(GenFdsGlobalVariable.ConfDir).ToolsDefTxt
> Dictionary
> +    ToolPathTmp = None
> +    ToolOption = None
> +    for ToolDef in ToolDefinition.items():
> +        if NameGuid == ToolDef[1]:
> +            KeyList = ToolDef[0].split('_')
> +            Key = KeyList[0] + \
> +                  '_' + \
> +                  KeyList[1] + \
> +                  '_' + \
> +                  KeyList[2]
> +            if Key in KeyStringList and KeyList[4] == 'GUID':
> +
> +                ToolPath = ToolDefinition.get(Key + \
> +                                               '_' + \
> +                                               KeyList[3] + \
> +                                               '_' + \
> +                                               'PATH')
> +
> +                ToolOption = ToolDefinition.get(Key + \
> +                                                '_' + \
> +                                                KeyList[3] + \
> +                                                '_' + \
> +                                                'FLAGS')
> +                if ToolPathTmp == None:
> +                    ToolPathTmp = ToolPath
> +                else:
> +                    if ToolPathTmp != ToolPath:
> +                        EdkLogger.error("GenFds", GENFDS_ERROR, "Don't know which
> tool to use, %s or %s ?" % (ToolPathTmp, ToolPath))
> +
> +    GenFdsGlobalVariable.GuidToolDefinition[NameGuid] = (ToolPathTmp,
> ToolOption)
> +    return ToolPathTmp, ToolOption
> +
>  ## Parse command line options
>  #
>  # Using standard Python module optparse to parse command line option of
> this tool.
>  #
>  #   @retval Opt   A optparse.Values object containing the parsed options
> diff --git a/BaseTools/Source/Python/GenFds/GuidSection.py
> b/BaseTools/Source/Python/GenFds/GuidSection.py
> index ac5ae58..f199dcd 100644
> --- a/BaseTools/Source/Python/GenFds/GuidSection.py
> +++ b/BaseTools/Source/Python/GenFds/GuidSection.py
> @@ -25,10 +25,11 @@ from Common import ToolDefClassObject
>  import sys
>  from Common import EdkLogger
>  from Common.BuildToolError import *
>  from FvImageSection import FvImageSection
>  from Common.LongFilePathSupport import OpenLongFilePath as open
> +from GenFds import FindExtendTool
> 
>  ## generate GUIDed section
>  #
>  #
>  class GuidSection(GuidSectionClassObject) :
> @@ -126,11 +127,11 @@ class GuidSection(GuidSectionClassObject) :
>          OutputFile = os.path.normpath(OutputFile)
> 
>          ExternalTool = None
>          ExternalOption = None
>          if self.NameGuid != None:
> -            ExternalTool, ExternalOption = self.__FindExtendTool__()
> +            ExternalTool, ExternalOption = FindExtendTool(self.KeyStringList,
> self.CurrentArchList, self.NameGuid)
> 
>          #
>          # If not have GUID , call default
>          # GENCRC32 section
>          #
> @@ -247,63 +248,7 @@ class GuidSection(GuidSectionClassObject) :
>                  self.Alignment = None
>                  self.IncludeFvSection = False
>                  self.ProcessRequired = "TRUE"
>              return OutputFileList, self.Alignment
> 
> -    ## __FindExtendTool()
> -    #
> -    #    Find location of tools to process section data
> -    #
> -    #   @param  self        The object pointer
> -    #
> -    def __FindExtendTool__(self):
> -        # if user not specify filter, try to deduce it from global data.
> -        if self.KeyStringList == None or self.KeyStringList == []:
> -            Target = GenFdsGlobalVariable.TargetName
> -            ToolChain = GenFdsGlobalVariable.ToolChainTag
> -            ToolDb =
> ToolDefClassObject.ToolDefDict(GenFdsGlobalVariable.ConfDir).ToolsDefTxt
> Database
> -            if ToolChain not in ToolDb['TOOL_CHAIN_TAG']:
> -                EdkLogger.error("GenFds", GENFDS_ERROR, "Can not find external
> tool because tool tag %s is not defined in tools_def.txt!" % ToolChain)
> -            self.KeyStringList = [Target + '_' + ToolChain + '_' +
> self.CurrentArchList[0]]
> -            for Arch in self.CurrentArchList:
> -                if Target + '_' + ToolChain + '_' + Arch not in self.KeyStringList:
> -                    self.KeyStringList.append(Target + '_' + ToolChain + '_' + Arch)
> -
> -        if GenFdsGlobalVariable.GuidToolDefinition:
> -            if self.NameGuid in GenFdsGlobalVariable.GuidToolDefinition.keys():
> -                return GenFdsGlobalVariable.GuidToolDefinition[self.NameGuid]
> -
> -        ToolDefinition =
> ToolDefClassObject.ToolDefDict(GenFdsGlobalVariable.ConfDir).ToolsDefTxt
> Dictionary
> -        ToolPathTmp = None
> -        ToolOption = None
> -        for ToolDef in ToolDefinition.items():
> -            if self.NameGuid == ToolDef[1]:
> -                KeyList = ToolDef[0].split('_')
> -                Key = KeyList[0] + \
> -                      '_' + \
> -                      KeyList[1] + \
> -                      '_' + \
> -                      KeyList[2]
> -                if Key in self.KeyStringList and KeyList[4] == 'GUID':
> -
> -                    ToolPath = ToolDefinition.get(Key + \
> -                                                   '_' + \
> -                                                   KeyList[3] + \
> -                                                   '_' + \
> -                                                   'PATH')
> -
> -                    ToolOption = ToolDefinition.get(Key + \
> -                                                    '_' + \
> -                                                    KeyList[3] + \
> -                                                    '_' + \
> -                                                    'FLAGS')
> -                    if ToolPathTmp == None:
> -                        ToolPathTmp = ToolPath
> -                    else:
> -                        if ToolPathTmp != ToolPath:
> -                            EdkLogger.error("GenFds", GENFDS_ERROR, "Don't know
> which tool to use, %s or %s ?" % (ToolPathTmp, ToolPath))
> -
> -        GenFdsGlobalVariable.GuidToolDefinition[self.NameGuid] =
> (ToolPathTmp, ToolOption)
> -        return ToolPathTmp, ToolOption
> -
> 
> 
> --
> 2.6.1.windows.1



^ permalink raw reply	[flat|nested] 8+ messages in thread

* Re: [Patch 2/3] BaseTools: Rsa2048Sha256Sign add new option to support Monotonic count
  2016-08-15  8:17 ` [Patch 2/3] BaseTools: Rsa2048Sha256Sign add new option to support Monotonic count Yonghong Zhu
@ 2016-08-19  5:41   ` Gao, Liming
  0 siblings, 0 replies; 8+ messages in thread
From: Gao, Liming @ 2016-08-19  5:41 UTC (permalink / raw)
  To: Zhu, Yonghong, edk2-devel@lists.01.org

Reviewed-by: Liming Gao <liming.gao@intel.com>

> -----Original Message-----
> From: Zhu, Yonghong
> Sent: Monday, August 15, 2016 4:18 PM
> To: edk2-devel@lists.01.org
> Cc: Gao, Liming <liming.gao@intel.com>
> Subject: [Patch 2/3] BaseTools: Rsa2048Sha256Sign add new option to
> support Monotonic count
> 
> the EFI_FIRMWARE_IMAGE_AUTHENTICATION struct require the AuthInfo
> which
> is a signature across the image data and the Monotonic Count value, so we
> add the new option to support Monotonic count.
> 
> Cc: Liming Gao <liming.gao@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Yonghong Zhu <yonghong.zhu@intel.com>
> ---
>  .../Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py  | 31
> +++++++++++++++++-----
>  1 file changed, 25 insertions(+), 6 deletions(-)
> 
> diff --git
> a/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py
> b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py
> index b3254d8..3410668 100644
> --- a/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py
> +++ b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py
> @@ -1,12 +1,12 @@
>  ## @file
> -# This tool encodes and decodes GUIDed FFS sections for a GUID type of
> +# This tool encodes and decodes GUIDed FFS sections or FMP capsule for a
> GUID type of
>  # EFI_CERT_TYPE_RSA2048_SHA256_GUID defined in the UEFI 2.4
> Specification as
>  #   {0xa7717414, 0xc616, 0x4977, {0x94, 0x20, 0x84, 0x47, 0x12, 0xa7, 0x35,
> 0xbf}}
>  # This tool has been tested with OpenSSL 1.0.1e 11 Feb 2013
>  #
> -# Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.<BR>
> +# Copyright (c) 2013 - 2016, 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
>  # http://opensource.org/licenses/bsd-license.php
>  #
> @@ -30,11 +30,11 @@ from Common.BuildVersion import gBUILD_VERSION
>  #
>  # Globals for help information
>  #
>  __prog__      = 'Rsa2048Sha256Sign'
>  __version__   = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)
> -__copyright__ = 'Copyright (c) 2013 - 2014, Intel Corporation. All rights
> reserved.'
> +__copyright__ = 'Copyright (c) 2013 - 2016, Intel Corporation. All rights
> reserved.'
>  __usage__     = '%s -e|-d [options] <input_file>' % (__prog__)
> 
>  #
>  # GUID for SHA 256 Hash Algorithm from UEFI Specification
>  #
> @@ -64,10 +64,11 @@ if __name__ == '__main__':
>    parser = argparse.ArgumentParser(prog=__prog__, version=__version__,
> usage=__usage__, description=__copyright__, conflict_handler='resolve')
>    group = parser.add_mutually_exclusive_group(required=True)
>    group.add_argument("-e", action="store_true", dest='Encode',
> help='encode file')
>    group.add_argument("-d", action="store_true", dest='Decode',
> help='decode file')
>    parser.add_argument("-o", "--output", dest='OutputFile', type=str,
> metavar='filename', help="specify the output filename", required=True)
> +  parser.add_argument("--monotonic-count", dest='MonotonicCountStr',
> type=str, help="specify the MonotonicCount in FMP capsule.")
>    parser.add_argument("--private-key", dest='PrivateKeyFile',
> type=argparse.FileType('rb'), help="specify the private key filename.  If not
> specified, a test signing key is used.")
>    parser.add_argument("-v", "--verbose", dest='Verbose',
> action="store_true", help="increase output messages")
>    parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true",
> help="reduce output messages")
>    parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]',
> choices=range(0,10), default=0, help="set debug level")
>    parser.add_argument(metavar="input_file", dest='InputFile',
> type=argparse.FileType('rb'), help="specify the input filename")
> @@ -153,17 +154,30 @@ if __name__ == '__main__':
>    while len(PublicKeyHexString) > 0:
>      PublicKey = PublicKey + chr(int(PublicKeyHexString[0:2],16))
>      PublicKeyHexString=PublicKeyHexString[2:]
>    if Process.returncode <> 0:
>      sys.exit(Process.returncode)
> -
> +
> +  if args.MonotonicCountStr:
> +    try:
> +      if args.MonotonicCountStr.upper().startswith('0X'):
> +        args.MonotonicCountValue = (long)(args.MonotonicCountStr, 16)
> +      else:
> +        args.MonotonicCountValue = (long)(args.MonotonicCountStr)
> +    except:
> +        pass
> +
>    if args.Encode:
> +    FullInputFileBuffer = args.InputFileBuffer
> +    if args.MonotonicCountStr:
> +      format = "Q%ds" % len(args.InputFileBuffer)
> +      FullInputFileBuffer = struct.pack(format,args.MonotonicCountValue,
> args.InputFileBuffer)
>      #
>      # Sign the input file using the specified private key and capture signature
> from STDOUT
>      #
>      Process = subprocess.Popen('%s sha256 -sign "%s"' % (OpenSslCommand,
> args.PrivateKeyFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
> stderr=subprocess.PIPE)
> -    Signature = Process.communicate(input=args.InputFileBuffer)[0]
> +    Signature = Process.communicate(input=FullInputFileBuffer)[0]
>      if Process.returncode <> 0:
>        sys.exit(Process.returncode)
> 
>      #
>      # Write output file that contains hash GUID, Public Key, Signature, and
> Input data
> @@ -194,20 +208,25 @@ if __name__ == '__main__':
>      #
>      if Header.PublicKey <> PublicKey:
>        print 'ERROR: Public key in input file does not match public key from
> private key file'
>        sys.exit(1)
> 
> +    FullInputFileBuffer = args.InputFileBuffer
> +    if args.MonotonicCountStr:
> +      format = "Q%ds" % len(args.InputFileBuffer)
> +      FullInputFileBuffer = struct.pack(format,args.MonotonicCountValue,
> args.InputFileBuffer)
> +
>      #
>      # Write Signature to output file
>      #
>      open(args.OutputFileName, 'wb').write(Header.Signature)
> 
>      #
>      # Verify signature
>      #
>      Process = subprocess.Popen('%s sha256 -prverify "%s" -signature %s' %
> (OpenSslCommand, args.PrivateKeyFileName, args.OutputFileName),
> stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
> -    Process.communicate(args.InputFileBuffer)
> +    Process.communicate(input=FullInputFileBuffer)
>      if Process.returncode <> 0:
>        print 'ERROR: Verification failed'
>        os.remove (args.OutputFileName)
>        sys.exit(Process.returncode)
> 
> --
> 2.6.1.windows.1



^ permalink raw reply	[flat|nested] 8+ messages in thread

end of thread, other threads:[~2016-08-19  5:41 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2016-08-15  8:17 [Patch 0/3] BaseTools: Add the support for FMP capsule generate auth info Yonghong Zhu
2016-08-15  8:17 ` [Patch 1/3] BaseTools: Add the PKCS7 tool Yonghong Zhu
2016-08-15  8:32   ` Yao, Jiewen
2016-08-15  8:34     ` Zhu, Yonghong
2016-08-15  8:17 ` [Patch 2/3] BaseTools: Rsa2048Sha256Sign add new option to support Monotonic count Yonghong Zhu
2016-08-19  5:41   ` Gao, Liming
2016-08-15  8:17 ` [Patch 3/3] BaseTools: FMP capsule add the support to generate auth info Yonghong Zhu
2016-08-19  5:41   ` Gao, Liming

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox