#!/usr/bin/env python """ Securely back up private keys from one Cryptech HSM to another. This works by having the destination HSM (the one importing keys) create an RSA keypair (the "KEKEK"), the public key of which can then be imported into the source HSM (the one exporting keys) and used to encrypt AES key encryption keys (KEKs) which in turn can be used to wrap the private keys being transfered. Transfers are encoded in JSON; the underlying ASN.1 formats are SubjectPublicKeyInfo (KEKEK public key) and PKCS #8 EncryptedPrivateKeyInfo (everything else). NOTE WELL: while this process makes it POSSIBLE to back up keys securely, it is not sufficient by itself: the operator MUST make sure only to export keys using a KEKEK known to have been generated by the target HSM. See the unit tests in the source repository for an example of how to fake this in a few lines of Python. We also implement a software-based variant on this backup mechanism, for cases where there is no second HSM. The protocol is much the same, but the KEKEK is generated in software and encrypted using a symmetric key derived from a passphrase using PBKDF2. This requires the PyCrypto library, and is only as secure as memory on the machine where you're running it (so it's theoretically vulnerable to root or anybody with access to /dev/mem). Don't use this mode unless you understand the risks, and see the "NOTE WELL" above. YOU HAVE BEEN WARNED. Be careful out there. """ # Diagram of the trivial protocol we're using: # # SOURCE HSM DESTINATION HSM # # Generate and export KEKEK: # hal_rpc_pkey_generate_rsa() # hal_rpc_pkey_get_public_key() # # Load KEKEK public <--------- Export KEKEK public # hal_rpc_pkey_load() # hal_rpc_pkey_export() # # Export PKCS #8 and KEK ----------> Load PKCS #8 and KEK, import key # hal_rpc_pkey_import() import sys import json import uuid import atexit import getpass import argparse from cryptech.libhal import * def main(): parser = argparse.ArgumentParser( formatter_class = argparse.RawDescriptionHelpFormatter, description = __doc__) subparsers = parser.add_subparsers( title = "Commands (use \"--help\" after command name for help with individual commands)", metavar = "") setup_parser = defcmd(subparsers, cmd_setup) export_parser = defcmd(subparsers, cmd_export) import_parser = defcmd(subparsers, cmd_import) setup_mutex_group = setup_parser.add_mutually_exclusive_group() parser.add_argument( "-p", "--pin", help = "wheel PIN") setup_mutex_group.add_argument( "-n", "--new", action = "store_true", help = "force creation of new KEKEK") setup_mutex_group.add_argument( "-u", "--uuid", help = "UUID of existing KEKEK to use") setup_mutex_group.add_argument( "-s", "--soft-backup", action = "store_true", help = "software-based backup, see warnings") setup_parser.add_argument( "-k", "--keylen", type = int, default = 2048, help = "length of new KEKEK if we need to create one") setup_parser.add_argument( "-o", "--output", type = argparse.FileType("w"), default = "-", help = "output file") export_parser.add_argument( "-i", "--input", type = argparse.FileType("r"), default = "-", help = "input file") export_parser.add_argument( "-o", "--output", type = argparse.FileType("w"), default = "-", help = "output file") import_parser.add_argument( "-i", "--input", type = argparse.FileType("r"), default = "-", help = "input file") args = parser.parse_args() hsm = HSM() try: hsm.login(HAL_USER_WHEEL, args.pin or getpass.getpass("Wheel PIN: ")) except HALError as e: sys.exit("Couldn't log into HSM: {}".format(e)) try: sys.exit(args.func(args, hsm)) finally: hsm.logout() def defcmd(subparsers, func): assert func.__name__.startswith("cmd_") subparser = subparsers.add_parser(func.__name__[4:], description = func.__doc__, help = func.__doc__.strip().splitlines()[0]) subparser.set_defaults(func = func) return subparser def b64(bytes): return bytes.encode("base64").splitlines() def b64join(lines): return "".join(lines).decode("base64") def cmd_setup(args, hsm): """ Set up backup HSM for subsequent import. Generates an RSA keypair with appropriate usage settings to use as a key-encryption-key-encryption-key (KEKEK), and writes the KEKEK to
# Copyright (c) 2015, NORDUnet A/S
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# - Neither the name of the NORDUnet nor the names of its contributors may
# be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
INC = ../hal.h
LIB = ../libhal.a
BIN = eim_peek_poke cores
CFLAGS = -g3 -Wall -fPIC -std=c99 -I..
all: ${BIN}
clean:
rm -f *.o ${BIN}
${BIN}: %: %.o ${LIB}
${CC} ${CFLAGS} -o $@ $^ ${LDFLAGS}
%.o: %.c ${INC}
${CC} ${CFLAGS} -c -o $@ $<