aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Makefile.in1
-rw-r--r--cryptech.h6
-rw-r--r--hash.c6
-rw-r--r--tests/test-hash.c6
4 files changed, 10 insertions, 9 deletions
diff --git a/Makefile.in b/Makefile.in
index bc60029..ee9daae 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -18,6 +18,7 @@ includedir = @includedir@
libdir = @libdir@
all: ${LIB}
+ cd tests; ${MAKE} $@
${OBJ}: ${INC}
diff --git a/cryptech.h b/cryptech.h
index 3ceab95..9ac73e8 100644
--- a/cryptech.h
+++ b/cryptech.h
@@ -479,9 +479,9 @@ extern hal_error_t hal_io_wait_valid(off_t offset);
extern hal_error_t hal_get_random(void *buffer, const size_t length);
extern void hal_hash_set_debug(int onoff);
-extern hal_error_t hash_sha1_core_present(void);
-extern hal_error_t hash_sha256_core_present(void);
-extern hal_error_t hash_sha512_core_present(void);
+extern hal_error_t hal_hash_sha1_core_present(void);
+extern hal_error_t hal_hash_sha256_core_present(void);
+extern hal_error_t hal_hash_sha512_core_present(void);
extern size_t hal_hash_state_size(void);
extern void hal_hash_state_initialize(void *state);
extern hal_error_t hal_hash_sha1(void *state, const uint8_t * data_buffer, const size_t data_buffer_length,
diff --git a/hash.c b/hash.c
index ae49c06..bd0daa8 100644
--- a/hash.c
+++ b/hash.c
@@ -92,17 +92,17 @@ void hal_hash_state_initialize(void *_state)
* Report whether cores are present.
*/
-hal_error_t hash_sha1_core_present(void)
+hal_error_t hal_hash_sha1_core_present(void)
{
return hal_io_expected(SHA1_ADDR_NAME0, (const uint8_t *) (SHA1_NAME0 SHA1_NAME1), 8);
}
-hal_error_t hash_sha256_core_present(void)
+hal_error_t hal_hash_sha256_core_present(void)
{
return hal_io_expected(SHA256_ADDR_NAME0, (const uint8_t *) (SHA256_NAME0 SHA256_NAME1), 8);
}
-hal_error_t hash_sha512_core_present(void)
+hal_error_t hal_hash_sha512_core_present(void)
{
return hal_io_expected(SHA512_ADDR_NAME0, (const uint8_t *) (SHA512_NAME0 SHA512_NAME1), 8);
}
diff --git a/tests/test-hash.c b/tests/test-hash.c
index 8144459..671f200 100644
--- a/tests/test-hash.c
+++ b/tests/test-hash.c
@@ -177,7 +177,7 @@ int main (int argc, char *argv[])
{
int ok = 1;
- if (hash_sha1_core_present() == HAL_OK) {
+ if (hal_hash_sha1_core_present() == HAL_OK) {
ok &= test_hash(hal_hash_sha1, nist_512_single, sha1_single_digest, "SHA-1 single block");
ok &= test_hash(hal_hash_sha1, nist_512_double, sha1_double_digest, "SHA-1 double block");
}
@@ -185,7 +185,7 @@ int main (int argc, char *argv[])
printf("SHA-1 core not present, skipping tests which depend on it\n");
}
- if (hash_sha256_core_present() == HAL_OK) {
+ if (hal_hash_sha256_core_present() == HAL_OK) {
ok &= test_hash(hal_hash_sha256, nist_512_single, sha256_single_digest, "SHA-256 single block");
ok &= test_hash(hal_hash_sha256, nist_512_double, sha256_double_digest, "SHA-256 double block");
}
@@ -193,7 +193,7 @@ int main (int argc, char *argv[])
printf("SHA-256 core not present, skipping tests which depend on it\n");
}
- if (hash_sha512_core_present() == HAL_OK) {
+ if (hal_hash_sha512_core_present() == HAL_OK) {
ok &= test_hash(hal_hash_sha512_224, nist_1024_single, sha512_224_single_digest, "SHA-512/224 single block");
ok &= test_hash(hal_hash_sha512_224, nist_1024_double, sha512_224_double_digest, "SHA-512/224 double block");
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
#!/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.

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_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 a JSON file for transfer to primary HSM.
    """

    result = {}

    uuids = []
    if args.uuid:
        uuids.append(args.uuid)
    elif not args.new:
        uuids.extend(hsm.pkey_match(
            type  = HAL_KEY_TYPE_RSA_PRIVATE,
            mask  = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT | HAL_KEY_FLAG_TOKEN,
            flags = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT | HAL_KEY_FLAG_TOKEN))

    for uuid in uuids:
        with hsm.pkey_open(uuid) as kekek:
            if kekek.key_type != HAL_KEY_TYPE_RSA_PRIVATE:
                sys.stderr.write("Key {} is not an RSA private key\n".format(uuid))
            elif (kekek.key_flags & HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT) == 0:
                sys.stderr.write("Key {} does not allow key encipherment\n".format(uuid))
            else:
                result.update(kekek_uuid   = str(kekek.uuid),
                              kekek_pubkey = b64(kekek.public_key))
                break

    if not result and not args.uuid:
        with hsm.pkey_generate_rsa(
                keylen = args.keylen,
                flags = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT | HAL_KEY_FLAG_TOKEN) as kekek:
            result.update(kekek_uuid   = str(kekek.uuid),
                          kekek_pubkey = b64(kekek.public_key))
    if not result:
        sys.exit("Could not find suitable KEKEK")

    result.update(comment = "KEKEK public key")
    json.dump(result, args.output, indent = 4, sort_keys = True)
    args.output.write("\n")


def key_flag_names(flags):
    names = dict(digitalsignature = HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE,
                 keyencipherment  = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT,
                 dataencipherment = HAL_KEY_FLAG_USAGE_DATAENCIPHERMENT,
                 token            = HAL_KEY_FLAG_TOKEN,
                 public           = HAL_KEY_FLAG_PUBLIC,
                 exportable       = HAL_KEY_FLAG_EXPORTABLE)
    return ", ".join(sorted(k for k, v in names.iteritems() if (flags & v) != 0))


def cmd_export(args, hsm):
    """
    Export encrypted keys from primary HSM.
    Takes a JSON file containing KEKEK (generated by running this
    script's "setup" command against the backup HSM), installs that
    key on the primary HSM, and backs up keys encrypted to the KEKEK
    by writing them to another JSON file for transfer to the backup HSM.
    """

    db = json.load(args.input)

    result = []

    kekek = None
    try:
        kekek = hsm.pkey_load(der   = b64join(db["kekek_pubkey"]),
                              flags = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT)

        for uuid in hsm.pkey_match(mask  = HAL_KEY_FLAG_EXPORTABLE,
                                   flags = HAL_KEY_FLAG_EXPORTABLE):
            with hsm.pkey_open(uuid) as pkey:

                if pkey.key_type in (HAL_KEY_TYPE_RSA_PRIVATE, HAL_KEY_TYPE_EC_PRIVATE):
                    pkcs8, kek = kekek.export_pkey(pkey)
                    result.append(dict(
                        comment = "Encrypted private key",
                        pkcs8   = b64(pkcs8),
                        kek     = b64(kek),
                        uuid    = str(pkey.uuid),
                        flags   = pkey.key_flags))

                elif pkey.key_type in (HAL_KEY_TYPE_RSA_PUBLIC, HAL_KEY_TYPE_EC_PUBLIC):
                    result.append(dict(
                        comment = "Public key",
                        spki    = b64(pkey.public_key),
                        uuid    = str(pkey.uuid),
                        flags   = pkey.key_flags))

    finally:
        if kekek is not None:
            kekek.delete()

    db.update(comment = "Cryptech Alpha encrypted key backup",
              keys    = result)
    json.dump(db, args.output, indent = 4, sort_keys = True)
    args.output.write("\n")


def cmd_import(args, hsm):
    """
    Import encrypted keys into backup HSM.
    Takes a JSON file containing a key backup (generated by running
    this script's "export" command against the primary HSM) and imports
    keys into the backup HSM.
    """

    db = json.load(args.input)
    with hsm.pkey_open(uuid.UUID(db["kekek_uuid"]).bytes) as kekek:
        for k in db["keys"]:
            pkcs8 = b64join(k.get("pkcs8", ""))
            spki  = b64join(k.get("spki",  ""))
            kek   = b64join(k.get("kek",   ""))
            flags =         k.get("flags",  0)
            if pkcs8 and kek:
                with kekek.import_pkey(pkcs8 = pkcs8, kek = kek, flags = flags) as pkey:
                    print "Imported {} as {}".format(k["uuid"], pkey.uuid)
            elif spki:
                with hsm.pkey_load(der = spki, flags = flags) as pkey:
                    print "Loaded {} as {}".format(k["uuid"], pkey.uuid)


if __name__ == "__main__":
    main()