Skip to content

Commit 5416016

Browse files
committed
[nrf fromlist] imgtool: Add pure signature support
Adds PureEdDSA signature support. The change includes implementation of SIG_PURE TLV that, when present, indicates the signature that is present is Pure type. Upstream PR: mcu-tools/mcuboot#2063 Signed-off-by: Dominik Ermel <[email protected]>
1 parent dd4bce1 commit 5416016

File tree

2 files changed

+80
-20
lines changed

2 files changed

+80
-20
lines changed

scripts/imgtool/image.py

Lines changed: 62 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,15 @@ def tlv_sha_to_sha(tlv):
188188
keys.X25519 : ['256', '512']
189189
}
190190

191-
def key_and_user_sha_to_alg_and_tlv(key, user_sha):
191+
ALLOWED_PURE_KEY_SHA = {
192+
keys.Ed25519 : ['512']
193+
}
194+
195+
ALLOWED_PURE_SIG_TLVS = [
196+
TLV_VALUES['ED25519']
197+
]
198+
199+
def key_and_user_sha_to_alg_and_tlv(key, user_sha, is_pure = False):
192200
"""Matches key and user requested sha to sha alogrithm and TLV name.
193201
194202
The returned tuple will contain hash functions and TVL name.
@@ -203,11 +211,17 @@ def key_and_user_sha_to_alg_and_tlv(key, user_sha):
203211
# If key is not None, then we have to filter hash to only allowed
204212
allowed = None
205213
try:
206-
allowed = ALLOWED_KEY_SHA[type(key)]
214+
if is_pure:
215+
allowed = ALLOWED_PURE_KEY_SHA[type(key)]
216+
else:
217+
allowed = ALLOWED_KEY_SHA[type(key)]
218+
207219
except KeyError:
208220
raise click.UsageError("Colud not find allowed hash algorithms for {}"
209221
.format(type(key)))
210-
if user_sha == 'auto':
222+
223+
# Pure enforces auto, and user selection is ignored
224+
if user_sha == 'auto' or is_pure:
211225
return USER_SHA_TO_ALG_AND_TLV[allowed[0]]
212226

213227
if user_sha in allowed:
@@ -445,12 +459,13 @@ def ecies_hkdf(self, enckey, plainkey):
445459
def create(self, key, public_key_format, enckey, dependencies=None,
446460
sw_type=None, custom_tlvs=None, compression_tlvs=None,
447461
compression_type=None, encrypt_keylen=128, clear=False,
448-
fixed_sig=None, pub_key=None, vector_to_sign=None, user_sha='auto'):
462+
fixed_sig=None, pub_key=None, vector_to_sign=None,
463+
user_sha='auto', is_pure=False):
449464
self.enckey = enckey
450465

451466
# key decides on sha, then pub_key; of both are none default is used
452467
check_key = key if key is not None else pub_key
453-
hash_algorithm, hash_tlv = key_and_user_sha_to_alg_and_tlv(check_key, user_sha)
468+
hash_algorithm, hash_tlv = key_and_user_sha_to_alg_and_tlv(check_key, user_sha, is_pure)
454469

455470
# Calculate the hash of the public key
456471
if key is not None:
@@ -590,9 +605,16 @@ def create(self, key, public_key_format, enckey, dependencies=None,
590605
sha = hash_algorithm()
591606
sha.update(self.payload)
592607
digest = sha.digest()
593-
message = digest;
594608
tlv.add(hash_tlv, digest)
595-
self.image_hash = digest
609+
# Unless pure, we are signing digest.
610+
message = digest
611+
612+
if is_pure:
613+
# Note that when Pure signature is used, hash TLV is not present.
614+
message = bytes(self.payload)
615+
e = STRUCT_ENDIAN_DICT[self.endian]
616+
sig_pure = struct.pack(e + '?', True)
617+
tlv.add('SIG_PURE', sig_pure)
596618

597619
if vector_to_sign == 'payload':
598620
# Stop amending data to the image
@@ -784,7 +806,7 @@ def verify(imgfile, key):
784806
version = struct.unpack('BBHI', b[20:28])
785807

786808
if magic != IMAGE_MAGIC:
787-
return VerifyResult.INVALID_MAGIC, None, None
809+
return VerifyResult.INVALID_MAGIC, None, None, None
788810

789811
tlv_off = header_size + img_size
790812
tlv_info = b[tlv_off:tlv_off + TLV_INFO_SIZE]
@@ -795,27 +817,43 @@ def verify(imgfile, key):
795817
magic, tlv_tot = struct.unpack('HH', tlv_info)
796818

797819
if magic != TLV_INFO_MAGIC:
798-
return VerifyResult.INVALID_TLV_INFO_MAGIC, None, None
820+
return VerifyResult.INVALID_TLV_INFO_MAGIC, None, None, None
821+
822+
# This is set by existence of TLV SIG_PURE
823+
is_pure = False
799824

800825
prot_tlv_size = tlv_off
801826
hash_region = b[:prot_tlv_size]
827+
tlv_end = tlv_off + tlv_tot
828+
tlv_off += TLV_INFO_SIZE # skip tlv info
829+
830+
# First scan all TLVs in search of SIG_PURE
831+
while tlv_off < tlv_end:
832+
tlv = b[tlv_off:tlv_off + TLV_SIZE]
833+
tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
834+
if tlv_type == TLV_VALUES['SIG_PURE']:
835+
is_pure = True
836+
break
837+
tlv_off += TLV_SIZE + tlv_len
838+
802839
digest = None
840+
tlv_off = header_size + img_size
803841
tlv_end = tlv_off + tlv_tot
804842
tlv_off += TLV_INFO_SIZE # skip tlv info
805843
while tlv_off < tlv_end:
806844
tlv = b[tlv_off:tlv_off + TLV_SIZE]
807845
tlv_type, _, tlv_len = struct.unpack('BBH', tlv)
808846
if is_sha_tlv(tlv_type):
809847
if not tlv_matches_key_type(tlv_type, key):
810-
return VerifyResult.KEY_MISMATCH, None, None
848+
return VerifyResult.KEY_MISMATCH, None, None, None
811849
off = tlv_off + TLV_SIZE
812850
digest = get_digest(tlv_type, hash_region)
813851
if digest == b[off:off + tlv_len]:
814852
if key is None:
815-
return VerifyResult.OK, version, digest
853+
return VerifyResult.OK, version, digest, None
816854
else:
817-
return VerifyResult.INVALID_HASH, None, None
818-
elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
855+
return VerifyResult.INVALID_HASH, None, None, None
856+
elif not is_pure and key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]:
819857
off = tlv_off + TLV_SIZE
820858
tlv_sig = b[off:off + tlv_len]
821859
payload = b[:prot_tlv_size]
@@ -824,9 +862,18 @@ def verify(imgfile, key):
824862
key.verify(tlv_sig, payload)
825863
else:
826864
key.verify_digest(tlv_sig, digest)
827-
return VerifyResult.OK, version, digest
865+
return VerifyResult.OK, version, digest, None
866+
except InvalidSignature:
867+
# continue to next TLV
868+
pass
869+
elif is_pure and key is not None and tlv_type in ALLOWED_PURE_SIG_TLVS:
870+
off = tlv_off + TLV_SIZE
871+
tlv_sig = b[off:off + tlv_len]
872+
try:
873+
key.verify_digest(tlv_sig, hash_region)
874+
return VerifyResult.OK, version, None, tlv_sig
828875
except InvalidSignature:
829876
# continue to next TLV
830877
pass
831878
tlv_off += TLV_SIZE + tlv_len
832-
return VerifyResult.INVALID_SIGNATURE, None, None
879+
return VerifyResult.INVALID_SIGNATURE, None, None, None

scripts/imgtool/main.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -226,11 +226,14 @@ def getpriv(key, minimal, format):
226226
@click.command(help="Check that signed image can be verified by given key")
227227
def verify(key, imgfile):
228228
key = load_key(key) if key else None
229-
ret, version, digest = image.Image.verify(imgfile, key)
229+
ret, version, digest, signature = image.Image.verify(imgfile, key)
230230
if ret == image.VerifyResult.OK:
231231
print("Image was correctly validated")
232232
print("Image version: {}.{}.{}+{}".format(*version))
233-
print("Image digest: {}".format(digest.hex()))
233+
if digest:
234+
print("Image digest: {}".format(digest.hex()))
235+
if signature and digest is None:
236+
print("Image signature over image: {}".format(signature.hex()))
234237
return
235238
elif ret == image.VerifyResult.INVALID_MAGIC:
236239
print("Invalid image magic; is this an MCUboot image?")
@@ -423,6 +426,10 @@ def convert(self, value, param, ctx):
423426
'the signature calculated using the public key')
424427
@click.option('--fix-sig-pubkey', metavar='filename',
425428
help='public key relevant to fixed signature')
429+
@click.option('--pure', 'is_pure', is_flag=True, default=False, show_default=True,
430+
help='Expected Pure variant of signature; the Pure variant is '
431+
'expected to be signature done over an image rather than hash of '
432+
'that image.')
426433
@click.option('--sig-out', metavar='filename',
427434
help='Path to the file to which signature will be written. '
428435
'The image signature will be encoded as base64 formatted string')
@@ -441,8 +448,8 @@ def sign(key, public_key_format, align, version, pad_sig, header_size,
441448
endian, encrypt_keylen, encrypt, compression, infile, outfile,
442449
dependencies, load_addr, hex_addr, erased_val, save_enctlv,
443450
security_counter, boot_record, custom_tlv, rom_fixed, max_align,
444-
clear, fix_sig, fix_sig_pubkey, sig_out, user_sha, vector_to_sign,
445-
non_bootable):
451+
clear, fix_sig, fix_sig_pubkey, sig_out, user_sha, is_pure,
452+
vector_to_sign, non_bootable):
446453

447454
if confirm:
448455
# Confirmed but non-padded images don't make much sense, because
@@ -509,9 +516,15 @@ def sign(key, public_key_format, align, version, pad_sig, header_size,
509516
'value': raw_signature
510517
}
511518

519+
if is_pure and user_sha != 'auto':
520+
raise click.UsageError(
521+
'Pure signatures, currently, enforces preferred hash algorithm, '
522+
'and forbids sha selection by user.')
523+
512524
img.create(key, public_key_format, enckey, dependencies, boot_record,
513525
custom_tlvs, compression_tlvs, int(encrypt_keylen), clear,
514-
baked_signature, pub_key, vector_to_sign, user_sha)
526+
baked_signature, pub_key, vector_to_sign, user_sha=user_sha,
527+
is_pure=is_pure)
515528

516529
if compression in ["lzma2", "lzma2armthumb"]:
517530
compressed_img = image.Image(version=decode_version(version),

0 commit comments

Comments
 (0)