udpkey.c: Refactor protocol reply logic.
[udpkey] / udpkey.c
CommitLineData
247f344a
MW
1/* -*-c-*-
2 *
3 * Request a key over UDP, or respond to such a request
4 *
5 * (c) 2012 Mark Wooding
6 */
7
8/*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of udpkey.
11 *
12 * The udpkey program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * The udpkey program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with udpkey; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 */
26
27/*----- Header files ------------------------------------------------------*/
28
29#include <ctype.h>
30#include <errno.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <time.h>
35
36#include <sys/types.h>
37#include <sys/time.h>
38#include <unistd.h>
39#include <fcntl.h>
40
41#include <syslog.h>
42
43#include <sys/socket.h>
44#include <arpa/inet.h>
45#include <netinet/in.h>
46#include <netdb.h>
47
48#include <mLib/alloc.h>
49#include <mLib/buf.h>
50#include <mLib/daemonize.h>
51#include <mLib/dstr.h>
52#include <mLib/fdflags.h>
53#include <mLib/fwatch.h>
54#include <mLib/hex.h>
55#include <mLib/mdwopt.h>
56#include <mLib/quis.h>
57#include <mLib/report.h>
58#include <mLib/sub.h>
59#include <mLib/tv.h>
60
61#include <catacomb/buf.h>
a5f873be 62#include <catacomb/ct.h>
247f344a
MW
63#include <catacomb/dh.h>
64#include <catacomb/ec.h>
65#include <catacomb/ec-keys.h>
66#include <catacomb/gcipher.h>
67#include <catacomb/gmac.h>
68#include <catacomb/group.h>
69#include <catacomb/key.h>
70#include <catacomb/mp.h>
71#include <catacomb/mprand.h>
72#include <catacomb/noise.h>
73#include <catacomb/rand.h>
74
75#include <catacomb/rijndael-counter.h>
76#include <catacomb/sha256.h>
77
78#ifdef DEBUG
79# define D(x) x
80#else
81# define D(x)
82#endif
83
84/*---- Static variables ---------------------------------------------------*/
85
86static unsigned flags = 0;
87#define f_bogus 1u
88#define f_listen 2u
89#define f_daemon 4u
90#define f_syslog 8u
91
92#define BUFSZ 65536
93static unsigned char ibuf[BUFSZ], obuf[BUFSZ];
94
95static key_file *kf;
96static const char *kfname = "keyring";
97static const char *pidfile;
98static fwatch kfwatch;
99static unsigned nq;
100
101/*----- Miscellaneous utilities -------------------------------------------*/
102
103/* Resolve NAME, storing the address in *ADDR. Exit on error. */
104static void resolve(const char *name, struct in_addr *addr)
105{
106 struct hostent *h;
107
108 if ((h = gethostbyname(name)) == 0)
109 die(1, "failed to resolve `%s': %s", name, hstrerror(h_errno));
110 if (h->h_addrtype != AF_INET)
111 die(1, "unexpected address type %d", h->h_addrtype);
112 memcpy(addr, h->h_addr, sizeof(struct in_addr));
113}
114
115/* Convert PORT to a port number (in host byte order). Exit on error. */
116static unsigned short getport(const char *port)
117{
118 unsigned long i = 0;
119 char *q;
120 int e = errno;
121
122 errno = 0;
123 if (!isdigit(*port) ||
124 (i = strtoul(port, &q, 0)) == 0 ||
125 i >= 65536 || *q || errno)
126 die(1, "invalid port number `%s'", port);
127 errno = e;
128 return ((unsigned short)i);
129}
130
131/* Read the file named by NAME into a buffer -- or at least an initial
132 * portion of it; set *P to the start and *SZ to the length. Return -1 if it
133 * didn't work. The buffer doesn't need to be freed: the data is stashed in
134 * ibuf.
135 */
136static int snarf(const char *name, void **p, size_t *sz)
137{
138 ssize_t n;
139 int fd;
140
141 if ((fd = open(name, O_RDONLY)) < 0) return (-1);
142 n = read(fd, ibuf, sizeof(ibuf));
143 close(fd);
144 if (n < 0) return (-1);
145 *p = ibuf; *sz = n;
146 return (0);
147}
148
149/* Complain about something. If f_syslog is set then complain to that;
150 * otherwise write to stderr. Don't use `%m' because that won't work when
151 * writing to stderr.
152 */
92469bdf 153static void PRINTF_LIKE(2, 3) complain(int sev, const char *msg, ...)
247f344a
MW
154{
155 va_list ap;
156
157 va_start(ap, msg);
158 if (flags & f_syslog)
159 vsyslog(sev, msg, ap);
160 else {
161 fprintf(stderr, "%s: ", QUIS);
162 vfprintf(stderr, msg, ap);
163 fputc('\n', stderr);
164 }
165}
166
167/*----- Reading key data --------------------------------------------------*/
168
169struct kinfo {
170 group *g;
171 ge *X;
172 mp *x;
173 const gccipher *cc;
174 const gcmac *mc; size_t tagsz;
175 const gchash *hc;
176};
177
178/* Clear a kinfo structure so it can be freed without trouble. */
179static void k_init(struct kinfo *k) { k->g = 0; k->x = 0; k->X = 0; }
180
181/* Free a kinfo structure. This is safe on any initialized kinfo
182 * structure.
183 */
184static void k_free(struct kinfo *k)
185{
186 if (k->X) { G_DESTROY(k->g, k->X); k->X = 0; }
187 if (k->x) { MP_DROP(k->x); k->x = 0; }
188 if (k->g) { G_DESTROYGROUP(k->g); k->g = 0; }
189}
190
191/* Empty macro arguments are forbidden. But arguments are expended during
192 * replacement, not while the call is being processed, so this hack is OK.
193 * Unfortunately, if a potentially empty argument is passed on to another
194 * macro then it needs to be guarded with a use of EMPTY too...
195 */
196#define EMPTY
197
198/* Table of key types. Entries have the form
199 *
200 * _(name, NAME, SETGROUP, SETPRIV, SETPUB)
201 *
202 * The name and NAME are lower- and uppercase names for the type used for
203 * constructing various type name constant names. The code fragment SETGROUP
204 * initializes k->g given the name_{pub,priv} structure in p; SETPRIV and
205 * SETPUB set up k->x and k->X respectively. (In this last case, k->X will
206 * have been created as a group element already.)
207 */
208#define KEYTYPES(_) \
209 \
210 _(dh, DH, \
211 { k->g = group_prime(&p.dp); }, \
212 { k->x = MP_COPY(p.x); }, \
213 { if (G_FROMINT(k->g, k->X, p.y)) { \
214 complain(LOG_ERR, "bad public key in `%s'", t->buf); \
215 goto fail; \
216 } \
217 }) \
218 \
219 _(ec, EC, \
220 { ec_info ei; const char *e; \
221 if ((e = ec_getinfo(&ei, p.cstr)) != 0) { \
222 complain(LOG_ERR, "bad elliptic curve in `%s': %s", t->buf, e); \
223 goto fail; \
224 } \
225 k->g = group_ec(&ei); \
226 }, \
227 { k->x = MP_COPY(p.x); }, \
228 { if (G_FROMEC(k->g, k->X, &p.p)) { \
229 complain(LOG_ERR, "bad public point in `%s'", t->buf); \
230 goto fail; \
231 } \
232 })
233
234/* Define load_tywhich, where which is `pub' or `priv', to load a public or
235 * private key. Other parameters are as for the KEYTYPES list above.
236 */
237#define KLOAD(ty, TY, which, WHICH, setgroup, setpriv, setpub) \
238static int load_##ty##which(key_data *kd, struct kinfo *k, dstr *t) \
239{ \
240 key_packstruct kps[TY##_##WHICH##FETCHSZ]; \
241 key_packdef *kp; \
242 ty##_##which p; \
243 int rc; \
244 \
245 /* Extract the key data from the keydata. */ \
246 kp = key_fetchinit(ty##_##which##fetch, kps, &p); \
247 if ((rc = key_unpack(kp, kd, t)) != 0) { \
248 complain(LOG_ERR, "failed to unpack key `%s': %s", \
249 t->buf, key_strerror(rc)); \
250 goto fail; \
251 } \
252 \
253 /* Extract the components as abstract group elements. */ \
254 setgroup; \
255 setpriv; \
256 k->X = G_CREATE(k->g); \
257 setpub; \
258 \
259 /* Dispose of stuff we don't need. */ \
260 key_fetchdone(kp); \
261 return (0); \
262 \
263 /* Tidy up after mishaps. */ \
264fail: \
265 k_free(k); \
266 key_fetchdone(kp); \
267 return (-1); \
268}
269
270/* Map over the KEYTYPES to declare the load_tywhich functions using KLOAD
271 * above.
272 */
273#define KEYTYPE_KLOAD(ty, TY, setgroup, setpriv, setpub) \
274 KLOAD(ty, TY, priv, PRIV, setgroup, setpriv, \
275 { G_EXP(k->g, k->X, k->g->g, k->x); }) \
276 KLOAD(ty, TY, pub, PUB, setgroup, { }, setpub)
277KEYTYPES(KEYTYPE_KLOAD)
278
279/* Define a table of group key-loading operations. */
280struct kload_ops {
281 const char *name;
282 int (*loadpriv)(key_data *, struct kinfo *, dstr *);
283 int (*loadpub)(key_data *, struct kinfo *, dstr *);
284};
285
286static const struct kload_ops kload_ops[] = {
287#define KEYTYPE_OPS(ty, TY, setgroup, setpriv, setpub) \
288 { #ty, load_##ty##priv, load_##ty##pub },
289KEYTYPES(KEYTYPE_OPS)
290 { 0 }
291};
292
293/* Load a private or public (indicated by PRIVP) key named TAG into a kinfo
294 * structure K. Also fill in the cipher suite selections extracted from the
295 * key attributes.
296 */
297static int loadkey(const char *tag, struct kinfo *k, int privp)
298{
299 const struct kload_ops *ops;
300 dstr d = DSTR_INIT, dd = DSTR_INIT;
301 key *ky;
302 key_data **kd;
303 const char *ty, *p;
304 char *q;
305 int tsz;
306 int rc;
307
308 /* Find the key data. */
309 if (key_qtag(kf, tag, &d, &ky, &kd)) {
310 complain(LOG_ERR, "unknown key tag `%s'", tag);
311 goto fail;
312 }
313
314 /* Find the key's group type and locate the group operations. */
315 ty = key_getattr(kf, ky, "group");
316 if (!ty && strncmp(ky->type, "udpkey-", 7) == 0) ty = ky->type + 7;
317 if (!ty) {
318 complain(LOG_ERR, "no group type for key %s", d.buf);
319 goto fail;
320 }
321 for (ops = kload_ops; ops->name; ops++) {
322 if (strcmp(ty, ops->name) == 0)
323 goto found;
324 }
325 complain(LOG_ERR, "unknown group type `%s' in key %s", ty, d.buf);
326 goto fail;
327
328found:
329 /* Extract the key data into an appropriately abstract form. */
330 k->g = 0; k->x = 0; k->X = 0;
331 if ((rc = (privp ? ops->loadpriv : ops->loadpub)(*kd, k, &d)) != 0)
332 goto fail;
333
334 /* Extract the chosen symmetric cipher. */
335 if ((p = key_getattr(kf, ky, "cipher")) == 0)
336 k->cc = &rijndael_counter;
337 else if ((k->cc = gcipher_byname(p)) == 0) {
338 complain(LOG_ERR, "unknown cipher `%s' in key %s", p, d.buf);
339 goto fail;
340 }
341
342 /* And the chosen hash function. */
343 if ((p = key_getattr(kf, ky, "hash")) == 0)
344 k->hc = &sha256;
345 else if ((k->hc = ghash_byname(p)) == 0) {
346 complain(LOG_ERR, "unknown hash `%s' in key %s", p, d.buf);
347 goto fail;
348 }
349
350 /* And finally a MAC. This is more fiddly because we must handle (a)
351 * truncation and (b) defaulting based on the hash.
352 */
353 if ((p = key_getattr(kf, ky, "mac")) == 0)
354 dstr_putf(&dd, "%s-hmac", k->hc->name);
355 else
356 dstr_puts(&dd, p);
357 if ((q = strchr(dd.buf, '/')) != 0) *q++ = 0;
358 else q = 0;
359 if ((k->mc = gmac_byname(dd.buf)) == 0) {
360 complain(LOG_ERR, "unknown mac `%s' in key %s", dd.buf, d.buf);
361 goto fail;
362 }
363 if (!q)
364 k->tagsz = k->mc->hashsz/2;
365 else {
366 tsz = atoi(q);
367 if (tsz <= 0 || tsz%8 || tsz/8 > k->mc->hashsz) {
46716e8f 368 complain(LOG_ERR, "bad tag size `%s' for mac `%s' in key %s",
247f344a
MW
369 q, k->mc->name, d.buf);
370 goto fail;
371 }
372 k->tagsz = tsz/8;
373 }
374
375 /* Done. */
376 rc = 0;
377 goto done;
378
379fail:
380 rc = -1;
381done:
382 dstr_destroy(&d);
383 dstr_destroy(&dd);
384 return (rc);
385}
386
387static void keymoan(const char *file, int line, const char *err, void *p)
388 { complain(LOG_ERR, "%s:%d: %s", file, line, err); }
389
390/* Update the keyring `kf' if the file has been changed since we last looked.
391 */
392static void kfupdate(void)
393{
394 key_file *kfnew;
395
396 if (!fwatch_update(&kfwatch, kfname)) return;
397 kfnew = CREATE(key_file);
398 if (key_open(kfnew, kfname, KOPEN_READ, keymoan, 0)) {
399 DESTROY(kfnew);
400 return;
401 }
402 key_close(kf);
403 DESTROY(kf);
404 kf = kfnew;
405}
406
407/*----- Low-level crypto operations ---------------------------------------*/
408
409/* Derive a key, writing its address to *KK and size to *N. The size is
410 * compatible with the keysz rules KSZ. It is generated for the purpose of
411 * keying a WHAT (used for key separation and in error messages), and NAME is
412 * the name of the specific instance (e.g., `twofish-counter') from the class
413 * name. The kinfo structure K tells us which algorithms to use for the
414 * derivation. The group elements U and Z are the cryptographic inputs
415 * for the derivation.
416 *
417 * Basically all we do is compute H(what || U || Z).
418 */
419static int derive(struct kinfo *k, ge *U, ge *Z,
420 const char *what, const char *name, const octet *ksz,
421 octet **kk, size_t *n)
422{
423 buf b;
424 ghash *h;
425 octet *p;
426
427 /* Find a suitable key size. */
428 if ((*n = keysz(k->hc->hashsz, ksz)) == 0) {
429 complain(LOG_ERR,
430 "failed to find suitable key size for %s `%s' and hash `%s'",
431 what, name, k->hc->name);
432 return (-1);
433 }
434
435 /* Build the hash preimage. */
436 buf_init(&b, obuf, sizeof(obuf));
437 buf_put(&b, "udpkey-", 7);
438 buf_putstrz(&b, what);
439 G_TORAW(k->g, &b, U);
440 G_TORAW(k->g, &b, Z);
441 if (BBAD(&b)) {
442 complain(LOG_ERR, "overflow while deriving key (prepare preimage)!");
443 return (-1);
444 }
445
446 /* Derive the output key. */
447 h = GH_INIT(k->hc);
448 GH_HASH(h, BBASE(&b), BLEN(&b));
449 buf_init(&b, obuf, sizeof(obuf));
450 if ((p = buf_get(&b, h->ops->c->hashsz)) == 0) {
451 complain(LOG_ERR, "overflow while deriving key (output hash)!");
452 GH_DESTROY(h);
453 return (-1);
454 }
455 GH_DONE(h, p);
456 GH_DESTROY(h);
457 *kk = p;
458 return (0);
459}
460
461#ifdef DEBUG
462static void debug_mp(const char *what, mp *x)
463 { fprintf(stderr, "%s: *** ", QUIS); MP_EPRINT(what, x); }
464static void debug_ge(const char *what, group *g, ge *X)
465{
466 fprintf(stderr, "%s: *** %s = ", QUIS, what);
467 group_writefile(g, X, stderr);
468 fputc('\n', stderr);
469}
470#endif
471
7f5ea7d3
MW
472/*----- Protocol summary --------------------------------------------------*
473 *
474 * * Request
475 * memz KEYTAG tag of wanted secret
476 * ge U public vector
477 *
478 * * Response
479 * ge V public vector: V = v P
480 * ge W encrypted clue: W = R - Y = r P - v U
481 * mem[TAGSZ] TAG MAC tag on ciphertext
482 * mem[KSZ] CT secret, encrypted with Z = r X
483 */
484
247f344a
MW
485/*----- Listening for requests --------------------------------------------*/
486
487/* Rate limiting parameters.
488 *
489 * There's a probabilistic rate-limiting mechanism. A counter starts at 0.
c33ded25 490 * Every time we process a request, we increment the counter. The counter
247f344a
MW
491 * drops by RATE_REFILL every second. If the counter is below RATE_CREDIT
492 * then the request is processed; otherwise it is processed with probability
493 * 1/(counter - RATE_CREDIT).
494 */
495#define RATE_REFILL 10 /* Credits per second. */
496#define RATE_CREDIT 1000 /* Initial credit. */
497
7f5ea7d3
MW
498static time_t now;
499
500static int fetch_key(const char *tag, struct sockaddr_in *sin,
501 key **ky, struct kinfo *k)
502{
503 dstr d = DSTR_INIT, dd = DSTR_INIT;
504 key_data **kkd;
505 char *p, *q;
506 const char *pp;
507 struct in_addr in;
508 int ch, mlen, rc = -1;
509
510 /* Find the key. */
511 kfupdate();
512 if (key_qtag(kf, tag, &d, ky, &kkd)) {
513 complain(LOG_WARNING, "unknown key tag `%s' from %s:%d",
514 tag, inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
515 goto done;
516 }
517
518 /* And make sure that it has the right shape. */
519 if (((*ky)->k->e & KF_ENCMASK) != KENC_BINARY) {
520 complain(LOG_ERR, "key %s is not plain binary data", d.buf);
521 goto done;
522 }
523
524 /* Find the list of clients, and look up the caller's address in the
525 * list. Entries have the form ADDRESS[/LEN][=TAG] and are separated by
526 * `;'.
527 */
528 if ((pp = key_getattr(kf, *ky, "clients")) == 0) {
529 complain(LOG_WARNING,
530 "key %s requested from %s:%d has no `clients' attribute",
531 d.buf, inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
532 goto done;
533 }
534 dstr_puts(&dd, pp);
535 p = dd.buf;
536 while (*p) {
537 q = p;
538 while (isdigit((unsigned char)*q) || *q == '.') q++;
539 ch = *q; *q++ = 0;
540 if (!inet_aton(p, &in)) goto skip;
541 if (ch != '/')
542 mlen = 32;
543 else {
544 p = q;
545 while (isdigit((unsigned char)*q)) q++;
546 ch = *q; *q++ = 0;
547 mlen = atoi(p);
548 }
549 if (((sin->sin_addr.s_addr ^ in.s_addr) &
550 htonl(0xffffffff << (32 - mlen))) == 0)
551 goto match;
552 skip:
553 if (!ch) break;
554 p = q;
555 while (*p && *p != ';') p++;
556 if (*p) p++;
557 }
558 complain(LOG_WARNING, "access to key %s denied to %s:%d",
559 d.buf, inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
560 goto done;
561
562match:
563 /* Build a tag name for the caller's KEM key, either from the client
564 * match or the source address.
565 */
566 if (ch != '=') {
567 DRESET(&dd);
568 dstr_puts(&dd, "client-");
569 dstr_puts(&dd, inet_ntoa(sin->sin_addr));
570 p = dd.buf;
571 } else {
572 p = q;
573 while (*q && *q != ';') q++;
574 if (*q == ';') *q++ = 0;
575 }
576
577 /* Report the match. */
578 complain(LOG_NOTICE, "client %s:%d (`%s') requests key %s",
579 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p, d.buf);
580
581 /* Load the KEM key. */
582 if (loadkey(p, k, 0)) goto done;
583 D( debug_ge("X", k.g, k.X); )
584
585 /* All complete. */
586 rc = 0;
587
588done:
589 /* Clean everything up. */
590 dstr_destroy(&d);
591 dstr_destroy(&dd);
592 if (rc) k_free(k);
593 return (rc);
594}
595
596static int respond_v0(buf *bin, buf *bout, struct sockaddr_in *sin)
597{
598 ge *R = 0, *U = 0, *V = 0, *W = 0, *Y = 0, *Z = 0;
599 mp *r = MP_NEW, *v = MP_NEW;
600 octet *kk, *t, *tt;
601 char *p;
602 size_t sz;
603 ghash *h = 0;
604 gmac *m = 0;
605 gcipher *c = 0;
606 struct kinfo k;
607 key *ky;
608 size_t ksz;
609 int rc = -1;
610
611 /* Clear out the key state. */
612 k_init(&k);
613
614 /* Extract the key tag name. */
615 if ((p = buf_getmemz(bin, &sz)) == 0) {
616 complain(LOG_WARNING, "invalid key tag from %s:%d",
617 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
618 goto done;
619 }
620
621 /* Find the client's key and check that it's allowed. */
622 if (fetch_key(p, sin, &ky, &k)) goto done;
623
624 /* Read the caller's ephemeral key. */
625 R = G_CREATE(k.g); W = G_CREATE(k.g);
626 U = G_CREATE(k.g); V = G_CREATE(k.g);
627 Y = G_CREATE(k.g); Z = G_CREATE(k.g);
628 if (G_FROMBUF(k.g, bin, U)) {
629 complain(LOG_WARNING, "failed to read ephemeral vector from %s:%d",
630 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
631 goto done;
632 }
633 D( debug_ge("U", k.g, U); )
634 if (BLEFT(bin)) {
635 complain(LOG_WARNING, "trailing junk in request from %s:%d",
636 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
637 goto done;
638 }
639
640 /* Ephemeral Diffie--Hellman. Choose v in GF(q) at random; compute
641 * V = v P and -Y = (-v) U.
642 */
643 v = mprand_range(v, k.g->r, &rand_global, 0);
644 G_EXP(k.g, V, k.g->g, v);
645 D( debug_mp("v", v); debug_ge("V", k.g, V); )
646 v = mp_sub(v, k.g->r, v);
647 G_EXP(k.g, Y, U, v);
648 D( debug_ge("-Y", k.g, Y); )
649
650 /* DLIES. Choose r in GF(q) at random; compute R = r P and Z = r X. Mask
651 * the clue R as W = R - Y. (Doing the subtraction here makes life easier
652 * at the other end, since we can determine -Y by negating v whereas the
653 * recipient must subtract vectors which may be less efficient.)
654 */
655 r = mprand_range(r, k.g->r, &rand_global, 0);
656 G_EXP(k.g, R, k.g->g, r);
657 D( debug_mp("r", r); debug_ge("R", k.g, R); )
658 G_EXP(k.g, Z, k.X, r);
659 G_MUL(k.g, W, R, Y);
660 D( debug_ge("Z", k.g, Z); debug_ge("W", k.g, W); )
661
662 /* Derive encryption and integrity keys. */
663 derive(&k, R, Z, "cipher", k.cc->name, k.cc->keysz, &kk, &ksz);
664 c = GC_INIT(k.cc, kk, ksz);
665 derive(&k, R, Z, "mac", k.mc->name, k.mc->keysz, &kk, &ksz);
666 m = GM_KEY(k.mc, kk, ksz);
667
668 /* Build the ciphertext and compute a MAC tag over it. */
669 rc = 0;
670 if (G_TOBUF(k.g, bout, V) ||
671 G_TOBUF(k.g, bout, W))
672 goto done;
673 if ((t = buf_get(bout, k.tagsz)) == 0) goto done;
674 sz = ky->k->u.k.sz;
675 if (BENSURE(bout, sz)) goto done;
676 GC_ENCRYPT(c, ky->k->u.k.k, BCUR(bout), sz);
677 h = GM_INIT(m);
678 GH_HASH(h, BCUR(bout), sz);
679 tt = GH_DONE(h, 0); memcpy(t, tt, k.tagsz);
680 BSTEP(bout, sz);
681
682done:
683 /* Clear everything up and go home. */
684 if (R) G_DESTROY(k.g, R);
685 if (U) G_DESTROY(k.g, U);
686 if (V) G_DESTROY(k.g, V);
687 if (W) G_DESTROY(k.g, W);
688 if (Y) G_DESTROY(k.g, Y);
689 if (Z) G_DESTROY(k.g, Z);
690 if (c) GC_DESTROY(c);
691 if (m) GM_DESTROY(m);
692 if (h) GH_DESTROY(h);
693 if (r) MP_DROP(r);
694 if (v) MP_DROP(v);
695 k_free(&k);
696 return (rc);
697}
698
247f344a
MW
699static int dolisten(int argc, char *argv[])
700{
701 int sk;
7f5ea7d3 702 char *p;
247f344a
MW
703 char *aspec;
704 ssize_t n;
247f344a
MW
705 fd_set fdin;
706 struct sockaddr_in sin;
247f344a
MW
707 socklen_t len;
708 buf bin, bout;
247f344a 709 FILE *fp = 0;
247f344a 710 unsigned bucket = 0, toks;
7f5ea7d3 711 time_t last = 0;
247f344a
MW
712
713 /* Set up the socket address. */
714 sin.sin_family = AF_INET;
715 aspec = xstrdup(argv[0]);
716 if ((p = strchr(aspec, ':')) == 0) {
717 p = aspec;
718 sin.sin_addr.s_addr = INADDR_ANY;
719 } else {
720 *p++ = 0;
721 resolve(aspec, &sin.sin_addr);
722 }
723 sin.sin_port = htons(getport(p));
724
725 /* Create and set up the socket itself. */
726 if ((sk = socket(PF_INET, SOCK_DGRAM, 0)) < 0 ||
727 fdflags(sk, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC) ||
728 bind(sk, (struct sockaddr *)&sin, sizeof(sin)))
729 die(1, "failed to create socket: %s", strerror(errno));
730
731 /* That's enough initialization. If we should fork, then do that. */
732 if (flags & f_daemon) {
733 if (pidfile && (fp = fopen(pidfile, "w")) == 0)
734 die(1, "failed to open pidfile `%s': %s", pidfile, strerror(errno));
735 openlog(QUIS, LOG_PID, LOG_DAEMON);
736 if (daemonize())
737 die(1, "failed to become background process: %s", strerror(errno));
738 if (pidfile) { fprintf(fp, "%ld\n", (long)getpid()); fclose(fp); }
739 flags |= f_syslog;
740 }
741
742 for (;;) {
743
247f344a
MW
744 /* Wait for something to happen. */
745 FD_ZERO(&fdin);
746 FD_SET(sk, &fdin);
747 if (select(sk + 1, &fdin, 0, 0, 0) < 0)
748 die(1, "select failed: %s", strerror(errno));
749 noise_timer(RAND_GLOBAL);
750
751 /* Fetch a packet. */
752 len = sizeof(sin);
753 n = recvfrom(sk, ibuf, sizeof(ibuf), 0, (struct sockaddr *)&sin, &len);
754 if (n < 0) {
755 if (errno != EAGAIN && errno != EINTR)
756 complain(LOG_ERR, "unexpected receive error: %s", strerror(errno));
7f5ea7d3 757 continue;
247f344a
MW
758 }
759
760 /* Refill the bucket, and see whether we should reject this packet. */
761 now = time(0);
762 if (bucket && now != last) {
763 toks = (now - last)*RATE_REFILL;
764 bucket = bucket < toks ? 0 : bucket - toks;
765 }
766 last = now;
767 if (bucket > RATE_CREDIT &&
768 grand_range(&rand_global, bucket - RATE_CREDIT))
7f5ea7d3 769 continue;
247f344a
MW
770 bucket++;
771
772 /* Set up the input buffer for parsing the request. */
773 buf_init(&bin, ibuf, n);
247f344a 774 buf_init(&bout, obuf, sizeof(obuf));
7f5ea7d3
MW
775
776 /* Handle the client's message. */
777 if (respond_v0(&bin, &bout, &sin)) continue;
247f344a
MW
778
779 /* Send the reply packet back to the caller. */
7f5ea7d3 780 if (!BOK(&bout)) goto bad;
247f344a
MW
781 if (sendto(sk, BBASE(&bout), BLEN(&bout), 0,
782 (struct sockaddr *)&sin, len) < 0) {
783 complain(LOG_ERR, "failed to send response to %s:%d: %s",
784 inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
785 strerror(errno));
7f5ea7d3 786 continue;
247f344a
MW
787 }
788
7f5ea7d3 789 continue;
247f344a
MW
790
791 bad:
792 /* Report a problem building the reply. */
793 complain(LOG_ERR, "failed to construct response to %s:%d",
794 inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
247f344a
MW
795 }
796
797 return (-1);
798}
799
800/*----- Sending requests and processing responses -------------------------*/
801
802struct query {
803 struct query *next;
804 octet *k;
805 size_t sz;
806 struct server *s;
807};
808
809struct server {
810 struct server *next;
811 struct sockaddr_in sin;
812 struct kinfo k;
813 mp *u;
814 ge *U;
815 octet *h;
816};
817
818/* Record a successful fetch of key material for a query Q. The data starts
819 * at K and is SZ bytes long. The data is copied: it's safe to overwrite it.
820 */
821static void donequery(struct query *q, const void *k, size_t sz)
822 { q->k = xmalloc(sz); memcpy(q->k, k, sz); q->sz = sz; nq--; }
823
824/* Initialize a query to a remote server. */
825static struct query *qinit_net(const char *tag, const char *spec)
826{
827 struct query *q;
828 struct server *s, **stail;
829 dstr d = DSTR_INIT, dd = DSTR_INIT;
830 hex_ctx hc;
831 char *p, *pp, ch;
832
833 /* Allocate the query block. */
834 q = CREATE(struct query);
835 stail = &q->s;
836
837 /* Put the spec somewhere we can hack at it. */
838 dstr_puts(&d, spec);
839 p = d.buf;
840
841 /* Parse the query spec. Entries have the form ADDRESS:PORT[=TAG][#HASH]
842 * and are separated by `;'.
843 */
844 while (*p) {
845
846 /* Allocate a new server node. */
847 s = CREATE(struct server);
848 s->sin.sin_family = AF_INET;
849
850 /* Extract the server address. */
851 if ((pp = strchr(p, ':')) == 0)
852 die(1, "invalid syntax: missing `:PORT'");
853 *pp++ = 0;
854 resolve(p, &s->sin.sin_addr);
855
856 /* Extract the port number. */
857 p = pp;
858 while (isdigit((unsigned char)*pp)) pp++;
859 ch = *pp; *pp++ = 0;
860 s->sin.sin_port = htons(getport(p));
861
862 /* If there's a key tag then extract that; otherwise use a default. */
863 if (ch != '=')
864 p = "udpkey-kem";
865 else {
866 p = pp;
867 pp += strcspn(pp, ";#");
868 ch = *pp; *pp++ = 0;
869 }
870 if (loadkey(p, &s->k, 1)) exit(1);
871 D( debug_mp("x", s->k.x); debug_ge("X", s->k.g, s->k.X); )
872
873 /* Choose an ephemeral private key u. Let x be our private key. We
874 * compute U = u P and transmit this.
875 */
876 s->u = mprand_range(MP_NEW, s->k.g->r, &rand_global, 0);
877 s->U = G_CREATE(s->k.g);
878 G_EXP(s->k.g, s->U, s->k.g->g, s->u);
879 D( debug_mp("u", s->u); debug_ge("U", s->k.g, s->U); )
880
881 /* Link the server on. */
882 *stail = s; stail = &s->next;
883
884 /* If there's a trailing hash then extract it. */
885 if (ch != '#')
886 s->h = 0;
887 else {
888 p = pp;
889 while (*pp == '-' || isxdigit((unsigned char)*pp)) pp++;
890 hex_init(&hc);
891 DRESET(&dd);
892 hex_decode(&hc, p, pp - p, &dd);
893 if (dd.len != s->k.hc->hashsz) die(1, "incorrect hash length");
894 s->h = xmalloc(dd.len);
895 memcpy(s->h, dd.buf, dd.len);
896 ch = *pp++;
897 }
898
899 /* If there are more servers, then continue parsing. */
900 if (!ch) break;
901 else if (ch != ';') die(1, "invalid syntax: expected `;'");
902 p = pp;
903 }
904
905 /* Terminate the server list and return. */
906 *stail = 0;
907 q->k = 0;
908 dstr_destroy(&d);
909 dstr_destroy(&dd);
910 return (q);
911}
912
913/* Handle a `query' to a local file. */
914static struct query *qinit_file(const char *tag, const char *file)
915{
916 struct query *q;
917 void *k;
918 size_t sz;
919
920 /* Snarf the file. */
921 q = CREATE(struct query);
922 if (snarf(file, &k, &sz))
923 die(1, "failed to read `%s': %s", file, strerror(errno));
924 q->s = 0;
925 donequery(q, k, sz);
926 return (q);
927}
928
c33ded25 929/* Retransmission and timeout parameters. */
247f344a
MW
930#define TO_NEXT(t) (((t) + 2)*4/3) /* Timeout growth function */
931#define TO_MAX 30 /* When to give up */
932
933static int doquery(int argc, char *argv[])
934{
935 struct query *q = 0, *qq, **qtail = &qq;
936 struct server *s = 0;
937 const char *tag = argv[0];
938 octet *p;
939 int i;
940 int sk;
941 fd_set fdin;
942 struct timeval now, when, tv;
943 struct sockaddr_in sin;
944 ge *R, *V = 0, *W = 0, *Y = 0, *Z = 0;
945 octet *kk, *t, *tt;
946 gcipher *c = 0;
947 gmac *m = 0;
948 ghash *h = 0;
949 socklen_t len;
950 unsigned next = 0;
951 buf bin, bout;
952 size_t n, j, ksz;
953 ssize_t nn;
954
955 /* Create a socket. We just use the one socket for everything. We don't
956 * care which port we get allocated.
957 */
958 if ((sk = socket(PF_INET, SOCK_DGRAM, 0)) < 0 ||
959 fdflags(sk, O_NONBLOCK, O_NONBLOCK, FD_CLOEXEC, FD_CLOEXEC))
960 die(1, "failed to create socket: %s", strerror(errno));
961
962 /* Parse the query target specifications. The adjustments of `nq' aren't
963 * in the right order but that doesn't matter.
964 */
965 for (i = 1; i < argc; i++) {
966 if (*argv[i] == '.' || *argv[i] == '/') q = qinit_file(tag, argv[i]);
967 else if (strchr(argv[i], ':')) q = qinit_net(tag, argv[i]);
968 else die(1, "unrecognized query target `%s'", argv[i]);
969 *qtail = q; qtail = &q->next; nq++;
970 }
971 *qtail = 0;
972
973 /* Find the current time so we can compute retransmission times properly.
974 */
975 gettimeofday(&now, 0);
976 when = now;
977
978 /* Continue retransmitting until we have all the answers. */
979 while (nq) {
980
981 /* Work out when we next want to wake up. */
982 if (TV_CMP(&now, >=, &when)) {
983 do {
984 if (next >= TO_MAX) die(1, "no responses: giving up");
985 next = TO_NEXT(next);
986 TV_ADDL(&when, &when, next, 0);
987 } while (TV_CMP(&when, <=, &now));
988 for (q = qq; q; q = q->next) {
989 if (q->k) continue;
990 for (s = q->s; s; s = s->next) {
991 buf_init(&bout, obuf, sizeof(obuf));
992 buf_putstrz(&bout, tag);
993 G_TOBUF(s->k.g, &bout, s->U);
994 if (BBAD(&bout)) {
995 moan("overflow while constructing request!");
996 continue;
997 }
998 sendto(sk, BBASE(&bout), BLEN(&bout), 0,
999 (struct sockaddr *)&s->sin, sizeof(s->sin));
1000 }
1001 }
1002 }
1003
1004 /* Wait until something interesting happens. */
1005 FD_ZERO(&fdin);
1006 FD_SET(sk, &fdin);
1007 TV_SUB(&tv, &when, &now);
1008 if (select(sk + 1, &fdin, 0, 0, &tv) < 0)
1009 die(1, "select failed: %s", strerror(errno));
1010 gettimeofday(&now, 0);
1011
1012 /* If we have an input event, process incoming packets. */
1013 if (FD_ISSET(sk, &fdin)) {
1014 for (;;) {
1015
1016 /* Read a packet and capture its address. */
1017 len = sizeof(sin);
1018 nn = recvfrom(sk, ibuf, sizeof(ibuf), 0,
1019 (struct sockaddr *)&sin, &len);
1020 if (nn < 0) {
1021 if (errno == EAGAIN) break;
1022 else if (errno == EINTR) continue;
1023 else {
1024 moan("error receiving reply: %s", strerror(errno));
1025 goto again;
1026 }
1027 }
1028
1f27bade 1029 /* See whether this corresponds to any of our servers. Don't just
c33ded25 1030 * check the active servers, since this may be late a reply caused by
247f344a
MW
1031 * retransmissions or similar.
1032 */
1033 for (q = qq; q; q = q->next) {
1034 for (s = q->s; s; s = s->next) {
1035 if (s->sin.sin_addr.s_addr == sin.sin_addr.s_addr &&
1036 s->sin.sin_port == sin.sin_port)
1037 goto found;
1038 }
1039 }
1040 moan("received reply from unexpected source %s:%d",
1041 inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1042 goto again;
1043
1044 found:
1045 /* If the query we found has now been satisfied, ignore this packet.
1046 */
1047 if (q->k) goto again;
1048
1049 /* Start parsing the reply. */
1050 buf_init(&bin, ibuf, nn);
1051 R = G_CREATE(s->k.g);
1052 V = G_CREATE(s->k.g); W = G_CREATE(s->k.g);
1053 Y = G_CREATE(s->k.g); Z = G_CREATE(s->k.g);
1054 if (G_FROMBUF(s->k.g, &bin, V)) {
1055 moan("invalid Diffie--Hellman vector from %s:%d",
1056 inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1057 goto again;
1058 }
1059 if (G_FROMBUF(s->k.g, &bin, W)) {
1060 moan("invalid clue vector from %s:%d",
1061 inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1062 goto again;
1063 }
1064 D( debug_ge("V", s->k.g, V); debug_ge("W", s->k.g, W); )
1065
1066 /* We have V and W from the server; determine Y = u V, R = W + Y and
1067 * Z = x R, and then derive the symmetric keys.
1068 */
1069 G_EXP(s->k.g, Y, V, s->u);
1070 G_MUL(s->k.g, R, W, Y);
1071 G_EXP(s->k.g, Z, R, s->k.x);
1072 D( debug_ge("R", s->k.g, R);
1073 debug_ge("Y", s->k.g, Y);
1074 debug_ge("Z", s->k.g, Z); )
1075 derive(&s->k, R, Z, "cipher", s->k.cc->name, s->k.cc->keysz,
1076 &kk, &ksz);
1077 c = GC_INIT(s->k.cc, kk, ksz);
1078 derive(&s->k, R, Z, "mac", s->k.cc->name, s->k.cc->keysz,
1079 &kk, &ksz);
1080 m = GM_KEY(s->k.mc, kk, ksz);
1081
1082 /* Find where the MAC tag is. */
1083 if ((t = buf_get(&bin, s->k.tagsz)) == 0) {
1084 moan("missing tag from %s:%d",
1085 inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1086 goto again;
1087 }
1088
1089 /* Check the integrity of the ciphertext against the tag. */
1090 p = BCUR(&bin); n = BLEFT(&bin);
1091 h = GM_INIT(m);
1092 GH_HASH(h, p, n);
1093 tt = GH_DONE(h, 0);
a5f873be 1094 if (!ct_memeq(t, tt, s->k.tagsz)) {
247f344a
MW
1095 moan("incorrect tag from %s:%d",
1096 inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1097 goto again;
1098 }
1099
1100 /* Decrypt the result and declare this server done. */
1101 GC_DECRYPT(c, p, p, n);
1102 if (s->h) {
1103 GH_DESTROY(h);
1104 h = GH_INIT(s->k.hc);
1105 GH_HASH(h, p, n);
1106 tt = GH_DONE(h, 0);
1107 if (memcmp(tt, s->h, h->ops->c->hashsz) != 0) {
1108 moan("response from %s:%d doesn't match hash",
1109 inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1110 goto again;
1111 }
1112 }
1113 donequery(q, p, n);
1114
1115 again:
1116 /* Tidy things up for the next run through. */
1117 if (R) { G_DESTROY(s->k.g, R); R = 0; }
1118 if (V) { G_DESTROY(s->k.g, V); V = 0; }
1119 if (W) { G_DESTROY(s->k.g, W); W = 0; }
1120 if (Y) { G_DESTROY(s->k.g, Y); Y = 0; }
1121 if (Z) { G_DESTROY(s->k.g, Z); Z = 0; }
1122 if (c) { GC_DESTROY(c); c = 0; }
1123 if (m) { GM_DESTROY(m); m = 0; }
1124 if (h) { GH_DESTROY(h); h = 0; }
1125 }
1126 }
1127 }
1128
1129 /* Check that all of the responses match up and XOR them together. */
1130 n = qq->sz;
1131 if (n > BUFSZ) die(1, "response too large");
1132 memset(obuf, 0, n);
1133 for (q = qq; q; q = q->next) {
1134 if (!q->k) die(1, "INTERNAL: query not complete");
1135 if (q->sz != n) die(1, "inconsistent response sizes");
1136 for (j = 0; j < n; j++) obuf[j] ^= q->k[j];
1137 }
1138
1139 /* Write out the completed answer. */
1140 p = obuf;
1141 while (n) {
1142 if ((nn = write(STDOUT_FILENO, p, n)) < 0)
1143 die(1, "error writing response: %s", strerror(errno));
1144 p += nn; n -= nn;
1145 }
1146 return (0);
1147}
1148
1149/*----- Main program ------------------------------------------------------*/
1150
1151static void usage(FILE *fp)
1152{
1153 pquis(fp, "Usage: \n\
461b1e7f 1154 $ [-OPTS] LABEL {ADDR:PORT[=TAG][#HASH];... | FILE} ...\n\
247f344a
MW
1155 $ [-OPTS] -l [ADDR:]PORT\n\
1156");
1157}
1158
1159static void version(FILE *fp)
a2fd0b74 1160 { pquis(fp, "$, version " VERSION "\n"); }
247f344a
MW
1161
1162static void help(FILE *fp)
1163{
1164 version(fp);
1165 putc('\n', fp);
1166 usage(fp);
1167 fputs("\n\
1168Options:\n\
1169\n\
1170 -d, --daemon Run in the background while listening.\n\
1171 -k, --keyring=FILE Read keys from FILE. [default = `keyring']\n\
1172 -l, --listen Listen for incoming requests and serve keys.\n\
1173 -p, --pidfile=FILE Write process id to FILE if in daemon mode.\n\
1174 -r, --random=FILE Key random number generator with contents of FILE.\n\
1175", fp);
1176}
1177
1178int main(int argc, char *argv[])
1179{
1180 int argmin, argmax;
1181 void *k;
1182 size_t sz;
1183
1184 ego(argv[0]);
1185 for (;;) {
1186 static const struct option opts[] = {
1187 { "help", 0, 0, 'h' },
1188 { "version", 0, 0, 'v' },
1189 { "usage", 0, 0, 'u' },
1190 { "daemon", 0, 0, 'd' },
1191 { "keyfile", OPTF_ARGREQ, 0, 'k' },
1192 { "listen", 0, 0, 'l' },
1193 { "pidfile", OPTF_ARGREQ, 0, 'p' },
1194 { "random", OPTF_ARGREQ, 0, 'r' },
1195 { 0 }
1196 };
1197
1198 int i = mdwopt(argc, argv, "hvu" "dk:lp:r:", opts, 0, 0, 0);
1199 if (i < 0) break;
1200
1201 switch (i) {
1202 case 'h': help(stdout); exit(0);
1203 case 'v': version(stdout); exit(0);
1204 case 'u': usage(stdout); exit(0);
1205
1206 case 'd': flags |= f_daemon; break;
1207 case 'k': kfname = optarg; break;
1208 case 'l': flags |= f_listen; break;
1209 case 'p': pidfile = optarg; break;
1210 case 'r':
1211 if (snarf(optarg, &k, &sz))
1212 die(1, "failed to read `%s': %s", optarg, strerror(errno));
1213 rand_key(RAND_GLOBAL, k, sz);
1214 break;
1215
1216 default: flags |= f_bogus; break;
1217 }
1218 }
1219
1220 argv += optind; argc -= optind;
1221 if (flags & f_listen) argmin = argmax = 1;
1222 else argmin = 2, argmax = -1;
1223 if ((flags & f_bogus) || argc < argmin || (argmax >= 0 && argc > argmax))
1224 { usage(stderr); exit(1); }
1225
1226 fwatch_init(&kfwatch, kfname);
1227 kf = CREATE(key_file);
1228 if (key_open(kf, kfname, KOPEN_READ, keymoan, 0))
1229 die(1, "failed to open keyring file `%s'", kfname);
1230
1231 rand_noisesrc(RAND_GLOBAL, &noise_source);
1232 rand_seed(RAND_GLOBAL, 512);
1233
1234 if (flags & f_listen) return dolisten(argc, argv);
1235 else return doquery(argc, argv);
1236}
1237
1238/*----- That's all, folks -------------------------------------------------*/