aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRob Austein <sra@hactrn.net>2014-10-30 16:27:33 -0400
committerRob Austein <sra@hactrn.net>2014-10-30 16:27:33 -0400
commit43511ee91bbfc41dbe8e05aa3ff5d5de51adeb25 (patch)
tree65fb1f04403f464b6f0ec5a5bab085d43a38b038
Initial working version of cryptech_novena_i2c_{coretest,simple} HALs
in simplified version of Cryptlib build wrapper environment.
-rw-r--r--.gitignore3
-rw-r--r--GNUmakefile83
-rw-r--r--README.md77
-rw-r--r--dist/cl342.zipbin0 -> 5839450 bytes
-rw-r--r--src/cryptech_novena_i2c_coretest.c829
-rw-r--r--src/cryptech_novena_i2c_simple.c542
-rw-r--r--tests/test_hashes.py104
7 files changed, 1638 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a25d100
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+*~
+TAGS
+build
diff --git a/GNUmakefile b/GNUmakefile
new file mode 100644
index 0000000..aed7b4a
--- /dev/null
+++ b/GNUmakefile
@@ -0,0 +1,83 @@
+# Cryptech project makefile for Cryptlib. This is a work in progress.
+
+# The one thing that must be configured here is which Hardware
+# Adaption Layer ("HAL") to build into Cryptlib. Due to the need to
+# support different Cryptech configurations on different boards, it's
+# not really possible to provide a single HAL which supports all
+# Cryptech configurations in a sane way, so you have to pick one.
+# This makefile provides a default, but you can override it by
+# providing a value for the CRYPTECH_HAL makefile variable on the
+# command line, or by setting the CRYPTECH_HAL environment variable
+# (explicit argument overrides environment variable, see GNU make
+# documentation for details).
+
+ifndef CRYPTECH_HAL
+ CRYPTECH_HAL := src/cryptech_novena_i2c_simple.c
+endif
+
+# Notes on the option settings we use when building cryptlib:
+#
+# - Python extension modules need to be position-independent code. We
+# could handle this by building cryptlib as a shared library, but
+# for the moment it's simpler to force even the static library to
+# use position independent code. Works with gcc and clang, anyway,
+# which are the only compilers we care about at the moment.
+#
+# - Point of the exercise is a hardware device, and we want the full
+# set of SHA-2 digests.
+#
+# - See config.h for other options we might want to add here. In
+# particular, USE_ECDH, USE_ECDSA, and USE_GCM all touch on subjects
+# that came up during the early Cryptech design discussions.
+
+################################################################
+
+# From here down is not intended to be user-servicable. Tinker to
+# your heart's content, but don't complain if it breaks.
+
+LIB = build/libcl.a
+
+PYTHONPATH = $(firstword $(wildcard build/bindings/build/lib.*))
+
+all: build/makefile.ready
+ cd build; ${MAKE}
+ @${MAKE} python-bindings
+
+clean:
+ rm -rf build
+
+build/makefile.ready: GNUmakefile dist/cl342.zip
+ rm -rf build
+ mkdir build
+ cd build; unzip -a ../dist/cl342.zip
+ sed <build/makefile >build/makefile.cryptech \
+ -e 's=device/hw_dummy=../$(basename ${CRYPTECH_HAL})=g' \
+ -e 's=hw_dummy=$(notdir $(basename ${CRYPTECH_HAL}))=g' \
+ -e '/^CFLAGS/s=$$= -fPIC -DUSE_SHA2_EXT -DUSE_HARDWARE -DUSE_DEVICES='
+ mv build/makefile.cryptech build/makefile
+ touch $@
+
+ifeq (,${PYTHONPATH})
+
+ python-bindings:
+ cd build/bindings; python setup.py build
+
+else
+
+ python-bindings: ${PYTHONPATH}/cryptlib_py.so
+
+ ${PYTHONPATH}/cryptlib_py.so: ${LIB}
+ cd build/bindings; python setup.py build --force
+
+endif
+
+test: all
+ @${MAKE} run-tests
+
+run-tests:
+ for script in tests/*.py; do echo Running $$script; PYTHONPATH=${PYTHONPATH} python $$script; done
+
+tags: TAGS
+
+TAGS: build/makefile.ready
+ find src build -type f -name '*.[ch]' | etags -
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..5ff675d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,77 @@
+cryptlib
+========
+
+## Introduction ##
+
+This is a port of Peter Gutmann's
+[cryptlib package](https://www.cs.auckland.ac.nz/~pgut001/cryptlib/)
+to the Cryptech project's environment. This is a work in progress,
+and still at a very early stage as of this writing.
+
+The main addition to the stock cryptlib environment is a set of
+Hardware Adaption Layer (HAL) implementations that use the Cryptech
+FPGA cores.
+
+While we expect to be making more significant use of cryptlib in the
+future, the main purposes of this code at the moment are
+proof-of-concept and connecting the Cryptech cores to a more complete
+cryptographic programming environment for testing and development
+purposes.
+
+## Current status ##
+
+At present, the Cryptech HAL code runs only on the Novena PVT1. There
+are two variants of the HAL, both using the I2C bus, but speaking
+different protocols:
+
+* An implementation using the `coretest` byte-stream protocol
+ implemented by the `core/novena` FPGA build.
+
+* An implementation using the simpler interface implemented by the
+ `core/novena_i2c_simple` environment.
+
+Both of these HAL implementations are in the `src/` directory. See
+the `GNUmakefile` for details on how to select the variant you want.
+
+At present, the only relevant Cryptech cores are the TRNG and several
+digest algorithms. The current HAL uses the SHA-1, SHA-256, and
+SHA-512 cores to implement the SHA-1, SHA-256, SHA-384, and SHA-512
+digests. SHA-512/224 and SHA-512/256 are not supported.
+
+The TRGN is not yet supported, due to lack of an I2C interface. At
+some point we will either add an I2C interface to the TRNG or skip
+over I2C entirely and go straight to EIM.
+
+In principal there is no reason why one could not write a HAL which
+spoke to a Terasic board, perhaps via the `coretest` protocol over a
+UART, but to date this has not been done.
+
+## Code import status ##
+
+Cryptlib itself is present in the repository in the form of a verbatim
+copy of the Cryptlib 3.4.2 distribution zipfile, which the top-level
+makefile unpacks while building. This has proven simpler to work with
+than importing the entire Cryptlib distribution into a vendor branch.
+
+Packaging Cryptlib this way has two implications:
+
+* You may need to `apt-get install unzip` on your Novena.
+
+* Any changes you might make to Cryptlib itself will be lost when you
+ run `make clean`.
+
+## Test code ##
+
+The `tests/` directory contains an initial test script, written in
+Python, using the standard Cryptlib Python bindings. The Cryptlib
+Python environment is a fairly literaly translation of the Cryptlib C
+environment, so portions of it will be a bit, um, surprising to Python
+programmers, but the basic functionality works.
+
+## Copyright status ##
+
+Cryptlib itself is copyright by Peter Gutmann. See the Cryptlib web
+site for licensing details.
+
+Code written for the Cryptech project is under the usual Cryptech
+BSD-style license.
diff --git a/dist/cl342.zip b/dist/cl342.zip
new file mode 100644
index 0000000..1d24e0e
--- /dev/null
+++ b/dist/cl342.zip
Binary files differ
diff --git a/src/cryptech_novena_i2c_coretest.c b/src/cryptech_novena_i2c_coretest.c
new file mode 100644
index 0000000..31b4345
--- /dev/null
+++ b/src/cryptech_novena_i2c_coretest.c
@@ -0,0 +1,829 @@
+/*
+ * cryptech_novena_i2c_coretest.c
+ * ------------------------------
+ *
+ * This is an early prototype Hardware Adaption Layer (HAL) for using
+ * Cryptlib with the Cryptech project's FGPA cores over an I2C bus on
+ * the Novena PVT1 development board using the "coretest" byte stream
+ * protocol. This is compatible with the core/novena FPGA build.
+ *
+ * The communication channel used here is not suitable for production
+ * use, this is just a prototype.
+ *
+ * Authors: Joachim Strömbergson, Paul Selkirk, Rob Austein
+ * Copyright (c) 2014, SUNET
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. 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.
+ *
+ * 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 OWNER 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.
+ *
+ * The HAL framework is taken from the Cryptlib hw_dummy.c template,
+ * and is Copyright 1998-2009 by Peter Gutmann.
+ */
+
+#include <assert.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+
+#if defined( INC_ALL )
+ #include "crypt.h"
+ #include "context.h"
+ #include "hardware.h"
+#else
+ #include "crypt.h"
+ #include "context/context.h"
+ #include "device/hardware.h"
+#endif /* Compiler-specific includes */
+
+/*
+ * I2C_SLAVE comes from /usr/include/linux/i2c-dev.h, but if we
+ * include that we won't be able to compile this except on Linux. It
+ * won't *run* anywhere but on Linux, but it's useful to be able to do
+ * compilation tests on other platforms, eg, with Clang, so for now we
+ * take the small risk that this one magic constant might change.
+ */
+
+#define I2C_SLAVE 0x0703
+
+
+#ifdef USE_HARDWARE
+
+/*
+ * I2C-related parameters, copied from hash_tester.c
+ */
+
+/* I2C configuration */
+#define I2C_DEV "/dev/i2c-2"
+#define I2C_ADDR 0x0f
+
+/* command codes */
+#define SOC 0x55
+#define EOC 0xaa
+#define READ_CMD 0x10
+#define WRITE_CMD 0x11
+#define RESET_CMD 0x01
+
+/* response codes */
+#define SOR 0xaa
+#define EOR 0x55
+#define READ_OK 0x7f
+#define WRITE_OK 0x7e
+#define RESET_OK 0x7d
+#define UNKNOWN 0xfe
+#define ERROR 0xfd
+
+/* addresses and codes common to all hash cores */
+#define ADDR_NAME0 0x00
+#define ADDR_NAME1 0x01
+#define ADDR_VERSION 0x02
+#define ADDR_CTRL 0x08
+#define CTRL_INIT_CMD 1
+#define CTRL_NEXT_CMD 2
+#define ADDR_STATUS 0x09
+#define STATUS_READY_BIT 0
+#define STATUS_VALID_BIT 1
+
+/*
+ * Addresses and codes for the specific hash cores.
+ * Lengths here are in bytes (not bits, not 32-bit words).
+ */
+
+#define SHA1_ADDR_PREFIX 0x10
+#define SHA1_ADDR_BLOCK 0x10
+#define SHA1_BLOCK_LEN bitsToBytes(512)
+#define SHA1_LENGTH_LEN bitsToBytes(64)
+#define SHA1_ADDR_DIGEST 0x20
+#define SHA1_DIGEST_LEN bitsToBytes(160)
+
+#define SHA256_ADDR_PREFIX 0x20
+#define SHA256_ADDR_BLOCK 0x10
+#define SHA256_BLOCK_LEN bitsToBytes(512)
+#define SHA256_LENGTH_LEN bitsToBytes(64)
+#define SHA256_ADDR_DIGEST 0x20
+#define SHA256_DIGEST_LEN bitsToBytes(256)
+
+#define SHA512_ADDR_PREFIX 0x30
+#define SHA512_CTRL_MODE_LOW 2
+#define SHA512_CTRL_MODE_HIGH 3
+#define SHA512_ADDR_BLOCK 0x10
+#define SHA512_BLOCK_LEN bitsToBytes(1024)
+#define SHA512_LENGTH_LEN bitsToBytes(128)
+#define SHA512_ADDR_DIGEST 0x40
+#define SHA384_DIGEST_LEN bitsToBytes(384)
+#define SHA512_DIGEST_LEN bitsToBytes(512)
+#define MODE_SHA_512_224 (0 << SHA512_CTRL_MODE_LOW)
+#define MODE_SHA_512_256 (1 << SHA512_CTRL_MODE_LOW)
+#define MODE_SHA_384 (2 << SHA512_CTRL_MODE_LOW)
+#define MODE_SHA_512 (3 << SHA512_CTRL_MODE_LOW)
+
+/* Longest digest block we support at the moment */
+#define MAX_BLOCK_LEN SHA512_BLOCK_LEN
+
+/* Hash state */
+typedef struct {
+ unsigned long long msg_length_high; /* Total data hashed in this message */
+ unsigned long long msg_length_low; /* (128 bits in SHA-512 cases) */
+ size_t block_length; /* Block length for this algorithm */
+ unsigned char block[MAX_BLOCK_LEN]; /* Block we're accumulating */
+ size_t block_used; /* How much of the block we've used */
+ unsigned block_count; /* Blocks sent */
+} hash_state_t;
+
+static int i2cfd = -1;
+static int debug = 0;
+
+/*
+ * I2C low-level code
+ */
+
+static int i2c_open(void)
+{
+ if (i2cfd >= 0)
+ return 1;
+
+ i2cfd = open(I2C_DEV, O_RDWR);
+
+ if (i2cfd < 0) {
+ perror("Unable to open " I2C_DEV);
+ i2cfd = -1;
+ return 0;
+ }
+
+ if (ioctl(i2cfd, I2C_SLAVE, I2C_ADDR) < 0) {
+ perror("Unable to set i2c slave device");
+ return 0;
+ }
+
+ if (debug)
+ fprintf(stderr, "[ Opened %s, fd %d ]\n", I2C_DEV, i2cfd);
+
+ return 1;
+}
+
+static int i2c_write_bytes(const unsigned char *buf, const size_t len)
+{
+ if (debug) {
+ int i;
+ fprintf(stderr, "write [");
+ for (i = 0; i < len; ++i)
+ fprintf(stderr, " %02x", buf[i]);
+ fprintf(stderr, " ]\n");
+ }
+
+ if (!i2c_open())
+ return 0;
+
+ if (write(i2cfd, buf, len) != len) {
+ perror("i2c write failed");
+ return 0;
+ }
+
+ return 1;
+}
+
+static int i2c_read_byte(unsigned char *b)
+{
+ /*
+ * read() on the i2c device only returns one byte at a time,
+ * and we need to parse the response one byte at a time anyway.
+ */
+
+ if (!i2c_open())
+ return 0;
+
+ if (read(i2cfd, b, 1) != 1) {
+ perror("i2c read failed");
+ return 0;
+ }
+
+ return 1;
+}
+
+static int i2c_send_write_cmd(const unsigned char addr0, const unsigned char addr1, const unsigned char data[])
+{
+ unsigned char buf[9];
+
+ buf[0] = SOC;
+ buf[1] = WRITE_CMD;
+ buf[2] = addr0;
+ buf[3] = addr1;
+ buf[4] = data[0];
+ buf[5] = data[1];
+ buf[6] = data[2];
+ buf[7] = data[3];
+ buf[8] = EOC;
+
+ return i2c_write_bytes(buf, sizeof(buf));
+}
+
+static int i2c_send_read_cmd(const unsigned char addr0, const unsigned char addr1)
+{
+ unsigned char buf[5];
+
+ buf[0] = SOC;
+ buf[1] = READ_CMD;
+ buf[2] = addr0;
+ buf[3] = addr1;
+ buf[4] = EOC;
+
+ return i2c_write_bytes(buf, sizeof(buf));
+}
+
+static int i2c_get_resp(unsigned char *buf, const size_t length)
+{
+ int i, len = length;
+
+ for (i = 0; i < len; ++i) {
+ assert(len <= length); /* Paranoia */
+
+ if (!i2c_read_byte(&buf[i]))
+ return 0;
+
+ switch (i) { /* Special handling for certain positions in response */
+
+ case 0:
+ if (buf[i] == SOR) /* Start of record (we hope) */
+ continue;
+ fprintf(stderr, "Lost sync: expected 0x%02x (SOR), got 0x%02x\n", SOR, buf[0]);
+ return 0;
+
+ case 1: /* Response code */
+ switch (buf[i]) {
+ case READ_OK:
+ len = 9;
+ continue;
+ case WRITE_OK:
+ len = 5;
+ continue;
+ case RESET_OK:
+ len = 3;
+ continue;
+ case ERROR:
+ case UNKNOWN:
+ len = 4;
+ continue;
+ default:
+ fprintf(stderr, "Lost sync: unknown response code 0x%02x\n", buf[i]);
+ return 0;
+ }
+ }
+ }
+
+ if (debug) {
+ fprintf(stderr, "read [");
+ for (i = 0; i < len; ++i)
+ fprintf(stderr, " %02x", buf[i]);
+ fprintf(stderr, " ]\n");
+ }
+
+ return 1;
+}
+
+static int i2c_check_expected(const unsigned char buf[], const int i, const unsigned char expected)
+{
+ if (buf[i] == expected)
+ return 1;
+ fprintf(stderr, "Response byte %d: expected 0x%02x, got 0x%02x\n", i, expected, buf[i]);
+ return 0;
+}
+
+static int i2c_write(const unsigned char addr0, const unsigned char addr1, const unsigned char data[])
+{
+ unsigned char buf[5];
+
+ if (!i2c_send_write_cmd(addr0, addr1, data) ||
+ !i2c_get_resp(buf, sizeof(buf)) ||
+ !i2c_check_expected(buf, 0, SOR) ||
+ !i2c_check_expected(buf, 1, WRITE_OK) ||
+ !i2c_check_expected(buf, 2, addr0) ||
+ !i2c_check_expected(buf, 3, addr1) ||
+ !i2c_check_expected(buf, 4, EOR))
+ return 0;
+
+ return 1;
+}
+
+static int i2c_read(const unsigned char addr0, const unsigned char addr1, unsigned char data[])
+{
+ unsigned char buf[9];
+
+ if (!i2c_send_read_cmd(addr0, addr1) ||
+ !i2c_get_resp(buf, sizeof(buf)) ||
+ !i2c_check_expected(buf, 0, SOR) ||
+ !i2c_check_expected(buf, 1, READ_OK) ||
+ !i2c_check_expected(buf, 2, addr0) ||
+ !i2c_check_expected(buf, 3, addr1) ||
+ !i2c_check_expected(buf, 8, EOR))
+ return 0;
+
+ data[0] = buf[4];
+ data[1] = buf[5];
+ data[2] = buf[6];
+ data[3] = buf[7];
+ return 1;
+}
+
+static int i2c_ctrl(const unsigned char addr0, const unsigned char ctrl_cmd)
+{
+ unsigned char data[4];
+ memset(data, 0, sizeof(data));
+ data[3] = ctrl_cmd;
+ return i2c_write(addr0, ADDR_CTRL, data);
+}
+
+static int i2c_wait(const unsigned char addr0, const unsigned char status)
+{
+ unsigned char buf[9];
+
+ do {
+ if (!i2c_send_read_cmd(addr0, ADDR_STATUS))
+ return 0;
+ if (!i2c_get_resp(buf, sizeof(buf)))
+ return 0;
+ if (buf[1] != READ_OK)
+ return 0;
+ } while ((buf[7] & status) != status);
+
+ if (debug)
+ fprintf(stderr, "[ Done waiting ]\n");
+
+ return 1;
+}
+
+static int i2c_wait_ready(const unsigned char addr0)
+{
+ if (debug)
+ fprintf(stderr, "[ Waiting for ready ]\n");
+ return i2c_wait(addr0, STATUS_READY_BIT);
+}
+
+static int i2c_wait_valid(const unsigned char addr0)
+{
+ if (debug)
+ fprintf(stderr, "[ Waiting for valid ]\n");
+ return i2c_wait(addr0, STATUS_VALID_BIT);
+}
+
+/*
+ * Send one block to a core.
+ */
+
+static int hash_write_block(const unsigned char addr_prefix,
+ const unsigned char addr_block,
+ const unsigned char ctrl_mode,
+ const hash_state_t *state)
+{
+ unsigned char ctrl_cmd;
+ int i;
+
+ assert(state != NULL && state->block_length % 4 == 0);
+
+ for (i = 0; i + 3 < state->block_length; i += 4)
+ if (!i2c_write(addr_prefix, addr_block + i/4, state->block + i))
+ return 0;
+
+ ctrl_cmd = state->block_count == 0 ? CTRL_INIT_CMD : CTRL_NEXT_CMD;
+
+ if (debug)
+ fprintf(stderr, "[ %s ]\n", state->block_count == 0 ? "init" : "next");
+
+ return i2c_ctrl(addr_prefix, ctrl_cmd|ctrl_mode) && i2c_wait_ready(addr_prefix);
+}
+
+/*
+ * Read hash result from core.
+ */
+
+static int hash_read_digest(const unsigned char addr_prefix, const unsigned char addr_digest,
+ unsigned char *digest, const size_t digest_length)
+{
+ int i;
+
+ assert(digest_length % 4 == 0);
+
+ if (!i2c_wait_valid(addr_prefix))
+ return 0;
+
+ for (i = 0; i + 3 < digest_length; i += 4)
+ if (!i2c_read(addr_prefix, addr_digest + i/4, digest + i))
+ return 0;
+
+ return 1;
+}
+
+/****************************************************************************
+ * *
+ * Random Numbers *
+ * *
+ ****************************************************************************/
+
+/*
+ * We have a TRNG core, but I don't think it's hooked up to I2C yet, so
+ * for the moment we use the toy generator from hw_dummy.c.
+ */
+
+static void dummyGenRandom(void *buffer, const int length)
+{
+ HASHFUNCTION_ATOMIC hashFunctionAtomic;
+ BYTE hashBuffer[CRYPT_MAX_HASHSIZE], *bufPtr = buffer;
+ static int counter = 0;
+ int hashSize, i;
+
+ assert(isWritePtr(buffer, length));
+
+ REQUIRES_V(length >= 1 && length < MAX_INTLENGTH);
+
+ /*
+ * Fill the buffer with random-ish data. This gets a bit tricky
+ * because we need to fool the entropy tests so we can't just fill
+ * it with a fixed (or even semi-random) pattern but have to set up
+ * a somewhat kludgy PRNG.
+ */
+ getHashAtomicParameters(CRYPT_ALGO_SHA1, 0, &hashFunctionAtomic, &hashSize);
+ memset(hashBuffer, counter, hashSize);
+ counter++;
+ for (i = 0; i < length; i++) {
+ if (i % hashSize == 0)
+ hashFunctionAtomic(hashBuffer, CRYPT_MAX_HASHSIZE, hashBuffer, hashSize);
+ bufPtr[i] = hashBuffer[i % hashSize];
+ }
+}
+
+/****************************************************************************
+ * *
+ * Hash/MAC Capability Interface Routines *
+ * *
+ ****************************************************************************/
+
+/*
+ * Return context subtype-specific information. All supported hash
+ * algorithms currently use the same state object, so they can all use
+ * this method.
+ */
+
+static int hashGetInfo(const CAPABILITY_INFO_TYPE type,
+ CONTEXT_INFO *contextInfoPtr,
+ void *data, const int length)
+{
+ switch (type) {
+ case CAPABILITY_INFO_STATESIZE:
+ /*
+ * Tell cryptlib how much hash-state storage we want allocated.
+ */
+ *(int *) data = sizeof(hash_state_t);
+ return CRYPT_OK;
+
+ default:
+ return getDefaultInfo(type, contextInfoPtr, data, length);
+ }
+}
+
+/*
+ * Hash data. All supported hash algorithms use similar block
+ * manipulations and padding algorithms, so all can use this method
+ * with a few parameters which we handle via closures below.
+ */
+
+static int doHash(CONTEXT_INFO *contextInfoPtr, const unsigned char *buffer, int length,
+ const size_t block_length, const unsigned char addr_prefix, const unsigned char addr_block,
+ const size_t digest_length, const unsigned char addr_digest, const unsigned char ctrl_mode,
+ const size_t length_length)
+{
+ hash_state_t *state = NULL;
+ size_t n;
+ int i;
+
+ assert(isWritePtr(contextInfoPtr, sizeof(CONTEXT_INFO)));
+ assert(length == 0 || isWritePtr(buffer, length));
+
+ state = (hash_state_t *) contextInfoPtr->ctxHash->hashInfo;
+
+ /*
+ * If the hash state was reset to allow another round of hashing,
+ * reinitialise things.
+ */
+
+ if (!(contextInfoPtr->flags & CONTEXT_FLAG_HASH_INITED)) {
+ memset(state, 0, sizeof(*state));
+ state->block_length = block_length;
+ }
+
+ /* May want an assertion here that state->block_length is correct */
+
+ if (length > 0) { /* More data to hash */
+
+ const unsigned char *p = buffer;
+
+ while ((n = state->block_length - state->block_used) <= length) {
+ /*
+ * We have enough data for another complete block.
+ */
+ if (debug)
+ fprintf(stderr, "[ Full block, length %lu, used %lu, n %lu, msg_length %llu ]\n",
+ (unsigned long) length, (unsigned long) state->block_used, (unsigned long) n, state->msg_length_low);
+ memcpy(state->block + state->block_used, p, n);
+ if ((state->msg_length_low += n) < n)
+ state->msg_length_high++;
+ state->block_used = 0;
+ length -= n;
+ p += n;
+ if (!hash_write_block(addr_prefix, addr_block, ctrl_mode, state))
+ return CRYPT_ERROR_FAILED;
+ state->block_count++;
+ }
+
+ if (length > 0) {
+ /*
+ * Data left over, but not enough for a full block, stash it.
+ */
+ if (debug)
+ fprintf(stderr, "[ Partial block, length %lu, used %lu, n %lu, msg_length %llu ]\n",
+ (unsigned long) length, (unsigned long) state->block_used, (unsigned long) n, state->msg_length_low);
+ assert(length < n);
+ memcpy(state->block + state->block_used, p, length);
+ if ((state->msg_length_low += length) < length)
+ state->msg_length_high++;
+ state->block_used += length;
+ }
+ }
+
+ else { /* Done: add padding, then pull result from chip */
+
+ unsigned long long bit_length_low = (state->msg_length_low << 3);
+ unsigned long long bit_length_high = (state->msg_length_high << 3) | (state->msg_length_low >> 61);
+ unsigned char *p;
+
+ /* Initial pad byte */
+ assert(state->block_used < state->block_length);
+ state->block[state->block_used++] = 0x80;
+
+ /* If not enough room for bit count, zero and push current block */
+ if ((n = state->block_length - state->block_used) < length_length) {
+ if (debug)
+ fprintf(stderr, "[ Overflow block, length %lu, used %lu, n %lu, msg_length %llu ]\n",
+ (unsigned long) length, (unsigned long) state->block_used, (unsigned long) n, state->msg_length_low);
+ if (n > 0)
+ memset(state->block + state->block_used, 0, n);
+ if (!hash_write_block(addr_prefix, addr_block, ctrl_mode, state))
+ return CRYPT_ERROR_FAILED;
+ state->block_count++;
+ state->block_used = 0;
+ }
+
+ /* Pad final block */
+ n = state->block_length - state->block_used;
+ assert(n >= length_length);
+ if (n > 0)
+ memset(state->block + state->block_used, 0, n);
+ if (debug)
+ fprintf(stderr, "[ Final block, length %lu, used %lu, n %lu, msg_length %llu ]\n",
+ (unsigned long) length, (unsigned long) state->block_used, (unsigned long) n, state->msg_length_low);
+ p = state->block + state->block_length;
+ for (i = 0; (bit_length_low || bit_length_high) && i < length_length; i++) {
+ *--p = (unsigned char) (bit_length_low & 0xFF);
+ bit_length_low >>= 8;
+ if (bit_length_high) {
+ bit_length_low |= ((bit_length_high & 0xFF) << 56);
+ bit_length_high >>= 8;
+ }
+ }
+
+ /* Push final block */
+ if (!hash_write_block(addr_prefix, addr_block, ctrl_mode, state))
+ return CRYPT_ERROR_FAILED;
+ state->block_count++;
+
+ /* All data pushed to core, now we just need to read back the result */
+
+ assert(digest_length <= sizeof(contextInfoPtr->ctxHash->hash));
+ if (!hash_read_digest(addr_prefix, addr_digest, contextInfoPtr->ctxHash->hash, digest_length))
+ return CRYPT_ERROR_FAILED;
+ }
+
+ return CRYPT_OK;
+}
+
+/* Perform a self-test */
+
+static int sha1SelfTest(void)
+{
+ /*
+ * If we think of a self-test, insert it here.
+ */
+
+ return CRYPT_OK;
+}
+
+/* Hash data */
+
+static int sha1Hash(CONTEXT_INFO *contextInfoPtr, unsigned char *buffer, int length)
+{
+ return doHash(contextInfoPtr, buffer, length,
+ SHA1_BLOCK_LEN, SHA1_ADDR_PREFIX, SHA1_ADDR_BLOCK,
+ SHA1_DIGEST_LEN, SHA1_ADDR_DIGEST, 0, SHA1_LENGTH_LEN);
+}
+
+/* Perform a self-test */
+
+static int sha2SelfTest(void)
+{
+ /*
+ * If we think of a self-test, insert it here.
+ */
+
+ return CRYPT_OK;
+}
+
+/* Hash data */
+
+static int sha2Hash(CONTEXT_INFO *contextInfoPtr, unsigned char *buffer, int length)
+{
+ assert(contextInfoPtr != NULL && contextInfoPtr->capabilityInfo != NULL);
+
+ switch (contextInfoPtr->capabilityInfo->blockSize) {
+
+ case bitsToBytes(256):
+ return doHash(contextInfoPtr, buffer, length,
+ SHA256_BLOCK_LEN, SHA256_ADDR_PREFIX, SHA256_ADDR_BLOCK,
+ SHA256_DIGEST_LEN, SHA256_ADDR_DIGEST, 0, SHA256_LENGTH_LEN);
+
+ case bitsToBytes(384):
+ return doHash(contextInfoPtr, buffer, length,
+ SHA512_BLOCK_LEN, SHA512_ADDR_PREFIX, SHA512_ADDR_BLOCK,
+ SHA384_DIGEST_LEN, SHA512_ADDR_DIGEST, MODE_SHA_384,
+ SHA512_LENGTH_LEN);
+
+ case bitsToBytes(512):
+ return doHash(contextInfoPtr, buffer, length,
+ SHA512_BLOCK_LEN, SHA512_ADDR_PREFIX, SHA512_ADDR_BLOCK,
+ SHA512_DIGEST_LEN, SHA512_ADDR_DIGEST, MODE_SHA_512,
+ SHA512_LENGTH_LEN);
+
+ default:
+ return CRYPT_ERROR_FAILED;
+ }
+}
+
+/* Parameter initialization, to handle SHA-2 algorithms other than SHA-256 */
+
+static int sha2InitParams(INOUT CONTEXT_INFO *contextInfoPtr,
+ IN_ENUM(KEYPARAM) const KEYPARAM_TYPE paramType,
+ IN_OPT const void *data,
+ IN_INT const int dataLength)
+{
+ static const CAPABILITY_INFO capabilityInfoSHA384 = {
+ CRYPT_ALGO_SHA2, bitsToBytes( 384 ), "SHA-384", 7,
+ bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ),
+ sha2SelfTest, hashGetInfo, NULL, NULL, NULL, NULL, sha2Hash, sha2Hash
+ };
+
+ static const CAPABILITY_INFO capabilityInfoSHA512 = {
+ CRYPT_ALGO_SHA2, bitsToBytes( 512 ), "SHA-512", 7,
+ bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ),
+ sha2SelfTest, hashGetInfo, NULL, NULL, NULL, NULL, sha2Hash, sha2Hash
+ };
+
+ assert(isWritePtr(contextInfoPtr, sizeof(CONTEXT_INFO)));
+ REQUIRES(contextInfoPtr->type == CONTEXT_HASH);
+ REQUIRES(paramType > KEYPARAM_NONE && paramType < KEYPARAM_LAST);
+
+ if (paramType == KEYPARAM_BLOCKSIZE) {
+ switch (dataLength) {
+ case bitsToBytes(256):
+ return CRYPT_OK;
+ case bitsToBytes(384):
+ contextInfoPtr->capabilityInfo = &capabilityInfoSHA384;
+ return CRYPT_OK;
+ case bitsToBytes(512):
+ contextInfoPtr->capabilityInfo = &capabilityInfoSHA512;
+ return CRYPT_OK;
+ default:
+ return CRYPT_ARGERROR_NUM1;
+ }
+ }
+
+ return initGenericParams(contextInfoPtr, paramType, data, dataLength);
+}
+
+/****************************************************************************
+ * *
+ * Hardware External Interface *
+ * *
+ ****************************************************************************/
+
+/* The capability information for this device */
+
+static const CAPABILITY_INFO capabilities[] = {
+
+ { CRYPT_ALGO_SHA1, bitsToBytes( 160 ), "SHA-1", 5,
+ bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ),
+ sha1SelfTest, hashGetInfo, NULL, NULL, NULL, NULL, sha1Hash, sha1Hash },
+
+ { CRYPT_ALGO_SHA2, bitsToBytes( 256 ), "SHA-2", 5,
+ bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ),
+ sha2SelfTest, hashGetInfo, NULL, sha2InitParams, NULL, NULL, sha2Hash, sha2Hash },
+
+ { CRYPT_ALGO_NONE }, { CRYPT_ALGO_NONE }
+};
+
+/* Return the hardware capabilities list */
+
+int hwGetCapabilities(const CAPABILITY_INFO **capabilityInfo, int *noCapabilities)
+{
+ assert(isReadPtr(capabilityInfo, sizeof(CAPABILITY_INFO *)));
+ assert(isWritePtr(noCapabilities, sizeof(int)));
+
+ *capabilityInfo = capabilities;
+ *noCapabilities = FAILSAFE_ARRAYSIZE(capabilities, CAPABILITY_INFO);
+
+ return CRYPT_OK;
+}
+
+/*
+ * Get random data from the hardware. We have a TRNG core, but I
+ * don't think we hae I2C code for it yet, so leave this as a dummy
+ * for the moment.
+ */
+
+int hwGetRandom(void *buffer, const int length)
+{
+ assert(isWritePtr(buffer, length));
+
+ REQUIRES(length >= 1 && length < MAX_INTLENGTH);
+
+ /* Fill the buffer with random-ish data */
+ dummyGenRandom(buffer, length);
+
+ return CRYPT_OK;
+}
+
+/*
+ * These "personality" methods are trivial stubs, as we do not yet
+ * have any cores which do encyrption or signature. When we do, these
+ * methods will need to be rewritten, and whoever does that rewriting
+ * will definitely want to look at the detailed comments and template
+ * code in device/hw_dummy.c.
+ */
+
+/* Look up an item held in the hardware */
+
+int hwLookupItem(const void *keyID, const int keyIDlength, int *keyHandle)
+{
+ assert(keyHandle != NULL);
+ *keyHandle = CRYPT_ERROR;
+ return CRYPT_ERROR_NOTFOUND;
+}
+
+/* Delete an item held in the hardware */
+
+int hwDeleteItem(const int keyHandle)
+{
+ return CRYPT_OK;
+}
+
+/* Initialise/zeroise the hardware */
+
+int hwInitialise(void)
+{
+ return CRYPT_OK;
+}
+
+#endif /* USE_HARDWARE */
+
+/*
+ * "Any programmer who fails to comply with the standard naming, formatting,
+ * or commenting conventions should be shot. If it so happens that it is
+ * inconvenient to shoot him, then he is to be politely requested to recode
+ * his program in adherence to the above standard."
+ * -- Michael Spier, Digital Equipment Corporation
+ *
+ * Local variables:
+ * indent-tabs-mode: nil
+ * End:
+ */
diff --git a/src/cryptech_novena_i2c_simple.c b/src/cryptech_novena_i2c_simple.c
new file mode 100644
index 0000000..e023b3b
--- /dev/null
+++ b/src/cryptech_novena_i2c_simple.c
@@ -0,0 +1,542 @@
+/*
+ * cryptech_novena_i2c_simple.c
+ * ----------------------------
+ *
+ * This is an early prototype Hardware Adaption Layer (HAL) for using
+ * Cryptlib with the Cryptech project's FGPA cores over an I2C bus on
+ * the Novena PVT1 development board using a simple stream-based
+ * protocol in which each core is represented as a separate I2C device.
+ * This is compatible with the core/novena_i2c_simple FPGA build.
+ *
+ * The communication channel used here is not suitable for production
+ * use, this is just a prototype.
+ *
+ * Authors: Joachim Strömbergson, Paul Selkirk, Rob Austein
+ * Copyright (c) 2014, SUNET
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. 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.
+ *
+ * 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 OWNER 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.
+ *
+ * The HAL framework is taken from the Cryptlib hw_dummy.c template,
+ * and is Copyright 1998-2009 by Peter Gutmann.
+ */
+
+#include <assert.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+
+#if defined( INC_ALL )
+ #include "crypt.h"
+ #include "context.h"
+ #include "hardware.h"
+#else
+ #include "crypt.h"
+ #include "context/context.h"
+ #include "device/hardware.h"
+#endif /* Compiler-specific includes */
+
+/*
+ * I2C_SLAVE comes from /usr/include/linux/i2c-dev.h, but if we
+ * include that we won't be able to compile this except on Linux. It
+ * won't *run* anywhere but on Linux, but it's useful to be able to do
+ * compilation tests on other platforms, eg, with Clang, so for now we
+ * take the small risk that this one magic constant might change.
+ */
+
+#define I2C_SLAVE 0x0703
+
+#ifdef USE_HARDWARE
+
+/*
+ * I2C configuration. Note that, unlike the i2c_coretest HAL, each
+ * hash core has its own I2C address. The SHA-512 core still has mode
+ * bits to select which of its four hash algorithms we want, but since
+ * they're stuffed into the low bits of the I2C address, they look
+ * like separate devices to us, so we treat them that way.
+ */
+
+#define I2C_DEV "/dev/i2c-2"
+#define I2C_SHA1_ADDR 0x1e
+#define I2C_SHA256_ADDR 0x1f
+#define I2C_SHA384_ADDR 0x22
+#define I2C_SHA512_ADDR 0x23
+
+/*
+ * Length parameters for the various hashes.
+ */
+
+#define SHA1_BLOCK_LEN bitsToBytes(512)
+#define SHA1_LENGTH_LEN bitsToBytes(64)
+#define SHA1_DIGEST_LEN bitsToBytes(160)
+
+#define SHA256_BLOCK_LEN bitsToBytes(512)
+#define SHA256_LENGTH_LEN bitsToBytes(64)
+#define SHA256_DIGEST_LEN bitsToBytes(256)
+
+#define SHA384_BLOCK_LEN SHA512_BLOCK_LEN
+#define SHA384_LENGTH_LEN SHA512_LENGTH_LEN
+#define SHA384_DIGEST_LEN bitsToBytes(384)
+
+#define SHA512_BLOCK_LEN bitsToBytes(1024)
+#define SHA512_LENGTH_LEN bitsToBytes(128)
+#define SHA512_DIGEST_LEN bitsToBytes(512)
+
+#define MAX_BLOCK_LEN SHA512_BLOCK_LEN
+
+/* Hash state */
+typedef struct {
+ unsigned long long msg_length_high; /* Total data hashed in this message */
+ unsigned long long msg_length_low; /* (128 bits in SHA-512 cases) */
+} hash_state_t;
+
+static int i2cfd = -1;
+static int debug = 0;
+
+/*
+ * I2C low-level code
+ */
+
+static int i2c_open(void)
+{
+ if (i2cfd >= 0)
+ return 1;
+
+ i2cfd = open(I2C_DEV, O_RDWR);
+
+ if (i2cfd < 0) {
+ perror("Unable to open " I2C_DEV);
+ i2cfd = -1;
+ return 0;
+ }
+
+ if (debug)
+ fprintf(stderr, "[ Opened %s, fd %d ]\n", I2C_DEV, i2cfd);
+
+ return 1;
+}
+
+static int i2c_addr(const int addr)
+{
+ if (!addr)
+ return 1;
+
+ if (ioctl(i2cfd, I2C_SLAVE, addr) < 0) {
+ perror("Unable to set slave address on I2C " I2C_DEV);
+ return 0;
+ }
+
+ if (debug)
+ fprintf(stderr, "[ Selected I2C slave 0x%x ]\n", (unsigned) addr);
+
+ return 1;
+}
+
+static int i2c_write(const int addr, const unsigned char *buf, const size_t len)
+{
+ if (debug) {
+ int i;
+ fprintf(stderr, "write [");
+ for (i = 0; i < len; ++i)
+ fprintf(stderr, " %02x", buf[i]);
+ fprintf(stderr, " ]\n");
+ }
+
+ if (!i2c_open() || !i2c_addr(addr))
+ return 0;
+
+ if (write(i2cfd, buf, len) != len) {
+ perror("i2c write failed");
+ return 0;
+ }
+
+ return 1;
+}
+
+/*
+ * read() on i2c device returns one byte at a time.
+ */
+
+static int i2c_read(unsigned char *buf, const size_t len)
+{
+ size_t i;
+
+ assert(i2cfd >= 0);
+
+ for (i = 0; i < len; i++) {
+ if (read(i2cfd, buf + i, 1) != 1) {
+ perror("i2c read failed");
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+/****************************************************************************
+ * *
+ * Random Numbers *
+ * *
+ ****************************************************************************/
+
+/*
+ * We have a TRNG core, but I don't think it's hooked up to I2C yet, so
+ * for the moment we use the toy generator from hw_dummy.c.
+ */
+
+static void dummyGenRandom(void *buffer, const int length)
+{
+ HASHFUNCTION_ATOMIC hashFunctionAtomic;
+ BYTE hashBuffer[CRYPT_MAX_HASHSIZE], *bufPtr = buffer;
+ static int counter = 0;
+ int hashSize, i;
+
+ assert(isWritePtr(buffer, length));
+
+ REQUIRES_V(length >= 1 && length < MAX_INTLENGTH);
+
+ /*
+ * Fill the buffer with random-ish data. This gets a bit tricky
+ * because we need to fool the entropy tests so we can't just fill
+ * it with a fixed (or even semi-random) pattern but have to set up
+ * a somewhat kludgy PRNG.
+ */
+ getHashAtomicParameters(CRYPT_ALGO_SHA1, 0, &hashFunctionAtomic, &hashSize);
+ memset(hashBuffer, counter, hashSize);
+ counter++;
+ for (i = 0; i < length; i++) {
+ if (i % hashSize == 0)
+ hashFunctionAtomic(hashBuffer, CRYPT_MAX_HASHSIZE, hashBuffer, hashSize);
+ bufPtr[i] = hashBuffer[i % hashSize];
+ }
+}
+
+/****************************************************************************
+ * *
+ * Hash/MAC Capability Interface Routines *
+ * *
+ ****************************************************************************/
+
+/*
+ * Return context subtype-specific information. All supported hash
+ * algorithms currently use the same state object, so they can all use
+ * this method.
+ */
+
+static int hashGetInfo(const CAPABILITY_INFO_TYPE type,
+ CONTEXT_INFO *contextInfoPtr,
+ void *data, const int length)
+{
+ switch (type) {
+ case CAPABILITY_INFO_STATESIZE:
+ /*
+ * Tell cryptlib how much hash-state storage we want allocated.
+ */
+ *(int *) data = sizeof(hash_state_t);
+ return CRYPT_OK;
+
+ default:
+ return getDefaultInfo(type, contextInfoPtr, data, length);
+ }
+}
+
+/*
+ * Hash data. All supported hash algorithms use similar block
+ * manipulations and padding algorithms, so all can use this method
+ * with a few parameters which we handle via closures below.
+ */
+
+static int doHash(CONTEXT_INFO *contextInfoPtr,
+ const unsigned char *buffer,
+ int length,
+ const int addr,
+ const size_t block_length,
+ const size_t digest_length,
+ const size_t length_length)
+{
+ hash_state_t *state = NULL;
+
+ assert(isWritePtr(contextInfoPtr, sizeof(CONTEXT_INFO)));
+ assert(length == 0 || isWritePtr(buffer, length));
+
+ state = (hash_state_t *) contextInfoPtr->ctxHash->hashInfo;
+
+ /*
+ * If the hash state was reset to allow another round of hashing,
+ * reinitialise things.
+ */
+
+ if (!(contextInfoPtr->flags & CONTEXT_FLAG_HASH_INITED))
+ memset(state, 0, sizeof(*state));
+
+ if (length > 0) { /* More data to hash */
+
+ if (!i2c_write(addr, buffer, length))
+ return CRYPT_ERROR_FAILED;
+
+ if ((state->msg_length_low += length) < length)
+ state->msg_length_high++;
+
+ }
+
+ else { /* Done: add padding, then pull result from chip */
+
+ unsigned long long bit_length_low = (state->msg_length_low << 3);
+ unsigned long long bit_length_high = (state->msg_length_high << 3) | (state->msg_length_low >> 61);
+ unsigned char block[MAX_BLOCK_LEN];
+ unsigned char *p;
+ size_t n;
+ int i;
+
+ /* Prepare padding buffer */
+ memset(block, 0, sizeof(block));
+ block[0] = 0x80;
+
+ /* How much room is left in the current block */
+ n = block_length - ((state->msg_length_low) & (block_length - 1));
+
+ /* If there's not enough room for length count and initial padding byte, push an extra block */
+ if (n < length_length + 1) {
+ if (debug)
+ fprintf(stderr, "[ Overflow block, n %lu, msg_length %llu ]\n", n, state->msg_length_low);
+ if (!i2c_write(addr, block, n))
+ return CRYPT_ERROR_FAILED;
+ block[0] = 0;
+ n = block_length;
+ }
+
+ /* Finish padding with length count and push final block */
+ assert(n >= length_length + 1);
+ if (debug)
+ fprintf(stderr, "[ Final block, n %lu, msg_length %llu ]\n", (unsigned long) n, state->msg_length_low);
+ p = block + n;
+ for (i = 0; (bit_length_low || bit_length_high) && i < length_length; i++) {
+ *--p = (unsigned char) (bit_length_low & 0xFF);
+ bit_length_low >>= 8;
+ if (bit_length_high) {
+ bit_length_low |= ((bit_length_high & 0xFF) << 56);
+ bit_length_high >>= 8;
+ }
+ }
+ if (!i2c_write(addr, block, n))
+ return CRYPT_ERROR_FAILED;
+
+ /* All data pushed to core, now we just need to read back the result */
+
+ assert(digest_length <= sizeof(contextInfoPtr->ctxHash->hash));
+ if (!i2c_read(contextInfoPtr->ctxHash->hash, digest_length))
+ return CRYPT_ERROR_FAILED;
+ }
+
+ return CRYPT_OK;
+}
+
+/* Perform a self-test */
+
+static int sha1SelfTest(void)
+{
+ /*
+ * If we think of a self-test, insert it here.
+ */
+
+ return CRYPT_OK;
+}
+
+/* Hash data */
+
+static int sha1Hash(CONTEXT_INFO *contextInfoPtr, unsigned char *buffer, int length)
+{
+ return doHash(contextInfoPtr, buffer, length, I2C_SHA1_ADDR, SHA1_BLOCK_LEN, SHA1_DIGEST_LEN, SHA1_LENGTH_LEN);
+}
+
+/* Perform a self-test */
+
+static int sha2SelfTest(void)
+{
+ /*
+ * If we think of a self-test, insert it here.
+ */
+
+ return CRYPT_OK;
+}
+
+/* Hash data */
+
+static int sha2Hash(CONTEXT_INFO *contextInfoPtr, unsigned char *buffer, int length)
+{
+ assert(contextInfoPtr != NULL && contextInfoPtr->capabilityInfo != NULL);
+ switch (contextInfoPtr->capabilityInfo->blockSize) {
+ case bitsToBytes(256):
+ return doHash(contextInfoPtr, buffer, length, I2C_SHA256_ADDR, SHA256_BLOCK_LEN, SHA256_DIGEST_LEN, SHA256_LENGTH_LEN);
+ case bitsToBytes(384):
+ return doHash(contextInfoPtr, buffer, length, I2C_SHA384_ADDR, SHA384_BLOCK_LEN, SHA384_DIGEST_LEN, SHA384_LENGTH_LEN);
+ case bitsToBytes(512):
+ return doHash(contextInfoPtr, buffer, length, I2C_SHA512_ADDR, SHA512_BLOCK_LEN, SHA512_DIGEST_LEN, SHA512_LENGTH_LEN);
+ default:
+ return CRYPT_ERROR_FAILED;
+ }
+}
+
+/* Parameter initialization, to handle SHA-2 algorithms other than SHA-256 */
+
+static int sha2InitParams(INOUT CONTEXT_INFO *contextInfoPtr,
+ IN_ENUM(KEYPARAM) const KEYPARAM_TYPE paramType,
+ IN_OPT const void *data,
+ IN_INT const int dataLength)
+{
+ static const CAPABILITY_INFO capabilityInfoSHA384 = {
+ CRYPT_ALGO_SHA2, bitsToBytes( 384 ), "SHA-384", 7,
+ bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ),
+ sha2SelfTest, hashGetInfo, NULL, NULL, NULL, NULL, sha2Hash, sha2Hash
+ };
+
+ static const CAPABILITY_INFO capabilityInfoSHA512 = {
+ CRYPT_ALGO_SHA2, bitsToBytes( 512 ), "SHA-512", 7,
+ bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ),
+ sha2SelfTest, hashGetInfo, NULL, NULL, NULL, NULL, sha2Hash, sha2Hash
+ };
+
+ assert(isWritePtr(contextInfoPtr, sizeof(CONTEXT_INFO)));
+ REQUIRES(contextInfoPtr->type == CONTEXT_HASH);
+ REQUIRES(paramType > KEYPARAM_NONE && paramType < KEYPARAM_LAST);
+
+ if (paramType == KEYPARAM_BLOCKSIZE) {
+ switch (dataLength) {
+ case bitsToBytes(256):
+ return CRYPT_OK;
+ case bitsToBytes(384):
+ contextInfoPtr->capabilityInfo = &capabilityInfoSHA384;
+ return CRYPT_OK;
+ case bitsToBytes(512):
+ contextInfoPtr->capabilityInfo = &capabilityInfoSHA512;
+ return CRYPT_OK;
+ default:
+ return CRYPT_ARGERROR_NUM1;
+ }
+ }
+
+ return initGenericParams(contextInfoPtr, paramType, data, dataLength);
+}
+
+/****************************************************************************
+ * *
+ * Hardware External Interface *
+ * *
+ ****************************************************************************/
+
+/* The capability information for this device */
+
+static const CAPABILITY_INFO capabilities[] = {
+
+ { CRYPT_ALGO_SHA1, bitsToBytes( 160 ), "SHA-1", 5,
+ bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ),
+ sha1SelfTest, hashGetInfo, NULL, NULL, NULL, NULL, sha1Hash, sha1Hash },
+
+ { CRYPT_ALGO_SHA2, bitsToBytes( 256 ), "SHA-2", 5,
+ bitsToBytes( 0 ), bitsToBytes( 0 ), bitsToBytes( 0 ),
+ sha2SelfTest, hashGetInfo, NULL, sha2InitParams, NULL, NULL, sha2Hash, sha2Hash },
+
+ { CRYPT_ALGO_NONE }, { CRYPT_ALGO_NONE }
+};
+
+/* Return the hardware capabilities list */
+
+int hwGetCapabilities(const CAPABILITY_INFO **capabilityInfo, int *noCapabilities)
+{
+ assert(isReadPtr(capabilityInfo, sizeof(CAPABILITY_INFO *)));
+ assert(isWritePtr(noCapabilities, sizeof(int)));
+
+ *capabilityInfo = capabilities;
+ *noCapabilities = FAILSAFE_ARRAYSIZE(capabilities, CAPABILITY_INFO);
+
+ return CRYPT_OK;
+}
+
+/*
+ * Get random data from the hardware. We have a TRNG core, but I
+ * don't think we hae I2C code for it yet, so leave this as a dummy
+ * for the moment.
+ */
+
+int hwGetRandom(void *buffer, const int length)
+{
+ assert(isWritePtr(buffer, length));
+
+ REQUIRES(length >= 1 && length < MAX_INTLENGTH);
+
+ /* Fill the buffer with random-ish data */
+ dummyGenRandom(buffer, length);
+
+ return CRYPT_OK;
+}
+
+/*
+ * These "personality" methods are trivial stubs, as we do not yet
+ * have any cores which do encyrption or signature. When we do, these
+ * methods will need to be rewritten, and whoever does that rewriting
+ * will definitely want to look at the detailed comments and template
+ * code in device/hw_dummy.c.
+ */
+
+/* Look up an item held in the hardware */
+
+int hwLookupItem(const void *keyID, const int keyIDlength, int *keyHandle)
+{
+ assert(keyHandle != NULL);
+ *keyHandle = CRYPT_ERROR;
+ return CRYPT_ERROR_NOTFOUND;
+}
+
+/* Delete an item held in the hardware */
+
+int hwDeleteItem(const int keyHandle)
+{
+ return CRYPT_OK;
+}
+
+/* Initialise/zeroise the hardware */
+
+int hwInitialise(void)
+{
+ return CRYPT_OK;
+}
+
+#endif /* USE_HARDWARE */
+
+/*
+ * "Any programmer who fails to comply with the standard naming, formatting,
+ * or commenting conventions should be shot. If it so happens that it is
+ * inconvenient to shoot him, then he is to be politely requested to recode
+ * his program in adherence to the above standard."
+ * -- Michael Spier, Digital Equipment Corporation
+ *
+ * Local variables:
+ * indent-tabs-mode: nil
+ * End:
+ */
diff --git a/tests/test_hashes.py b/tests/test_hashes.py
new file mode 100644
index 0000000..2e38ca3
--- /dev/null
+++ b/tests/test_hashes.py
@@ -0,0 +1,104 @@
+# Trivial test of cryptech hash cores via cryptlib python interface.
+# Might upgrade to Python's unittest framework eventually.
+
+import atexit, os.path
+from cryptlib_py import *
+
+cryptInit()
+atexit.register(cryptEnd)
+
+hwdev = cryptDeviceOpen(CRYPT_UNUSED, CRYPT_DEVICE_HARDWARE, None)
+atexit.register(cryptDeviceClose, hwdev)
+
+# Usual NIST sample messages.
+
+def hextext(s):
+ return "".join(s.split()).lower()
+
+NIST_512_SINGLE = "abc"
+SHA1_SINGLE_DIGEST = hextext("A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D")
+SHA256_SINGLE_DIGEST = hextext("BA7816BF 8F01CFEA 414140DE 5DAE2223 B00361A3 96177A9C B410FF61 F20015AD")
+
+NIST_512_DOUBLE = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
+SHA1_DOUBLE_DIGEST = hextext("84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1")
+SHA256_DOUBLE_DIGEST = hextext("248D6A61 D20638B8 E5C02693 0C3E6039 A33CE459 64FF2167 F6ECEDD4 19DB06C1")
+
+NIST_1024_SINGLE = "abc"
+SHA384_SINGLE_DIGEST = hextext("CB00753F 45A35E8B B5A03D69 9AC65007 272C32AB 0EDED163"
+ "1A8B605A 43FF5BED 8086072B A1E7CC23 58BAECA1 34C825A7")
+SHA512_SINGLE_DIGEST = hextext("DDAF35A1 93617ABA CC417349 AE204131 12E6FA4E 89A97EA2 0A9EEEE6 4B55D39A"
+ "2192992A 274FC1A8 36BA3C23 A3FEEBBD 454D4423 643CE80E 2A9AC94F A54CA49F")
+
+NIST_1024_DOUBLE = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" \
+ "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"
+SHA384_DOUBLE_DIGEST = hextext("09330C33 F71147E8 3D192FC7 82CD1B47 53111B17 3B3B05D2"
+ "2FA08086 E3B0F712 FCC7C71A 557E2DB9 66C3E9FA 91746039")
+SHA512_DOUBLE_DIGEST = hextext("8E959B75 DAE313DA 8CF4F728 14FC143F 8F7779C6 EB9F7FA1 7299AEAD B6889018"
+ "501D289E 4900F7E4 331B99DE C4B5433A C7D329EE B6DD2654 5E96E55B 874BE909")
+
+def do_hash(ctx, s):
+ try:
+ cryptEncrypt(ctx, array("c", s))
+ cryptEncrypt(ctx, array("c", ""))
+ result = ctx.CRYPT_CTXINFO_HASHVALUE
+ return result.encode("hex")
+ finally:
+ cryptDestroyContext(ctx)
+
+def sha1(d, s):
+ if d is None:
+ ctx = cryptCreateContext(CRYPT_UNUSED, CRYPT_ALGO_SHA1)
+ else:
+ ctx = cryptDeviceCreateContext(d, CRYPT_ALGO_SHA1)
+ return do_hash(ctx, s)
+
+def sha256(d, s):
+ if d is None:
+ ctx = cryptCreateContext(CRYPT_UNUSED, CRYPT_ALGO_SHA2)
+ else:
+ ctx = cryptDeviceCreateContext(d, CRYPT_ALGO_SHA2)
+ return do_hash(ctx, s)
+
+def sha384(d, s):
+ if d is None:
+ ctx = cryptCreateContext(CRYPT_UNUSED, CRYPT_ALGO_SHA2)
+ else:
+ ctx = cryptDeviceCreateContext(d, CRYPT_ALGO_SHA2)
+ ctx.CTXINFO_BLOCKSIZE = 48
+ return do_hash(ctx, s)
+
+def sha512(d, s):
+ if d is None:
+ ctx = cryptCreateContext(CRYPT_UNUSED, CRYPT_ALGO_SHA2)
+ else:
+ ctx = cryptDeviceCreateContext(d, CRYPT_ALGO_SHA2)
+ ctx.CTXINFO_BLOCKSIZE = 64
+ return do_hash(ctx, s)
+
+have_i2c = os.path.exists("/dev/i2c-2")
+
+if not have_i2c:
+ print
+ print "I2C device not found, so testing software only, no hardware cores tested"
+
+def test(digest, text, expect):
+ print
+ print "Testing %s(%r)" % (digest.__name__, text)
+ hashes = [digest(None, text)]
+ if have_i2c:
+ hashes.append(digest(hwdev, text))
+ for hash in hashes:
+ if hash == expect:
+ print "+", hash
+ else:
+ print "-", hash
+ print "!", expect
+
+test(sha1, NIST_512_SINGLE, SHA1_SINGLE_DIGEST)
+test(sha1, NIST_512_DOUBLE, SHA1_DOUBLE_DIGEST)
+test(sha256, NIST_512_SINGLE, SHA256_SINGLE_DIGEST)
+test(sha256, NIST_512_DOUBLE, SHA256_DOUBLE_DIGEST)
+test(sha384, NIST_1024_SINGLE, SHA384_SINGLE_DIGEST)
+test(sha384, NIST_1024_DOUBLE, SHA384_DOUBLE_DIGEST)
+test(sha512, NIST_1024_SINGLE, SHA512_SINGLE_DIGEST)
+test(sha512, NIST_1024_DOUBLE, SHA512_DOUBLE_DIGEST)