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