Module rugged.tuf.generate_keys

Expand source code
import os
import shutil
from rugged.lib.constants import (
    RUGGED_SIGNING_KEY_DIR,
    RUGGED_VERIFICATION_KEY_DIR,
)
from rugged.lib.logger import get_logger, log_exception
from securesystemslib.interface import _generate_and_write_ed25519_keypair
from tempfile import TemporaryDirectory

log = get_logger()


def generate_keypair(key, role):
    """ Generate a keypair for a given role """

    if not _ensure_rugged_key_dirs():
        return (False, False)

    with TemporaryDirectory() as tempdir:
        temp_privkey_path = f"{ tempdir }/{ role }/{ key }"
        temp_pubkey_path = f"{ temp_privkey_path }.pub"

        log.debug(f"Generating keypair at { temp_privkey_path }.")
        # @TODO: Add support for passwords.
        _generate_and_write_ed25519_keypair(filepath=temp_privkey_path)

        privkey_result = _copy_key(temp_privkey_path, key, role, 'signing')
        pubkey_result = _copy_key(temp_pubkey_path, key, role, 'verification')

    return (privkey_result, pubkey_result)


def _ensure_rugged_key_dirs():
    """ Ensure the Rugged key directories exist. """

    for key_dir in [RUGGED_SIGNING_KEY_DIR, RUGGED_VERIFICATION_KEY_DIR]:
        try:
            os.makedirs(key_dir, mode=0o700, exist_ok=True)
        except PermissionError as e:
            log_exception(e)
            return False
    return True


def _copy_key(temp_key_path, key, role, type):
    """ Move a key into place, based on role and type. """

    if type == 'signing':
        key_path = f"{ RUGGED_SIGNING_KEY_DIR }/{ role }/{ key }"
    elif type == 'verification':
        key_path = f"{ RUGGED_VERIFICATION_KEY_DIR }/{ key }.pub"
    else:
        log.error(f"Received invalid key type: { type }")
        return False

    log.debug(f"Copying { type } key to { key_path }.")
    try:
        shutil.copy(temp_key_path, key_path)
        return key_path
    except FileNotFoundError as e:
        log_exception(e)
        return False
    except PermissionError as e:
        log_exception(e)
        return False

Functions

def generate_keypair(key, role)

Generate a keypair for a given role

Expand source code
def generate_keypair(key, role):
    """ Generate a keypair for a given role """

    if not _ensure_rugged_key_dirs():
        return (False, False)

    with TemporaryDirectory() as tempdir:
        temp_privkey_path = f"{ tempdir }/{ role }/{ key }"
        temp_pubkey_path = f"{ temp_privkey_path }.pub"

        log.debug(f"Generating keypair at { temp_privkey_path }.")
        # @TODO: Add support for passwords.
        _generate_and_write_ed25519_keypair(filepath=temp_privkey_path)

        privkey_result = _copy_key(temp_privkey_path, key, role, 'signing')
        pubkey_result = _copy_key(temp_pubkey_path, key, role, 'verification')

    return (privkey_result, pubkey_result)