Fix share id == 0 check for share at index 0
[shamirs] / shamirssecret.c
index 80f835c46318bb2ab825a40135af853d51b96821..f5ca5c5f135f6bd7eaad98d95e7c8905f0e2ea3f 100644 (file)
@@ -1,21 +1,44 @@
-#define _GNU_SOURCE
+/*
+ * Shamir's secret sharing implementation
+ *
+ * Copyright (C) 2013 Matt Corallo <git@bluematt.me>
+ *
+ * This file is part of ASSS (Audit-friendly Shamir's Secret Sharing)
+ *
+ * ASSS is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of
+ * the License, or (at your option) any later version.
+ *
+ * ASSS is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with ASSS.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ */
 
-#include <stdint.h>
-#include <stdio.h>
+#ifndef IN_KERNEL
 #include <assert.h>
-#include <string.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <sys/mman.h>
+#define CHECKSTATE(x) assert(x)
+#else
+#include <linux/bug.h>
+#define CHECKSTATE(x) BUG_ON(!(x))
+#endif
 
-#define MAX_LENGTH 1024
-#define ERROREXIT(str...) {fprintf(stderr, str); exit(1);}
+#include "shamirssecret.h"
+
+#ifndef noinline
+#define noinline __attribute__((noinline))
+#endif
 
 /*
  * Calculations across the finite field GF(2^8)
  */
-#define P 256
 
+#ifndef TEST
 static uint8_t field_add(uint8_t a, uint8_t b) {
        return a ^ b;
 }
@@ -27,7 +50,11 @@ static uint8_t field_sub(uint8_t a, uint8_t b) {
 static uint8_t field_neg(uint8_t a) {
        return field_sub(0, a);
 }
+#endif
 
+//TODO: Using static tables will very likely create side-channel attacks when measuring cache hits
+//      Because these are fairly small tables, we can probably get them loaded mostly/fully into
+//      cache before use to break such attacks.
 static const uint8_t exp[P] = {
        0x01, 0x03, 0x05, 0x0f, 0x11, 0x33, 0x55, 0xff, 0x1a, 0x2e, 0x72, 0x96, 0xa1, 0xf8, 0x13, 0x35,
        0x5f, 0xe1, 0x38, 0x48, 0xd8, 0x73, 0x95, 0xa4, 0xf7, 0x02, 0x06, 0x0a, 0x1e, 0x22, 0x66, 0xaa,
@@ -65,7 +92,7 @@ static const uint8_t log[P] = {
        0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07};
 
 // We disable lots of optimizations that result in non-constant runtime (+/- branch delays)
-static uint8_t field_mul_ret(uint8_t calc, uint8_t a, uint8_t b) __attribute__((optimize("-O0"))) __attribute__((noinline));
+static uint8_t field_mul_ret(uint8_t calc, uint8_t a, uint8_t b) __attribute__((optimize("-O0"))) noinline;
 static uint8_t field_mul_ret(uint8_t calc, uint8_t a, uint8_t b) {
        uint8_t ret, ret2;
        if (a == 0)
@@ -83,12 +110,12 @@ static uint8_t field_mul(uint8_t a, uint8_t b)  {
 }
 
 static uint8_t field_invert(uint8_t a) {
-       assert(a != 0);
+       CHECKSTATE(a != 0);
        return exp[0xff - log[a]]; // log[1] == 0xff
 }
 
 // We disable lots of optimizations that result in non-constant runtime (+/- branch delays)
-static uint8_t field_pow_ret(uint8_t calc, uint8_t a, uint8_t e) __attribute__((optimize("-O0"))) __attribute__((noinline));
+static uint8_t field_pow_ret(uint8_t calc, uint8_t a, uint8_t e) __attribute__((optimize("-O0"))) noinline;
 static uint8_t field_pow_ret(uint8_t calc, uint8_t a, uint8_t e) {
        uint8_t ret, ret2;
        if (a == 0)
@@ -105,7 +132,7 @@ static uint8_t field_pow(uint8_t a, uint8_t e) {
 #ifndef TEST
        // Although this function works for a==0, its not trivially obvious why,
        // and since we never call with a==0, we just assert a != 0 (except when testing)
-       assert(a != 0);
+       CHECKSTATE(a != 0);
 #endif
        return field_pow_ret(exp[(log[a] * e) % 255], a, e);
 }
@@ -136,18 +163,18 @@ static uint8_t field_pow_calc(uint8_t a, uint8_t e) {
 int main() {
        // Test inversion with the logarithm tables
        for (uint16_t i = 1; i < P; i++)
-               assert(field_mul_calc(i, field_invert(i)) == 1);
+               CHECKSTATE(field_mul_calc(i, field_invert(i)) == 1);
 
        // Test multiplication with the logarithm tables
        for (uint16_t i = 0; i < P; i++) {
                for (uint16_t j = 0; j < P; j++)
-                       assert(field_mul(i, j) == field_mul_calc(i, j));
+                       CHECKSTATE(field_mul(i, j) == field_mul_calc(i, j));
        }
 
        // Test exponentiation with the logarithm tables
        for (uint16_t i = 0; i < P; i++) {
                for (uint16_t j = 0; j < P; j++)
-                       assert(field_pow(i, j) == field_pow_calc(i, j));
+                       CHECKSTATE(field_pow(i, j) == field_pow_calc(i, j));
        }
 }
 #endif // defined(TEST)
@@ -158,22 +185,29 @@ int main() {
  * Calculations across the polynomial q
  */
 #ifndef TEST
-static uint8_t calculateQ(uint8_t a[], uint8_t k, uint8_t x) {
-       assert(x != 0); // q(0) == secret, though so does a[0]
-       uint8_t ret = a[0];
-       for (uint8_t i = 1; i < k; i++) {
-               ret = field_add(ret, field_mul(a[i], field_pow(x, i)));
+/**
+ * Calculates the Y coordinate that the point with the given X
+ * coefficients[0] == secret, the rest are random values
+ */
+uint8_t calculateQ(uint8_t coefficients[], uint8_t shares_required, uint8_t x) {
+       uint8_t ret = coefficients[0], i;
+       CHECKSTATE(x != 0); // q(0) == secret, though so does a[0]
+       for (i = 1; i < shares_required; i++) {
+               ret = field_add(ret, field_mul(coefficients[i], field_pow(x, i)));
        }
        return ret;
 }
 
-uint8_t calculateSecret(uint8_t x[], uint8_t q[], uint8_t k) {
+/**
+ * Derives the secret given a set of shares_required points (x and q coordinates)
+ */
+uint8_t calculateSecret(uint8_t x[], uint8_t q[], uint8_t shares_required) {
        // Calculate the x^0 term using a derivation of the forumula at
        // http://en.wikipedia.org/wiki/Lagrange_polynomial#Example_2
-       uint8_t ret = 0;
-       for (uint8_t i = 0; i < k; i++) {
+       uint8_t ret = 0, i, j;
+       for (i = 0; i < shares_required; i++) {
                uint8_t temp = q[i];
-               for (uint8_t j = 0; j < k; j++) {
+               for (j = 0; j < shares_required; j++) {
                        if (i == j)
                                continue;
                        temp = field_mul(temp, field_neg(x[j]));
@@ -183,194 +217,4 @@ uint8_t calculateSecret(uint8_t x[], uint8_t q[], uint8_t k) {
        }
        return ret;
 }
-
-
-
-int main(int argc, char* argv[]) {
-       assert(mlockall(MCL_CURRENT | MCL_FUTURE) == 0);
-
-       char split = 0;
-       uint8_t total_shares = 0, shares_required = 0;
-       char* files[P]; uint8_t files_count = 0;
-       char *in_file = (void*)0, *out_file_param = (void*)0;
-
-       int i;
-       while((i = getopt(argc, argv, "scn:k:f:o:i:h?")) != -1)
-               switch(i) {
-               case 's':
-                       if ((split & 0x2) && !(split & 0x1))
-                               ERROREXIT("-s (split) and -c (combine) are mutually exclusive\n")
-                       else
-                               split = (0x2 | 0x1);
-                       break;
-               case 'c':
-                       if ((split & 0x2) && (split & 0x1))
-                               ERROREXIT("-s (split) and -c (combine) are mutually exclusive\n")
-                       else
-                               split = 0x2;
-                       break;
-               case 'n': {
-                       int t = atoi(optarg);
-                       if (t <= 0 || t >= P)
-                               ERROREXIT("n must be > 0 and < %u\n", P)
-                       else
-                               total_shares = t;
-                       break;
-               }
-               case 'k': {
-                       int t = atoi(optarg);
-                       if (t <= 0 || t >= P)
-                               ERROREXIT("n must be > 0 and < %u\n", P)
-                       else
-                               shares_required = t;
-                       break;
-               }
-               case 'i':
-                       in_file = optarg;
-                       break;
-               case 'o':
-                       out_file_param = optarg;
-                       break;
-               case 'f':
-                       if (files_count >= P-1)
-                               ERROREXIT("May only specify up to %u files\n", P-1)
-                       files[files_count++] = optarg;
-                       break;
-               case 'h':
-               case '?':
-                       printf("Split usage: -s -n <total shares> -k <shares required> -i <input file> -o <output file path base>\n");
-                       printf("Combine usage: -c -k <shares provided == shares required> <-f <share>>*k -o <output file>\n");
-                       exit(0);
-                       break;
-               default:
-                       ERROREXIT("getopt failed?\n")
-               }
-       if (!(split & 0x2))
-               ERROREXIT("Must specify one of -c, -s or -?\n")
-       split &= 0x1;
-
-       if (argc != optind)
-               ERROREXIT("Invalid argument\n")
-
-       if (split) {
-               if (!total_shares || !shares_required)
-                       ERROREXIT("n and k must be set.\n")
-
-               if (shares_required > total_shares)
-                       ERROREXIT("k must be <= n\n")
-
-               if (files_count != 0 || !in_file || !out_file_param)
-                       ERROREXIT("Must specify -i <input file> and -o <output file path base> but not -f in split mode.\n")
-
-               FILE* random = fopen("/dev/random", "r");
-               assert(random);
-               FILE* secret_file = fopen(in_file, "r");
-               if (!secret_file)
-                       ERROREXIT("Could not open %s for reading.\n", in_file)
-
-               uint8_t secret[MAX_LENGTH];
-
-               size_t secret_length = fread(secret, 1, MAX_LENGTH*sizeof(uint8_t), secret_file);
-               if (secret_length == 0)
-                       ERROREXIT("Error reading secret\n")
-               if (fread(secret, 1, 1, secret_file) > 0)
-                       ERROREXIT("Secret may not be longer than %u\n", MAX_LENGTH)
-               fclose(secret_file);
-               printf("Using secret of length %lu\n", secret_length);
-
-               uint8_t a[shares_required], D[total_shares][secret_length];
-
-               for (uint32_t i = 0; i < secret_length; i++) {
-                       a[0] = secret[i];
-
-                       for (uint8_t j = 1; j < shares_required; j++)
-                               assert(fread(&a[j], sizeof(uint8_t), 1, random) == 1);
-                       for (uint8_t j = 0; j < total_shares; j++)
-                               D[j][i] = calculateQ(a, shares_required, j+1);
-
-                       if (i % 32 == 0 && i != 0)
-                               printf("Finished processing %u bytes.\n", i);
-               }
-
-               char out_file_name_buf[strlen(out_file_param) + 4];
-               strcpy(out_file_name_buf, out_file_param);
-               for (uint8_t i = 0; i < total_shares; i++) {
-                       /*printf("%u-", i);
-                       for (uint8_t j = 0; j < secret_length; j++)
-                               printf("%02x", D[i][j]);
-                       printf("\n");*/
-
-                       sprintf(((char*)out_file_name_buf) + strlen(out_file_param), "%u", i);
-                       FILE* out_file = fopen(out_file_name_buf, "w+");
-                       if (!out_file)
-                               ERROREXIT("Could not open output file %s\n", out_file_name_buf)
-
-                       uint8_t x = i+1;
-                       if (fwrite(&x, sizeof(uint8_t), 1, out_file) != 1)
-                               ERROREXIT("Could not write 1 byte to %s\n", out_file_name_buf)
-
-                       if (fwrite(D[i], 1, secret_length, out_file) != secret_length)
-                               ERROREXIT("Could not write %lu bytes to %s\n", secret_length, out_file_name_buf)
-
-                       fclose(out_file);
-               }
-               /*printf("secret = ");
-               for (uint8_t i = 0; i < secret_length; i++)
-                       printf("%02x", secret[i]);
-               printf("\n");*/
-
-               // Clear sensitive data (No, GCC 4.7.2 is currently not optimizing this out)
-               memset(secret, 0, sizeof(uint8_t)*secret_length);
-               memset(a, 0, sizeof(uint8_t)*shares_required);
-               memset(in_file, 0, strlen(in_file));
-
-               fclose(random);
-       } else {
-               if (!shares_required)
-                       ERROREXIT("k must be set.\n")
-
-               if (files_count != shares_required || in_file || !out_file_param)
-                       ERROREXIT("Must not specify -i and must specify -o and exactly k -f <input file>s in combine mode.\n")
-
-               uint8_t x[shares_required], q[shares_required];
-               FILE* files_fps[shares_required];
-
-               for (uint8_t i = 0; i < shares_required; i++) {
-                       files_fps[i] = fopen(files[i], "r");
-                       if (!files_fps[i])
-                               ERROREXIT("Couldn't open file %s for reading.\n", files[i])
-                       if (fread(&x[i], sizeof(uint8_t), 1, files_fps[i]) != 1)
-                               ERROREXIT("Couldn't read the x byte of %s\n", files[i])
-               }
-
-               uint8_t secret[MAX_LENGTH];
-
-               uint32_t i = 0;
-               while (fread(&q[0], sizeof(uint8_t), 1, files_fps[0]) == 1) {
-                       for (uint8_t j = 1; j < shares_required; j++) {
-                               if (fread(&q[j], sizeof(uint8_t), 1, files_fps[j]) != 1)
-                                       ERROREXIT("Couldn't read next byte from %s\n", files[j])
-                       }
-                       secret[i++] = calculateSecret(x, q, shares_required);
-               }
-               printf("Got secret of length %u\n", i);
-
-               FILE* out_file = fopen(out_file_param, "w+");
-               fwrite(secret, sizeof(uint8_t), i, out_file);
-               fclose(out_file);
-
-               for (uint8_t i = 0; i < shares_required; i++)
-                       fclose(files_fps[i]);
-
-               // Clear sensitive data (No, GCC 4.7.2 is currently not optimizing this out)
-               memset(secret, 0, sizeof(uint8_t)*i);
-               memset(q, 0, sizeof(uint8_t)*shares_required);
-               memset(out_file_param, 0, strlen(out_file_param));
-               for (uint8_t i = 0; i < shares_required; i++)
-                       memset(files[i], 0, strlen(files[i]));
-               memset(x, 0, sizeof(uint8_t)*shares_required);
-       }
-
-       return 0;
-}
 #endif // !defined(TEST)