Commit 8101d1fa authored by Fabio Utzig's avatar Fabio Utzig Committed by Fabio Utzig
Browse files

Add ed25519 signing support to imgtool

This adds ed25519 signature support using the "prehash" method. Instead
of using the direct contents of the image and header payloads, a sha256
is generated and signed (SHA256-Ed25519). This allows for compatibility
with already existing tools that use the sha256 hash, like mcumgr, etc.

Signed-off-by: default avatarFabio Utzig <utzig@apache.org>
parent fc07eab1
Loading
Loading
Loading
Loading
+4 −4
Changes for docs/imgtool.md: 4 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -12,13 +12,13 @@ Python libraries. These can be installed using 'pip3':

## Managing keys

This tool currently supports rsa-2048, rsa-3072 and ecdsa-p256 keys.  You
can generate a keypair for one of these types using the 'keygen' command:
This tool currently supports rsa-2048, rsa-3072, ecdsa-p256 and ed25519 keys.
You can generate a keypair for one of these types using the 'keygen' command:

    ./scripts/imgtool.py keygen -k filename.pem -t rsa-2048

or use ecdsa-p256 for the type.  The key type used should match what
mcuboot is configured to verify.
or use rsa-3072, ecdsa-p256, or ed25519 for the type.  The key type used
should match what mcuboot is configured to verify.

This key file is what is used to sign images, this file should be
protected, and not widely distributed.
+10
Changes for scripts/imgtool/image.py: 10 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -52,6 +52,7 @@ TLV_VALUES = {
        'ECDSA224': 0x21,
        'ECDSA256': 0x22,
        'RSA3072': 0x23,
        'ED25519': 0x24,
        'ENCRSA2048': 0x30,
        'ENCKW128': 0x31,
        'DEPENDENCY': 0x40
@@ -241,7 +242,13 @@ class Image():
            pubbytes = sha.digest()
            tlv.add('KEYHASH', pubbytes)

            # `sign` expects the full image payload (sha256 done internally),
            # while `sign_digest` expects only the digest of the payload

            if hasattr(key, 'sign'):
                sig = key.sign(bytes(self.payload))
            else:
                sig = key.sign_digest(digest)
            tlv.add(key.sig_tlv(), sig)

        if enckey is not None:
@@ -354,7 +361,10 @@ class Image():
                tlv_sig = b[off:off+tlv_len]
                payload = b[:header_size+img_size]
                try:
                    if hasattr(key, 'verify'):
                        key.verify(tlv_sig, payload)
                    else:
                        key.verify_digest(tlv_sig, digest)
                    return VerifyResult.OK
                except InvalidSignature:
                    # continue to next TLV
+6
Changes for scripts/imgtool/keys/__init__.py: 6 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -20,9 +20,11 @@ from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey, EllipticCurvePublicKey
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

from .rsa import RSA, RSAPublic, RSAUsageError, RSA_KEY_SIZES
from .ecdsa import ECDSA256P1, ECDSA256P1Public, ECDSAUsageError
from .ed25519 import Ed25519, Ed25519Public, Ed25519UsageError

class PasswordRequired(Exception):
    """Raised to indicate that the key is password protected, but a
@@ -72,5 +74,9 @@ def load(path, passwd=None):
        if pk.key_size != 256:
            raise Exception("Unsupported EC size: " + pk.key_size)
        return ECDSA256P1Public(pk)
    elif isinstance(pk, Ed25519PrivateKey):
        return Ed25519(pk)
    elif isinstance(pk, Ed25519PublicKey):
        return Ed25519Public(pk)
    else:
        raise Exception("Unknown key type: " + str(type(pk)))
+98
Changes for scripts/imgtool/keys/ed25519.py: 98 added lines, 0 removed lines.
Original line number Diff line number Diff line
"""
ECDSA key management
"""

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519

from .general import KeyClass


class Ed25519UsageError(Exception):
    pass


class Ed25519Public(KeyClass):
    def __init__(self, key):
        self.key = key

    def shortname(self):
        return "ed25519"

    def _unsupported(self, name):
        raise Ed25519UsageError("Operation {} requires private key".format(name))

    def _get_public(self):
        return self.key

    def get_public_bytes(self):
        # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format
        return self._get_public().public_bytes(
                encoding=serialization.Encoding.DER,
                format=serialization.PublicFormat.SubjectPublicKeyInfo)

    def export_private(self, path, passwd=None):
        self._unsupported('export_private')

    def export_public(self, path):
        """Write the public key to the given file."""
        pem = self._get_public().public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo)
        with open(path, 'wb') as f:
            f.write(pem)

    def sig_type(self):
        return "ED25519"

    def sig_tlv(self):
        return "ED25519"

    def sig_len(self):
        return 64


class Ed25519(Ed25519Public):
    """
    Wrapper around an ECDSA private key.
    """

    def __init__(self, key):
        """key should be an instance of EllipticCurvePrivateKey"""
        self.key = key

    @staticmethod
    def generate():
        pk = ed25519.Ed25519PrivateKey.generate()
        return Ed25519(pk)

    def _get_public(self):
        return self.key.public_key()

    def export_private(self, path, passwd=None):
        """
        Write the private key to the given file, protecting it with the
        optional password.
        """
        if passwd is None:
            enc = serialization.NoEncryption()
        else:
            enc = serialization.BestAvailableEncryption(passwd)
        pem = self.key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=enc)
        with open(path, 'wb') as f:
            f.write(pem)

    def sign_digest(self, digest):
        """Return the actual signature"""
        return self.key.sign(data=digest)

    def verify_digest(self, signature, digest):
        """Verify that signature is valid for given digest"""
        k = self.key
        if isinstance(self.key, ed25519.Ed25519PrivateKey):
            k = self.key.public_key()
        return k.verify(signature=signature, data=digest)
+96
Changes for scripts/imgtool/keys/ed25519_test.py: 96 added lines, 0 removed lines.
Original line number Diff line number Diff line
"""
Tests for ECDSA keys
"""

import io
import os.path
import sys
import tempfile
import unittest

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric import ed25519

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))

from imgtool.keys import load, Ed25519, Ed25519UsageError


class Ed25519KeyGeneration(unittest.TestCase):

    def setUp(self):
        self.test_dir = tempfile.TemporaryDirectory()

    def tname(self, base):
        return os.path.join(self.test_dir.name, base)

    def tearDown(self):
        self.test_dir.cleanup()

    def test_keygen(self):
        name1 = self.tname("keygen.pem")
        k = Ed25519.generate()
        k.export_private(name1, b'secret')

        self.assertIsNone(load(name1))

        k2 = load(name1, b'secret')

        pubname = self.tname('keygen-pub.pem')
        k2.export_public(pubname)
        pk2 = load(pubname)

        # We should be able to export the public key from the loaded
        # public key, but not the private key.
        pk2.export_public(self.tname('keygen-pub2.pem'))
        self.assertRaises(Ed25519UsageError,
                          pk2.export_private, self.tname('keygen-priv2.pem'))

    def test_emit(self):
        """Basic sanity check on the code emitters."""
        k = Ed25519.generate()

        ccode = io.StringIO()
        k.emit_c(ccode)
        self.assertIn("ed25519_pub_key", ccode.getvalue())
        self.assertIn("ed25519_pub_key_len", ccode.getvalue())

        rustcode = io.StringIO()
        k.emit_rust(rustcode)
        self.assertIn("ED25519_PUB_KEY", rustcode.getvalue())

    def test_emit_pub(self):
        """Basic sanity check on the code emitters."""
        pubname = self.tname("public.pem")
        k = Ed25519.generate()
        k.export_public(pubname)

        k2 = load(pubname)

        ccode = io.StringIO()
        k2.emit_c(ccode)
        self.assertIn("ed25519_pub_key", ccode.getvalue())
        self.assertIn("ed25519_pub_key_len", ccode.getvalue())

        rustcode = io.StringIO()
        k2.emit_rust(rustcode)
        self.assertIn("ED25519_PUB_KEY", rustcode.getvalue())

    def test_sig(self):
        k = Ed25519.generate()
        buf = b'This is the message'
        sig = k.raw_sign(buf)

        # The code doesn't have any verification, so verify this
        # manually.
        k.key.public_key().verify(signature=sig, data=buf)

        # Modify the message to make sure the signature fails.
        self.assertRaises(InvalidSignature,
                          k.key.public_key().verify,
                          signature=sig,
                          data=b'This is thE message')


if __name__ == '__main__':
    unittest.main()
Loading