Merge from vendor branch FILE:
[dragonfly.git] / usr.sbin / setkey / setkey.c
1 /*      $FreeBSD: src/usr.sbin/setkey/setkey.c,v 1.1.2.3 2003/04/26 23:53:54 sumikawa Exp $     */
2 /*      $DragonFly: src/usr.sbin/setkey/setkey.c,v 1.5 2004/12/18 22:48:14 swildner Exp $       */
3 /*      $KAME: setkey.c,v 1.18 2001/05/08 04:36:39 itojun Exp $ */
4
5 /*
6  * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #include <sys/types.h>
35 #include <sys/param.h>
36 #include <sys/socket.h>
37 #include <sys/time.h>
38 #include <err.h>
39 #include <net/route.h>
40 #include <netinet/in.h>
41 #include <net/pfkeyv2.h>
42 #include <netkey/keydb.h>
43 #include <netkey/key_debug.h>
44 #include <netinet6/ipsec.h>
45
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <limits.h>
49 #include <string.h>
50 #include <ctype.h>
51 #include <unistd.h>
52 #include <errno.h>
53 #include <netdb.h>
54
55 #include "libpfkey.h"
56
57 void Usage(void);
58 int main(int, char **);
59 int get_supported(void);
60 void sendkeyshort(u_int);
61 void promisc(void);
62 int sendkeymsg(void);
63 int postproc(struct sadb_msg *, int);
64 const char *numstr(int);
65 void shortdump_hdr(void);
66 void shortdump(struct sadb_msg *);
67 static void printdate(void);
68 static int32_t gmt2local(time_t);
69
70 #define MODE_SCRIPT     1
71 #define MODE_CMDDUMP    2
72 #define MODE_CMDFLUSH   3
73 #define MODE_PROMISC    4
74
75 int so;
76
77 int f_forever = 0;
78 int f_all = 0;
79 int f_debug = 0;
80 int f_verbose = 0;
81 int f_mode = 0;
82 int f_cmddump = 0;
83 int f_policy = 0;
84 int f_hexdump = 0;
85 int f_tflag = 0;
86 char *pname;
87
88 u_char m_buf[BUFSIZ];
89 u_int m_len;
90
91 static time_t thiszone;
92
93 extern int lineno;
94
95 extern int parse(FILE **);
96
97 void
98 Usage()
99 {
100         printf("Usage:\t%s [-dv] -c\n", pname);
101         printf("\t%s [-dv] -f (file)\n", pname);
102         printf("\t%s [-Padlv] -D\n", pname);
103         printf("\t%s [-Pdv] -F\n", pname);
104         printf("\t%s [-h] -x\n", pname);
105         pfkey_close(so);
106         exit(1);
107 }
108
109 int
110 main(int argc, char **argv)
111 {
112         FILE *fp = stdin;
113         int c;
114
115         pname = *argv;
116
117         if (argc == 1) Usage();
118
119         thiszone = gmt2local(0);
120
121         while ((c = getopt(argc, argv, "acdf:hlvxDFP")) != -1) {
122                 switch (c) {
123                 case 'c':
124                         f_mode = MODE_SCRIPT;
125                         fp = stdin;
126                         break;
127                 case 'f':
128                         f_mode = MODE_SCRIPT;
129                         if ((fp = fopen(optarg, "r")) == NULL) {
130                                 err(-1, "fopen");
131                                 /*NOTREACHED*/
132                         }
133                         break;
134                 case 'D':
135                         f_mode = MODE_CMDDUMP;
136                         break;
137                 case 'F':
138                         f_mode = MODE_CMDFLUSH;
139                         break;
140                 case 'a':
141                         f_all = 1;
142                         break;
143                 case 'l':
144                         f_forever = 1;
145                         break;
146                 case 'h':
147                         f_hexdump = 1;
148                         break;
149                 case 'x':
150                         f_mode = MODE_PROMISC;
151                         f_tflag++;
152                         break;
153                 case 'P':
154                         f_policy = 1;
155                         break;
156                 case 'd':
157                         f_debug = 1;
158                         break;
159                 case 'v':
160                         f_verbose = 1;
161                         break;
162                 default:
163                         Usage();
164                         /*NOTREACHED*/
165                 }
166         }
167
168         switch (f_mode) {
169         case MODE_CMDDUMP:
170                 sendkeyshort(f_policy ? SADB_X_SPDDUMP: SADB_DUMP);
171                 break;
172         case MODE_CMDFLUSH:
173                 sendkeyshort(f_policy ? SADB_X_SPDFLUSH: SADB_FLUSH);
174                 pfkey_close(so);
175                 break;
176         case MODE_SCRIPT:
177                 if (get_supported() < 0) {
178                         errx(-1, "%s", ipsec_strerror());
179                         /*NOTREACHED*/
180                 }
181                 if (parse(&fp))
182                         exit (1);
183                 break;
184         case MODE_PROMISC:
185                 promisc();
186                 /*NOTREACHED*/
187         default:
188                 Usage();
189                 /*NOTREACHED*/
190         }
191
192         exit(0);
193 }
194
195 int
196 get_supported(void)
197 {
198         int so;
199
200         if ((so = pfkey_open()) < 0) {
201                 perror("pfkey_open");
202                 return -1;
203         }
204
205         /* debug mode ? */
206         if (f_debug)
207                 return 0;
208
209         if (pfkey_send_register(so, SADB_SATYPE_UNSPEC) < 0)
210                 return -1;
211
212         if (pfkey_recv_register(so) < 0)
213                 return -1;
214
215         return 0;
216 }
217
218 void
219 sendkeyshort(u_int type)
220 {
221         struct sadb_msg *m_msg = (struct sadb_msg *)m_buf;
222
223         m_len = sizeof(struct sadb_msg);
224
225         m_msg->sadb_msg_version = PF_KEY_V2;
226         m_msg->sadb_msg_type = type;
227         m_msg->sadb_msg_errno = 0;
228         m_msg->sadb_msg_satype = SADB_SATYPE_UNSPEC;
229         m_msg->sadb_msg_len = PFKEY_UNIT64(m_len);
230         m_msg->sadb_msg_reserved = 0;
231         m_msg->sadb_msg_seq = 0;
232         m_msg->sadb_msg_pid = getpid();
233
234         sendkeymsg();
235 }
236
237 void
238 promisc(void)
239 {
240         struct sadb_msg *m_msg = (struct sadb_msg *)m_buf;
241         u_char rbuf[1024 * 32]; /* XXX: Enough ? Should I do MSG_PEEK ? */
242         int so, len;
243
244         m_len = sizeof(struct sadb_msg);
245
246         m_msg->sadb_msg_version = PF_KEY_V2;
247         m_msg->sadb_msg_type = SADB_X_PROMISC;
248         m_msg->sadb_msg_errno = 0;
249         m_msg->sadb_msg_satype = 1;
250         m_msg->sadb_msg_len = PFKEY_UNIT64(m_len);
251         m_msg->sadb_msg_reserved = 0;
252         m_msg->sadb_msg_seq = 0;
253         m_msg->sadb_msg_pid = getpid();
254
255         if ((so = socket(PF_KEY, SOCK_RAW, PF_KEY_V2)) < 0) {
256                 err(1, "socket(PF_KEY)");
257                 /*NOTREACHED*/
258         }
259
260         if ((len = send(so, m_buf, m_len, 0)) < 0) {
261                 err(1, "send");
262                 /*NOTREACHED*/
263         }
264
265         while (1) {
266                 struct sadb_msg *base;
267
268                 if ((len = recv(so, rbuf, sizeof(*base), MSG_PEEK)) < 0) {
269                         err(1, "recv");
270                         /*NOTREACHED*/
271                 }
272
273                 if (len != sizeof(*base))
274                         continue;
275
276                 base = (struct sadb_msg *)rbuf;
277                 if ((len = recv(so, rbuf, PFKEY_UNUNIT64(base->sadb_msg_len),
278                                 0)) < 0) {
279                         err(1, "recv");
280                         /*NOTREACHED*/
281                 }
282                 printdate();
283                 if (f_hexdump) {
284                         int i;
285                         for (i = 0; i < len; i++) {
286                                 if (i % 16 == 0)
287                                         printf("%08x: ", i);
288                                 printf("%02x ", rbuf[i] & 0xff);
289                                 if (i % 16 == 15)
290                                         printf("\n");
291                         }
292                         if (len % 16)
293                                 printf("\n");
294                 }
295                 /* adjust base pointer for promisc mode */
296                 if (base->sadb_msg_type == SADB_X_PROMISC) {
297                         if (sizeof(*base) < len)
298                                 base++;
299                         else
300                                 base = NULL;
301                 }
302                 if (base) {
303                         kdebug_sadb(base);
304                         printf("\n");
305                         fflush(stdout);
306                 }
307         }
308 }
309
310 int
311 sendkeymsg(void)
312 {
313         int so;
314         u_char rbuf[1024 * 32]; /* XXX: Enough ? Should I do MSG_PEEK ? */
315         int len;
316         struct sadb_msg *msg;
317         struct timeval tv;
318
319         if ((so = pfkey_open()) < 0) {
320                 perror("pfkey_open");
321                 return -1;
322         }
323
324         tv.tv_sec = 1;
325         tv.tv_usec = 0;
326         if (setsockopt(so, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
327                 perror("setsockopt");
328                 goto end;
329         }
330
331         if (f_forever)
332                 shortdump_hdr();
333 again:
334         if (f_verbose) {
335                 kdebug_sadb((struct sadb_msg *)m_buf);
336                 printf("\n");
337         }
338
339         if ((len = send(so, m_buf, m_len, 0)) < 0) {
340                 perror("send");
341                 goto end;
342         }
343
344         msg = (struct sadb_msg *)rbuf;
345         do {
346                 if ((len = recv(so, rbuf, sizeof(rbuf), 0)) < 0) {
347                         perror("recv");
348                         goto end;
349                 }
350
351                 if (PFKEY_UNUNIT64(msg->sadb_msg_len) != len) {
352                         warnx("invalid keymsg length");
353                         break;
354                 }
355
356                 if (f_verbose) {
357                         kdebug_sadb((struct sadb_msg *)rbuf);
358                         printf("\n");
359                 }
360                 if (postproc(msg, len) < 0)
361                         break;
362         } while (msg->sadb_msg_errno || msg->sadb_msg_seq);
363
364         if (f_forever) {
365                 fflush(stdout);
366                 sleep(1);
367                 goto again;
368         }
369
370 end:
371         pfkey_close(so);
372         return(0);
373 }
374
375 int
376 postproc(struct sadb_msg *msg, int len)
377 {
378         if (msg->sadb_msg_errno != 0) {
379                 char inf[80];
380                 char *errmsg = NULL;
381
382                 if (f_mode == MODE_SCRIPT)
383                         snprintf(inf, sizeof(inf), "The result of line %d: ", lineno);
384                 else
385                         inf[0] = '\0';
386
387                 switch (msg->sadb_msg_errno) {
388                 case ENOENT:
389                         switch (msg->sadb_msg_type) {
390                         case SADB_DELETE:
391                         case SADB_GET:
392                         case SADB_X_SPDDELETE:
393                                 errmsg = "No entry";
394                                 break;
395                         case SADB_DUMP:
396                                 errmsg = "No SAD entries";
397                                 break;
398                         case SADB_X_SPDDUMP:
399                                 errmsg = "No SPD entries";
400                                 break;
401                         }
402                         break;
403                 default:
404                         errmsg = strerror(msg->sadb_msg_errno);
405                 }
406                 printf("%s%s.\n", inf, errmsg);
407                 return(-1);
408         }
409
410         switch (msg->sadb_msg_type) {
411         case SADB_GET:
412                 pfkey_sadump(msg);
413                 break;
414
415         case SADB_DUMP:
416                 /* filter out DEAD SAs */
417                 if (!f_all) {
418                         caddr_t mhp[SADB_EXT_MAX + 1];
419                         struct sadb_sa *sa;
420                         pfkey_align(msg, mhp);
421                         pfkey_check(mhp);
422                         if ((sa = (struct sadb_sa *)mhp[SADB_EXT_SA]) != NULL) {
423                                 if (sa->sadb_sa_state == SADB_SASTATE_DEAD)
424                                         break;
425                         }
426                 }
427                 if (f_forever)
428                         shortdump(msg);
429                 else
430                         pfkey_sadump(msg);
431                 msg = (struct sadb_msg *)((caddr_t)msg +
432                                      PFKEY_UNUNIT64(msg->sadb_msg_len));
433                 if (f_verbose) {
434                         kdebug_sadb((struct sadb_msg *)msg);
435                         printf("\n");
436                 }
437                 break;
438
439         case SADB_X_SPDDUMP:
440                 pfkey_spdump(msg);
441                 if (msg->sadb_msg_seq == 0) break;
442                 msg = (struct sadb_msg *)((caddr_t)msg +
443                                      PFKEY_UNUNIT64(msg->sadb_msg_len));
444                 if (f_verbose) {
445                         kdebug_sadb((struct sadb_msg *)msg);
446                         printf("\n");
447                 }
448                 break;
449         }
450
451         return(0);
452 }
453
454 /*------------------------------------------------------------*/
455 static char *satype[] = {
456         NULL, NULL, "ah", "esp"
457 };
458 static char *sastate[] = {
459         "L", "M", "D", "d"
460 };
461 static char *ipproto[] = {
462 /*0*/   "ip", "icmp", "igmp", "ggp", "ip4",
463         NULL, "tcp", NULL, "egp", NULL,
464 /*10*/  NULL, NULL, NULL, NULL, NULL,
465         NULL, NULL, "udp", NULL, NULL,
466 /*20*/  NULL, NULL, "idp", NULL, NULL,
467         NULL, NULL, NULL, NULL, "tp",
468 /*30*/  NULL, NULL, NULL, NULL, NULL,
469         NULL, NULL, NULL, NULL, NULL,
470 /*40*/  NULL, "ip6", NULL, "rt6", "frag6",
471         NULL, "rsvp", "gre", NULL, NULL,
472 /*50*/  "esp", "ah", NULL, NULL, NULL,
473         NULL, NULL, NULL, "icmp6", "none",
474 /*60*/  "dst6",
475 };
476
477 #define STR_OR_ID(x, tab) \
478         (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x))
479
480 const char *
481 numstr(int x)
482 {
483         static char buf[20];
484         snprintf(buf, sizeof(buf), "#%d", x);
485         return buf;
486 }
487
488 void
489 shortdump_hdr()
490 {
491         printf("%-4s %-3s %-1s %-8s %-7s %s -> %s\n",
492                 "time", "p", "s", "spi", "ltime", "src", "dst");
493 }
494
495 void
496 shortdump(struct sadb_msg *msg)
497 {
498         caddr_t mhp[SADB_EXT_MAX + 1];
499         char buf[NI_MAXHOST], pbuf[NI_MAXSERV];
500         struct sadb_sa *sa;
501         struct sadb_address *saddr;
502         struct sadb_lifetime *lts, *lth, *ltc;
503         struct sockaddr *s;
504         u_int t;
505         time_t cur;
506
507         cur = time(0);
508
509         pfkey_align(msg, mhp);
510         pfkey_check(mhp);
511
512         printf("%02lu%02lu", (u_long)(cur % 3600) / 60, (u_long)(cur % 60));
513
514         printf(" %-3s", STR_OR_ID(msg->sadb_msg_satype, satype));
515
516         if ((sa = (struct sadb_sa *)mhp[SADB_EXT_SA]) != NULL) {
517                 printf(" %-1s", STR_OR_ID(sa->sadb_sa_state, sastate));
518                 printf(" %08x", (u_int32_t)ntohl(sa->sadb_sa_spi));
519         } else
520                 printf("%-1s %-8s", "?", "?");
521
522         lts = (struct sadb_lifetime *)mhp[SADB_EXT_LIFETIME_SOFT];
523         lth = (struct sadb_lifetime *)mhp[SADB_EXT_LIFETIME_HARD];
524         ltc = (struct sadb_lifetime *)mhp[SADB_EXT_LIFETIME_CURRENT];
525         if (lts && lth && ltc) {
526                 if (ltc->sadb_lifetime_addtime == 0)
527                         t = (u_long)0;
528                 else
529                         t = (u_long)(cur - ltc->sadb_lifetime_addtime);
530                 if (t >= 1000)
531                         strcpy(buf, " big/");
532                 else
533                         snprintf(buf, sizeof(buf), " %3lu/", (u_long)t);
534                 printf("%s", buf);
535
536                 t = (u_long)lth->sadb_lifetime_addtime;
537                 if (t >= 1000)
538                         strcpy(buf, "big");
539                 else
540                         snprintf(buf, sizeof(buf), "%-3lu", (u_long)t);
541                 printf("%s", buf);
542         } else
543                 printf(" ??\?/???");    /* backslash to avoid trigraph ??/ */
544
545         printf(" ");
546
547         if ((saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC]) != NULL) {
548                 if (saddr->sadb_address_proto)
549                         printf("%s ", STR_OR_ID(saddr->sadb_address_proto, ipproto));
550                 s = (struct sockaddr *)(saddr + 1);
551                 getnameinfo(s, s->sa_len, buf, sizeof(buf),
552                         pbuf, sizeof(pbuf), NI_NUMERICHOST|NI_NUMERICSERV);
553                 if (strcmp(pbuf, "0") != 0)
554                         printf("%s[%s]", buf, pbuf);
555                 else
556                         printf("%s", buf);
557         } else
558                 printf("?");
559
560         printf(" -> ");
561
562         if ((saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST]) != NULL) {
563                 if (saddr->sadb_address_proto)
564                         printf("%s ", STR_OR_ID(saddr->sadb_address_proto, ipproto));
565
566                 s = (struct sockaddr *)(saddr + 1);
567                 getnameinfo(s, s->sa_len, buf, sizeof(buf),
568                         pbuf, sizeof(pbuf), NI_NUMERICHOST|NI_NUMERICSERV);
569                 if (strcmp(pbuf, "0") != 0)
570                         printf("%s[%s]", buf, pbuf);
571                 else
572                         printf("%s", buf);
573         } else
574                 printf("?");
575
576         printf("\n");
577 }
578
579 /* From: tcpdump(1):gmt2local.c and util.c */
580 /*
581  * Print the timestamp
582  */
583 static void
584 printdate(void)
585 {
586         struct timeval tp;
587         int s;
588
589         if (gettimeofday(&tp, NULL) == -1) {
590                 perror("gettimeofday");
591                 return;
592         }
593
594         if (f_tflag == 1) {
595                 /* Default */
596                 s = (tp.tv_sec + thiszone ) % 86400;
597                 printf("%02d:%02d:%02d.%06u ",
598                     s / 3600, (s % 3600) / 60, s % 60, (u_int32_t)tp.tv_usec);
599         } else if (f_tflag > 1) {
600                 /* Unix timeval style */
601                 printf("%u.%06u ", (u_int32_t)tp.tv_sec, (u_int32_t)tp.tv_usec);
602         }
603
604         printf("\n");
605 }
606
607 /*
608  * Returns the difference between gmt and local time in seconds.
609  * Use gmtime() and localtime() to keep things simple.
610  */
611 int32_t
612 gmt2local(time_t t)
613 {
614         int dt, dir;
615         struct tm *gmt, *loc;
616         struct tm sgmt;
617
618         if (t == 0)
619                 t = time(NULL);
620         gmt = &sgmt;
621         *gmt = *gmtime(&t);
622         loc = localtime(&t);
623         dt = (loc->tm_hour - gmt->tm_hour) * 60 * 60 +
624             (loc->tm_min - gmt->tm_min) * 60;
625
626         /*
627          * If the year or julian day is different, we span 00:00 GMT
628          * and must add or subtract a day. Check the year first to
629          * avoid problems when the julian day wraps.
630          */
631         dir = loc->tm_year - gmt->tm_year;
632         if (dir == 0)
633                 dir = loc->tm_yday - gmt->tm_yday;
634         dt += dir * 24 * 60 * 60;
635
636         return (dt);
637 }