implement chain and message verify
[oweals/ucert.git] / ucert.c
1 /*
2  * Copyright (C) 2018 Daniel Golle <daniel@makrotopia.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 3
6  * as published by the Free Software Foundation
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  */
13
14 #define _GNU_SOURCE
15
16 #include <fcntl.h>
17 #include <dlfcn.h>
18 #include <stdio.h>
19 #include <stdbool.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <getopt.h>
23 #include <stdint.h>
24 #include <unistd.h>
25 #include <inttypes.h>
26 #include <sys/stat.h>
27 #include <sys/wait.h>
28
29 #include <json-c/json.h>
30 #include <libubox/blob.h>
31 #include <libubox/utils.h>
32 #include <libubox/list.h>
33 #include <libubox/vlist.h>
34 #include <libubox/blobmsg_json.h>
35
36 #include "usign.h"
37
38 #define CERT_BUF_LEN 4096
39
40 static enum {
41         CMD_APPEND,
42         CMD_DUMP,
43         CMD_ISSUE,
44         CMD_REVOKE,
45         CMD_VERIFY,
46         CMD_NONE,
47 } cmd = CMD_NONE;
48
49 static bool quiet;
50
51 enum cert_attr {
52         CERT_ATTR_SIGNATURE,
53         CERT_ATTR_PAYLOAD,
54         CERT_ATTR_MAX
55 };
56
57 static const struct blob_attr_info cert_policy[CERT_ATTR_MAX] = {
58         [CERT_ATTR_SIGNATURE] = { .type = BLOB_ATTR_BINARY },
59         [CERT_ATTR_PAYLOAD] = { .type = BLOB_ATTR_NESTED },
60 };
61
62 enum cert_cont_attr {
63         CERT_CT_ATTR_PAYLOAD,
64         CERT_CT_ATTR_MAX
65 };
66
67 static const struct blobmsg_policy cert_cont_policy[CERT_CT_ATTR_MAX] = {
68         [CERT_CT_ATTR_PAYLOAD] = { .name = "ucert", .type = BLOBMSG_TYPE_TABLE },
69 };
70
71 enum cert_payload_attr {
72         CERT_PL_ATTR_CERTTYPE,
73         CERT_PL_ATTR_CERTID,
74         CERT_PL_ATTR_VALIDFROMTIME,
75         CERT_PL_ATTR_EXPIRETIME,
76         CERT_PL_ATTR_PUBKEY,
77         CERT_PL_ATTR_KEY_FINGERPRINT,
78         CERT_PL_ATTR_MAX
79 };
80
81 enum certtype_id {
82         CERTTYPE_UNSPEC,
83         CERTTYPE_AUTH,
84         CERTTYPE_REVOKE
85 };
86
87 static const struct blobmsg_policy cert_payload_policy[CERT_PL_ATTR_MAX] = {
88         [CERT_PL_ATTR_CERTTYPE] = { .name = "certtype", .type = BLOBMSG_TYPE_INT32 },
89         [CERT_PL_ATTR_CERTID] = { .name = "certid", .type = BLOBMSG_TYPE_INT32 },
90         [CERT_PL_ATTR_VALIDFROMTIME] = { .name = "validfrom", .type = BLOBMSG_TYPE_INT64 },
91         [CERT_PL_ATTR_EXPIRETIME] = { .name = "expiresat", .type = BLOBMSG_TYPE_INT64 },
92         [CERT_PL_ATTR_PUBKEY] = { .name = "pubkey", .type = BLOBMSG_TYPE_STRING },
93         [CERT_PL_ATTR_KEY_FINGERPRINT] = { .name = "fingerprint", .type = BLOBMSG_TYPE_STRING },
94 };
95
96 struct cert_object {
97         struct list_head list;
98         struct blob_attr **cert;
99 };
100
101 static int write_file(const char *filename, void *buf, size_t len, bool append) {
102         FILE *f;
103         size_t outlen;
104
105         f = fopen(filename, append?"a":"w");
106         if (!f)
107                 return 1;
108
109         outlen = fwrite(buf, 1, len, f);
110         fclose(f);
111         return (outlen == len);
112 }
113
114 static int cert_load(const char *certfile, struct list_head *chain) {
115         FILE *f;
116         struct blob_attr *certtb[CERT_ATTR_MAX];
117         struct cert_object *cobj;
118         char filebuf[CERT_BUF_LEN];
119         int ret = 0;
120         int len;
121
122         f = fopen(certfile, "r");
123         if (!f)
124                 return 1;
125
126         len = fread(&filebuf, 1, CERT_BUF_LEN - 1, f);
127         if (len < 64)
128                 return 1;
129
130         ret = ferror(f) || !feof(f);
131         fclose(f);
132         if (ret)
133                 return 1;
134
135         /* TODO: read more than one blob from file */
136         ret = blob_parse(filebuf, certtb, cert_policy, CERT_ATTR_MAX);
137         cobj = calloc(1, sizeof(*cobj));
138         cobj->cert = &certtb;
139         list_add_tail(&cobj->list, chain);
140
141         return (ret <= 0);
142 }
143
144 static int cert_append(const char *certfile, const char *pubkeyfile, const char *sigfile) {
145         fprintf(stderr, "not implemented\n");
146         return 1;
147 }
148
149 static int cert_verify_blob(struct blob_attr *cert[CERT_ATTR_MAX],
150                        const char *pubkeyfile, const char *pubkeydir) {
151         int i;
152         char msgfname[256], sigfname[256];
153         int ret;
154         char tmpdir[] = "/tmp/ucert-XXXXXX";
155
156         if (mkdtemp(tmpdir) == NULL)
157                 return errno;
158
159         snprintf(msgfname, sizeof(msgfname) - 1, "%s/%s", tmpdir, "payload");
160         snprintf(sigfname, sizeof(sigfname) - 1, "%s/%s", tmpdir, "payload.sig");
161
162         for (i = 0; i < CERT_ATTR_MAX; i++) {
163                 struct blob_attr *v = cert[i];
164
165                 if (!v)
166                         break;
167
168                 switch(cert_policy[i].type) {
169                 case BLOB_ATTR_BINARY:
170                         write_file(sigfname, blob_data(v), blob_len(v), false);
171                         break;
172                 case BLOB_ATTR_NESTED:
173                         write_file(msgfname, blob_data(v), blob_len(v), false);
174                         break;
175                 }
176         }
177
178         ret = usign_v(msgfname, pubkeyfile, pubkeydir, sigfname, quiet);
179
180         unlink(msgfname);
181         unlink(sigfname);
182         rmdir(tmpdir);
183
184         return ret;
185 }
186
187 static int chain_verify(const char *msgfile, const char *pubkeyfile,
188                         const char *pubkeydir, struct list_head *chain) {
189         struct cert_object *cobj;
190         struct blob_attr *containertb[CERT_CT_ATTR_MAX];
191         struct blob_attr *payloadtb[CERT_PL_ATTR_MAX];
192         char tmpdir[] = "/tmp/ucert-XXXXXX";
193         char chainedpubkey[256] = {0};
194         char extsigfile[256] = {0};
195         int ret = 1;
196         int checkmsg = 0;
197
198         if (mkdtemp(tmpdir) == NULL)
199                 return errno;
200
201         if (msgfile)
202                 checkmsg = -1;
203
204         list_for_each_entry(cobj, chain, list) {
205                 ret = cert_verify_blob(cobj->cert, chainedpubkey[0]?chainedpubkey:pubkeyfile, pubkeydir);
206                 if (ret)
207                         goto clean_and_return;
208
209                 if (cobj->cert[CERT_ATTR_PAYLOAD]) {
210                         struct timeval tv;
211                         uint64_t validfrom;
212                         uint64_t expiresat;
213                         uint32_t certtype;
214
215                         blobmsg_parse(cert_cont_policy,
216                                       ARRAY_SIZE(cert_cont_policy),
217                                       containertb,
218                                       blob_data(cobj->cert[CERT_ATTR_PAYLOAD]),
219                                       blob_len(cobj->cert[CERT_ATTR_PAYLOAD]));
220                         if (!containertb[CERT_CT_ATTR_PAYLOAD]) {
221                                 ret = 1;
222                                 fprintf(stderr, "no ucert in signed payload\n");
223                                 goto clean_and_return;
224                         }
225                         blobmsg_parse(cert_payload_policy,
226                                       ARRAY_SIZE(cert_payload_policy),
227                                       payloadtb,
228                                       blobmsg_data(containertb[CERT_CT_ATTR_PAYLOAD]),
229                                       blobmsg_data_len(containertb[CERT_CT_ATTR_PAYLOAD]));
230
231                         if (!payloadtb[CERT_PL_ATTR_CERTTYPE] ||
232                             !payloadtb[CERT_PL_ATTR_VALIDFROMTIME] ||
233                             !payloadtb[CERT_PL_ATTR_EXPIRETIME] ||
234                             !payloadtb[CERT_PL_ATTR_PUBKEY]) {
235                                 ret = 1;
236                                 fprintf(stderr, "missing mandatory ucert attributes\n");
237                                 goto clean_and_return;
238                         }
239                         certtype = blobmsg_get_u32(payloadtb[CERT_PL_ATTR_CERTTYPE]);
240                         validfrom = blobmsg_get_u64(payloadtb[CERT_PL_ATTR_VALIDFROMTIME]);
241                         expiresat = blobmsg_get_u64(payloadtb[CERT_PL_ATTR_EXPIRETIME]);
242
243                         if (certtype != CERTTYPE_AUTH) {
244                                 ret = 2;
245                                 fprintf(stderr, "wrong certificate type\n");
246                                 goto clean_and_return;
247                         }
248
249                         gettimeofday(&tv, NULL);
250                         if (tv.tv_sec < validfrom ||
251                             tv.tv_sec >= expiresat) {
252                                 ret = 3;
253                                 fprintf(stderr, "certificate expired\n");
254                                 goto clean_and_return;
255                         }
256
257                         snprintf(chainedpubkey, sizeof(chainedpubkey) - 1, "%s/%s", tmpdir, "chained-pubkey");
258                         write_file(chainedpubkey,
259                                    blobmsg_data(payloadtb[CERT_PL_ATTR_PUBKEY]),
260                                    blobmsg_data_len(payloadtb[CERT_PL_ATTR_PUBKEY]),
261                                    false);
262                 } else {
263                         if (msgfile) {
264                                 snprintf(extsigfile, sizeof(extsigfile) - 1, "%s/%s", tmpdir, "ext-sig");
265                                 write_file(extsigfile,
266                                            blob_data(cobj->cert[CERT_ATTR_SIGNATURE]),
267                                            blob_len(cobj->cert[CERT_ATTR_SIGNATURE]),
268                                            false);
269                                 checkmsg = ret = usign_v(msgfile,
270                                               chainedpubkey[0]?chainedpubkey:pubkeyfile,
271                                               pubkeydir, extsigfile, quiet);
272                                 unlink(extsigfile);
273                         } else {
274                                 fprintf(stderr, "stray trailing signature without anything to verify!\n");
275                                 ret = 1;
276                         };
277                 }
278         }
279
280         if (checkmsg == -1)
281                 fprintf(stderr, "missing signature to verify message!\n");
282
283 clean_and_return:
284         if (chainedpubkey[0])
285                 unlink(chainedpubkey);
286         rmdir(tmpdir);
287         return ret | checkmsg;
288 }
289
290 static void cert_dump_blob(struct blob_attr *cert[CERT_ATTR_MAX]) {
291         int i;
292
293         for (i = 0; i < CERT_ATTR_MAX; i++) {
294                 struct blob_attr *v = cert[i];
295
296                 if (!v)
297                         continue;
298
299                 switch(cert_policy[i].type) {
300                 case BLOB_ATTR_BINARY:
301                         fprintf(stdout, "signature:\n---\n%s\n---\n", (char *) blob_data(v));
302                         break;
303                 case BLOB_ATTR_NESTED:
304                         fprintf(stdout, "payload:\n---\n%s\n---\n", blobmsg_format_json_indent(blob_data(v), false, 0));
305                         break;
306                 }
307         }
308 }
309
310 static int cert_dump(const char *certfile) {
311         struct cert_object *cobj;
312         static LIST_HEAD(certchain);
313
314         if (cert_load(certfile, &certchain)) {
315                 fprintf(stderr, "cannot parse cert\n");
316                 return 1;
317         }
318
319         list_for_each_entry(cobj, &certchain, list)
320                 cert_dump_blob(cobj->cert);
321
322         return 0;
323 }
324
325 static int cert_issue(const char *certfile, const char *pubkeyfile, const char *seckeyfile) {
326         struct blob_buf certbuf;
327         struct blob_buf payloadbuf;
328         struct timeval tv;
329         struct stat st;
330         int pklen, siglen;
331         int revoker = 1;
332         void *c;
333         FILE *pkf, *sigf;
334         char pkb[512];
335         char sigb[512];
336         char fname[256], sfname[256];
337         char pkfp[17];
338         char tmpdir[] = "/tmp/ucert-XXXXXX";
339
340         if (stat(certfile, &st) == 0) {
341                 fprintf(stderr, "certfile %s exists, won't overwrite.\n", certfile);
342                 return -1;
343         }
344
345         pkf = fopen(pubkeyfile, "r");
346         if (!pkf)
347                 return -1;
348
349         pklen = fread(pkb, 1, 512, pkf);
350         pkb[pklen] = '\0';
351
352         if (pklen < 32)
353                 return -1;
354
355         fclose(pkf);
356
357         if (usign_f_pubkey(pkfp, pubkeyfile))
358                 return -1;
359
360         gettimeofday(&tv, NULL);
361
362         if (mkdtemp(tmpdir) == NULL)
363                 return errno;
364
365         while (revoker >= 0) {
366                 blob_buf_init(&payloadbuf, 0);
367                 c = blobmsg_open_table(&payloadbuf, "ucert");
368                 blobmsg_add_u32(&payloadbuf, "certtype", revoker?CERTTYPE_REVOKE:CERTTYPE_AUTH);
369                 blobmsg_add_u64(&payloadbuf, "validfrom", tv.tv_sec);
370                 if (!revoker) {
371                         blobmsg_add_u64(&payloadbuf, "expiresat", tv.tv_sec + 60 * 60 * 24 * 365);
372                         blobmsg_add_string(&payloadbuf, "pubkey", pkb);
373                 } else {
374                         blobmsg_add_string(&payloadbuf, "fingerprint", pkfp);
375                 }
376
377                 blobmsg_close_table(&payloadbuf, c);
378
379                 snprintf(fname, sizeof(fname) - 1, "%s/%s", tmpdir, revoker?"revoker":"payload");
380                 write_file(fname, blob_data(payloadbuf.head), blob_len(payloadbuf.head), false);
381
382                 snprintf(sfname, sizeof(sfname) - 1, "%s/%s", tmpdir, revoker?"revoker.sig":"payload.sig");
383                 if (usign_s(fname, seckeyfile, sfname, quiet))
384                         return 1;
385
386                 sigf = fopen(sfname, "r");
387                 if (!sigf)
388                         return 1;
389
390                 siglen = fread(sigb, 1, 1024, sigf);
391                 if (siglen < 1)
392                         return 1;
393
394                 sigb[siglen-1] = '\0';
395                 fclose(sigf);
396
397                 unlink(fname);
398                 unlink(sfname);
399
400                 blob_buf_init(&certbuf, 0);
401                 blob_put(&certbuf, CERT_ATTR_SIGNATURE, sigb, siglen);
402                 blob_put(&certbuf, CERT_ATTR_PAYLOAD, blob_data(payloadbuf.head), blob_len(payloadbuf.head));
403                 snprintf(fname, sizeof(fname) - 1, "%s%s", certfile, revoker?".revoke":"");
404                 write_file(fname, certbuf.head, blob_raw_len(certbuf.head), false);
405                 revoker--;
406         }
407
408         rmdir(tmpdir);
409
410         return 0;
411 }
412
413 static int cert_process_revoker(const char *certfile) {
414         fprintf(stderr, "not implemented\n");
415         return 1;
416 }
417
418 static int cert_verify(const char *certfile, const char *pubkeyfile, const char *pubkeydir, const char *msgfile) {
419         static LIST_HEAD(certchain);
420
421         if (cert_load(certfile, &certchain)) {
422                 fprintf(stderr, "cannot parse cert\n");
423                 return 1;
424         }
425
426         return chain_verify(msgfile, pubkeyfile, pubkeydir, &certchain);
427 }
428
429 static int usage(const char *cmd)
430 {
431         fprintf(stderr,
432                 "Usage: %s <command> <options>\n"
433                 "Commands:\n"
434                 "  -A:                  append (needs -c and -p and/or -x)\n"
435                 "  -D:                  dump\n"
436                 "  -I:                  issue cert and revoker (needs -c and -p and -s)\n"
437                 "  -R:                  process revoker certificate (needs -c)\n"
438                 "  -V:                  verify (needs -c and -p|-P)\n"
439                 "Options:\n"
440                 "  -c <file>:           certificate file\n"
441                 "  -m <file>:           message file (verify only)\n"
442                 "  -p <file>:           public key file\n"
443                 "  -P <path>:           public key directory (verify only)\n"
444                 "  -q:                  quiet (do not print verification result, use return code only)\n"
445                 "  -s <file>:           secret key file (issue only)\n"
446                 "  -x <file>:           signature file\n"
447                 "\n",
448                 cmd);
449         return 1;
450 }
451
452 int main(int argc, char *argv[]) {
453         int ch;
454         const char *msgfile = NULL;
455         const char *sigfile = NULL;
456         const char *pubkeyfile = NULL;
457         const char *pubkeydir = NULL;
458         const char *certfile = NULL;
459         const char *seckeyfile = NULL;
460
461         quiet = false;
462         while ((ch = getopt(argc, argv, "ADIRVc:m:p:P:qs:x:")) != -1) {
463                 switch (ch) {
464                 case 'A':
465                         cmd = CMD_APPEND;
466                         break;
467                 case 'D':
468                         cmd = CMD_DUMP;
469                         break;
470                 case 'I':
471                         cmd = CMD_ISSUE;
472                         break;
473                 case 'R':
474                         cmd = CMD_REVOKE;
475                         break;
476                 case 'V':
477                         cmd = CMD_VERIFY;
478                         break;
479                 case 'c':
480                         certfile = optarg;
481                         break;
482                 case 'm':
483                         msgfile = optarg;
484                         break;
485                 case 'p':
486                         pubkeyfile = optarg;
487                         break;
488                 case 'P':
489                         pubkeydir = optarg;
490                         break;
491                 case 's':
492                         seckeyfile = optarg;
493                         break;
494                 case 'q':
495                         quiet = true;
496                         break;
497                 case 'x':
498                         sigfile = optarg;
499                         break;
500                 default:
501                         return usage(argv[0]);
502                 }
503         }
504
505         switch (cmd) {
506         case CMD_APPEND:
507                 if (certfile && (pubkeyfile || sigfile))
508                         return cert_append(certfile, pubkeyfile, sigfile);
509                 else
510                         return usage(argv[0]);
511         case CMD_DUMP:
512                 if (certfile)
513                         return cert_dump(certfile);
514                 else
515                         return usage(argv[0]);
516         case CMD_ISSUE:
517                 if (certfile && pubkeyfile && seckeyfile)
518                         return cert_issue(certfile, pubkeyfile, seckeyfile);
519                 else
520                         return usage(argv[0]);
521         case CMD_REVOKE:
522                 if (certfile)
523                         return cert_process_revoker(certfile);
524                 else
525                         return usage(argv[0]);
526         case CMD_VERIFY:
527                 if (certfile && (pubkeyfile || pubkeydir))
528                         return cert_verify(certfile, pubkeyfile, pubkeydir, msgfile);
529                 else
530                         return usage(argv[0]);
531         case CMD_NONE:
532                 return usage(argv[0]);
533         }
534
535         /* unreachable */
536         return usage(argv[0]);
537 }