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