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