Relicense under AGPL (as with all my software, ask for a relicense and you'll probabl...
[shamirs] / main.c
1 /*
2  * Shamir's secret sharing CLI interface
3  *
4  * Copyright (C) 2013 Matt Corallo <git@bluematt.me>
5  *
6  * This file is part of ASSS (Audit-friendly Shamir's Secret Sharing)
7  *
8  * ASSS is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU Affero General Public License as
10  * published by the Free Software Foundation, either version 3 of
11  * the License, or (at your option) any later version.
12  *
13  * ASSS is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU Affero General Public License for more details.
17  *
18  * You should have received a copy of the GNU Affero General Public
19  * License along with ASSS.  If not, see
20  * <http://www.gnu.org/licenses/>.
21  */
22
23 #define _GNU_SOURCE
24
25 #include <stdio.h>
26 #include <stdbool.h>
27 #include <assert.h>
28 #include <string.h>
29 #include <sys/mman.h>
30 #include <unistd.h>
31 #include <stdlib.h>
32
33 #include "shamirssecret.h"
34
35 #define MAX_LENGTH 1024
36 #define ERROREXIT(str...) {fprintf(stderr, str); exit(1);}
37
38 #ifndef RAND_SOURCE
39 #define RAND_SOURCE "/dev/random"
40 #endif
41
42 #ifndef TEST
43 static void derive_missing_part(uint8_t total_shares, uint8_t shares_required, bool parts_have[], const uint8_t* split_version, const uint8_t* split_x, uint8_t split_index, uint8_t split_size) {
44         const uint8_t (*D)[split_size] = (const uint8_t (*)[split_size])split_version;
45         uint8_t x[shares_required], q[shares_required];
46
47         // Fill in x/q with the selected shares
48         uint16_t x_pos = 0;
49         for (uint8_t i = 0; i < P-1; i++) {
50                 if (parts_have[i]) {
51                         x[x_pos] = split_x[i];
52                         q[x_pos++] = D[i][split_index];
53                 }
54         }
55         assert(x_pos == shares_required - 1);
56
57         // Now loop through ALL x we didn't already set (despite not having that many
58         // shares, because more shares could be added arbitrarily, any x should not be
59         // able to rule out any possible secrets) and try each possible q, making sure
60         // that each q gives us a new possibility for the secret.
61         bool impossible_secrets[P];
62         memset(impossible_secrets, 0, sizeof(impossible_secrets));
63         for (uint16_t final_x = 1; final_x < P; final_x++) { 
64                 bool x_already_used = false;
65                 for (uint8_t j = 0; j < shares_required; j++) {
66                         if (x[j] == final_x)
67                                 x_already_used = true;
68                 }
69                 if (x_already_used)
70                         continue;
71
72                 x[shares_required-1] = final_x;
73                 bool possible_secrets[P];
74                 memset(possible_secrets, 0, sizeof(possible_secrets));
75                 for (uint16_t new_q = 0; new_q < P; new_q++) {
76                         q[shares_required-1] = new_q;
77                         possible_secrets[calculateSecret(x, q, shares_required)] = 1;
78                 }
79
80                 for (uint16_t i = 0; i < P; i++)
81                         assert(possible_secrets[i]);
82         }
83
84         //TODO: Check that gcc isn't optimizing this one away
85         memset(q, 0, sizeof(q));
86 }
87
88 static void check_possible_missing_part_derivations_intern(uint8_t total_shares, uint8_t shares_required, bool parts_have[], uint8_t parts_included, uint16_t progress, const uint8_t* split_version, const uint8_t* x, uint8_t split_index, uint8_t split_size) {
89         if (parts_included == shares_required-1)
90                 return derive_missing_part(total_shares, shares_required, parts_have, split_version, x, split_index, split_size);
91
92         if (total_shares - progress < shares_required)
93                 return;
94
95         check_possible_missing_part_derivations_intern(total_shares, shares_required, parts_have, parts_included, progress+1, split_version, x, split_index, split_size);
96         parts_have[progress] = 1;
97         check_possible_missing_part_derivations_intern(total_shares, shares_required, parts_have, parts_included+1, progress+1, split_version, x, split_index, split_size);
98         parts_have[progress] = 0;
99 }
100
101 static void check_possible_missing_part_derivations(uint8_t total_shares, uint8_t shares_required, const uint8_t* split_version, const uint8_t* x, uint8_t split_index, uint8_t split_size) {
102         bool parts_have[P];
103         memset(parts_have, 0, sizeof(parts_have));
104         check_possible_missing_part_derivations_intern(total_shares, shares_required, parts_have, 0, 0, split_version, x, split_index, split_size);
105 }
106
107
108 int main(int argc, char* argv[]) {
109         assert(mlockall(MCL_CURRENT | MCL_FUTURE) == 0);
110
111         char split = 0;
112         uint8_t total_shares = 0, shares_required = 0;
113         char* files[P]; uint8_t files_count = 0;
114         char *in_file = (void*)0, *out_file_param = (void*)0;
115
116         int i;
117         while((i = getopt(argc, argv, "scn:k:f:o:i:h?")) != -1)
118                 switch(i) {
119                 case 's':
120                         if ((split & 0x2) && !(split & 0x1))
121                                 ERROREXIT("-s (split) and -c (combine) are mutually exclusive\n")
122                         else
123                                 split = (0x2 | 0x1);
124                         break;
125                 case 'c':
126                         if ((split & 0x2) && (split & 0x1))
127                                 ERROREXIT("-s (split) and -c (combine) are mutually exclusive\n")
128                         else
129                                 split = 0x2;
130                         break;
131                 case 'n': {
132                         int t = atoi(optarg);
133                         if (t <= 0 || t >= P)
134                                 ERROREXIT("n must be > 0 and < %u\n", P)
135                         else
136                                 total_shares = t;
137                         break;
138                 }
139                 case 'k': {
140                         int t = atoi(optarg);
141                         if (t <= 0 || t >= P)
142                                 ERROREXIT("n must be > 0 and < %u\n", P)
143                         else
144                                 shares_required = t;
145                         break;
146                 }
147                 case 'i':
148                         in_file = optarg;
149                         break;
150                 case 'o':
151                         out_file_param = optarg;
152                         break;
153                 case 'f':
154                         if (files_count >= P-1)
155                                 ERROREXIT("May only specify up to %u files\n", P-1)
156                         files[files_count++] = optarg;
157                         break;
158                 case 'h':
159                 case '?':
160                         printf("Split usage: -s -n <total shares> -k <shares required> -i <input file> -o <output file path base>\n");
161                         printf("Combine usage: -c -k <shares provided == shares required> <-f <share>>*k -o <output file>\n");
162                         exit(0);
163                         break;
164                 default:
165                         ERROREXIT("getopt failed?\n")
166                 }
167         if (!(split & 0x2))
168                 ERROREXIT("Must specify one of -c, -s or -?\n")
169         split &= 0x1;
170
171         if (argc != optind)
172                 ERROREXIT("Invalid argument\n")
173
174         if (split) {
175                 if (!total_shares || !shares_required)
176                         ERROREXIT("n and k must be set.\n")
177
178                 if (shares_required > total_shares)
179                         ERROREXIT("k must be <= n\n")
180
181                 if (files_count != 0 || !in_file || !out_file_param)
182                         ERROREXIT("Must specify -i <input file> and -o <output file path base> but not -f in split mode.\n")
183
184                 FILE* random = fopen(RAND_SOURCE, "r");
185                 assert(random);
186                 FILE* secret_file = fopen(in_file, "r");
187                 if (!secret_file)
188                         ERROREXIT("Could not open %s for reading.\n", in_file)
189
190                 uint8_t secret[MAX_LENGTH];
191
192                 size_t secret_length = fread(secret, 1, MAX_LENGTH*sizeof(uint8_t), secret_file);
193                 if (secret_length == 0)
194                         ERROREXIT("Error reading secret\n")
195                 if (fread(secret, 1, 1, secret_file) > 0)
196                         ERROREXIT("Secret may not be longer than %u\n", MAX_LENGTH)
197                 fclose(secret_file);
198                 printf("Using secret of length %lu\n", secret_length);
199
200                 uint8_t a[shares_required], x[total_shares], D[total_shares][secret_length];
201
202                 // TODO: The following loop may take a long time and eat lots of /dev/random if total_shares is high
203                 for (uint32_t i = 0; i < total_shares; i++) {
204                         int32_t j = 0;
205                         do {
206                                 assert(fread(&x[i], sizeof(uint8_t), 1, random) == 1);
207                                 if (x[i] == 0)
208                                         continue;
209                                 for (j = 0; j < i; j++)
210                                         if (x[j] == x[i])
211                                                 break;
212                         } while (j < i); // Inner loop will get to j = i when x[j] != x[i] for all j
213                         if (i % 32 == 31)
214                                 printf("Finished picking X coordinates for %u shares\n", i+1);
215                 }
216                 for (uint32_t i = 0; i < secret_length; i++) {
217                         a[0] = secret[i];
218
219                         for (uint8_t j = 1; j < shares_required; j++)
220                                 assert(fread(&a[j], sizeof(uint8_t), 1, random) == 1);
221                         for (uint8_t j = 0; j < total_shares; j++)
222                                 D[j][i] = calculateQ(a, shares_required, x[j]);
223
224                         // Now, for paranoia's sake, we ensure that no matter which piece we are missing, we can derive no information about the secret
225                         check_possible_missing_part_derivations(total_shares, shares_required, &(D[0][0]), x, i, secret_length);
226
227                         if (i % 32 == 31)
228                                 printf("Finished processing %u bytes.\n", i+1);
229                 }
230
231                 char out_file_name_buf[strlen(out_file_param) + 4];
232                 strcpy(out_file_name_buf, out_file_param);
233                 for (uint8_t i = 0; i < total_shares; i++) {
234                         sprintf(((char*)out_file_name_buf) + strlen(out_file_param), "%u", i);
235                         FILE* out_file = fopen(out_file_name_buf, "w+");
236                         if (!out_file)
237                                 ERROREXIT("Could not open output file %s\n", out_file_name_buf)
238
239                         if (fwrite(&x[i], sizeof(uint8_t), 1, out_file) != 1)
240                                 ERROREXIT("Could not write 1 byte to %s\n", out_file_name_buf)
241
242                         if (fwrite(D[i], 1, secret_length, out_file) != secret_length)
243                                 ERROREXIT("Could not write %lu bytes to %s\n", secret_length, out_file_name_buf)
244
245                         fclose(out_file);
246                 }
247
248                 // Clear sensitive data (No, GCC 4.7.2 is currently not optimizing this out)
249                 memset(secret, 0, sizeof(uint8_t)*secret_length);
250                 memset(a, 0, sizeof(uint8_t)*shares_required);
251                 memset(x, 0, sizeof(uint8_t)*total_shares);
252                 memset(in_file, 0, strlen(in_file));
253
254                 fclose(random);
255         } else {
256                 if (!shares_required)
257                         ERROREXIT("k must be set.\n")
258
259                 if (files_count != shares_required || in_file || !out_file_param)
260                         ERROREXIT("Must not specify -i and must specify -o and exactly k -f <input file>s in combine mode.\n")
261
262                 uint8_t x[shares_required], q[shares_required];
263                 FILE* files_fps[shares_required];
264
265                 for (uint8_t i = 0; i < shares_required; i++) {
266                         files_fps[i] = fopen(files[i], "r");
267                         if (!files_fps[i])
268                                 ERROREXIT("Couldn't open file %s for reading.\n", files[i])
269                         if (fread(&x[i], sizeof(uint8_t), 1, files_fps[i]) != 1)
270                                 ERROREXIT("Couldn't read the x byte of %s\n", files[i])
271                 }
272
273                 uint8_t secret[MAX_LENGTH];
274
275                 uint32_t i = 0;
276                 while (fread(&q[0], sizeof(uint8_t), 1, files_fps[0]) == 1) {
277                         for (uint8_t j = 1; j < shares_required; j++) {
278                                 if (fread(&q[j], sizeof(uint8_t), 1, files_fps[j]) != 1)
279                                         ERROREXIT("Couldn't read next byte from %s\n", files[j])
280                         }
281                         secret[i++] = calculateSecret(x, q, shares_required);
282                 }
283                 printf("Got secret of length %u\n", i);
284
285                 FILE* out_file = fopen(out_file_param, "w+");
286                 fwrite(secret, sizeof(uint8_t), i, out_file);
287                 fclose(out_file);
288
289                 for (uint8_t i = 0; i < shares_required; i++)
290                         fclose(files_fps[i]);
291
292                 // Clear sensitive data (No, GCC 4.7.2 is currently not optimizing this out)
293                 memset(secret, 0, sizeof(uint8_t)*i);
294                 memset(q, 0, sizeof(uint8_t)*shares_required);
295                 memset(out_file_param, 0, strlen(out_file_param));
296                 for (uint8_t i = 0; i < shares_required; i++)
297                         memset(files[i], 0, strlen(files[i]));
298                 memset(x, 0, sizeof(uint8_t)*shares_required);
299         }
300
301         return 0;
302 }
303 #endif // !defined(TEST)