diff options
Diffstat (limited to 'projects/hsm')
-rw-r--r-- | projects/hsm/Makefile | 50 | ||||
-rwxr-xr-x | projects/hsm/cryptech_miniterm | 45 | ||||
-rwxr-xr-x | projects/hsm/cryptech_probe | 158 | ||||
-rwxr-xr-x | projects/hsm/cryptech_upload | 385 | ||||
-rw-r--r-- | projects/hsm/hsm.c | 522 | ||||
-rw-r--r-- | projects/hsm/log.c | 68 | ||||
-rw-r--r-- | projects/hsm/main.c | 226 | ||||
-rw-r--r-- | projects/hsm/mgmt-bootloader.c | 89 | ||||
-rw-r--r-- | projects/hsm/mgmt-bootloader.h | 51 | ||||
-rw-r--r-- | projects/hsm/mgmt-cli.c | 220 | ||||
-rw-r--r-- | projects/hsm/mgmt-cli.h | 49 | ||||
-rw-r--r-- | projects/hsm/mgmt-firmware.c | 75 | ||||
-rw-r--r-- | projects/hsm/mgmt-firmware.h | 42 | ||||
-rw-r--r-- | projects/hsm/mgmt-fpga.c | 194 | ||||
-rw-r--r-- | projects/hsm/mgmt-fpga.h | 49 | ||||
-rw-r--r-- | projects/hsm/mgmt-keystore.c | 408 | ||||
-rw-r--r-- | projects/hsm/mgmt-keystore.h | 42 | ||||
-rw-r--r-- | projects/hsm/mgmt-masterkey.c | 244 | ||||
-rw-r--r-- | projects/hsm/mgmt-masterkey.h | 42 | ||||
-rw-r--r-- | projects/hsm/mgmt-misc.c | 259 | ||||
-rw-r--r-- | projects/hsm/mgmt-misc.h | 47 | ||||
-rw-r--r-- | projects/hsm/mgmt-task.c | 136 | ||||
-rw-r--r-- | projects/hsm/mgmt-task.h | 42 |
23 files changed, 3209 insertions, 234 deletions
diff --git a/projects/hsm/Makefile b/projects/hsm/Makefile index f5546d8..7fd3ad6 100644 --- a/projects/hsm/Makefile +++ b/projects/hsm/Makefile @@ -1,19 +1,53 @@ PROJ = hsm -SRCS = main.c +# objs in addition to $(PROJ).o +OBJS = mgmt-cli.o \ + mgmt-firmware.o \ + mgmt-bootloader.o \ + mgmt-fpga.o \ + mgmt-keystore.o \ + mgmt-masterkey.o \ + mgmt-misc.o \ + mgmt-task.o \ + log.o \ + $(TOPLEVEL)/task.o -OBJS = $(SRCS:.c=.o) +CFLAGS += -DNUM_RPC_TASK=8 -CFLAGS += -I $(LIBHAL_DIR) +CFLAGS += -I$(LIBHAL_SRC) +CFLAGS += -I$(LIBCLI_SRC) +CFLAGS += -I$(LIBTFM_BLD) +CFLAGS += -Wno-missing-field-initializers -LIBS += $(LIBHAL_DIR)/libhal.a $(LIBTFM_DIR)/libtfm.a +LIBS += $(LIBHAL_BLD)/libhal.a $(LIBTFM_BLD)/libtfm.a +LIBS += $(LIBCLI_BLD)/libcli.a + +LDFLAGS += -mcpu=cortex-m4 -mthumb -mlittle-endian -mthumb-interwork +LDFLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16 +LDFLAGS += -Wl,--gc-sections + +ifdef DO_PROFILING +LDFLAGS += --specs=rdimon.specs -lc -lrdimon +endif + +ifdef DO_TASK_METRICS +CFLAGS += -DDO_TASK_METRICS +endif + +ifdef DO_TIMING +CFLAGS += -DDO_TIMING +CFLAGS += -I../cli-test +CFLAGS += -DCLI_STACK_SIZE=65536 +OBJS += ../cli-test/mgmt-timing.o $(TOPLEVEL)/stm-dwt.o +LDFLAGS += -lm +endif all: $(PROJ:=.elf) -$(PROJ).elf: $(OBJS) $(BOARD_OBJS) $(LIBS) - $(CC) $(CFLAGS) $^ -o $@ -T$(LDSCRIPT) -g -Wl,-Map=$(PROJ).map - $(OBJCOPY) -O binary $(PROJ).elf $(PROJ).bin - $(SIZE) $(PROJ).elf +%.elf: %.o $(BOARD_OBJS) $(OBJS) $(LIBS) + $(CC) $^ -o $@ -T$(LDSCRIPT) -g -Wl,-Map=$*.map $(LDFLAGS) + $(OBJCOPY) -O binary $*.elf $*.bin + $(SIZE) $*.elf clean: rm -f *.o diff --git a/projects/hsm/cryptech_miniterm b/projects/hsm/cryptech_miniterm new file mode 100755 index 0000000..b646811 --- /dev/null +++ b/projects/hsm/cryptech_miniterm @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2016, 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. + +""" +Utility to run PySerial's "miniterm" with default settings suitable +for talking to the Cryptech Alpha's console port. +""" + +import serial.tools.miniterm +import sys +import os + +default_port = os.getenv("CRYPTECH_CTY_CLIENT_SERIAL_DEVICE") +default_baud = os.getenv("CRYPTECH_CTY_CLIENT_SERIAL_SPEED", 921600) + +sys.exit(serial.tools.miniterm.main(default_port = default_port, + default_baudrate = int(default_baud))) + diff --git a/projects/hsm/cryptech_probe b/projects/hsm/cryptech_probe new file mode 100755 index 0000000..356931a --- /dev/null +++ b/projects/hsm/cryptech_probe @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2016, 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. + +""" +Utility to probe USB serial port(s) trying to figure out which one(s) +we have plugged in today. stdout is environment variable settings, +suitable for use in bash with "eval `cryptech_probe`"; all other output +goes to stderr. +""" + +import sys +import time +import argparse +import serial.tools.list_ports_posix + +if sys.version_info.major == 2: + def colon_hex(raw): + return ":".join("{:02x}".format(ord(b)) for b in raw) +else: + def colon_hex(raw): + return ":".join("{:02x}".format(b) for b in raw) + +class positive_integer(int): + def __init__(self, value): + if self <= 0: + raise ValueError + +parser = argparse.ArgumentParser(formatter_class = argparse.ArgumentDefaultsHelpFormatter) +parser.add_argument("-v", "--verbose", action = "store_true", help = "produce human-readable output") +parser.add_argument("-d", "--debug", action = "store_true", help = "blather about what we're doing") +parser.add_argument("--no-cleanup", action = "store_true", help = "don't send cleanup sequences after probing") +parser.add_argument("--read-buffer-size", type = positive_integer, help = "size of read buffer", default = 1024) +args = parser.parse_args() + +SLIP_END = b"\300" # Indicates end of SLIP packet +SLIP_ESC = b"\333" # Indicates byte stuffing +SLIP_ESC_END = b"\334" # ESC ESC_END means END data byte +SLIP_ESC_ESC = b"\335" # ESC ESC_ESC means ESC data byte + +Control_U = b"\025" # Console: clear line +Control_M = b"\015" # Console: end of line + +RPC_query = b"\0" * 8 # client_handle = 0, function code = RPC_FUNC_GET_VERSION +RPC_reply = b"\0" * 12 # opcode = RPC_FUNC_GET_VERSION, client_handle = 0, valret = HAL_OK + +# This is the query string we send to each USB port we find. It's +# intended to be relatively harmless, at least for either of the HSM +# ports: the final Control-U should prevent the console from trying to +# interpret the RPC command, and the SLIP_END markers should cause +# the RPC server to treat the ASCII control characters as noise. +# +# Yes, this is a total kludge. Useful identifiers for the USB ports +# are are on the wish list for a future revision of the hardware, but +# for the moment, we do what we can with what we have. + +probe_string = SLIP_END + Control_U + SLIP_END + RPC_query + SLIP_END + Control_U + Control_M + +ports = [port for port, desc, hwid in serial.tools.list_ports_posix.comports() + if "VID:PID=0403:6014" in hwid] + +if not ports: + sys.exit("Couldn't find any likely USB ports") + +if args.debug: + sys.stderr.write("Candidate USB ports: {}\n".format(", ".join(ports))) + +env = {} + +for port in ports: + + while True: + try: + tty = serial.Serial(port, 921600, timeout=0.1) + break + except serial.SerialException: + time.sleep(0.2) + + # Not sure we really need to dribble the probe string out this slowly anymore, + # but once upon a time we did this for a reason and it's not like this program + # is a performance bottleneck, so stick with the safe version. + + for i in range(len(probe_string)): + tty.write(probe_string[i:i+1]) + time.sleep(0.1) + + response = tty.read(args.read_buffer_size) + if args.debug: + sys.stderr.write("Received from {}: {!r} ({})\n".format(port, response, colon_hex(response))) + + # Check whether we got a known console prompt. + + is_cty = any(prompt in response for prompt in (b"Username:", b"Password:", b"cryptech>")) + + # Check whether we got something that looks like the response to an RPC version query. + # We skip over the version value itself, as it might change, but we check that it's + # terminated properly. This is fragile, and will need to handle SLIP decoding if + # we ever bump one of the version fields up into the range where the SLIP control + # characters live, but it will do for the moment. + + try: + is_hsm = response[response.index(SLIP_END + RPC_reply) + len(SLIP_END + RPC_reply) + 4] == SLIP_END[0] + except ValueError: + is_hsm = False + except IndexError: + is_hsm = False + + if is_cty and args.verbose: + sys.stderr.write("{} looks like the Cryptech HSM console port\n".format(port)) + + if is_hsm and args.verbose: + sys.stderr.write("{} looks like the Cryptech HSM RPC port\n".format(port)) + + if is_cty: + env.update(CRYPTECH_CTY_CLIENT_SERIAL_DEVICE = port) + + if is_hsm: + env.update(CRYPTECH_RPC_CLIENT_SERIAL_DEVICE = port) + + if (is_cty or is_hsm) and not args.no_cleanup: + if is_cty: + tty.write(Control_U) + if is_hsm: + tty.write(SLIP_END) + while tty.read(args.read_buffer_size): + pass + + tty.close() + +if env: + sys.stdout.write("export {}\n".format( + " ".join("{}='{}'".format(var, env[var]) for var in sorted(env)))) diff --git a/projects/hsm/cryptech_upload b/projects/hsm/cryptech_upload new file mode 100755 index 0000000..b40427d --- /dev/null +++ b/projects/hsm/cryptech_upload @@ -0,0 +1,385 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2016-2017, 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. + +""" +Utility to upload a new firmware image or FPGA bitstream. +""" + +import os +import sys +import time +import struct +import serial +import socket +import getpass +import os.path +import tarfile +import argparse +import platform + +from binascii import crc32, hexlify + +FIRMWARE_CHUNK_SIZE = 4096 +FPGA_CHUNK_SIZE = 4096 + + +def parse_args(): + """ + Parse the command line arguments + """ + + share_directory = "/usr/share" if platform.system() == "Linux" else "/usr/local/share" + + default_tarball = os.path.join(share_directory, "cryptech-alpha-firmware.tar.gz") + + if not os.path.exists(default_tarball): + default_tarball = None + + parser = argparse.ArgumentParser(description = __doc__, + formatter_class = argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument("-d", "--device", + default = os.getenv("CRYPTECH_CTY_CLIENT_SERIAL_DEVICE", "/dev/ttyUSB0"), + help = "Name of management port USB serial device", + ) + + parser.add_argument("--socket", + default = os.getenv("CRYPTECH_CTY_CLIENT_SOCKET_NAME", + "/tmp/.cryptech_muxd.cty"), + help = "Name of cryptech_muxd management port socket", + ) + + parser.add_argument("--firmware-tarball", + type = argparse.FileType("rb"), + default = default_tarball, + help = "Location of firmware tarball", + ) + + parser.add_argument("--username", + choices = ("so", "wheel"), + default = "so", + help = "Username to use when logging into the HSM", + ) + + parser.add_argument("--pin", + help = "PIN to use when logging into the HSM", + ) + + parser.add_argument("--separate-pins", + action = "store_true", + help = "Prompt separately for each PIN required during firmware upload") + + actions = parser.add_mutually_exclusive_group(required = True) + actions.add_argument("--fpga", + action = "store_true", + help = "Upload FPGA bitstream", + ) + actions.add_argument("--firmware", "--hsm", + action = "store_true", + help = "Upload HSM firmware image", + ) + actions.add_argument("--bootloader", + action = "store_true", + help = "Upload bootloader image (dangerous!)", + ) + + parser.add_argument("--simon-says-whack-my-bootloader", + action = "store_true", + help = "Confirm that you really want to risk bricking the HSM", + ) + + parser.add_argument("-i", "--explicit-image", + type = argparse.FileType("rb"), + help = "Explicit source image file for upload, overrides firmware tarball") + + parser.add_argument("--debug", + action = "store_true", + help = "Enable debugging of upload protocol", + ) + + parser.add_argument("-q", "--quiet", + action = "store_true", + help = "Only report errors", + ) + + return parser.parse_args() + + +class ManagementPortAbstract(object): + """ + Abstract class encapsulating actions on the HSM management port. + """ + + def __init__(self, args): + self.args = args + + def write(self, data): + numeric = isinstance(data, int) + if numeric: + data = struct.pack("<I", data) + self.send(data) + if self.args.debug: + if numeric: + print("Wrote 0x{}".format(hexlify(data).decode("ascii"))) + else: + print("Wrote {!r}".format(data)) + + def read(self): + res = b"" + x = self.recv() + while not x: + x = self.recv() + while x: + res += x + x = self.recv() + if self.args.debug: + print("Read {!r}".format(res)) + return res + + def execute(self, cmd): + self.write(b"\r") + prompt = self.read() + #if prompt.endswith("This is the bootloader speaking..."): + # prompt = self.read() + if prompt.endswith(b"Username: "): + self.write(self.args.username.encode("ascii") + b"\r") + prompt = self.read() + if prompt.endswith(b"Password: "): + if not self.args.pin or self.args.separate_pins: + self.args.pin = getpass.getpass("{} PIN: ".format(self.args.username)) + self.write(self.args.pin.encode("ascii") + b"\r") + prompt = self.read() + if not prompt.endswith((b"> ", b"# ")): + print("Device does not seem to be ready for a file transfer (got {!r})".format(prompt)) + return prompt + self.write(cmd + b"\r") + response = self.read() + return response + + +class ManagementPortSerial(ManagementPortAbstract): + """ + Implmentation of HSM management port abstraction over a direct + serial connection. + """ + + def __init__(self, args, timeout = 1): + super(ManagementPortSerial, self).__init__(args) + self.serial = serial.Serial(args.device, 921600, timeout = timeout) + + def send(self, data): + self.serial.write(data) + self.serial.flush() + + def recv(self): + return self.serial.read(1) + + def set_timeout(self, timeout): + self.serial.timeout = timeout + + def close(self): + self.serial.close() + +class ManagementPortSocket(ManagementPortAbstract): + """ + Implmentation of HSM management port abstraction over a PF_UNIX + socket connection to the cryptech_muxd management socket. + """ + + def __init__(self, args, timeout = 1): + super(ManagementPortSocket, self).__init__(args) + self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.socket.connect(args.socket) + self.socket.settimeout(timeout) + + def send(self, data): + self.socket.sendall(data) + + def recv(self): + try: + return self.socket.recv(1) + except socket.timeout: + return b"" + + def set_timeout(self, timeout): + self.socket.settimeout(timeout) + + def close(self): + self.socket.close() + + +def send_file(src, size, args, dst): + """ + Upload an image from some file-like source to the management port. + Details depend on what kind of image it is. + """ + + if args.fpga: + chunk_size = FPGA_CHUNK_SIZE + response = dst.execute(b"fpga bitstream upload") + elif args.firmware: + chunk_size = FIRMWARE_CHUNK_SIZE + response = dst.execute(b"firmware upload") + if b"Rebooting" in response: + response = dst.execute(b"firmware upload") + elif args.bootloader: + chunk_size = FIRMWARE_CHUNK_SIZE + response = dst.execute(b"bootloader upload") + if b"Access denied" in response: + print("Access denied") + return False + if not b"OK" in response: + print("Device did not accept the upload command (got {!r})".format(response)) + return False + + dst.set_timeout(0.001) + crc = 0 + counter = 0 + # 1. Write size of file (4 bytes) + dst.write(struct.pack("<I", size)) + response = dst.read() + if not response.startswith(b"Send "): + print(response) + return False + + # 2. Write file contents while calculating CRC-32 + chunks = int((size + chunk_size - 1) / chunk_size) + for counter in range(chunks): + data = src.read(chunk_size) + dst.write(data) + if not args.quiet: + print("Wrote {!s} bytes (chunk {!s}/{!s})".format(len(data), counter + 1, chunks)) + # read ACK (a counter of number of 4k chunks received) + ack_bytes = b"" + while len(ack_bytes) < 4: + ack_bytes += dst.read() + ack = struct.unpack("<I", ack_bytes[:4])[0] + if ack != counter + 1: + print("ERROR: Did not receive the expected counter as ACK (got {!r}/{!r}, not {!r})".format(ack, ack_bytes, counter)) + return False + counter += 1 + + crc = crc32(data, crc) & 0xffffffff + + # 3. Write CRC-32 (4 bytes) + dst.write(struct.pack("<I", crc)) + response = dst.read() + if not args.quiet: + print(response) + + src.close() + + if args.fpga: + # tell the fpga to read its new configuration + dst.execute(b"fpga reset") + # log out of the CLI + # (firmware/bootloader upgrades reboot, don't need an exit) + dst.execute(b"exit") + + return True + + +dire_bootloader_warning = ''' + WARNING + +Updating the bootloader risks bricking your HSM! If something goes +badly wrong here, or you upload a bad bootloader image, you will not +be able to recover without an ST-LINK programmer. + +In most cases a normal "--firmware" upgrade should be all that is +necessary to bring your HSM up to date, there is seldom any real need +to update the bootloader. + +Do not proceed with this unless you REALLY know what you are doing. + +If you got here by accident, ^C now, without answering the PIN prompt. +''' + + +def main(): + global args + args = parse_args() + + + if args.bootloader: + if not args.simon_says_whack_my_bootloader: + sys.exit("You didn't say \"Simon says\"") + print(dire_bootloader_warning) + args.pin = None + + if args.explicit_image is None and args.firmware_tarball is None: + sys.exit("No source file specified for upload and firmware tarball not found") + + if args.explicit_image: + src = args.explicit_image # file-like object, thanks to argparse + size = os.fstat(src.fileno()).st_size + if size == 0: # Flashing from stdin won't work, sorry + sys.exit("Can't flash from a pipe or zero-length file") + if not args.quiet: + print("Uploading from explicitly-specified file {}".format(args.explicit_image.name)) + + else: + tar = tarfile.open(fileobj = args.firmware_tarball) + if not args.quiet: + print("Firmware tarball {} content:".format(args.firmware_tarball.name)) + tar.list(True) + if args.fpga: + name = "alpha_fmc.bit" + elif args.firmware: + name = "hsm.bin" + elif args.bootloader: + name = "bootloader.bin" + else: + # Somebody updated other part of this script without updating this part :( + sys.exit("Don't know which component to select from firmware tarball, sorry") + try: + size = tar.getmember(name).size + except KeyError: + sys.exit("Expected component {} missing from firmware tarball {}".format(name, args.firmware_tarball.name)) + src = tar.extractfile(name) + if not args.quiet: + print("Uploading {} from {}".format(name, args.firmware_tarball.name)) + + if not args.quiet: + print("Initializing management port and synchronizing with HSM, this may take a few seconds") + try: + dst = ManagementPortSocket(args, timeout = 1) + except socket.error as e: + dst = ManagementPortSerial(args, timeout = 1) + send_file(src, size, args, dst) + dst.close() + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + pass diff --git a/projects/hsm/hsm.c b/projects/hsm/hsm.c new file mode 100644 index 0000000..52157c9 --- /dev/null +++ b/projects/hsm/hsm.c @@ -0,0 +1,522 @@ +/* + * hsm.c + * ---------------- + * Main module for the HSM project. + * + * Copyright (c) 2016-2017, 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. + */ + +/* + * This is the main RPC server module. At the moment, it has a single + * worker thread to handle RPC requests, while the main thread handles CLI + * activity. The design allows for multiple worker threads to handle + * concurrent RPC requests from multiple clients (muxed through a daemon + * on the host). + */ + +#include <string.h> + +/* Rename both CMSIS HAL_OK and libhal HAL_OK to disambiguate */ +#define HAL_OK CMSIS_HAL_OK +#include "stm-init.h" +#include "stm-led.h" +#include "stm-fmc.h" +#include "stm-uart.h" +#include "stm-sdram.h" +#include "task.h" + +#include "mgmt-cli.h" + +#undef HAL_OK +#define HAL_OK LIBHAL_OK +#include "hal.h" +#include "hal_internal.h" +#include "slip_internal.h" +#include "xdr_internal.h" +#undef HAL_OK + +#ifndef NUM_RPC_TASK +#define NUM_RPC_TASK 1 +#elif NUM_RPC_TASK < 1 || NUM_RPC_TASK > 10 +#error invalid NUM_RPC_TASK +#endif + +#ifndef TASK_STACK_SIZE +/* Define an absurdly large task stack, because some pkey operation use a + * lot of stack variables. This has to go in SDRAM, because it exceeds the + * total RAM on the ARM. + */ +#define TASK_STACK_SIZE 200*1024 +#endif + +/* Stack for the busy task. This doesn't need to be very big. + */ +#ifndef BUSY_STACK_SIZE +#define BUSY_STACK_SIZE 1*1024 +#endif +static uint8_t busy_stack[BUSY_STACK_SIZE]; + +/* Stack for the CLI task. This needs to be big enough to accept a + * 4096-byte block of an FPGA or bootloader image upload. + */ +#ifndef CLI_STACK_SIZE +#define CLI_STACK_SIZE 16*1024 +#endif + +/* RPC buffers. For each active request, there will be two - input and output. + */ +typedef struct rpc_buffer_s { + size_t len; + uint8_t buf[HAL_RPC_MAX_PKT_SIZE]; + struct rpc_buffer_s *next; /* for ibuf queue linking */ +} rpc_buffer_t; + +/* RPC input (requst) buffers */ +static rpc_buffer_t *ibufs; + +/* ibuf queue structure */ +typedef struct { + rpc_buffer_t *head, *tail; + size_t len, max; /* for reporting */ +} ibufq_t; + +/* ibuf queues. These correspond roughly to task states - 'waiting' is for + * unallocated ibufs, while 'ready' is for requests that are ready to be + * processed. + */ +static ibufq_t ibuf_waiting, ibuf_ready; + +/* Get an ibuf from a queue. */ +static rpc_buffer_t *ibuf_get(ibufq_t *q) +{ + hal_critical_section_start(); + rpc_buffer_t *ibuf = q->head; + if (ibuf) { + q->head = ibuf->next; + if (q->head == NULL) + q->tail = NULL; + ibuf->next = NULL; + --q->len; + } + hal_critical_section_end(); + return ibuf; +} + +/* Put an ibuf on a queue. */ +static void ibuf_put(ibufq_t *q, rpc_buffer_t *ibuf) +{ + hal_critical_section_start(); + if (q->tail) + q->tail->next = ibuf; + else + q->head = ibuf; + q->tail = ibuf; + ibuf->next = NULL; + if (++q->len > q->max) + q->max = q->len; + hal_critical_section_end(); +} + +/* Get the current length of the 'ready' queue, for reporting in the CLI. */ +size_t request_queue_len(void) +{ + size_t n; + + hal_critical_section_start(); + n = ibuf_ready.len; + hal_critical_section_end(); + + return n; +} + +/* Get the maximum length of the 'ready' queue, for reporting in the CLI. */ +size_t request_queue_max(void) +{ + size_t n; + + hal_critical_section_start(); + n = ibuf_ready.max; + hal_critical_section_end(); + + return n; +} + +static void dispatch_task(void); +static void busy_task(void); +static tcb_t *busy_tcb; + +/* Select an available dispatch task. For simplicity, this doesn't try to + * allocate tasks in a round-robin fashion, so the lowest-numbered task + * will see the most action. OTOH, this lets us gauge the level of system + * activity in the CLI's 'task show' command. + */ +static tcb_t *task_next_waiting(void) +{ + for (tcb_t *t = task_iterate(NULL); t; t = task_iterate(t)) { + if (task_get_func(t) == dispatch_task && + task_get_state(t) == TASK_WAITING) + return t; + } + return NULL; +} + +static uint8_t *sdram_malloc(size_t size); + +/* Callback for HAL_UART_Receive_DMA(). + */ +static void RxCallback(uint8_t c) +{ + int complete; + static rpc_buffer_t *ibuf = NULL; + + /* If we couldn't previously get an ibuf, a task may have freed one up + * in the meantime. Otherwise, allocate one from SDRAM. In normal + * operation, the number of ibufs will expand to the number of remote + * clients (which we don't know and can't predict). It would take an + * active attempt to DOS the system to exhaust SDRAM, and there are + * easier ways to attack the device (don't release hash or pkey handles). + */ + if (ibuf == NULL) { + ibuf = ibuf_get(&ibuf_waiting); + if (ibuf == NULL) { + ibuf = (rpc_buffer_t *)sdram_malloc(sizeof(rpc_buffer_t)); + if (ibuf == NULL) + Error_Handler(); + } + ibuf->len = 0; + } + + /* Process this character into the ibuf. */ + if (hal_slip_process_char(c, ibuf->buf, &ibuf->len, sizeof(ibuf->buf), &complete) != LIBHAL_OK) + Error_Handler(); + + if (complete) { + /* Add the ibuf to the request queue, and try to get another ibuf. + */ + ibuf_put(&ibuf_ready, ibuf); + ibuf = ibuf_get(&ibuf_waiting); + if (ibuf != NULL) + ibuf->len = 0; + /* else all ibufs are busy, try again next time */ + + /* Wake a dispatch task to deal with this request, or wake the + * busy task to re-try scheduling a dispatch task. + */ + tcb_t *t = task_next_waiting(); + if (t) + task_wake(t); + else + task_wake(busy_tcb); + } +} + +/* A ring buffer for the UART DMA receiver. In theory, it should get at most + * 92 characters per 1ms tick, but we're going to up-size it for safety. + */ +#ifndef RPC_UART_RECVBUF_SIZE +#define RPC_UART_RECVBUF_SIZE 1024 /* must be a power of 2 */ +#endif +#define RPC_UART_RECVBUF_MASK (RPC_UART_RECVBUF_SIZE - 1) + +typedef struct { + uint32_t ridx; + uint8_t buf[RPC_UART_RECVBUF_SIZE]; +} uart_ringbuf_t; + +volatile uart_ringbuf_t uart_ringbuf = {0, {0}}; + +#define RINGBUF_RIDX(rb) (rb.ridx & RPC_UART_RECVBUF_MASK) +#define RINGBUF_WIDX(rb) (sizeof(rb.buf) - __HAL_DMA_GET_COUNTER(huart_user.hdmarx)) +#define RINGBUF_COUNT(rb) ((RINGBUF_WIDX(rb) - RINGBUF_RIDX(rb)) & RPC_UART_RECVBUF_MASK) +#define RINGBUF_READ(rb, dst) {dst = rb.buf[RINGBUF_RIDX(rb)]; rb.ridx++;} + +size_t uart_rx_max = 0; + +void HAL_SYSTICK_Callback(void) +{ +#ifdef DO_PROFILING + extern void profil_callback(void); + profil_callback(); +#endif + + size_t count = RINGBUF_COUNT(uart_ringbuf); + if (uart_rx_max < count) uart_rx_max = count; + + while (RINGBUF_COUNT(uart_ringbuf)) { + uint8_t c; + RINGBUF_READ(uart_ringbuf, c); + RxCallback(c); + } +} + +/* Send one character over the UART. This is called from + * hal_slip_send_char(). + */ +hal_error_t hal_serial_send_char(uint8_t c) +{ + return (uart_send_char2(STM_UART_USER, c) == 0) ? LIBHAL_OK : HAL_ERROR_RPC_TRANSPORT; +} + +/* Task entry point for the RPC request handler. + */ +static void dispatch_task(void) +{ + rpc_buffer_t obuf_s, *obuf = &obuf_s; + + while (1) { + /* Wait for a complete RPC request */ + task_sleep(); + + rpc_buffer_t *ibuf = ibuf_get(&ibuf_ready); + if (ibuf == NULL) + /* probably an error, but go back to sleep */ + continue; + + memset(obuf, 0, sizeof(*obuf)); + obuf->len = sizeof(obuf->buf); + + /* Process the request */ + hal_error_t ret = hal_rpc_server_dispatch(ibuf->buf, ibuf->len, obuf->buf, &obuf->len); + ibuf_put(&ibuf_waiting, ibuf); + if (ret == LIBHAL_OK) { + /* Send the response */ + if (hal_rpc_sendto(obuf->buf, obuf->len, NULL) != LIBHAL_OK) + Error_Handler(); + } + /* Else hal_rpc_server_dispatch failed with an XDR error, which + * probably means the request packet was garbage. In any case, we + * have nothing to transmit. + */ + } +} + +/* Task entry point for the task-rescheduling task. + */ +static void busy_task(void) +{ + while (1) { + /* Wake as many tasks as we have requests. + */ + size_t n; + for (n = request_queue_len(); n > 0; --n) { + tcb_t *t; + if ((t = task_next_waiting()) != NULL) + task_wake(t); + else + break; + } + if (n == 0) + /* flushed the queue, our work here is done */ + task_sleep(); + else + /* more work to do, try again after some tasks have run */ + task_yield(); + } +} + +#include "stm-fpgacfg.h" + +static void hashsig_restart_task(void) +{ + /* wait for the fpga to configure itself on cold-boot */ + while (fpgacfg_check_done() != CMSIS_HAL_OK) + task_yield(); + + /* reinitialize the hashsig key structures after a device restart */ + hal_hashsig_ks_init(); + + /* done, convert this task to an RPC handler */ + task_mod((char *)task_get_cookie(NULL), dispatch_task, NULL); +} + +/* end of variables declared with __attribute__((section(".sdram1"))) */ +extern uint8_t _esdram1 __asm ("_esdram1"); +/* end of SDRAM1 section */ +extern uint8_t __end_sdram1 __asm ("__end_sdram1"); +static uint8_t *sdram_heap = &_esdram1; + +/* Allocate memory from SDRAM1. */ +static uint8_t *sdram_malloc(size_t size) +{ + uint8_t *p = sdram_heap; + +#define pad(n) (((n) + 3) & ~3) + size = pad(size); + + if (p + size + sizeof(uint32_t) > &__end_sdram1) + return NULL; + + *(uint32_t *)p = (uint32_t)size; + p += sizeof(uint32_t); + + sdram_heap += size + sizeof(uint32_t); + return p; +} + +/* A very limited form of free(), which only frees memory if it's at the + * top of the heap. + */ +static hal_error_t sdram_free(uint8_t *ptr) +{ + uint8_t *p = ptr - sizeof(uint32_t); + uint32_t size = *(uint32_t *)p; + if (ptr + size == sdram_heap) { + sdram_heap = p; + return LIBHAL_OK; + } + else + return HAL_ERROR_FORBIDDEN; +} + +hal_error_t sdram_stats(size_t *used, size_t *available) +{ + if (used == NULL || available == NULL) + return HAL_ERROR_BAD_ARGUMENTS; + + *used = sdram_heap - &_esdram1; + *available = &__end_sdram1 - sdram_heap; + + return LIBHAL_OK; +} + +/* Implement static memory allocation for libhal over sdram_malloc(). + */ +void *hal_allocate_static_memory(const size_t size) +{ + return sdram_malloc(size); +} + +hal_error_t hal_free_static_memory(const void * const ptr) +{ + return sdram_free((uint8_t *)ptr); +} + +/* Critical section start/end - temporarily disable interrupts. + */ +void hal_critical_section_start(void) +{ + __disable_irq(); +} + +void hal_critical_section_end(void) +{ + __enable_irq(); +} + +/* A genericized public interface to task_yield(), for calling from + * libhal. + */ +void hal_task_yield(void) +{ + task_yield(); +} + +void hal_task_yield_maybe(void) +{ + task_yield_maybe(); +} + +/* A mutex to arbitrate concurrent access to the keystore. + */ +task_mutex_t ks_mutex = { 0 }; +void hal_ks_lock(void) { task_mutex_lock(&ks_mutex); } +void hal_ks_unlock(void) { task_mutex_unlock(&ks_mutex); } + +/* A mutex to arbitrary concurrent access to the RSA blinding factors cache. + */ +task_mutex_t rsa_bf_mutex = { 0 }; +void hal_rsa_bf_lock(void) { task_mutex_lock(&rsa_bf_mutex); } +void hal_rsa_bf_unlock(void) { task_mutex_unlock(&rsa_bf_mutex); } + +/* Sleep for specified number of seconds. + */ +void hal_sleep(const unsigned seconds) { task_delay(seconds * 1000); } + +/* The main task. This does all the setup, and the worker tasks handle + * the rest. + */ +int main(void) +{ + stm_init(); + led_on(LED_GREEN); + + if (hal_rpc_server_init() != LIBHAL_OK) + Error_Handler(); + + /* Initialize the ibuf queues. */ + ibufs = (rpc_buffer_t *)sdram_malloc(NUM_RPC_TASK * sizeof(rpc_buffer_t)); + if (ibufs == NULL) + Error_Handler(); + memset(ibufs, 0, NUM_RPC_TASK * sizeof(rpc_buffer_t)); + memset(&ibuf_waiting, 0, sizeof(ibuf_waiting)); + memset(&ibuf_ready, 0, sizeof(ibuf_ready)); + for (size_t i = 0; i < NUM_RPC_TASK; ++i) + ibuf_put(&ibuf_waiting, &ibufs[i]); + + /* Create the rpc dispatch worker tasks. */ + static char label[NUM_RPC_TASK][sizeof("dispatch0")]; + for (int i = 0; i < NUM_RPC_TASK; ++i) { + sprintf(label[i], "dispatch%d", i); + void *stack = (void *)sdram_malloc(TASK_STACK_SIZE); + if (stack == NULL) + Error_Handler(); + if (i == NUM_RPC_TASK - 1) { + if (task_add("hashsig_restart", hashsig_restart_task, label[i], stack, TASK_STACK_SIZE) == NULL) + Error_Handler(); + } + else { + if (task_add(label[i], dispatch_task, NULL, stack, TASK_STACK_SIZE) == NULL) + Error_Handler(); + } + } + + /* Create the busy task. */ + busy_tcb = task_add("busy", busy_task, NULL, busy_stack, sizeof(busy_stack)); + if (busy_tcb == NULL) + Error_Handler(); + + /* Start the UART receiver. */ + if (HAL_UART_Receive_DMA(&huart_user, (uint8_t *) uart_ringbuf.buf, sizeof(uart_ringbuf.buf)) != CMSIS_HAL_OK) + Error_Handler(); + + /* Launch other tasks (csprng warm-up task?) + * Wait for FPGA_DONE interrupt. + */ + + /* Create the CLI task. */ + void *cli_stack = (void *)sdram_malloc(CLI_STACK_SIZE); + if (task_add("cli", (funcp_t)cli_main, NULL, cli_stack, CLI_STACK_SIZE) == NULL) + Error_Handler(); + + /* Start the tasker */ + task_yield(); + + /*NOTREACHED*/ + return 0; +} diff --git a/projects/hsm/log.c b/projects/hsm/log.c new file mode 100644 index 0000000..fbc0e73 --- /dev/null +++ b/projects/hsm/log.c @@ -0,0 +1,68 @@ +/* + * log.c + * ----- + * Implement libhal logging API on Alpha. + * + * Copyright (c) 2017, 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. + */ + +#include <stdio.h> +#include <stdarg.h> + +#define HAL_OK CMSIS_HAL_OK +#include "stm-uart.h" +#undef HAL_OK + +#define HAL_OK LIBHAL_OK +#include "hal.h" +#include "hal_internal.h" +#undef HAL_OK + +static hal_log_level_t current_log_level; + +void hal_log_set_level(const hal_log_level_t level) +{ + current_log_level = level; +} + +void hal_log(const hal_log_level_t level, const char *format, ...) +{ + if (level < current_log_level) + return; + + char buffer[2048]; + va_list ap; + + va_start(ap, format); + vsnprintf(buffer, sizeof(buffer), format, ap); + va_end(ap); + + uart_send_string(buffer); + uart_send_string("\r\n"); +} diff --git a/projects/hsm/main.c b/projects/hsm/main.c deleted file mode 100644 index 79c567b..0000000 --- a/projects/hsm/main.c +++ /dev/null @@ -1,226 +0,0 @@ -/* - * rpc_server.c - * ------------ - * Remote procedure call server-side private API implementation. - * - * Copyright (c) 2016, 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. - */ - -/* - * This is the main RPC server moddule. It creates a new thread to deal - * with each request, to prevent a long-running request (e.g. RSA keygen) - * from blocking independent requests from other clients. This has a - * number of consequences. We can't do a blocking receive in the main - * thread, because that prevents the dispatch thread from transmitting the - * response (because they both want to lock the UART - see - * stm32f4xx_hal_uart.c). So we have to do a non-blocking receive with a - * callback routine. But we can't create a thread from the callback - * routine, because it's in the context of an ISR, so we raise a semaphore - * for the main thread to create the dispatch thread. - */ - -#include <string.h> - -#include "cmsis_os.h" - -#include "stm-init.h" -#include "stm-led.h" -#include "stm-fmc.h" -#include "stm-uart.h" - -/* stm32f4xx_hal_def.h and hal.h both define HAL_OK as an enum value */ -#define HAL_OK HAL_OKAY - -#include "hal.h" -#include "hal_internal.h" -#include "slip_internal.h" -#include "xdr_internal.h" - -/* RPC buffers. For each active RPC, there will be two - input and output. - */ - -#ifndef NUM_RPC_BUFFER -/* An arbitrary number, but we don't expect to have more than 8 concurrent - * RPC requests. - */ -#define NUM_RPC_BUFFER 16 -#endif - -#ifndef MAX_PKT_SIZE -/* Another arbitrary number, more or less driven by the 4096-bit RSA - * keygen test. - */ -#define MAX_PKT_SIZE 4096 -#endif - -/* The thread entry point takes a single void* argument, so we bundle the - * packet buffer and length arguments together. - */ -typedef struct { - size_t len; - uint8_t buf[MAX_PKT_SIZE]; -} rpc_buffer_t; - -osPoolDef(rpc_buffer_pool, NUM_RPC_BUFFER, rpc_buffer_t); -osPoolId rpc_buffer_pool; - -static rpc_buffer_t *rpc_buffer_alloc(void) -{ - return (rpc_buffer_t *)osPoolCAlloc(rpc_buffer_pool); -} - -/* A mutex to arbitrate concurrent UART transmits, from RPC responses. - */ -osMutexId uart_mutex; -osMutexDef(uart_mutex); - -/* Thread entry point for the RPC request handler. - */ -static void dispatch_thread(void const *args) -{ - rpc_buffer_t *ibuf = (rpc_buffer_t *)args; - rpc_buffer_t *obuf = rpc_buffer_alloc(); - if (obuf == NULL) { - uint8_t buf[8]; - uint8_t * bufptr = &buf[4]; - const uint8_t * const limit = buf + sizeof(buf); - memcpy(buf, ibuf->buf, 4); - hal_xdr_encode_int(&bufptr, limit, HAL_ERROR_ALLOCATION_FAILURE); - osMutexWait(uart_mutex, osWaitForever); - hal_rpc_sendto(ibuf->buf, sizeof(buf), NULL); - osMutexRelease(uart_mutex); - osPoolFree(rpc_buffer_pool, ibuf); - Error_Handler(); - } - /* copy client ID from request to response */ - memcpy(obuf->buf, ibuf->buf, 4); - obuf->len = sizeof(obuf->buf) - 4; - hal_rpc_server_dispatch(ibuf->buf + 4, ibuf->len - 4, obuf->buf + 4, &obuf->len); - osPoolFree(rpc_buffer_pool, ibuf); - osMutexWait(uart_mutex, osWaitForever); - hal_error_t ret = hal_rpc_sendto(obuf->buf, obuf->len + 4, NULL); - osMutexRelease(uart_mutex); - osPoolFree(rpc_buffer_pool, obuf); - if (ret != HAL_OK) - Error_Handler(); -} -osThreadDef(dispatch_thread, osPriorityNormal, DEFAULT_STACK_SIZE); - -/* Semaphore to inform the main thread that there's a new RPC request. - */ -osSemaphoreId rpc_sem; -osSemaphoreDef(rpc_sem); - -static uint8_t c; /* current character received from UART */ -static rpc_buffer_t *ibuf; /* current RPC input buffer */ - -/* Callback for HAL_UART_Receive_IT(). - */ -void HAL_UART2_RxCpltCallback(UART_HandleTypeDef *huart) -{ - int complete; - hal_slip_recv_char(ibuf->buf, &ibuf->len, sizeof(ibuf->buf), &complete); - if (complete) - osSemaphoreRelease(rpc_sem); - - HAL_UART_Receive_IT(huart, &c, 1); -} - -hal_error_t hal_serial_send_char(uint8_t c) -{ - return (uart_send_char(c) == 0) ? HAL_OK : HAL_ERROR_RPC_TRANSPORT; -} - -hal_error_t hal_serial_recv_char(uint8_t *cp) -{ - /* return the character from HAL_UART_Receive_IT */ - *cp = c; - return HAL_OK; -} - -/* The main thread. After the system setup, it waits for the RPC-request - * semaphore from HAL_UART_RxCpltCallback, and spawns a dispatch thread. - */ -int main() -{ - stm_init(); - -#ifdef TARGET_CRYPTECH_DEV_BRIDGE - /* Wait six seconds to not upset the Novena at boot. */ - led_on(LED_BLUE); - for (int i = 0; i < 12; i++) { - osDelay(500); - led_toggle(LED_BLUE); - } - led_off(LED_BLUE); -#endif - led_on(LED_GREEN); - /* Prepare FMC interface. */ - fmc_init(); - - /* Haaaack. probe_cores() calls malloc(), which works from the main - * thread, but not from a spawned thread. It would be better to - * rewrite it to use static memory, but for now, just force it to - * probe early. - */ - hal_core_iterate(NULL); - - rpc_buffer_pool = osPoolCreate(osPool(rpc_buffer_pool)); - uart_mutex = osMutexCreate(osMutex(uart_mutex)); - rpc_sem = osSemaphoreCreate(osSemaphore(rpc_sem), 0); - -#ifdef TARGET_CRYPTECH_ALPHA - /* Launch other threads: - * - admin thread on USART1 - * - csprng warm-up thread? - */ -#endif - - if (hal_rpc_server_init() != HAL_OK) - Error_Handler(); - - ibuf = rpc_buffer_alloc(); - if (ibuf == NULL) - /* Something is badly wrong. */ - Error_Handler(); - - /* Start the non-blocking receive */ - HAL_UART_Receive_IT(&huart_user, &c, 1); - - while (1) { - osSemaphoreWait(rpc_sem, osWaitForever); - if (osThreadCreate(osThread(dispatch_thread), (void *)ibuf) == NULL) - Error_Handler(); - while ((ibuf = rpc_buffer_alloc()) == NULL); - /* XXX There's a potential race condition, where another request - * could write into the old ibuf, or into the null pointer if - * we're out of ibufs. - */ - } -} diff --git a/projects/hsm/mgmt-bootloader.c b/projects/hsm/mgmt-bootloader.c new file mode 100644 index 0000000..1d8b8ad --- /dev/null +++ b/projects/hsm/mgmt-bootloader.c @@ -0,0 +1,89 @@ +/* + * mgmt-bootloader.c + * ----------------- + * CLI code for updating the bootloader. + * + * Copyright (c) 2016, 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. + */ + +/* Rename both CMSIS HAL_OK and libhal HAL_OK to disambiguate */ +#define HAL_OK CMSIS_HAL_OK +#include "stm-init.h" +#include "stm-uart.h" +#include "stm-flash.h" +#include "mgmt-cli.h" +#include "mgmt-misc.h" +#include "mgmt-bootloader.h" + +#undef HAL_OK +#define HAL_OK LIBHAL_OK +#include "hal.h" +#undef HAL_OK + +extern hal_user_t user; + +static uint32_t dfu_offset; + +static HAL_StatusTypeDef _flash_write_callback(uint8_t *buf, size_t len) +{ + HAL_StatusTypeDef status = stm_flash_write32(dfu_offset, (uint32_t *)buf, len/4); + dfu_offset += DFU_UPLOAD_CHUNK_SIZE; + return status; +} + +static int cmd_bootloader_upload(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + argv = argv; + argc = argc; + + if (user < HAL_USER_SO) { + cli_print(cli, "Permission denied."); + return CLI_ERROR; + } + + uint8_t buf[DFU_UPLOAD_CHUNK_SIZE]; + dfu_offset = DFU_BOOTLOADER_ADDR; + + int ret = cli_receive_data(cli, buf, sizeof(buf), _flash_write_callback); + if (ret == CLI_OK) { + cli_print(cli, "\nRebooting\n"); + HAL_NVIC_SystemReset(); + } + return ret; +} + +void configure_cli_bootloader(struct cli_def *cli) +{ + struct cli_command *c; + + c = cli_register_command(cli, NULL, "bootloader", NULL, 0, 0, NULL); + + cli_register_command(cli, c, "upload", cmd_bootloader_upload, 0, 0, "Upload new bootloader image"); +} diff --git a/projects/hsm/mgmt-bootloader.h b/projects/hsm/mgmt-bootloader.h new file mode 100644 index 0000000..31dbefc --- /dev/null +++ b/projects/hsm/mgmt-bootloader.h @@ -0,0 +1,51 @@ +/* + * mgmt-bootloader.h + * --------------- + * Management CLI bootloader upgrade code. + * + * Copyright (c) 2016, 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. + */ + +#ifndef __STM32_CLI_MGMT_BOOTLOADER_H +#define __STM32_CLI_MGMT_BOOTLOADER_H + +#include <libcli.h> + +/* symbols defined in the linker script (STM32F429BI_bootloader.ld) */ +extern uint32_t CRYPTECH_BOOTLOADER_START; +extern uint32_t CRYPTECH_BOOTLOADER_END; +extern uint32_t CRYPTECH_DFU_CONTROL; + +#define DFU_BOOTLOADER_ADDR ((uint32_t) &CRYPTECH_BOOTLOADER_START) +#define DFU_BOOTLOADER_END_ADDR ((uint32_t) &CRYPTECH_BOOTLOADER_END) +#define DFU_UPLOAD_CHUNK_SIZE 4096 + +extern void configure_cli_bootloader(struct cli_def *cli); + +#endif /* __STM32_CLI_MGMT_BOOTLOADER_H */ diff --git a/projects/hsm/mgmt-cli.c b/projects/hsm/mgmt-cli.c new file mode 100644 index 0000000..fd5c90a --- /dev/null +++ b/projects/hsm/mgmt-cli.c @@ -0,0 +1,220 @@ +/* + * mgmt-cli.c + * --------- + * Management CLI code. + * + * Copyright (c) 2016-2017, NORDUnet A/S All rights reserved. + * Copyright: 2020, The Commons Conservancy Cryptech Project + * SPDX-License-Identifier: BSD-3-Clause + * + * 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 copyright holder 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. + */ + +#include <string.h> + +/* Rename both CMSIS HAL_OK and libhal HAL_OK to disambiguate */ +#define HAL_OK CMSIS_HAL_OK +#include "stm-init.h" +#include "stm-uart.h" +#include "stm-led.h" +#include "task.h" + +#include "mgmt-cli.h" +#include "mgmt-firmware.h" +#include "mgmt-bootloader.h" +#include "mgmt-fpga.h" +#include "mgmt-misc.h" +#include "mgmt-keystore.h" +#include "mgmt-masterkey.h" +#include "mgmt-task.h" +#ifdef DO_TIMING +#include "mgmt-timing.h" +#endif + +#undef HAL_OK +#define HAL_OK LIBHAL_OK +#include "hal.h" +#warning Refactor so we do not need to include hal_internal.h here +#include "hal_internal.h" +#undef HAL_OK + +static tcb_t *cli_task; + +#ifndef CLI_UART_RECVBUF_SIZE +#define CLI_UART_RECVBUF_SIZE 256 +#endif + +typedef struct { + unsigned ridx; + unsigned widx; + mgmt_cli_dma_state_t rx_state; + uint8_t buf[CLI_UART_RECVBUF_SIZE]; +} ringbuf_t; + +inline void ringbuf_init(ringbuf_t *rb) +{ + memset(rb, 0, sizeof(*rb)); +} + +/* return number of characters read */ +inline int ringbuf_read_char(ringbuf_t *rb, uint8_t *c) +{ + if (rb->ridx != rb->widx) { + *c = rb->buf[rb->ridx]; + if (++rb->ridx >= sizeof(rb->buf)) + rb->ridx = 0; + return 1; + } + return 0; +} + +inline void ringbuf_write_char(ringbuf_t *rb, uint8_t c) +{ + rb->buf[rb->widx] = c; + if (++rb->widx >= sizeof(rb->buf)) + rb->widx = 0; +} + +static ringbuf_t uart_ringbuf; + +/* current character received from UART */ +static uint8_t uart_rx; + +/* Callback for HAL_UART_Receive_DMA(). + */ +void HAL_UART1_RxCpltCallback(UART_HandleTypeDef *huart) +{ + huart = huart; + + ringbuf_write_char(&uart_ringbuf, uart_rx); + task_wake(cli_task); +} + +static void uart_cli_print(struct cli_def *cli __attribute__ ((unused)), const char *buf) +{ + char crlf[] = "\r\n"; + uart_send_string(buf); + uart_send_string(crlf); +} + +static ssize_t uart_cli_read(struct cli_def *cli __attribute__ ((unused)), void *buf, size_t count) +{ + for (size_t i = 0; i < count; ++i) { + while (ringbuf_read_char(&uart_ringbuf, (uint8_t *)(buf + i)) == 0) + task_sleep(); + } + return (ssize_t)count; +} + +static ssize_t uart_cli_write(struct cli_def *cli __attribute__ ((unused)), const void *buf, size_t count) +{ + uart_send_bytes((uint8_t *) buf, count); + return (ssize_t)count; +} + +int control_mgmt_uart_dma_rx(mgmt_cli_dma_state_t state) +{ + if (state == DMA_RX_START) { + if (uart_ringbuf.rx_state != DMA_RX_START) { + ringbuf_init(&uart_ringbuf); + HAL_UART_Receive_DMA(&huart_mgmt, &uart_rx, 1); + uart_ringbuf.rx_state = DMA_RX_START; + } + return 1; + } else if (state == DMA_RX_STOP) { + if (HAL_UART_DMAStop(&huart_mgmt) != CMSIS_HAL_OK) return 0; + uart_ringbuf.rx_state = DMA_RX_STOP; + return 1; + } + return 0; +} + +hal_user_t user; + +static int check_auth(const char *username, const char *password) +{ + hal_client_handle_t client = { -1 }; + + /* PIN-based login */ + if (strcmp(username, "wheel") == 0) + user = HAL_USER_WHEEL; + else if (strcmp(username, "so") == 0) + user = HAL_USER_SO; + else if (strcmp(username, "user") == 0) + user = HAL_USER_NORMAL; + else + user = HAL_USER_NONE; + + if (hal_rpc_login(client, user, password, strlen(password)) == LIBHAL_OK) + return CLI_OK; + + user = HAL_USER_NONE; + return CLI_ERROR; +} + +int cli_main(void) +{ + cli_task = task_get_tcb(); + + struct cli_def *cli; + cli = cli_init(); + if (cli == NULL) + Error_Handler(); + + cli_read_callback(cli, uart_cli_read); + cli_write_callback(cli, uart_cli_write); + cli_print_callback(cli, uart_cli_print); + cli_set_banner(cli, "Cryptech Alpha"); + cli_set_hostname(cli, "cryptech"); + cli_set_auth_callback(cli, check_auth); + + /* we don't have any privileged commands at the moment */ + cli_unregister_command(cli, "enable"); + + configure_cli_fpga(cli); + configure_cli_keystore(cli); + configure_cli_masterkey(cli); + configure_cli_firmware(cli); + configure_cli_bootloader(cli); + configure_cli_misc(cli); + configure_cli_task(cli); +#ifdef DO_TIMING + configure_cli_timing(cli); +#endif + + while (1) { + control_mgmt_uart_dma_rx(DMA_RX_START); + + cli_loop(cli, 0); + /* cli_loop returns when the user enters 'quit' or 'exit' */ + cli_print(cli, "\nLogging out...\n"); + user = HAL_USER_NONE; + } + + /*NOTREACHED*/ + return -1; +} diff --git a/projects/hsm/mgmt-cli.h b/projects/hsm/mgmt-cli.h new file mode 100644 index 0000000..0b9c40c --- /dev/null +++ b/projects/hsm/mgmt-cli.h @@ -0,0 +1,49 @@ +/* + * mgmt-cli.h + * --------- + * Management CLI code. + * + * Copyright (c) 2016, 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. + */ + +#ifndef __STM32_MGMT_CLI_H +#define __STM32_MGMT_CLI_H + +#include <libcli.h> + +typedef enum { + DMA_RX_STOP, + DMA_RX_START, +} mgmt_cli_dma_state_t; + +extern int control_mgmt_uart_dma_rx(mgmt_cli_dma_state_t state); + +extern int cli_main(void); + +#endif /* __STM32_MGMT_CLI_H */ diff --git a/projects/hsm/mgmt-firmware.c b/projects/hsm/mgmt-firmware.c new file mode 100644 index 0000000..b6b3321 --- /dev/null +++ b/projects/hsm/mgmt-firmware.c @@ -0,0 +1,75 @@ +/* + * mgmt-firmware.c + * --------------- + * CLI code for managing the loaded firmware. + * + * Copyright (c) 2016, 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. + */ + +/* Rename both CMSIS HAL_OK and libhal HAL_OK to disambiguate */ +#define HAL_OK CMSIS_HAL_OK +#include "stm-init.h" +#include "stm-uart.h" + +#include "mgmt-cli.h" + +#undef HAL_OK +#define HAL_OK LIBHAL_OK +#include "hal.h" +#undef HAL_OK + +extern hal_user_t user; + +static int cmd_firmware_upload(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + argv = argv; + argc = argc; + + if (user < HAL_USER_SO) { + cli_print(cli, "Permission denied."); + return CLI_ERROR; + } + + /* reboot and let the bootloader handle the upload */ + cli_print(cli, "\n\n\nRebooting\n\n\n"); + HAL_NVIC_SystemReset(); + + /*NOTREACHED*/ + return CLI_OK; +} + +void configure_cli_firmware(struct cli_def *cli) +{ + struct cli_command *c; + + c = cli_register_command(cli, NULL, "firmware", NULL, 0, 0, NULL); + + cli_register_command(cli, c, "upload", cmd_firmware_upload, 0, 0, "Upload new firmware image"); +} diff --git a/projects/hsm/mgmt-firmware.h b/projects/hsm/mgmt-firmware.h new file mode 100644 index 0000000..af7c67c --- /dev/null +++ b/projects/hsm/mgmt-firmware.h @@ -0,0 +1,42 @@ +/* + * mgmt-firmware.h + * --------------- + * Management CLI Device Firmware Upgrade code. + * + * Copyright (c) 2016, 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. + */ + +#ifndef __STM32_CLI_MGMT_FIRMWARE_H +#define __STM32_CLI_MGMT_FIRMWARE_H + +#include <libcli.h> + +extern void configure_cli_firmware(struct cli_def *cli); + +#endif /* __STM32_CLI_MGMT_FIRMWARE_H */ diff --git a/projects/hsm/mgmt-fpga.c b/projects/hsm/mgmt-fpga.c new file mode 100644 index 0000000..af7ba11 --- /dev/null +++ b/projects/hsm/mgmt-fpga.c @@ -0,0 +1,194 @@ +/* + * mgmt-fpga.c + * ----------- + * CLI code to manage the FPGA configuration etc. + * + * Copyright (c) 2016-2017, 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. + */ + +/* Rename both CMSIS HAL_OK and libhal HAL_OK to disambiguate */ +#define HAL_OK CMSIS_HAL_OK +#include "stm-init.h" +#include "stm-uart.h" +#include "stm-fpgacfg.h" + +#include "mgmt-cli.h" +#include "mgmt-fpga.h" +#include "mgmt-misc.h" + +#undef HAL_OK +#define HAL_OK LIBHAL_OK +#include "hal.h" +#undef HAL_OK + +#include <string.h> + + +extern hal_user_t user; + +static volatile uint32_t dfu_offset = 0; + + +static HAL_StatusTypeDef _flash_write_callback(uint8_t *buf, size_t len) +{ + HAL_StatusTypeDef res; + + if ((dfu_offset % FPGACFG_SECTOR_SIZE) == 0) + /* first page in sector, need to erase sector */ + if ((res = fpgacfg_erase_sector(dfu_offset / FPGACFG_SECTOR_SIZE)) != CMSIS_HAL_OK) + return res; + + /* fpgacfg_write_data (a thin wrapper around n25q128_write_data) + * requires the offset and length to be page-aligned. The last chunk + * will be short, so we pad it out to the full chunk size. + */ + len = len; + res = fpgacfg_write_data(dfu_offset, buf, BITSTREAM_UPLOAD_CHUNK_SIZE); + dfu_offset += BITSTREAM_UPLOAD_CHUNK_SIZE; + return res; +} + +static int cmd_fpga_bitstream_upload(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + argv = argv; + argc = argc; + + if (user < HAL_USER_SO) { + cli_print(cli, "Permission denied."); + return CLI_ERROR; + } + + uint8_t buf[BITSTREAM_UPLOAD_CHUNK_SIZE]; + + dfu_offset = 0; + + fpgacfg_access_control(ALLOW_ARM); + + cli_print(cli, "Checking if FPGA config memory is accessible"); + if (fpgacfg_check_id() != CMSIS_HAL_OK) { + cli_print(cli, "ERROR: FPGA config memory not accessible. Check that jumpers JP7 and JP8 are installed."); + return CLI_ERROR; + } + + cli_receive_data(cli, &buf[0], sizeof(buf), _flash_write_callback); + + fpgacfg_access_control(ALLOW_FPGA); + + cli_print(cli, "DFU offset now: %li (%li chunks)", dfu_offset, dfu_offset / BITSTREAM_UPLOAD_CHUNK_SIZE); + return CLI_OK; +} + +static int cmd_fpga_bitstream_erase(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + argv = argv; + argc = argc; + + fpgacfg_access_control(ALLOW_ARM); + + cli_print(cli, "Checking if FPGA config memory is accessible"); + if (fpgacfg_check_id() != CMSIS_HAL_OK) { + cli_print(cli, "ERROR: FPGA config memory not accessible. Check that jumpers JP7 and JP8 are installed."); + return CLI_ERROR; + } + + /* Erasing the whole config memory takes a while, we just need to erase the first sector. + * The bitstream has an EOF marker, so even if the next bitstream uploaded is shorter than + * the current one there should be no problem. + * + * This command could be made to accept an argument indicating the whole memory should be erased. + */ + if (fpgacfg_erase_sector(0) != CMSIS_HAL_OK) { + cli_print(cli, "Erasing first sector in FPGA config memory failed"); + return CLI_ERROR; + } + + cli_print(cli, "Erased FPGA config memory"); + fpgacfg_access_control(ALLOW_FPGA); + + return CLI_OK; +} + +static int cmd_fpga_reset(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + argv = argv; + argc = argc; + + fpgacfg_access_control(ALLOW_FPGA); + fpgacfg_reset_fpga(RESET_FULL); + hal_core_reset_table(); + cli_print(cli, "FPGA has been reset"); + + return CLI_OK; +} + +static int cmd_fpga_show_cores(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + hal_core_t *core; + const hal_core_info_t *info; + + command = command; + argv = argv; + argc = argc; + + if (fpgacfg_check_done() != CMSIS_HAL_OK) { + cli_print(cli, "FPGA has not loaded a bitstream"); + return CLI_OK; + } + + for (core = hal_core_iterate(NULL); core != NULL; core = hal_core_iterate(core)) { + info = hal_core_info(core); + cli_print(cli, "%04x: %8.8s %4.4s", + (unsigned int)info->base, info->name, info->version); + } + + return CLI_OK; +} + +void configure_cli_fpga(struct cli_def *cli) +{ + struct cli_command *c = cli_register_command(cli, NULL, "fpga", NULL, 0, 0, NULL); + + struct cli_command *c_show = cli_register_command(cli, c, "show", NULL, 0, 0, NULL); + struct cli_command *c_bitstream = cli_register_command(cli, c, "bitstream", NULL, 0, 0, NULL); + + /* fpga show cores */ + cli_register_command(cli, c_show, "cores", cmd_fpga_show_cores, 0, 0, "Show FPGA core names and versions"); + + /* fpga reset */ + cli_register_command(cli, c, "reset", cmd_fpga_reset, 0, 0, "Reset FPGA (config reset)"); + + /* fpga bitstream upload */ + cli_register_command(cli, c_bitstream, "upload", cmd_fpga_bitstream_upload, 0, 0, "Upload new FPGA bitstream"); + + /* fpga bitstream erase */ + cli_register_command(cli, c_bitstream, "erase", cmd_fpga_bitstream_erase, 0, 0, "Erase FPGA config memory"); +} diff --git a/projects/hsm/mgmt-fpga.h b/projects/hsm/mgmt-fpga.h new file mode 100644 index 0000000..9d0aedc --- /dev/null +++ b/projects/hsm/mgmt-fpga.h @@ -0,0 +1,49 @@ +/* + * mgmt-fpga.h + * ----------- + * Management FPGA related code. + * + * Copyright (c) 2016, 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. + */ + +#ifndef __STM32_CLI_MGMT_FPGA_H +#define __STM32_CLI_MGMT_FPGA_H + +#include <libcli.h> + + +/* The chunk size have to be a multiple of the SPI flash page size (256 bytes), + and it has to match the chunk size in the program sending the bitstream over the UART. +*/ +#define BITSTREAM_UPLOAD_CHUNK_SIZE 4096 + + +extern void configure_cli_fpga(struct cli_def *cli); + +#endif /* __STM32_CLI_MGMT_FPGA_H */ diff --git a/projects/hsm/mgmt-keystore.c b/projects/hsm/mgmt-keystore.c new file mode 100644 index 0000000..9eb42da --- /dev/null +++ b/projects/hsm/mgmt-keystore.c @@ -0,0 +1,408 @@ +/* + * mgmt-keystore.c + * --------------- + * CLI 'keystore' commands. + * + * Copyright (c) 2016-2017, 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. + */ + +/* Rename both CMSIS HAL_OK and libhal HAL_OK to disambiguate */ +#define HAL_OK CMSIS_HAL_OK +#include "stm-init.h" +#include "stm-keystore.h" +#include "stm-fpgacfg.h" +#include "stm-uart.h" + +#include "mgmt-cli.h" + +#undef HAL_OK +#define LIBHAL_OK HAL_OK +#include "hal.h" +#warning Really should not be including hal_internal.h here, fix API instead of bypassing it +#include "hal_internal.h" +#undef HAL_OK + +#include <stdlib.h> +#include <string.h> +#include <strings.h> +#include <ctype.h> + + +static int cmd_keystore_set_pin(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + hal_user_t user; + hal_error_t status; + hal_client_handle_t client = { -1 }; + + command = command; + + if (argc != 2) { + cli_print(cli, "Wrong number of arguments (%i).", argc); + cli_print(cli, "Syntax: keystore set pin <user|so|wheel> <pin>"); + return CLI_ERROR; + } + + if (strcmp(argv[0], "user") == 0) + user = HAL_USER_NORMAL; + else if (strcmp(argv[0], "so") == 0) + user = HAL_USER_SO; + else if (strcmp(argv[0], "wheel") == 0) + user = HAL_USER_WHEEL; + else { + cli_print(cli, "First argument must be 'user', 'so' or 'wheel' - not '%s'", argv[0]); + return CLI_ERROR; + } + + status = hal_rpc_set_pin(client, user, argv[1], strlen(argv[1])); + if (status != LIBHAL_OK) { + cli_print(cli, "Failed setting PIN: %s", hal_error_string(status)); + return CLI_ERROR; + } + + return CLI_OK; +} + +static int cmd_keystore_clear_pin(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + hal_user_t user; + hal_error_t status; + hal_client_handle_t client = { -1 }; + + command = command; + + if (argc != 1) { + cli_print(cli, "Wrong number of arguments (%i).", argc); + cli_print(cli, "Syntax: keystore clear pin <user|so|wheel>"); + return CLI_ERROR; + } + + user = HAL_USER_NONE; + if (strcmp(argv[0], "user") == 0) + user = HAL_USER_NORMAL; + else if (strcmp(argv[0], "so") == 0) + user = HAL_USER_SO; + else if (strcmp(argv[0], "wheel") == 0) + user = HAL_USER_WHEEL; + else { + cli_print(cli, "First argument must be 'user', 'so' or 'wheel' - not '%s'", argv[0]); + return CLI_ERROR; + } + + if ((status = hal_rpc_set_pin(client, user, "", 0)) != LIBHAL_OK) { + cli_print(cli, "Failed clearing PIN: %s", hal_error_string(status)); + return CLI_ERROR; + } + + return CLI_OK; +} + +static int cmd_keystore_set_pin_iterations(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + hal_error_t status; + hal_client_handle_t client = { -1 }; + + command = command; + + if (argc != 1) { + cli_print(cli, "Wrong number of arguments (%i).", argc); + cli_print(cli, "Syntax: keystore set pin iterations <number>"); + return CLI_ERROR; + } + + status = hal_set_pin_default_iterations(client, strtoul(argv[0], NULL, 0)); + if (status != LIBHAL_OK) { + cli_print(cli, "Failed setting iterations: %s", hal_error_string(status)); + return CLI_ERROR; + } + + return CLI_OK; +} + +static int cmd_keystore_delete_key(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + const hal_client_handle_t client = { -1 }; + const hal_session_handle_t session = { HAL_HANDLE_NONE }; + hal_pkey_handle_t pkey = { HAL_HANDLE_NONE }; + hal_error_t status; + hal_uuid_t name; + + command = command; + + if (argc != 1) { + cli_print(cli, "Wrong number of arguments (%i).", argc); + cli_print(cli, "Syntax: keystore delete key <name>"); + return CLI_ERROR; + } + + if ((status = hal_uuid_parse(&name, argv[0])) != LIBHAL_OK) { + cli_print(cli, "Couldn't parse key name: %s", hal_error_string(status)); + return CLI_ERROR; + } + + if ((status = hal_rpc_pkey_open(client, session, &pkey, &name)) != LIBHAL_OK) { + cli_print(cli, "Couldn't find key: %s", hal_error_string(status)); + return CLI_ERROR; + } + + if ((status = hal_rpc_pkey_delete(pkey)) != LIBHAL_OK) { + cli_print(cli, "Failed deleting key: %s", hal_error_string(status)); + (void) hal_rpc_pkey_close(pkey); + return CLI_ERROR; + } + + cli_print(cli, "Deleted key %s", argv[0]); + + return CLI_OK; +} + +#include "ks.h" + +static int show_keys(struct cli_def *cli, const char *title) +{ + const hal_client_handle_t client = { -1 }; + const hal_session_handle_t session = { HAL_HANDLE_NONE }; + char key_name[HAL_UUID_TEXT_SIZE]; + hal_uuid_t previous_uuid = {{0}}; + hal_pkey_handle_t pkey; + hal_curve_name_t curve; + hal_key_flags_t flags; + unsigned n, state = 0; + hal_uuid_t uuids[50]; + hal_key_type_t type; + hal_error_t status; + int count = 0; + int done = 0; + + cli_print(cli, title); + + size_t avail; + if ((status = hal_ks_available(hal_ks_token, &avail)) == HAL_OK) + cli_print(cli, "Token keystore: %d available", avail); + else + cli_print(cli, "Error reading token keystore: %s", hal_error_string(status)); + if ((status = hal_ks_available(hal_ks_volatile, &avail)) == HAL_OK) + cli_print(cli, "Volatile keystore: %d available", avail); + else + cli_print(cli, "Error reading volatile keystore: %s", hal_error_string(status)); + + while (!done) { + + if ((status = hal_rpc_pkey_match(client, session, HAL_KEY_TYPE_NONE, HAL_CURVE_NONE, + 0, 0, NULL, 0, &state, uuids, &n, + sizeof(uuids)/sizeof(*uuids), + &previous_uuid)) != LIBHAL_OK) { + cli_print(cli, "Could not fetch UUID list: %s", hal_error_string(status)); + return CLI_ERROR; + } + + done = n < sizeof(uuids)/sizeof(*uuids); + + if (!done) + previous_uuid = uuids[sizeof(uuids)/sizeof(*uuids) - 1]; + + for (unsigned i = 0; i < n; i++) { + + if ((status = hal_uuid_format(&uuids[i], key_name, sizeof(key_name))) != LIBHAL_OK) { + cli_print(cli, "Could not convert key name, skipping: %s", + hal_error_string(status)); + continue; + } + + if ((status = hal_rpc_pkey_open(client, session, &pkey, &uuids[i])) != LIBHAL_OK) { + cli_print(cli, "Could not open key %s, skipping: %s", + key_name, hal_error_string(status)); + continue; + } + + if ((status = hal_rpc_pkey_get_key_type(pkey, &type)) != LIBHAL_OK || + (status = hal_rpc_pkey_get_key_curve(pkey, &curve)) != LIBHAL_OK || + (status = hal_rpc_pkey_get_key_flags(pkey, &flags)) != LIBHAL_OK) + cli_print(cli, "Could not fetch metadata for key %s, skipping: %s", + key_name, hal_error_string(status)); + + if (status == LIBHAL_OK) + status = hal_rpc_pkey_close(pkey); + else + (void) hal_rpc_pkey_close(pkey); + + if (status != LIBHAL_OK) + continue; + + const char *type_name = "unknown"; + switch (type) { + case HAL_KEY_TYPE_NONE: type_name = "none"; break; + case HAL_KEY_TYPE_RSA_PRIVATE: type_name = "RSA private"; break; + case HAL_KEY_TYPE_RSA_PUBLIC: type_name = "RSA public"; break; + case HAL_KEY_TYPE_EC_PRIVATE: type_name = "EC private"; break; + case HAL_KEY_TYPE_EC_PUBLIC: type_name = "EC public"; break; + case HAL_KEY_TYPE_HASHSIG_PRIVATE: type_name = "hashsig private"; break; + case HAL_KEY_TYPE_HASHSIG_PUBLIC: type_name = "hashsig public"; break; + case HAL_KEY_TYPE_HASHSIG_LMS: type_name = "hashsig lms"; break; + case HAL_KEY_TYPE_HASHSIG_LMOTS: type_name = "hashsig lmots"; break; + } + + const char *curve_name = "unknown"; + switch (curve) { + case HAL_CURVE_NONE: curve_name = "none"; break; + case HAL_CURVE_P256: curve_name = "P-256"; break; + case HAL_CURVE_P384: curve_name = "P-384"; break; + case HAL_CURVE_P521: curve_name = "P-521"; break; + } + + cli_print(cli, "Key %2i, name %s, type %s, curve %s, flags 0x%lx", + count++, key_name, type_name, curve_name, (unsigned long) flags); + } + } + + return CLI_OK; +} + +static int show_pin(struct cli_def *cli, char *label, hal_user_t user) +{ + const hal_ks_pin_t *p; + + if (hal_get_pin(user, &p) != HAL_OK) + return CLI_ERROR; + + /* + * I'm not sure iterations is the most interesting thing to show, but + * it's what we had before. + */ + + cli_print(cli, "%s iterations: 0x%lx", label, p->iterations); + return CLI_OK; +} + +static int cmd_keystore_show_keys(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + argv = argv; + argc = argc; + + int err = 0; + + err |= show_keys(cli, "Keystore:"); + + cli_print(cli, "\nPins:"); + err |= show_pin(cli, "Wheel", HAL_USER_WHEEL); + err |= show_pin(cli, "SO ", HAL_USER_SO); + err |= show_pin(cli, "User ", HAL_USER_NORMAL); + + return err ? CLI_ERROR : CLI_OK; +} + +static int cmd_keystore_erase(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + hal_error_t err; + HAL_StatusTypeDef status; + int preserve_PINs = 0; + + command = command; + + if (argc < 1 || argc > 2 || strcmp(argv[0], "YesIAmSure") != 0) { + usage: + cli_print(cli, "Syntax: keystore erase YesIAmSure [preservePINs]"); + return CLI_ERROR; + } + if (argc == 2) { + if (strcasecmp(argv[1], "preservePINs") != 0) + goto usage; + else + preserve_PINs = 1; + } + + hal_user_t users[3] = { HAL_USER_NORMAL, HAL_USER_SO, HAL_USER_WHEEL }; + hal_ks_pin_t pins[3]; + if (preserve_PINs) { + for (size_t i = 0; i < 3; ++i) { + const hal_ks_pin_t *pin; + if (hal_get_pin(users[i], &pin) != HAL_OK) { + cli_print(cli, "Failed to get the PINs"); + return CLI_ERROR; + } + memcpy(&pins[i], pin, sizeof(*pin)); + } + } + + cli_print(cli, "OK, erasing keystore, this will take about 45 seconds..."); + if ((status = keystore_erase_bulk()) != CMSIS_HAL_OK) { + cli_print(cli, "Failed erasing token keystore: %i", status); + return CLI_ERROR; + } + + if ((err = hal_ks_init(hal_ks_token, 0)) != LIBHAL_OK) { + cli_print(cli, "Failed to reinitialize token keystore: %s", hal_error_string(err)); + return CLI_ERROR; + } + + if ((err = hal_ks_init(hal_ks_volatile, 0)) != LIBHAL_OK) { + cli_print(cli, "Failed to reinitialize memory keystore: %s", hal_error_string(err)); + return CLI_ERROR; + } + + if (preserve_PINs) { + for (size_t i = 0; i < 3; ++i) { + if (hal_set_pin(users[i], &pins[i]) != HAL_OK) { + cli_print(cli, "Failed to restore the PINs"); + return CLI_ERROR; + } + } + } + + cli_print(cli, "Keystore erased"); + return CLI_OK; +} + +void configure_cli_keystore(struct cli_def *cli) +{ + struct cli_command *c = cli_register_command(cli, NULL, "keystore", NULL, 0, 0, NULL); + + struct cli_command *c_show = cli_register_command(cli, c, "show", NULL, 0, 0, NULL); + struct cli_command *c_set = cli_register_command(cli, c, "set", NULL, 0, 0, NULL); + struct cli_command *c_clear = cli_register_command(cli, c, "clear", NULL, 0, 0, NULL); + struct cli_command *c_delete = cli_register_command(cli, c, "delete", NULL, 0, 0, NULL); + + /* keystore show keys */ + cli_register_command(cli, c_show, "keys", cmd_keystore_show_keys, 0, 0, "Show what PINs and keys are in the keystore"); + + /* keystore set pin */ + struct cli_command *c_set_pin = cli_register_command(cli, c_set, "pin", cmd_keystore_set_pin, 0, 0, "Set either 'wheel', 'user' or 'so' PIN"); + + /* keystore set pin iterations */ + cli_register_command(cli, c_set_pin, "iterations", cmd_keystore_set_pin_iterations, 0, 0, "Set PBKDF2 iterations for PINs"); + + /* keystore clear pin */ + cli_register_command(cli, c_clear, "pin", cmd_keystore_clear_pin, 0, 0, "Clear either 'wheel', 'user' or 'so' PIN"); + + /* keystore delete key */ + cli_register_command(cli, c_delete, "key", cmd_keystore_delete_key, 0, 0, "Delete a key"); + + /* keystore erase */ + cli_register_command(cli, c, "erase", cmd_keystore_erase, 0, 0, "Erase the whole keystore"); +} diff --git a/projects/hsm/mgmt-keystore.h b/projects/hsm/mgmt-keystore.h new file mode 100644 index 0000000..9e14ac6 --- /dev/null +++ b/projects/hsm/mgmt-keystore.h @@ -0,0 +1,42 @@ +/* + * mgmt-keystore.h + * ---------- + * Management CLI 'keystore' functions. + * + * Copyright (c) 2016, 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. + */ + +#ifndef __STM32_CLI_MGMT_KEYSTORE_H +#define __STM32_CLI_MGMT_KEYSTORE_H + +#include <libcli.h> + +extern void configure_cli_keystore(struct cli_def *cli); + +#endif /* __STM32_CLI_MGMT_KEYSTORE_H */ diff --git a/projects/hsm/mgmt-masterkey.c b/projects/hsm/mgmt-masterkey.c new file mode 100644 index 0000000..97e62a0 --- /dev/null +++ b/projects/hsm/mgmt-masterkey.c @@ -0,0 +1,244 @@ +/* + * mgmt-masterkey.c + * ---------------- + * Masterkey CLI functions. + * + * Copyright (c) 2016, 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. + */ + +/* Rename both CMSIS HAL_OK and libhal HAL_OK to disambiguate */ +#define HAL_OK CMSIS_HAL_OK +#include "stm-init.h" +#include "stm-uart.h" +#include "mgmt-cli.h" +#include "mgmt-masterkey.h" + +#undef HAL_OK +#define LIBHAL_OK HAL_OK +#include <hal.h> +#warning Refactor so we do not need to include hal_internal.h here +#include <hal_internal.h> +#undef HAL_OK + +#include <stdlib.h> + +static char * _status2str(const hal_error_t status) +{ + switch (status) { + case LIBHAL_OK: + return (char *) "Set"; + case HAL_ERROR_MASTERKEY_NOT_SET: + return (char *) "Not set"; + default: + return (char *) "Unknown"; + } +} + +static int cmd_masterkey_status(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + hal_error_t status; + + command = command; + argv = argv; + argc = argc; + + cli_print(cli, "Status of master key:\n"); + + status = hal_keywrap_mkm_status(NULL); + cli_print(cli, " volatile: %s / %s", _status2str(status), hal_error_string(status)); + + status = hal_mkm_flash_read(NULL, 0); + cli_print(cli, " flash: %s / %s", _status2str(status), hal_error_string(status)); + + return CLI_OK; +} + +static int str_to_hex_digit(char c) +{ + if (c >= '0' && c <= '9') + c -= '0'; + else if (c >= 'a' && c <= 'f') + c = c - 'a' + 10; + else if (c >= 'A' && c <= 'F') + c = c - 'A' + 10; + else + return -1; + + return c; +} + +static inline char hex_to_str_digit(const uint8_t c) +{ + return (c < 10) ? ((char)c + '0') : ((char)c + 'A' - 10); +} + +static char *hexdump_kek(const uint8_t * const kek) +{ + /* This is only for dumping masterkey values, so has no length checks. + * Do not use it for anything else. + * + * For convenience of possibly hand-copying and hand-retyping, the key + * is divided into 8 4-byte (8-character) groups. + */ + + static char buf[2 * KEK_LENGTH + 8]; + char *dst = buf; + + for (size_t i = 0; i < KEK_LENGTH; ++i) { + uint8_t b = kek[i]; + *dst++ = hex_to_str_digit(b >> 4); + *dst++ = hex_to_str_digit(b & 0xf); + if ((i & 3) == 3) + *dst++ = ' '; + } + buf[sizeof(buf) - 1] = '\0'; + + return buf; +} + +static int _masterkey_set(struct cli_def *cli, char *argv[], int argc, + char *label, hal_error_t (*writer)(const uint8_t * const, const size_t)) +{ + uint8_t buf[KEK_LENGTH] = {0}; + hal_error_t err; + + if (argc == 0) { + /* fill master key with yummy randomness */ + if ((err = hal_get_random(NULL, buf, sizeof(buf))) != LIBHAL_OK) { + cli_print(cli, "Error getting random key: %s", hal_error_string(err)); + return CLI_ERROR; + } + cli_print(cli, "Random key:\n%s", hexdump_kek(buf)); + } + + else { + /* input is 32 hex bytes, arranged however the user wants */ + size_t len = 0; + for (int i = 0; i < argc; ++i) { + for (char *cp = argv[i]; *cp != '\0'; ) { + int c; + if ((c = str_to_hex_digit(*cp++)) < 0) + goto errout; + buf[len] = c << 4; + if ((c = str_to_hex_digit(*cp++)) < 0) + goto errout; + buf[len] |= c & 0xf; + if (++len > KEK_LENGTH) + goto errout; + } + } + if (len < KEK_LENGTH) { + errout: + cli_print(cli, "Failed parsing master key, expected exactly %d hex bytes", KEK_LENGTH); + return CLI_ERROR; + } + + cli_print(cli, "Parsed key:\n%s", hexdump_kek(buf)); + } + + if ((err = writer(buf, sizeof(buf))) == LIBHAL_OK) { + cli_print(cli, "Master key set in %s memory", label); + } else { + cli_print(cli, "Failed writing key to %s memory: %s", label, hal_error_string(err)); + } + return CLI_OK; +} + +static hal_error_t _mkm_volatile_write(const uint8_t *kek, const size_t kek_len) +{ + return hal_keywrap_mkm_write(NULL, kek, kek_len); +} + +static int cmd_masterkey_set(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + + return _masterkey_set(cli, argv, argc, "volatile", _mkm_volatile_write); +} + +static int cmd_masterkey_erase(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + hal_error_t err; + + command = command; + argv = argv; + argc = argc; + + if ((err = hal_keywrap_mkm_erase(NULL, KEK_LENGTH)) == LIBHAL_OK) { + cli_print(cli, "Erased master key from volatile memory"); + } else { + cli_print(cli, "Failed erasing master key from volatile memory: %s", hal_error_string(err)); + } + return CLI_OK; +} + +static int cmd_masterkey_unsecure_set(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + + return _masterkey_set(cli, argv, argc, "flash", hal_mkm_flash_write); +} + +static int cmd_masterkey_unsecure_erase(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + hal_error_t err; + + command = command; + argv = argv; + argc = argc; + + if ((err = hal_mkm_flash_erase(KEK_LENGTH)) == LIBHAL_OK) { + cli_print(cli, "Erased unsecure master key from flash"); + } else { + cli_print(cli, "Failed erasing unsecure master key from flash: %s", hal_error_string(err)); + } + return CLI_OK; +} + +void configure_cli_masterkey(struct cli_def *cli) +{ + struct cli_command *c = cli_register_command(cli, NULL, "masterkey", NULL, 0, 0, NULL); + + /* masterkey status */ + cli_register_command(cli, c, "status", cmd_masterkey_status, 0, 0, "Show status of master key in RAM/flash"); + + /* masterkey set */ + cli_register_command(cli, c, "set", cmd_masterkey_set, 0, 0, "Set the master key in the volatile Master Key Memory"); + + /* masterkey erase */ + cli_register_command(cli, c, "erase", cmd_masterkey_erase, 0, 0, "Erase the master key from the volatile Master Key Memory"); + + struct cli_command *c_unsecure = cli_register_command(cli, c, "unsecure", NULL, 0, 0, NULL); + + /* masterkey unsecure set */ + cli_register_command(cli, c_unsecure, "set", cmd_masterkey_unsecure_set, 0, 0, "Set master key in unprotected flash memory (if unsure, DON'T)"); + + /* masterkey unsecure erase */ + cli_register_command(cli, c_unsecure, "erase", cmd_masterkey_unsecure_erase, 0, 0, "Erase master key from unprotected flash memory"); +} diff --git a/projects/hsm/mgmt-masterkey.h b/projects/hsm/mgmt-masterkey.h new file mode 100644 index 0000000..67835e9 --- /dev/null +++ b/projects/hsm/mgmt-masterkey.h @@ -0,0 +1,42 @@ +/* + * mgmt-masterkey.h + * ----------- + * Management CLI masterkeyellaneous functions. + * + * Copyright (c) 2016, 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. + */ + +#ifndef __STM32_CLI_MGMT_MASTERKEY_H +#define __STM32_CLI_MGMT_MASTERKEY_H + +#include <libcli.h> + +extern void configure_cli_masterkey(struct cli_def *cli); + +#endif /* __STM32_CLI_MGMT_MASTERKEY_H */ diff --git a/projects/hsm/mgmt-misc.c b/projects/hsm/mgmt-misc.c new file mode 100644 index 0000000..377af73 --- /dev/null +++ b/projects/hsm/mgmt-misc.c @@ -0,0 +1,259 @@ +/* + * mgmt-misc.c + * ----------- + * Miscellaneous CLI functions. + * + * Copyright (c) 2016-2018, NORDUnet A/S All rights reserved. + * Copyright: 2020, The Commons Conservancy Cryptech Project + * SPDX-License-Identifier: BSD-3-Clause + * + * 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 copyright holder 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. + */ + +#define HAL_OK CMSIS_HAL_OK +#include "stm-init.h" +#include "stm-uart.h" +#include "mgmt-cli.h" +#include "mgmt-misc.h" +#undef HAL_OK + +#define HAL_OK LIBHAL_OK +#include "hal.h" +#include "hal_internal.h" +#undef HAL_OK + +#include <string.h> + + +int cli_receive_data(struct cli_def *cli, uint8_t *buf, size_t len, cli_data_callback data_callback) +{ + hal_crc32_t crc = 0, my_crc = hal_crc32_init(); + uint32_t filesize = 0, counter = 0; + size_t n = len; + + if (! control_mgmt_uart_dma_rx(DMA_RX_STOP)) { + cli_print(cli, "Failed stopping DMA"); + goto okay; + } + + cli_print(cli, "OK, write size (4 bytes), data in %li byte chunks, CRC-32 (4 bytes)", (uint32_t) n); + + if (uart_receive_bytes((void *) &filesize, sizeof(filesize), 2000) != CMSIS_HAL_OK) { + cli_print(cli, "Receive timed out"); + goto fail; + } + + cli_print(cli, "Send %li bytes of data", filesize); + + while (filesize) { + /* By initializing buf to the same value that erased flash has (0xff), we don't + * have to try and be smart when writing the last page of data to a flash memory. + */ + memset(buf, 0xff, len); + + if (filesize < n) n = filesize; + + if (uart_receive_bytes((void *) buf, n, 2000) != CMSIS_HAL_OK) { + cli_print(cli, "Receive timed out"); + goto fail; + } + filesize -= n; + my_crc = hal_crc32_update(my_crc, buf, n); + + /* After reception of a chunk but before ACKing we have "all" the time in the world to + * calculate CRC and invoke the data_callback. + */ + if (data_callback != NULL && data_callback(buf, n) != CMSIS_HAL_OK) { + cli_print(cli, "Data processing failed"); + goto okay; + } + + counter++; + uart_send_bytes((void *) &counter, 4); + } + + my_crc = hal_crc32_finalize(my_crc); + cli_print(cli, "Send CRC-32"); + uart_receive_bytes((void *) &crc, sizeof(crc), 2000); + cli_print(cli, "CRC-32 0x%x, calculated CRC 0x%x", (unsigned int) crc, (unsigned int) my_crc); + if (crc == my_crc) { + cli_print(cli, "CRC checksum MATCHED"); + } else { + cli_print(cli, "CRC checksum did NOT match"); + } + + okay: + control_mgmt_uart_dma_rx(DMA_RX_START); + return CLI_OK; + + fail: + control_mgmt_uart_dma_rx(DMA_RX_START); + return CLI_ERROR; +} + +#ifdef DO_PROFILING +static int cmd_profile_start(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + cli = cli; + command = command; + argv = argv; + argc = argc; + + extern uint32_t CRYPTECH_FIRMWARE_START; + extern char __etext; /* end of text/code symbol, defined by linker */ + extern void monstartup (size_t lowpc, size_t highpc); + monstartup((size_t)&CRYPTECH_FIRMWARE_START, (size_t)&__etext); + return CLI_OK; +} + +static int cmd_profile_stop(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + cli = cli; + command = command; + argv = argv; + argc = argc; + + extern void _mcleanup(void); + _mcleanup(); + return CLI_OK; +} + +#endif + +static int cmd_reboot(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + argv = argv; + argc = argc; + + cli_print(cli, "\n\n\nRebooting\n\n\n"); + HAL_NVIC_SystemReset(); + + /*NOTREACHED*/ + return CLI_OK; +} + +static int cmd_rsa_blinding(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + if (argc != 1) { + cli_print(cli, "Wrong number of arguments (%i).", argc); + cli_print(cli, "Syntax: %s <on|off|clear>", command); + return CLI_ERROR; + } + + if (strcmp(argv[0], "on") == 0) + hal_rsa_set_blinding(1); + else if (strcmp(argv[0], "off") == 0) + hal_rsa_set_blinding(0); + else if (strcmp(argv[0], "clear") == 0) + hal_rsa_clear_blinding_cache(); + else { + cli_print(cli, "Argument must be 'on', 'off', or 'clear' - not '%s'", argv[0]); + return CLI_ERROR; + } + + return CLI_OK; +} + +static int cmd_rsa_crt(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + int onoff; + + if (argc != 1) { + cli_print(cli, "Wrong number of arguments (%i).", argc); + cli_print(cli, "Syntax: %s <on|off>", command); + return CLI_ERROR; + } + + if (strcmp(argv[0], "on") == 0) + onoff = 1; + else if (strcmp(argv[0], "off") == 0) + onoff = 0; + else { + cli_print(cli, "Argument must be 'on' or 'off' - not '%s'", argv[0]); + return CLI_ERROR; + } + + hal_rsa_set_crt(onoff); + + return CLI_OK; +} + +static int cmd_rsa_modexpng(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + int onoff; + + if (argc != 1) { + cli_print(cli, "Wrong number of arguments (%i).", argc); + cli_print(cli, "Syntax: %s <on|off>", command); + return CLI_ERROR; + } + + if (strcmp(argv[0], "on") == 0) + onoff = 1; + else if (strcmp(argv[0], "off") == 0) + onoff = 0; + else { + cli_print(cli, "Argument must be 'on' or 'off' - not '%s'", argv[0]); + return CLI_ERROR; + } + + hal_error_t err; + if ((err = hal_modexp_use_modexpng(onoff)) == LIBHAL_OK) + return CLI_OK; + + cli_print(cli, hal_error_string(err)); + return CLI_ERROR; +} + +void configure_cli_misc(struct cli_def *cli) +{ +#ifdef DO_PROFILING + struct cli_command *c_profile = cli_register_command(cli, NULL, "profile", NULL, 0, 0, NULL); + + /* profile start */ + cli_register_command(cli, c_profile, "start", cmd_profile_start, 0, 0, "Start collecting profiling data"); + + /* profile stop */ + cli_register_command(cli, c_profile, "stop", cmd_profile_stop, 0, 0, "Stop collecting profiling data"); +#endif + + struct cli_command *c_rsa = cli_register_command(cli, NULL, "rsa", NULL, 0, 0, NULL); + + /* rsa blinding */ + cli_register_command(cli, c_rsa, "blinding", cmd_rsa_blinding, 0, 0, "Set use of RSA blinding"); + + /* rsa crt */ + cli_register_command(cli, c_rsa, "crt", cmd_rsa_crt, 0, 0, "Set use of RSA CRT"); + + /* rsa modexpng */ + cli_register_command(cli, c_rsa, "modexpng", cmd_rsa_modexpng, 0, 0, "Set use of ModExpNG"); + + /* reboot */ + cli_register_command(cli, NULL, "reboot", cmd_reboot, 0, 0, "Reboot the STM32"); +} + diff --git a/projects/hsm/mgmt-misc.h b/projects/hsm/mgmt-misc.h new file mode 100644 index 0000000..ef63a9e --- /dev/null +++ b/projects/hsm/mgmt-misc.h @@ -0,0 +1,47 @@ +/* + * mgmt-misc.h + * ----------- + * Management CLI miscellaneous functions. + * + * Copyright (c) 2016, 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. + */ + +#ifndef __STM32_CLI_MGMT_MISC_H +#define __STM32_CLI_MGMT_MISC_H + +#include <libcli.h> + +/* Write a chunk of received data to flash. */ +typedef HAL_StatusTypeDef (*cli_data_callback)(uint8_t *, size_t); + +extern int cli_receive_data(struct cli_def *cli, uint8_t *buf, size_t len, cli_data_callback data_callback); + +extern void configure_cli_misc(struct cli_def *cli); + +#endif /* __STM32_CLI_MGMT_MISC_H */ diff --git a/projects/hsm/mgmt-task.c b/projects/hsm/mgmt-task.c new file mode 100644 index 0000000..180c6d9 --- /dev/null +++ b/projects/hsm/mgmt-task.c @@ -0,0 +1,136 @@ +/* + * mgmt-task.c + * ----------- + * CLI 'task' functions. + * + * Copyright (c) 2016-2017, 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. + */ + +/* + * Show the active tasks. This is mostly for debugging, and looks deeply + * into OS-level structures, but sometimes you just need to know... + */ + +#include "mgmt-cli.h" +#include "mgmt-task.h" +#include "task.h" + +static char *task_state[] = { + "INIT", + "WAITING", + "READY" +}; + +extern size_t request_queue_len(void); +extern size_t request_queue_max(void); + +static int cmd_task_show(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + argv = argv; + argc = argc; + + cli_print(cli, "name state stack high water"); + cli_print(cli, "-------- -------- ----------------"); + + for (tcb_t *t = task_iterate(NULL); t != NULL; t = task_iterate(t)) { + cli_print(cli, "%-15s %-15s %d", + task_get_name(t), + task_state[task_get_state(t)], + task_get_stack_highwater(t)); + } + + cli_print(cli, " "); + cli_print(cli, "RPC request queue current length: %u", request_queue_len()); + cli_print(cli, "RPC request queue maximum length: %u", request_queue_max()); + + extern size_t uart_rx_max; + cli_print(cli, " "); + cli_print(cli, "UART receive queue maximum length: %u", uart_rx_max); + + size_t used, available; + extern void sdram_stats(size_t *used, size_t *available); + sdram_stats(&used, &available); + cli_print(cli, " "); + cli_print(cli, "SDRAM used: %u, available: %u", used, available); + + return CLI_OK; +} + +#ifdef DO_TASK_METRICS +static int cmd_task_show_metrics(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + command = command; + argv = argv; + argc = argc; + + struct task_metrics tm; + + task_get_metrics(&tm); + + cli_print(cli, "avg time between yields: %ld.%06ld sec", tm.avg.tv_sec, tm.avg.tv_usec); + cli_print(cli, "max time between yields: %ld.%06ld sec", tm.max.tv_sec, tm.max.tv_usec); + + return CLI_OK; +} + +static int cmd_task_reset_metrics(struct cli_def *cli, const char *command, char *argv[], int argc) +{ + cli = cli; + command = command; + argv = argv; + argc = argc; + + task_reset_metrics(); + + return CLI_OK; +} +#endif + +void configure_cli_task(struct cli_def *cli) +{ + struct cli_command *c = cli_register_command(cli, NULL, "task", NULL, 0, 0, NULL); + + /* task show */ +#ifdef DO_TASK_METRICS + struct cli_command *c_show = +#endif + cli_register_command(cli, c, "show", cmd_task_show, 0, 0, "Show the active tasks"); + +#ifdef DO_TASK_METRICS + /* task show metrics */ + cli_register_command(cli, c_show, "metrics", cmd_task_show_metrics, 0, 0, "Show task metrics"); + + /* task reset */ + struct cli_command *c_reset = cli_register_command(cli, c, "reset", NULL, 0, 0, NULL); + + /* task reset metrics */ + cli_register_command(cli, c_reset, "metrics", cmd_task_reset_metrics, 0, 0, "Reset task metrics"); +#endif +} diff --git a/projects/hsm/mgmt-task.h b/projects/hsm/mgmt-task.h new file mode 100644 index 0000000..f903962 --- /dev/null +++ b/projects/hsm/mgmt-task.h @@ -0,0 +1,42 @@ +/* + * mgmt-task.h + * ----------- + * Management CLI 'task' functions. + * + * Copyright (c) 2016-2017, 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. + */ + +#ifndef __STM32_CLI_MGMT_TASK_H +#define __STM32_CLI_MGMT_TASK_H + +#include <libcli.h> + +extern void configure_cli_task(struct cli_def *cli); + +#endif /* __STM32_CLI_MGMT_TASK_H */ |