Small cleanups
[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         for (uint16_t final_x = 1; final_x < P; final_x++) { 
62                 bool x_already_used = false;
63                 for (uint8_t j = 0; j < shares_required; j++) {
64                         if (x[j] == final_x)
65                                 x_already_used = true;
66                 }
67                 if (x_already_used)
68                         continue;
69
70                 x[shares_required-1] = final_x;
71                 bool possible_secrets[P];
72                 memset(possible_secrets, 0, sizeof(possible_secrets));
73                 for (uint16_t new_q = 0; new_q < P; new_q++) {
74                         q[shares_required-1] = new_q;
75                         possible_secrets[calculateSecret(x, q, shares_required)] = 1;
76                 }
77
78                 for (uint16_t i = 0; i < P; i++)
79                         assert(possible_secrets[i]);
80         }
81
82         //TODO: Check that gcc isn't optimizing this one away
83         memset(q, 0, sizeof(q));
84 }
85
86 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) {
87         if (parts_included == shares_required-1)
88                 return derive_missing_part(total_shares, shares_required, parts_have, split_version, x, split_index, split_size);
89
90         if (total_shares - progress < shares_required)
91                 return;
92
93         check_possible_missing_part_derivations_intern(total_shares, shares_required, parts_have, parts_included, progress+1, split_version, x, split_index, split_size);
94         parts_have[progress] = 1;
95         check_possible_missing_part_derivations_intern(total_shares, shares_required, parts_have, parts_included+1, progress+1, split_version, x, split_index, split_size);
96         parts_have[progress] = 0;
97 }
98
99 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) {
100         bool parts_have[P];
101         memset(parts_have, 0, sizeof(parts_have));
102         check_possible_missing_part_derivations_intern(total_shares, shares_required, parts_have, 0, 0, split_version, x, split_index, split_size);
103 }
104
105
106 int main(int argc, char* argv[]) {
107         assert(mlockall(MCL_CURRENT | MCL_FUTURE) == 0);
108
109         char split = 0;
110         uint8_t total_shares = 0, shares_required = 0;
111         char* files[P]; uint8_t files_count = 0;
112         char *in_file = (void*)0, *out_file_param = (void*)0;
113
114         int i;
115         while((i = getopt(argc, argv, "scn:k:f:o:i:h?")) != -1)
116                 switch(i) {
117                 case 's':
118                         if ((split & 0x2) && !(split & 0x1))
119                                 ERROREXIT("-s (split) and -c (combine) are mutually exclusive\n")
120                         else
121                                 split = (0x2 | 0x1);
122                         break;
123                 case 'c':
124                         if ((split & 0x2) && (split & 0x1))
125                                 ERROREXIT("-s (split) and -c (combine) are mutually exclusive\n")
126                         else
127                                 split = 0x2;
128                         break;
129                 case 'n': {
130                         int t = atoi(optarg);
131                         if (t <= 0 || t >= P)
132                                 ERROREXIT("n must be > 0 and < %u\n", P)
133                         else
134                                 total_shares = t;
135                         break;
136                 }
137                 case 'k': {
138                         int t = atoi(optarg);
139                         if (t <= 0 || t >= P)
140                                 ERROREXIT("n must be > 0 and < %u\n", P)
141                         else
142                                 shares_required = t;
143                         break;
144                 }
145                 case 'i':
146                         in_file = optarg;
147                         break;
148                 case 'o':
149                         out_file_param = optarg;
150                         break;
151                 case 'f':
152                         if (files_count >= P-1)
153                                 ERROREXIT("May only specify up to %u files\n", P-1)
154                         files[files_count++] = optarg;
155                         break;
156                 case 'h':
157                 case '?':
158                         printf("Split usage: -s -n <total shares> -k <shares required> -i <input file> -o <output file path base>\n");
159                         printf("Combine usage: -c -k <shares provided == shares required> <-f <share>>*k -o <output file>\n");
160                         exit(0);
161                         break;
162                 default:
163                         ERROREXIT("getopt failed?\n")
164                 }
165         if (!(split & 0x2))
166                 ERROREXIT("Must specify one of -c, -s or -?\n")
167         split &= 0x1;
168
169         if (argc != optind)
170                 ERROREXIT("Invalid argument\n")
171
172         if (split) {
173                 if (!total_shares || !shares_required)
174                         ERROREXIT("n and k must be set.\n")
175
176                 if (shares_required > total_shares)
177                         ERROREXIT("k must be <= n\n")
178
179                 if (files_count != 0 || !in_file || !out_file_param)
180                         ERROREXIT("Must specify -i <input file> and -o <output file path base> but not -f in split mode.\n")
181
182                 FILE* random = fopen(RAND_SOURCE, "r");
183                 assert(random);
184                 FILE* secret_file = fopen(in_file, "r");
185                 if (!secret_file)
186                         ERROREXIT("Could not open %s for reading.\n", in_file)
187
188                 uint8_t secret[MAX_LENGTH];
189
190                 size_t secret_length = fread(secret, 1, MAX_LENGTH*sizeof(uint8_t), secret_file);
191                 if (secret_length == 0)
192                         ERROREXIT("Error reading secret\n")
193                 if (fread(secret, 1, 1, secret_file) > 0)
194                         ERROREXIT("Secret may not be longer than %u\n", MAX_LENGTH)
195                 fclose(secret_file);
196                 printf("Using secret of length %lu\n", secret_length);
197
198                 uint8_t a[shares_required], x[total_shares], D[total_shares][secret_length];
199
200                 // TODO: The following loop may take a long time and eat lots of /dev/random if total_shares is high
201                 for (uint32_t i = 0; i < total_shares; i++) {
202                         int32_t j = -1;
203                         do {
204                                 assert(fread(&x[i], sizeof(uint8_t), 1, random) == 1);
205                                 if (x[i] == 0)
206                                         continue;
207                                 for (j = 0; j < i; j++)
208                                         if (x[j] == x[i])
209                                                 break;
210                         } while (j < (int32_t)i); // Inner loop will get to j = i when x[j] != x[i] for all j
211                         if (i % 32 == 31)
212                                 printf("Finished picking X coordinates for %u shares\n", i+1);
213                 }
214                 for (uint32_t i = 0; i < secret_length; i++) {
215                         a[0] = secret[i];
216
217                         for (uint8_t j = 1; j < shares_required; j++)
218                                 assert(fread(&a[j], sizeof(uint8_t), 1, random) == 1);
219                         for (uint8_t j = 0; j < total_shares; j++)
220                                 D[j][i] = calculateQ(a, shares_required, x[j]);
221
222                         // Now, for paranoia's sake, we ensure that no matter which piece we are missing, we can derive no information about the secret
223                         check_possible_missing_part_derivations(total_shares, shares_required, &(D[0][0]), x, i, secret_length);
224
225                         if (i % 32 == 31)
226                                 printf("Finished processing %u bytes.\n", i+1);
227                 }
228
229                 char out_file_name_buf[strlen(out_file_param) + 4];
230                 strcpy(out_file_name_buf, out_file_param);
231                 for (uint8_t i = 0; i < total_shares; i++) {
232                         sprintf(((char*)out_file_name_buf) + strlen(out_file_param), "%u", i);
233                         FILE* out_file = fopen(out_file_name_buf, "w+");
234                         if (!out_file)
235                                 ERROREXIT("Could not open output file %s\n", out_file_name_buf)
236
237                         if (fwrite(&x[i], sizeof(uint8_t), 1, out_file) != 1)
238                                 ERROREXIT("Could not write 1 byte to %s\n", out_file_name_buf)
239
240                         if (fwrite(D[i], 1, secret_length, out_file) != secret_length)
241                                 ERROREXIT("Could not write %lu bytes to %s\n", secret_length, out_file_name_buf)
242
243                         fclose(out_file);
244                 }
245
246                 // Clear sensitive data (No, GCC 4.7.2 is currently not optimizing this out)
247                 memset(secret, 0, sizeof(uint8_t)*secret_length);
248                 memset(a, 0, sizeof(uint8_t)*shares_required);
249                 memset(x, 0, sizeof(uint8_t)*total_shares);
250                 memset(in_file, 0, strlen(in_file));
251
252                 fclose(random);
253         } else {
254                 if (!shares_required)
255                         ERROREXIT("k must be set.\n")
256
257                 if (files_count != shares_required || in_file || !out_file_param)
258                         ERROREXIT("Must not specify -i and must specify -o and exactly k -f <input file>s in combine mode.\n")
259
260                 uint8_t x[shares_required], q[shares_required];
261                 FILE* files_fps[shares_required];
262
263                 for (uint8_t i = 0; i < shares_required; i++) {
264                         files_fps[i] = fopen(files[i], "r");
265                         if (!files_fps[i])
266                                 ERROREXIT("Couldn't open file %s for reading.\n", files[i])
267                         if (fread(&x[i], sizeof(uint8_t), 1, files_fps[i]) != 1)
268                                 ERROREXIT("Couldn't read the x byte of %s\n", files[i])
269                 }
270
271                 uint8_t secret[MAX_LENGTH];
272
273                 uint32_t i = 0;
274                 while (fread(&q[0], sizeof(uint8_t), 1, files_fps[0]) == 1) {
275                         for (uint8_t j = 1; j < shares_required; j++) {
276                                 if (fread(&q[j], sizeof(uint8_t), 1, files_fps[j]) != 1)
277                                         ERROREXIT("Couldn't read next byte from %s\n", files[j])
278                         }
279                         secret[i++] = calculateSecret(x, q, shares_required);
280                 }
281                 printf("Got secret of length %u\n", i);
282
283                 FILE* out_file = fopen(out_file_param, "w+");
284                 fwrite(secret, sizeof(uint8_t), i, out_file);
285                 fclose(out_file);
286
287                 for (uint8_t i = 0; i < shares_required; i++)
288                         fclose(files_fps[i]);
289
290                 // Clear sensitive data (No, GCC 4.7.2 is currently not optimizing this out)
291                 memset(secret, 0, sizeof(uint8_t)*i);
292                 memset(q, 0, sizeof(uint8_t)*shares_required);
293                 memset(out_file_param, 0, strlen(out_file_param));
294                 for (uint8_t i = 0; i < shares_required; i++)
295                         memset(files[i], 0, strlen(files[i]));
296                 memset(x, 0, sizeof(uint8_t)*shares_required);
297         }
298
299         return 0;
300 }
301 #endif // !defined(TEST)