summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJoakim Bech <joakim.bech@linaro.org>2016-08-29 15:00:47 +0200
committerJoakim Bech <joakim.bech@linaro.org>2016-08-29 15:00:47 +0200
commita4f010c19e742a9dc02b214bfeba0314b22a52ff (patch)
tree43ad7a262fe0396d2aa2d79ac2226ef834880b08
Initial version
Signed-off-by: Joakim Bech <joakim.bech@linaro.org>
-rw-r--r--.gitignore2
-rwxr-xr-xpatch_mynewt_img.py87
2 files changed, 89 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b948985
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+*.swp
+*.pyc
diff --git a/patch_mynewt_img.py b/patch_mynewt_img.py
new file mode 100755
index 0000000..26d2b4d
--- /dev/null
+++ b/patch_mynewt_img.py
@@ -0,0 +1,87 @@
+#!/usr/bin/python2
+import hashlib
+import mmap
+import os
+import struct
+import sys
+from ctypes import *
+
+def patch_header(img):
+ image_size = os.path.getsize(img + ".elf.bin")
+ print("Image size (bin): %d" % image_size)
+
+ try:
+ with open(img + ".img", "r+b") as f:
+ print("[*] Loading : {0}".format(img))
+
+ # Patch the header size (Hardcoded to 0x80)
+ f.seek(8)
+ f.write('\x80\x00')
+
+ # Patch the image size, start by convert int to hex string.
+ image_size = struct.pack('i', image_size)
+ f.seek(12)
+ f.write(image_size)
+
+ #
+ f.close()
+ except IOError:
+ print("[*] Cannot open {0} (!) ".format(img))
+
+
+def extend_image(img):
+ try:
+ with open(img + ".img", "r+b") as f:
+ print("[*] Loading : {0}".format(img))
+ mm=mmap.mmap(f.fileno(),0)
+ f.write(mm[0:32] + ('\xFF' * 0x60) + mm[33:])
+ f.close()
+ except IOError:
+ print("[*] Cannot open {0} (!) ".format(img))
+
+
+def calculate_hash(img):
+ sha256 = hashlib.sha256()
+ with open(img + ".img", "rb") as f:
+ for chunk in iter(lambda: f.read(4096), b""):
+ sha256.update(chunk)
+ return sha256.hexdigest()
+
+
+def append_hash(img, digest):
+ with open(img + ".img", "ab") as f:
+
+ # Start by settings the TLV type
+ # https://github.com/apache/incubator-mynewt-newt/blob/master/newt/image/image.go#L109-L116
+ tlv_type = struct.pack('b', 1) # 1: SHA256, 2: RSA2048, 3: ECDSA224
+
+ # Next 1 byte padding
+ tlv_pad = '\x00'
+
+ # Finally the size of the TLV, for SHA256 that is 32 bytes
+ tlv_len = struct.pack('h', 0x20)
+
+ f.write(tlv_type)
+ f.write(tlv_pad)
+ f.write(tlv_len)
+ f.write(digest.decode('hex'))
+ f.close()
+
+def main(img):
+ patch_header(img)
+ extend_image(img)
+
+ digest = calculate_hash(img)
+ print("Hash of intermediate image: %s" % digest)
+
+ append_hash(img, digest)
+
+if __name__ == "__main__":
+ if sys.argv[1]:
+ try:
+ main(sys.argv[1])
+ except KeyboardInterrupt:
+ sys.exit(0)
+ else:
+ print("[*] Not enough arguments (!) ")
+ print("[*] Usage : parser.py bin")