]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py
BaseTools: Replace StandardError with Expression
[mirror_edk2.git] / BaseTools / Source / Python / Rsa2048Sha256Sign / Rsa2048Sha256Sign.py
index b4c9aa4ce4a5d001f2f53c741a9533c2a3a30007..2e164c4a2da6c319753a2396dc4962668f568f4f 100644 (file)
@@ -1,10 +1,10 @@
 ## @file\r
-# This tool encodes and decodes GUIDed FFS sections for a GUID type of\r
+# This tool encodes and decodes GUIDed FFS sections or FMP capsule for a GUID type of\r
 # EFI_CERT_TYPE_RSA2048_SHA256_GUID defined in the UEFI 2.4 Specification as\r
 #   {0xa7717414, 0xc616, 0x4977, {0x94, 0x20, 0x84, 0x47, 0x12, 0xa7, 0x35, 0xbf}}\r
 # This tool has been tested with OpenSSL 1.0.1e 11 Feb 2013\r
 #\r
-# Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.<BR>\r
+# Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.<BR>\r
 # This program and the accompanying materials\r
 # are licensed and made available under the terms and conditions of the BSD License\r
 # which accompanies this distribution.  The full text of the license may be found at\r
@@ -17,6 +17,7 @@
 '''\r
 Rsa2048Sha256Sign\r
 '''\r
+from __future__ import print_function\r
 \r
 import os\r
 import sys\r
@@ -25,6 +26,15 @@ import subprocess
 import uuid\r
 import struct\r
 import collections\r
+from Common.BuildVersion import gBUILD_VERSION\r
+\r
+#\r
+# Globals for help information\r
+#\r
+__prog__      = 'Rsa2048Sha256Sign'\r
+__version__   = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)\r
+__copyright__ = 'Copyright (c) 2013 - 2016, Intel Corporation. All rights reserved.'\r
+__usage__     = '%s -e|-d [options] <input_file>' % (__prog__)\r
 \r
 #\r
 # GUID for SHA 256 Hash Algorithm from UEFI Specification\r
@@ -49,30 +59,19 @@ EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT = struct.Struct('16s256s256s')
 TEST_SIGNING_PRIVATE_KEY_FILENAME = 'TestSigningPrivateKey.pem'\r
 \r
 if __name__ == '__main__':\r
-  #\r
-  # Save name of the program\r
-  #\r
-  ProgramName = sys.argv[0]\r
-  \r
-  #\r
-  # Print copyright \r
-  #\r
-  print '%s - Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.' % (ProgramName)\r
-  \r
   #\r
   # Create command line argument parser object\r
   #  \r
-  parser = argparse.ArgumentParser(prog=ProgramName, usage='%(prog)s -e|-d [options] <input_file>', add_help=False)\r
+  parser = argparse.ArgumentParser(prog=__prog__, version=__version__, usage=__usage__, description=__copyright__, conflict_handler='resolve')\r
   group = parser.add_mutually_exclusive_group(required=True)\r
   group.add_argument("-e", action="store_true", dest='Encode', help='encode file')\r
   group.add_argument("-d", action="store_true", dest='Decode', help='decode file')\r
-  parser.add_argument("-o", "--output", dest='OutputFile', type=argparse.FileType('wb'), metavar='filename', help="specify the output filename", required=True)\r
+  parser.add_argument("-o", "--output", dest='OutputFile', type=str, metavar='filename', help="specify the output filename", required=True)\r
+  parser.add_argument("--monotonic-count", dest='MonotonicCountStr', type=str, help="specify the MonotonicCount in FMP capsule.")\r
   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.")\r
   parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages")\r
   parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages")\r
   parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0,10), default=0, help="set debug level")\r
-  parser.add_argument("--version", dest='Version', action="store_true", help="display the program version and exit")\r
-  parser.add_argument("-h", "--help", dest='Help', action="help", help="display this help text")\r
   parser.add_argument(metavar="input_file", dest='InputFile', type=argparse.FileType('rb'), help="specify the input filename")\r
 \r
   #\r
@@ -87,6 +86,8 @@ if __name__ == '__main__':
   try:\r
     OpenSslPath = os.environ['OPENSSL_PATH']\r
     OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand)\r
+    if ' ' in OpenSslCommand:\r
+      OpenSslCommand = '"' + OpenSslCommand + '"'\r
   except:\r
     pass\r
 \r
@@ -94,16 +95,16 @@ if __name__ == '__main__':
   # Verify that Open SSL command is available\r
   #\r
   try:\r
-    Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r
+    Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
   except:  \r
-    print 'ERROR: Open SSL command not available.  Please verify PATH or set OPENSSL_PATH'\r
+    print('ERROR: Open SSL command not available.  Please verify PATH or set OPENSSL_PATH')\r
     sys.exit(1)\r
     \r
   Version = Process.communicate()\r
-  if Process.returncode <> 0:\r
-    print 'ERROR: Open SSL command not available.  Please verify PATH or set OPENSSL_PATH'\r
+  if Process.returncode != 0:\r
+    print('ERROR: Open SSL command not available.  Please verify PATH or set OPENSSL_PATH')\r
     sys.exit(Process.returncode)\r
-  print Version[0]\r
+  print(Version[0])\r
   \r
   #\r
   # Read input file into a buffer and save input filename\r
@@ -113,10 +114,13 @@ if __name__ == '__main__':
   args.InputFile.close()\r
 \r
   #\r
-  # Save output filename and close output file\r
+  # Save output filename and check if path exists\r
   #\r
-  args.OutputFileName = args.OutputFile.name\r
-  args.OutputFile.close()\r
+  OutputDir = os.path.dirname(args.OutputFile)\r
+  if not os.path.exists(OutputDir):\r
+    print('ERROR: The output path does not exist: %s' % OutputDir)\r
+    sys.exit(1)\r
+  args.OutputFileName = args.OutputFile\r
 \r
   #\r
   # Save private key filename and close private key file\r
@@ -141,28 +145,41 @@ if __name__ == '__main__':
       args.PrivateKeyFile = open(args.PrivateKeyFileName, 'rb')\r
       args.PrivateKeyFile.close()\r
     except:\r
-      print 'ERROR: test signing private key file %s missing' % (args.PrivateKeyFileName)\r
+      print('ERROR: test signing private key file %s missing' % (args.PrivateKeyFileName))\r
       sys.exit(1)\r
 \r
   #\r
   # Extract public key from private key into STDOUT\r
   #\r
-  Process = subprocess.Popen('%s rsa -in "%s" -modulus -noout' % (OpenSslCommand, args.PrivateKeyFileName), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r
+  Process = subprocess.Popen('%s rsa -in "%s" -modulus -noout' % (OpenSslCommand, args.PrivateKeyFileName), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
   PublicKeyHexString = Process.communicate()[0].split('=')[1].strip()\r
   PublicKey = ''\r
   while len(PublicKeyHexString) > 0:\r
     PublicKey = PublicKey + chr(int(PublicKeyHexString[0:2],16))\r
     PublicKeyHexString=PublicKeyHexString[2:]\r
-  if Process.returncode <> 0:\r
+  if Process.returncode != 0:\r
     sys.exit(Process.returncode)\r
-  \r
+\r
+  if args.MonotonicCountStr:\r
+    try:\r
+      if args.MonotonicCountStr.upper().startswith('0X'):\r
+        args.MonotonicCountValue = (long)(args.MonotonicCountStr, 16)\r
+      else:\r
+        args.MonotonicCountValue = (long)(args.MonotonicCountStr)\r
+    except:\r
+        pass\r
+\r
   if args.Encode:\r
+    FullInputFileBuffer = args.InputFileBuffer\r
+    if args.MonotonicCountStr:\r
+      format = "%dsQ" % len(args.InputFileBuffer)\r
+      FullInputFileBuffer = struct.pack(format, args.InputFileBuffer, args.MonotonicCountValue)\r
     # \r
     # Sign the input file using the specified private key and capture signature from STDOUT\r
     #\r
-    Process = subprocess.Popen('%s sha256 -sign "%s"' % (OpenSslCommand, args.PrivateKeyFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r
-    Signature = Process.communicate(input=args.InputFileBuffer)[0]\r
-    if Process.returncode <> 0:\r
+    Process = subprocess.Popen('%s dgst -sha256 -sign "%s"' % (OpenSslCommand, args.PrivateKeyFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
+    Signature = Process.communicate(input=FullInputFileBuffer)[0]\r
+    if Process.returncode != 0:\r
       sys.exit(Process.returncode)\r
       \r
     #\r
@@ -185,17 +202,22 @@ if __name__ == '__main__':
     #\r
     # Verify that the Hash Type matches the expected SHA256 type\r
     #\r
-    if uuid.UUID(bytes_le = Header.HashType) <> EFI_HASH_ALGORITHM_SHA256_GUID:\r
-      print 'ERROR: unsupport hash GUID'\r
+    if uuid.UUID(bytes_le = Header.HashType) != EFI_HASH_ALGORITHM_SHA256_GUID:\r
+      print('ERROR: unsupport hash GUID')\r
       sys.exit(1)\r
 \r
     #\r
     # Verify the public key\r
     #\r
-    if Header.PublicKey <> PublicKey:\r
-      print 'ERROR: Public key in input file does not match public key from private key file'\r
+    if Header.PublicKey != PublicKey:\r
+      print('ERROR: Public key in input file does not match public key from private key file')\r
       sys.exit(1)\r
 \r
+    FullInputFileBuffer = args.InputFileBuffer\r
+    if args.MonotonicCountStr:\r
+      format = "%dsQ" % len(args.InputFileBuffer)\r
+      FullInputFileBuffer = struct.pack(format, args.InputFileBuffer, args.MonotonicCountValue)\r
+\r
     #\r
     # Write Signature to output file\r
     #\r
@@ -204,10 +226,10 @@ if __name__ == '__main__':
     #\r
     # Verify signature\r
     #    \r
-    Process = subprocess.Popen('%s sha256 -prverify "%s" -signature %s' % (OpenSslCommand, args.PrivateKeyFileName, args.OutputFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r
-    Process.communicate(args.InputFileBuffer)\r
-    if Process.returncode <> 0:\r
-      print 'ERROR: Verification failed'\r
+    Process = subprocess.Popen('%s dgst -sha256 -prverify "%s" -signature %s' % (OpenSslCommand, args.PrivateKeyFileName, args.OutputFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
+    Process.communicate(input=FullInputFileBuffer)\r
+    if Process.returncode != 0:\r
+      print('ERROR: Verification failed')\r
       os.remove (args.OutputFileName)\r
       sys.exit(Process.returncode)\r
 \r