parse.y revision 1.126
1/*	$OpenBSD: parse.y,v 1.126 2007/09/12 20:22:59 hshoexer Exp $	*/
2
3/*
4 * Copyright (c) 2002, 2003, 2004 Henning Brauer <henning@openbsd.org>
5 * Copyright (c) 2001 Markus Friedl.  All rights reserved.
6 * Copyright (c) 2001 Daniel Hartmeier.  All rights reserved.
7 * Copyright (c) 2001 Theo de Raadt.  All rights reserved.
8 * Copyright (c) 2004, 2005 Hans-Joerg Hoexer <hshoexer@openbsd.org>
9 *
10 * Permission to use, copy, modify, and distribute this software for any
11 * purpose with or without fee is hereby granted, provided that the above
12 * copyright notice and this permission notice appear in all copies.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 */
22
23%{
24#include <sys/types.h>
25#include <sys/ioctl.h>
26#include <sys/queue.h>
27#include <sys/socket.h>
28#include <sys/stat.h>
29#include <net/if.h>
30#include <netinet/in.h>
31#include <netinet/ip_ipsp.h>
32#include <arpa/inet.h>
33
34#include <ctype.h>
35#include <err.h>
36#include <errno.h>
37#include <fcntl.h>
38#include <ifaddrs.h>
39#include <limits.h>
40#include <netdb.h>
41#include <stdarg.h>
42#include <stdio.h>
43#include <string.h>
44#include <syslog.h>
45#include <unistd.h>
46#include <netdb.h>
47
48#include "ipsecctl.h"
49
50#define KEYSIZE_LIMIT	1024
51
52static struct ipsecctl	*ipsec = NULL;
53static FILE		*fin = NULL;
54static int		 lineno = 1;
55static int		 errors = 0;
56static int		 debug = 0;
57
58const struct ipsec_xf authxfs[] = {
59	{ "unknown",		AUTHXF_UNKNOWN,		0,	0 },
60	{ "none",		AUTHXF_NONE,		0,	0 },
61	{ "hmac-md5",		AUTHXF_HMAC_MD5,	16,	0 },
62	{ "hmac-ripemd160",	AUTHXF_HMAC_RIPEMD160,	20,	0 },
63	{ "hmac-sha1",		AUTHXF_HMAC_SHA1,	20,	0 },
64	{ "hmac-sha2-256",	AUTHXF_HMAC_SHA2_256,	32,	0 },
65	{ "hmac-sha2-384",	AUTHXF_HMAC_SHA2_384,	48,	0 },
66	{ "hmac-sha2-512",	AUTHXF_HMAC_SHA2_512,	64,	0 },
67	{ NULL,			0,			0,	0 },
68};
69
70const struct ipsec_xf encxfs[] = {
71	{ "unknown",		ENCXF_UNKNOWN,		0,	0 },
72	{ "none",		ENCXF_NONE,		0,	0 },
73	{ "3des-cbc",		ENCXF_3DES_CBC,		24,	24 },
74	{ "des-cbc",		ENCXF_DES_CBC,		8,	8 },
75	{ "aes",		ENCXF_AES,		16,	32 },
76	{ "aesctr",		ENCXF_AESCTR,		16+4,	32+4 },
77	{ "blowfish",		ENCXF_BLOWFISH,		5,	56 },
78	{ "cast128",		ENCXF_CAST128,		5,	16 },
79	{ "null",		ENCXF_NULL,		0,	0 },
80	{ "skipjack",		ENCXF_SKIPJACK,		10,	10 },
81	{ NULL,			0,			0,	0 },
82};
83
84const struct ipsec_xf compxfs[] = {
85	{ "unknown",		COMPXF_UNKNOWN,		0,	0 },
86	{ "deflate",		COMPXF_DEFLATE,		0,	0 },
87	{ "lzs",		COMPXF_LZS,		0,	0 },
88	{ NULL,			0,			0,	0 },
89};
90
91const struct ipsec_xf groupxfs[] = {
92	{ "unknown",		GROUPXF_UNKNOWN,	0,	0 },
93	{ "none",		GROUPXF_NONE,		0,	0 },
94	{ "modp768",		GROUPXF_768,		768,	0 },
95	{ "grp1",		GROUPXF_768,		768,	0 },
96	{ "modp1024",		GROUPXF_1024,		1024,	0 },
97	{ "grp2",		GROUPXF_1024,		1024,	0 },
98	{ "modp1536",		GROUPXF_1536,		1536,	0 },
99	{ "grp5",		GROUPXF_1536,		1536,	0 },
100	{ "modp2048",		GROUPXF_2048,		2048,	0 },
101	{ "grp14",		GROUPXF_2048,		2048,	0 },
102	{ "modp3072",		GROUPXF_3072,		3072,	0 },
103	{ "grp15",		GROUPXF_3072,		3072,	0 },
104	{ "modp4096",		GROUPXF_4096,		4096,	0 },
105	{ "grp16",		GROUPXF_4096,		4096,	0 },
106	{ "modp6144",		GROUPXF_6144,		6144,	0 },
107	{ "grp17",		GROUPXF_6144,		6144,	0 },
108	{ "modp8192",		GROUPXF_8192,		8192,	0 },
109	{ "grp18",		GROUPXF_8192,		8192,	0 },
110	{ NULL,			0,			0,	0 },
111};
112
113int			 yyerror(const char *, ...);
114int			 yyparse(void);
115int			 kw_cmp(const void *, const void *);
116int			 lookup(char *);
117int			 lgetc(FILE *);
118int			 lungetc(int);
119int			 findeol(void);
120int			 yylex(void);
121
122TAILQ_HEAD(symhead, sym)	 symhead = TAILQ_HEAD_INITIALIZER(symhead);
123struct sym {
124	TAILQ_ENTRY(sym)	 entries;
125	int		 used;
126	int		 persist;
127	char		*nam;
128	char		*val;
129};
130
131int			 symset(const char *, const char *, int);
132int			 cmdline_symset(char *);
133char			*symget(const char *);
134int			 atoul(char *, u_long *);
135int			 atospi(char *, u_int32_t *);
136u_int8_t		 x2i(unsigned char *);
137struct ipsec_key	*parsekey(unsigned char *, size_t);
138struct ipsec_key	*parsekeyfile(char *);
139struct ipsec_addr_wrap	*host(const char *);
140struct ipsec_addr_wrap	*host_v6(const char *, int);
141struct ipsec_addr_wrap	*host_v4(const char *, int);
142struct ipsec_addr_wrap	*host_dns(const char *, int);
143struct ipsec_addr_wrap	*host_if(const char *, int);
144void			 ifa_load(void);
145int			 ifa_exists(const char *);
146struct ipsec_addr_wrap	*ifa_lookup(const char *ifa_name);
147struct ipsec_addr_wrap	*ifa_grouplookup(const char *);
148void			 set_ipmask(struct ipsec_addr_wrap *, u_int8_t);
149const struct ipsec_xf	*parse_xf(const char *, const struct ipsec_xf *);
150struct ipsec_life	*parse_life(int);
151struct ipsec_transforms *copytransforms(const struct ipsec_transforms *);
152struct ipsec_life	*copylife(const struct ipsec_life *);
153struct ipsec_auth	*copyipsecauth(const struct ipsec_auth *);
154struct ike_auth		*copyikeauth(const struct ike_auth *);
155struct ipsec_key	*copykey(struct ipsec_key *);
156struct ipsec_addr_wrap	*copyhost(const struct ipsec_addr_wrap *);
157char			*copytag(const char *);
158struct ipsec_rule	*copyrule(struct ipsec_rule *);
159int			 validate_af(struct ipsec_addr_wrap *,
160			    struct ipsec_addr_wrap *);
161int			 validate_sa(u_int32_t, u_int8_t,
162			     struct ipsec_transforms *, struct ipsec_key *,
163			     struct ipsec_key *, u_int8_t);
164struct ipsec_rule	*create_sa(u_int8_t, u_int8_t, struct ipsec_hosts *,
165			     u_int32_t, struct ipsec_transforms *,
166			     struct ipsec_key *, struct ipsec_key *);
167struct ipsec_rule	*reverse_sa(struct ipsec_rule *, u_int32_t,
168			     struct ipsec_key *, struct ipsec_key *);
169struct ipsec_rule	*create_sagroup(struct ipsec_addr_wrap *, u_int8_t,
170			     u_int32_t, struct ipsec_addr_wrap *, u_int8_t,
171			     u_int32_t);
172struct ipsec_rule	*create_flow(u_int8_t, u_int8_t, struct ipsec_hosts *,
173			     struct ipsec_hosts *, u_int8_t, char *, char *,
174			     u_int8_t);
175void			 expand_any(struct ipsec_addr_wrap *);
176int			 expand_rule(struct ipsec_rule *, u_int8_t, u_int32_t,
177			     struct ipsec_key *, struct ipsec_key *, int);
178struct ipsec_rule	*reverse_rule(struct ipsec_rule *);
179struct ipsec_rule	*create_ike(u_int8_t, struct ipsec_hosts *,
180			     struct ipsec_hosts *, struct ike_mode *,
181			     struct ike_mode *, u_int8_t, u_int8_t, u_int8_t,
182			     char *, char *, struct ike_auth *, char *);
183int			 add_sagroup(struct ipsec_rule *);
184int			 get_id_type(char *);
185
186struct ipsec_transforms *ipsec_transforms;
187
188typedef struct {
189	union {
190		int64_t	 	 number;
191		u_int8_t	 ikemode;
192		u_int8_t	 dir;
193		u_int8_t	 satype;	/* encapsulating prococol */
194		u_int8_t	 proto;		/* encapsulated protocol */
195		u_int8_t	 tmode;
196		char		*string;
197		u_int16_t	 port;
198		struct ipsec_hosts hosts;
199		struct ipsec_hosts peers;
200		struct ipsec_addr_wrap *singlehost;
201		struct ipsec_addr_wrap *host;
202		struct {
203			char *srcid;
204			char *dstid;
205		} ids;
206		char		*id;
207		u_int8_t	 type;
208		struct ike_auth	 ikeauth;
209		struct {
210			u_int32_t	spiout;
211			u_int32_t	spiin;
212		} spis;
213		struct {
214			struct ipsec_key *keyout;
215			struct ipsec_key *keyin;
216		} authkeys;
217		struct {
218			struct ipsec_key *keyout;
219			struct ipsec_key *keyin;
220		} enckeys;
221		struct {
222			struct ipsec_key *keyout;
223			struct ipsec_key *keyin;
224		} keys;
225		struct ipsec_transforms *transforms;
226		struct ipsec_life	*life;
227		struct ike_mode		*mode;
228	} v;
229	int lineno;
230} YYSTYPE;
231
232%}
233
234%token	FLOW FROM ESP AH IN PEER ON OUT TO SRCID DSTID RSA PSK TCPMD5 SPI
235%token	AUTHKEY ENCKEY FILENAME AUTHXF ENCXF ERROR IKE MAIN QUICK AGGRESSIVE
236%token	PASSIVE ACTIVE ANY IPIP IPCOMP COMPXF TUNNEL TRANSPORT DYNAMIC LIFE
237%token	TYPE DENY BYPASS LOCAL PROTO USE ACQUIRE REQUIRE DONTACQ GROUP PORT TAG
238%token	<v.string>		STRING
239%token	<v.number>		NUMBER
240%type	<v.string>		string
241%type	<v.dir>			dir
242%type	<v.satype>		satype
243%type	<v.proto>		proto
244%type	<v.number>		protoval
245%type	<v.tmode>		tmode
246%type	<v.hosts>		hosts
247%type	<v.port>		port
248%type	<v.number>		portval
249%type	<v.peers>		peers
250%type	<v.singlehost>		singlehost
251%type	<v.host>		host host_list
252%type	<v.ids>			ids
253%type	<v.id>			id
254%type	<v.spis>		spispec
255%type	<v.authkeys>		authkeyspec
256%type	<v.enckeys>		enckeyspec
257%type	<v.keys>		keyspec
258%type	<v.transforms>		transforms
259%type	<v.ikemode>		ikemode
260%type	<v.ikeauth>		ikeauth
261%type	<v.type>		type
262%type	<v.life>		life
263%type	<v.mode>		phase1mode phase2mode
264%type	<v.string>		tag
265%%
266
267grammar		: /* empty */
268		| grammar '\n'
269		| grammar ikerule '\n'
270		| grammar flowrule '\n'
271		| grammar sarule '\n'
272		| grammar tcpmd5rule '\n'
273		| grammar varset '\n'
274		| grammar error '\n'		{ errors++; }
275		;
276
277comma		: ','
278		| /* empty */
279		;
280
281tcpmd5rule	: TCPMD5 hosts spispec authkeyspec	{
282			struct ipsec_rule	*r;
283
284			r = create_sa(IPSEC_TCPMD5, IPSEC_TRANSPORT, &$2,
285			    $3.spiout, NULL, $4.keyout, NULL);
286			if (r == NULL)
287				YYERROR;
288
289			if (expand_rule(r, 0, $3.spiin, $4.keyin, NULL, 0))
290				errx(1, "tcpmd5rule: expand_rule");
291		}
292		;
293
294sarule		: satype tmode hosts spispec transforms authkeyspec
295		    enckeyspec {
296			struct ipsec_rule	*r;
297
298			r = create_sa($1, $2, &$3, $4.spiout, $5, $6.keyout,
299			    $7.keyout);
300			if (r == NULL)
301				YYERROR;
302
303			if (expand_rule(r, 0, $4.spiin, $6.keyin, $7.keyin, 1))
304				errx(1, "sarule: expand_rule");
305		}
306		;
307
308flowrule	: FLOW satype dir proto hosts peers ids type {
309			struct ipsec_rule	*r;
310
311			r = create_flow($3, $4, &$5, &$6, $2, $7.srcid,
312			    $7.dstid, $8);
313			if (r == NULL)
314				YYERROR;
315
316			if (expand_rule(r, $3, 0, NULL, NULL, 0))
317				errx(1, "flowrule: expand_rule");
318		}
319		;
320
321ikerule		: IKE ikemode satype tmode proto hosts peers
322		    phase1mode phase2mode ids ikeauth tag {
323			struct ipsec_rule	*r;
324
325			r = create_ike($5, &$6, &$7, $8, $9, $3, $4, $2,
326			    $10.srcid, $10.dstid, &$11, $12);
327			if (r == NULL)
328				YYERROR;
329
330			if (expand_rule(r, 0, 0, NULL, NULL, 0))
331				errx(1, "ikerule: expand_rule");
332		}
333		;
334
335satype		: /* empty */			{ $$ = IPSEC_ESP; }
336		| ESP				{ $$ = IPSEC_ESP; }
337		| AH				{ $$ = IPSEC_AH; }
338		| IPCOMP			{ $$ = IPSEC_IPCOMP; }
339		| IPIP				{ $$ = IPSEC_IPIP; }
340		;
341
342proto		: /* empty */			{ $$ = 0; }
343		| PROTO protoval		{ $$ = $2; }
344		| PROTO ESP 			{ $$ = IPPROTO_ESP; }
345		| PROTO AH			{ $$ = IPPROTO_AH; }
346		;
347
348protoval	: STRING			{
349			struct protoent *p;
350
351			p = getprotobyname($1);
352			if (p == NULL) {
353				yyerror("unknown protocol: %s", $1);
354				YYERROR;
355			}
356			$$ = p->p_proto;
357			free($1);
358		}
359		| NUMBER			{
360			if ($1 > 255 || $1 < 0) {
361				yyerror("protocol outside range");
362				YYERROR;
363			}
364		}
365		;
366
367tmode		: /* empty */			{ $$ = IPSEC_TUNNEL; }
368		| TUNNEL			{ $$ = IPSEC_TUNNEL; }
369		| TRANSPORT			{ $$ = IPSEC_TRANSPORT; }
370		;
371
372dir		: /* empty */			{ $$ = IPSEC_INOUT; }
373		| IN				{ $$ = IPSEC_IN; }
374		| OUT				{ $$ = IPSEC_OUT; }
375		;
376
377hosts		: FROM host port TO host port		{
378			$$.src = $2;
379			$$.sport = $3;
380			$$.dst = $5;
381			$$.dport = $6;
382		}
383		| TO host port FROM host port		{
384			$$.src = $5;
385			$$.sport = $6;
386			$$.dst = $2;
387			$$.dport = $3;
388		}
389		;
390
391port		: /* empty */				{ $$ = 0; }
392		| PORT portval				{ $$ = $2; }
393		;
394
395portval		: STRING				{
396			struct servent *s;
397
398			if ((s = getservbyname($1, "tcp")) != NULL ||
399			    (s = getservbyname($1, "udp")) != NULL) {
400				$$ = s->s_port;
401			} else {
402				yyerror("unknown port: %s", $1);
403				YYERROR;
404			}
405		}
406		| NUMBER				{
407			if ($1 > USHRT_MAX || $1 < 0) {
408				yyerror("port outside range");
409				YYERROR;
410			}
411			$$ = htons($1);
412		}
413		;
414
415peers		: /* empty */				{
416			$$.dst = NULL;
417			$$.src = NULL;
418		}
419		| PEER singlehost LOCAL singlehost	{
420			$$.dst = $2;
421			$$.src = $4;
422		}
423		| LOCAL singlehost PEER singlehost	{
424			$$.dst = $4;
425			$$.src = $2;
426		}
427		| PEER singlehost			{
428			$$.dst = $2;
429			$$.src = NULL;
430		}
431		| LOCAL singlehost			{
432			$$.dst = NULL;
433			$$.src = $2;
434		}
435		;
436
437singlehost	: /* empty */			{ $$ = NULL; }
438		| STRING			{
439			if (($$ = host($1)) == NULL) {
440				free($1);
441				yyerror("could not parse host specification");
442				YYERROR;
443			}
444			free($1);
445		}
446		;
447
448host_list	: host				{ $$ = $1; }
449		| host_list comma host		{
450			if ($3 == NULL)
451				$$ = $1;
452			else if ($1 == NULL)
453				$$ = $3;
454			else {
455				$1->tail->next = $3;
456				$1->tail = $3->tail;
457				$$ = $1;
458			}
459		}
460		;
461
462host		: STRING			{
463			if (($$ = host($1)) == NULL) {
464				free($1);
465				yyerror("could not parse host specification");
466				YYERROR;
467			}
468			free($1);
469		}
470		| STRING '/' NUMBER		{
471			char	*buf;
472
473			if (asprintf(&buf, "%s/%lld", $1, $3) == -1)
474				err(1, "host: asprintf");
475			free($1);
476			if (($$ = host(buf)) == NULL)	{
477				free(buf);
478				yyerror("could not parse host specification");
479				YYERROR;
480			}
481			free(buf);
482		}
483		| ANY				{
484			struct ipsec_addr_wrap	*ipa;
485
486			ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
487			if (ipa == NULL)
488				err(1, "host: calloc");
489			ipa->af = AF_UNSPEC;
490			ipa->netaddress = 1;
491			ipa->tail = ipa;
492			$$ = ipa;
493		}
494		| '{' host_list '}'		{ $$ = $2; }
495		;
496
497ids		: /* empty */			{
498			$$.srcid = NULL;
499			$$.dstid = NULL;
500		}
501		| SRCID id DSTID id		{
502			$$.srcid = $2;
503			$$.dstid = $4;
504		}
505		| SRCID id			{
506			$$.srcid = $2;
507			$$.dstid = NULL;
508		}
509		| DSTID id			{
510			$$.srcid = NULL;
511			$$.dstid = $2;
512		}
513		;
514
515type		: /* empty */			{
516			$$ = TYPE_REQUIRE;
517		}
518		| TYPE USE			{
519			$$ = TYPE_USE;
520		}
521		| TYPE ACQUIRE			{
522			$$ = TYPE_ACQUIRE;
523		}
524		| TYPE REQUIRE			{
525			$$ = TYPE_REQUIRE;
526		}
527		| TYPE DENY			{
528			$$ = TYPE_DENY;
529		}
530		| TYPE BYPASS			{
531			$$ = TYPE_BYPASS;
532		}
533		| TYPE DONTACQ			{
534			$$ = TYPE_DONTACQ;
535		}
536		;
537
538id		: STRING			{ $$ = $1; }
539		;
540
541spispec		: SPI STRING			{
542			u_int32_t	 spi;
543			char		*p = strchr($2, ':');
544
545			if (p != NULL) {
546				*p++ = 0;
547
548				if (atospi(p, &spi) == -1) {
549					free($2);
550					YYERROR;
551				}
552				$$.spiin = spi;
553			} else
554				$$.spiin = 0;
555
556			if (atospi($2, &spi) == -1) {
557				free($2);
558				YYERROR;
559			}
560			$$.spiout = spi;
561
562
563			free($2);
564		}
565		| SPI NUMBER			{
566			if ($2 > UINT_MAX || $2 < 0) {
567				yyerror("%lld not a valid spi", $2);
568				YYERROR;
569			}
570			if ($2 >= SPI_RESERVED_MIN && $2 <= SPI_RESERVED_MAX) {
571				yyerror("%lld within reserved spi range", $2);
572				YYERROR;
573			}
574
575			$$.spiin = 0;
576			$$.spiout = $2;
577		}
578		;
579
580transforms	:					{
581			if ((ipsec_transforms = calloc(1,
582			    sizeof(struct ipsec_transforms))) == NULL)
583				err(1, "transforms: calloc");
584		}
585		    transforms_l
586			{ $$ = ipsec_transforms; }
587		| /* empty */				{
588			if (($$ = calloc(1,
589			    sizeof(struct ipsec_transforms))) == NULL)
590				err(1, "transforms: calloc");
591		}
592		;
593
594transforms_l	: transforms_l transform
595		| transform
596		;
597
598transform	: AUTHXF STRING			{
599			if (ipsec_transforms->authxf)
600				yyerror("auth already set");
601			else {
602				ipsec_transforms->authxf = parse_xf($2,
603				    authxfs);
604				if (!ipsec_transforms->authxf)
605					yyerror("%s not a valid transform", $2);
606			}
607		}
608		| ENCXF STRING			{
609			if (ipsec_transforms->encxf)
610				yyerror("enc already set");
611			else {
612				ipsec_transforms->encxf = parse_xf($2, encxfs);
613				if (!ipsec_transforms->encxf)
614					yyerror("%s not a valid transform", $2);
615			}
616		}
617		| COMPXF STRING			{
618			if (ipsec_transforms->compxf)
619				yyerror("comp already set");
620			else {
621				ipsec_transforms->compxf = parse_xf($2,
622				    compxfs);
623				if (!ipsec_transforms->compxf)
624					yyerror("%s not a valid transform", $2);
625			}
626		}
627		| GROUP STRING			{
628			if (ipsec_transforms->groupxf)
629				yyerror("group already set");
630			else {
631				ipsec_transforms->groupxf = parse_xf($2,
632				    groupxfs);
633				if (!ipsec_transforms->groupxf)
634					yyerror("%s not a valid transform", $2);
635			}
636		}
637		;
638
639phase1mode	: /* empty */	{
640			struct ike_mode		*p1;
641
642			/* We create just an empty main mode */
643			if ((p1 = calloc(1, sizeof(struct ike_mode))) == NULL)
644				err(1, "phase1mode: calloc");
645			p1->ike_exch = IKE_MM;
646			$$ = p1;
647		}
648		| MAIN transforms life		{
649			struct ike_mode	*p1;
650
651			if ((p1 = calloc(1, sizeof(struct ike_mode))) == NULL)
652				err(1, "phase1mode: calloc");
653			p1->xfs = $2;
654			p1->life = $3;
655			p1->ike_exch = IKE_MM;
656			$$ = p1;
657		}
658		| AGGRESSIVE transforms life		{
659			struct ike_mode	*p1;
660
661			if ((p1 = calloc(1, sizeof(struct ike_mode))) == NULL)
662				err(1, "phase1mode: calloc");
663			p1->xfs = $2;
664			p1->life = $3;
665			p1->ike_exch = IKE_AM;
666			$$ = p1;
667		}
668		;
669
670phase2mode	: /* empty */	{
671			struct ike_mode		*p2;
672
673			/* We create just an empty quick mode */
674			if ((p2 = calloc(1, sizeof(struct ike_mode))) == NULL)
675				err(1, "phase1mode: calloc");
676			p2->ike_exch = IKE_QM;
677			$$ = p2;
678		}
679		| QUICK transforms life		{
680			struct ike_mode	*p2;
681
682			if ((p2 = calloc(1, sizeof(struct ike_mode))) == NULL)
683				err(1, "phase1mode: calloc");
684			p2->xfs = $2;
685			p2->life = $3;
686			p2->ike_exch = IKE_QM;
687			$$ = p2;
688		}
689		;
690
691life		: /* empty */			{
692			struct ipsec_life *life;
693
694			/* We create just an empty transform */
695			if ((life = calloc(1, sizeof(struct ipsec_life)))
696			    == NULL)
697				err(1, "life: calloc");
698			life->lifetime = -1;
699			life->lifevolume = -1;
700			$$ = life;
701		}
702		| LIFE NUMBER			{
703			if ($2 > INT_MAX || $2 < 0) {
704				yyerror("%lld not a valid lifetime", $2);
705				YYERROR;
706			}
707			$$ = parse_life($2);
708		}
709		;
710
711authkeyspec	: /* empty */			{
712			$$.keyout = NULL;
713			$$.keyin = NULL;
714		}
715		| AUTHKEY keyspec		{
716			$$.keyout = $2.keyout;
717			$$.keyin = $2.keyin;
718		}
719		;
720
721enckeyspec	: /* empty */			{
722			$$.keyout = NULL;
723			$$.keyin = NULL;
724		}
725		| ENCKEY keyspec		{
726			$$.keyout = $2.keyout;
727			$$.keyin = $2.keyin;
728		}
729		;
730
731keyspec		: STRING			{
732			unsigned char	*hex;
733			unsigned char	*p = strchr($1, ':');
734
735			if (p != NULL ) {
736				*p++ = 0;
737
738				if (!strncmp(p, "0x", 2))
739					p += 2;
740				$$.keyin = parsekey(p, strlen(p));
741			} else
742				$$.keyin = NULL;
743
744			hex = $1;
745			if (!strncmp(hex, "0x", 2))
746				hex += 2;
747			$$.keyout = parsekey(hex, strlen(hex));
748
749			free($1);
750		}
751		| FILENAME STRING		{
752			unsigned char	*p = strchr($2, ':');
753
754			if (p != NULL) {
755				*p++ = 0;
756				$$.keyin = parsekeyfile(p);
757			}
758			$$.keyout = parsekeyfile($2);
759			free($2);
760		}
761		;
762
763ikemode		: /* empty */			{ $$ = IKE_ACTIVE; }
764		| PASSIVE			{ $$ = IKE_PASSIVE; }
765		| DYNAMIC			{ $$ = IKE_DYNAMIC; }
766		| ACTIVE			{ $$ = IKE_ACTIVE; }
767		;
768
769ikeauth		: /* empty */			{
770			$$.type = IKE_AUTH_RSA;
771			$$.string = NULL;
772		}
773		| RSA				{
774			$$.type = IKE_AUTH_RSA;
775			$$.string = NULL;
776		}
777		| PSK STRING			{
778			$$.type = IKE_AUTH_PSK;
779			if (($$.string = strdup($2)) == NULL)
780				err(1, "ikeauth: strdup");
781		}
782		;
783
784tag		: /* empty */
785		{
786			$$ = NULL;
787		}
788		| TAG STRING
789		{
790			$$ = $2;
791		}
792		;
793
794string		: string STRING
795		{
796			if (asprintf(&$$, "%s %s", $1, $2) == -1)
797				err(1, "string: asprintf");
798			free($1);
799			free($2);
800		}
801		| STRING
802		;
803
804varset		: STRING '=' string
805		{
806			if (ipsec->opts & IPSECCTL_OPT_VERBOSE)
807				printf("%s = \"%s\"\n", $1, $3);
808			if (symset($1, $3, 0) == -1)
809				err(1, "cannot store variable");
810			free($1);
811			free($3);
812		}
813		;
814
815%%
816
817struct keywords {
818	const char	*k_name;
819	int		 k_val;
820};
821
822int
823yyerror(const char *fmt, ...)
824{
825	va_list		 ap;
826	extern const char *infile;
827
828	errors = 1;
829	va_start(ap, fmt);
830	fprintf(stderr, "%s: %d: ", infile, yylval.lineno);
831	vfprintf(stderr, fmt, ap);
832	fprintf(stderr, "\n");
833	va_end(ap);
834	return (0);
835}
836
837int
838kw_cmp(const void *k, const void *e)
839{
840	return (strcmp(k, ((const struct keywords *)e)->k_name));
841}
842
843int
844lookup(char *s)
845{
846	/* this has to be sorted always */
847	static const struct keywords keywords[] = {
848		{ "acquire",		ACQUIRE },
849		{ "active",		ACTIVE },
850		{ "aggressive",		AGGRESSIVE },
851		{ "ah",			AH },
852		{ "any",		ANY },
853		{ "auth",		AUTHXF },
854		{ "authkey",		AUTHKEY },
855		{ "bypass",		BYPASS },
856		{ "comp",		COMPXF },
857		{ "deny",		DENY },
858		{ "dontacq",		DONTACQ },
859		{ "dstid",		DSTID },
860		{ "dynamic",		DYNAMIC },
861		{ "enc",		ENCXF },
862		{ "enckey",		ENCKEY },
863		{ "esp",		ESP },
864		{ "file",		FILENAME },
865		{ "flow",		FLOW },
866		{ "from",		FROM },
867		{ "group",		GROUP },
868		{ "ike",		IKE },
869		{ "in",			IN },
870		{ "ipcomp",		IPCOMP },
871		{ "ipip",		IPIP },
872		{ "life",		LIFE },
873		{ "local",		LOCAL },
874		{ "main",		MAIN },
875		{ "out",		OUT },
876		{ "passive",		PASSIVE },
877		{ "peer",		PEER },
878		{ "port",		PORT },
879		{ "proto",		PROTO },
880		{ "psk",		PSK },
881		{ "quick",		QUICK },
882		{ "require",		REQUIRE },
883		{ "rsa",		RSA },
884		{ "spi",		SPI },
885		{ "srcid",		SRCID },
886		{ "tag",		TAG },
887		{ "tcpmd5",		TCPMD5 },
888		{ "to",			TO },
889		{ "transport",		TRANSPORT },
890		{ "tunnel",		TUNNEL },
891		{ "type",		TYPE },
892		{ "use",		USE }
893	};
894	const struct keywords	*p;
895
896	p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
897	    sizeof(keywords[0]), kw_cmp);
898
899	if (p) {
900		if (debug > 1)
901			fprintf(stderr, "%s: %d\n", s, p->k_val);
902		return (p->k_val);
903	} else {
904		if (debug > 1)
905			fprintf(stderr, "string: %s\n", s);
906		return (STRING);
907	}
908}
909
910#define MAXPUSHBACK	128
911
912char	*parsebuf;
913int	 parseindex;
914char	 pushback_buffer[MAXPUSHBACK];
915int	 pushback_index = 0;
916
917int
918lgetc(FILE *f)
919{
920	int	c, next;
921
922	if (parsebuf) {
923		/* Read character from the parsebuffer instead of input. */
924		if (parseindex >= 0) {
925			c = parsebuf[parseindex++];
926			if (c != '\0')
927				return (c);
928			parsebuf = NULL;
929		} else
930			parseindex++;
931	}
932
933	if (pushback_index)
934		return (pushback_buffer[--pushback_index]);
935
936	while ((c = getc(f)) == '\\') {
937		next = getc(f);
938		if (next != '\n') {
939			c = next;
940			break;
941		}
942		yylval.lineno = lineno;
943		lineno++;
944	}
945	if (c == '\t' || c == ' ') {
946		/* Compress blanks to a single space. */
947		do {
948			c = getc(f);
949		} while (c == '\t' || c == ' ');
950		ungetc(c, f);
951		c = ' ';
952	}
953
954	return (c);
955}
956
957int
958lungetc(int c)
959{
960	if (c == EOF)
961		return (EOF);
962	if (parsebuf) {
963		parseindex--;
964		if (parseindex >= 0)
965			return (c);
966	}
967	if (pushback_index < MAXPUSHBACK-1)
968		return (pushback_buffer[pushback_index++] = c);
969	else
970		return (EOF);
971}
972
973int
974findeol(void)
975{
976	int	c;
977
978	parsebuf = NULL;
979	pushback_index = 0;
980
981	/* skip to either EOF or the first real EOL */
982	while (1) {
983		c = lgetc(fin);
984		if (c == '\n') {
985			lineno++;
986			break;
987		}
988		if (c == EOF)
989			break;
990	}
991	return (ERROR);
992}
993
994int
995yylex(void)
996{
997	char	 buf[8096];
998	char	*p, *val;
999	int	 endc, c;
1000	int	 token;
1001
1002top:
1003	p = buf;
1004	while ((c = lgetc(fin)) == ' ')
1005		; /* nothing */
1006
1007	yylval.lineno = lineno;
1008	if (c == '#')
1009		while ((c = lgetc(fin)) != '\n' && c != EOF)
1010			; /* nothing */
1011	if (c == '$' && parsebuf == NULL) {
1012		while (1) {
1013			if ((c = lgetc(fin)) == EOF)
1014				return (0);
1015
1016			if (p + 1 >= buf + sizeof(buf) - 1) {
1017				yyerror("string too long");
1018				return (findeol());
1019			}
1020			if (isalnum(c) || c == '_') {
1021				*p++ = (char)c;
1022				continue;
1023			}
1024			*p = '\0';
1025			lungetc(c);
1026			break;
1027		}
1028		val = symget(buf);
1029		if (val == NULL) {
1030			yyerror("macro \"%s\" not defined", buf);
1031			return (findeol());
1032		}
1033		parsebuf = val;
1034		parseindex = 0;
1035		goto top;
1036	}
1037
1038	switch (c) {
1039	case '\'':
1040	case '"':
1041		endc = c;
1042		while (1) {
1043			if ((c = lgetc(fin)) == EOF)
1044				return (0);
1045			if (c == endc) {
1046				*p = '\0';
1047				break;
1048			}
1049			if (c == '\n') {
1050				lineno++;
1051				continue;
1052			}
1053			if (p + 1 >= buf + sizeof(buf) - 1) {
1054				yyerror("string too long");
1055				return (findeol());
1056			}
1057			*p++ = (char)c;
1058		}
1059		yylval.v.string = strdup(buf);
1060		if (yylval.v.string == NULL)
1061			err(1, "yylex: strdup");
1062		return (STRING);
1063	}
1064
1065#define allowed_to_end_number(x) \
1066	(isspace(x) || x == ')' || x ==',' || x == '/' || x == '}')
1067
1068	if (c == '-' || isdigit(c)) {
1069		do {
1070			*p++ = c;
1071			if ((unsigned)(p-buf) >= sizeof(buf)) {
1072				yyerror("string too long");
1073				return (findeol());
1074			}
1075		} while ((c = lgetc(fin)) != EOF && isdigit(c));
1076		lungetc(c);
1077		if (p == buf + 1 && buf[0] == '-')
1078			goto nodigits;
1079		if (c == EOF || allowed_to_end_number(c)) {
1080			const char *errstr = NULL;
1081
1082			*p = '\0';
1083			yylval.v.number = strtonum(buf, LLONG_MIN,
1084			    LLONG_MAX, &errstr);
1085			if (errstr) {
1086				yyerror("\"%s\" invalid number: %s",
1087				    buf, errstr);
1088				return (findeol());
1089			}
1090			return (NUMBER);
1091		} else {
1092nodigits:
1093			while (p > buf + 1)
1094				lungetc(*--p);
1095			c = *--p;
1096			if (c == '-')
1097				return (c);
1098		}
1099	}
1100
1101#define allowed_in_string(x) \
1102	(isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
1103	x != '{' && x != '}' && x != '<' && x != '>' && \
1104	x != '!' && x != '=' && x != '/' && x != '#' && \
1105	x != ','))
1106
1107	if (isalnum(c) || c == ':' || c == '_' || c == '*') {
1108		do {
1109			*p++ = c;
1110			if ((unsigned)(p-buf) >= sizeof(buf)) {
1111				yyerror("string too long");
1112				return (findeol());
1113			}
1114		} while ((c = lgetc(fin)) != EOF && (allowed_in_string(c)));
1115		lungetc(c);
1116		*p = '\0';
1117		if ((token = lookup(buf)) == STRING)
1118			if ((yylval.v.string = strdup(buf)) == NULL)
1119				err(1, "yylex: strdup");
1120		return (token);
1121	}
1122	if (c == '\n') {
1123		yylval.lineno = lineno;
1124		lineno++;
1125	}
1126	if (c == EOF)
1127		return (0);
1128	return (c);
1129}
1130
1131int
1132parse_rules(FILE *input, struct ipsecctl *ipsecx)
1133{
1134	struct sym	*sym;
1135
1136	ipsec = ipsecx;
1137	fin = input;
1138	lineno = 1;
1139	errors = 0;
1140
1141	yyparse();
1142
1143	/* Free macros and check which have not been used. */
1144	while ((sym = TAILQ_FIRST(&symhead))) {
1145		if ((ipsec->opts & IPSECCTL_OPT_VERBOSE2) && !sym->used)
1146			fprintf(stderr, "warning: macro '%s' not "
1147			    "used\n", sym->nam);
1148		TAILQ_REMOVE(&symhead, sym, entries);
1149		free(sym->nam);
1150		free(sym->val);
1151		free(sym);
1152	}
1153
1154	return (errors ? -1 : 0);
1155}
1156
1157int
1158symset(const char *nam, const char *val, int persist)
1159{
1160	struct sym	*sym;
1161
1162	for (sym = TAILQ_FIRST(&symhead); sym && strcmp(nam, sym->nam);
1163	    sym = TAILQ_NEXT(sym, entries))
1164		;	/* nothing */
1165
1166	if (sym != NULL) {
1167		if (sym->persist == 1)
1168			return (0);
1169		else {
1170			TAILQ_REMOVE(&symhead, sym, entries);
1171			free(sym->nam);
1172			free(sym->val);
1173			free(sym);
1174		}
1175	}
1176	if ((sym = calloc(1, sizeof(*sym))) == NULL)
1177		return (-1);
1178
1179	sym->nam = strdup(nam);
1180	if (sym->nam == NULL) {
1181		free(sym);
1182		return (-1);
1183	}
1184	sym->val = strdup(val);
1185	if (sym->val == NULL) {
1186		free(sym->nam);
1187		free(sym);
1188		return (-1);
1189	}
1190	sym->used = 0;
1191	sym->persist = persist;
1192	TAILQ_INSERT_TAIL(&symhead, sym, entries);
1193	return (0);
1194}
1195
1196int
1197cmdline_symset(char *s)
1198{
1199	char	*sym, *val;
1200	int	ret;
1201	size_t	len;
1202
1203	if ((val = strrchr(s, '=')) == NULL)
1204		return (-1);
1205
1206	len = strlen(s) - strlen(val) + 1;
1207	if ((sym = malloc(len)) == NULL)
1208		err(1, "cmdline_symset: malloc");
1209
1210	strlcpy(sym, s, len);
1211
1212	ret = symset(sym, val + 1, 1);
1213	free(sym);
1214
1215	return (ret);
1216}
1217
1218char *
1219symget(const char *nam)
1220{
1221	struct sym	*sym;
1222
1223	TAILQ_FOREACH(sym, &symhead, entries)
1224		if (strcmp(nam, sym->nam) == 0) {
1225			sym->used = 1;
1226			return (sym->val);
1227		}
1228	return (NULL);
1229}
1230
1231int
1232atoul(char *s, u_long *ulvalp)
1233{
1234	u_long	 ulval;
1235	char	*ep;
1236
1237	errno = 0;
1238	ulval = strtoul(s, &ep, 0);
1239	if (s[0] == '\0' || *ep != '\0')
1240		return (-1);
1241	if (errno == ERANGE && ulval == ULONG_MAX)
1242		return (-1);
1243	*ulvalp = ulval;
1244	return (0);
1245}
1246
1247int
1248atospi(char *s, u_int32_t *spivalp)
1249{
1250	unsigned long	ulval;
1251
1252	if (atoul(s, &ulval) == -1)
1253		return (-1);
1254	if (ulval > UINT_MAX) {
1255		yyerror("%lld not a valid spi", ulval);
1256		return (-1);
1257	}
1258	if (ulval >= SPI_RESERVED_MIN && ulval <= SPI_RESERVED_MAX) {
1259		yyerror("%lld within reserved spi range", ulval);
1260		return (-1);
1261	}
1262	*spivalp = ulval;
1263	return (0);
1264}
1265
1266u_int8_t
1267x2i(unsigned char *s)
1268{
1269	char	ss[3];
1270
1271	ss[0] = s[0];
1272	ss[1] = s[1];
1273	ss[2] = 0;
1274
1275	if (!isxdigit(s[0]) || !isxdigit(s[1])) {
1276		yyerror("keys need to be specified in hex digits");
1277		return (-1);
1278	}
1279	return ((u_int8_t)strtoul(ss, NULL, 16));
1280}
1281
1282struct ipsec_key *
1283parsekey(unsigned char *hexkey, size_t len)
1284{
1285	struct ipsec_key *key;
1286	int		  i;
1287
1288	key = calloc(1, sizeof(struct ipsec_key));
1289	if (key == NULL)
1290		err(1, "parsekey: calloc");
1291
1292	key->len = len / 2;
1293	key->data = calloc(key->len, sizeof(u_int8_t));
1294	if (key->data == NULL)
1295		err(1, "parsekey: calloc");
1296
1297	for (i = 0; i < (int)key->len; i++)
1298		key->data[i] = x2i(hexkey + 2 * i);
1299
1300	return (key);
1301}
1302
1303struct ipsec_key *
1304parsekeyfile(char *filename)
1305{
1306	struct stat	 sb;
1307	int		 fd;
1308	unsigned char	*hex;
1309
1310	if ((fd = open(filename, O_RDONLY)) < 0)
1311		err(1, "open %s", filename);
1312	if (fstat(fd, &sb) < 0)
1313		err(1, "parsekeyfile: stat %s", filename);
1314	if ((sb.st_size > KEYSIZE_LIMIT) || (sb.st_size == 0))
1315		errx(1, "%s: key too %s", filename, sb.st_size ? "large" :
1316		    "small");
1317	if ((hex = calloc(sb.st_size, sizeof(unsigned char))) == NULL)
1318		err(1, "parsekeyfile: calloc");
1319	if (read(fd, hex, sb.st_size) < sb.st_size)
1320		err(1, "parsekeyfile: read");
1321	close(fd);
1322	return (parsekey(hex, sb.st_size));
1323}
1324
1325int
1326get_id_type(char *string)
1327{
1328	if (string && strchr(string, '@'))
1329		return (ID_UFQDN);
1330	return (ID_FQDN);
1331}
1332
1333struct ipsec_addr_wrap *
1334host(const char *s)
1335{
1336	struct ipsec_addr_wrap	*ipa = NULL;
1337	int			 mask, cont = 1;
1338	char			*p, *q, *ps;
1339
1340	if ((p = strrchr(s, '/')) != NULL) {
1341		errno = 0;
1342		mask = strtol(p + 1, &q, 0);
1343		if (errno == ERANGE || !q || *q || mask > 128 || q == (p + 1))
1344			errx(1, "host: invalid netmask '%s'", p);
1345		if ((ps = malloc(strlen(s) - strlen(p) + 1)) == NULL)
1346			err(1, "host: calloc");
1347		strlcpy(ps, s, strlen(s) - strlen(p) + 1);
1348	} else {
1349		if ((ps = strdup(s)) == NULL)
1350			err(1, "host: strdup");
1351		mask = -1;
1352	}
1353
1354	/* Does interface with this name exist? */
1355	if (cont && (ipa = host_if(ps, mask)) != NULL)
1356		cont = 0;
1357
1358	/* IPv4 address? */
1359	if (cont && (ipa = host_v4(s, mask == -1 ? 32 : mask)) != NULL)
1360		cont = 0;
1361
1362	/* IPv6 address? */
1363	if (cont && (ipa = host_v6(ps, mask == -1 ? 128 : mask)) != NULL)
1364		cont = 0;
1365
1366	/* dns lookup */
1367	if (cont && mask == -1 && (ipa = host_dns(s, mask)) != NULL)
1368		cont = 0;
1369	free(ps);
1370
1371	if (ipa == NULL || cont == 1) {
1372		fprintf(stderr, "no IP address found for %s\n", s);
1373		return (NULL);
1374	}
1375	return (ipa);
1376}
1377
1378struct ipsec_addr_wrap *
1379host_v6(const char *s, int prefixlen)
1380{
1381	struct ipsec_addr_wrap	*ipa = NULL;
1382	struct addrinfo		 hints, *res;
1383	char			 hbuf[NI_MAXHOST];
1384
1385	bzero(&hints, sizeof(struct addrinfo));
1386	hints.ai_family = AF_INET6;
1387	hints.ai_socktype = SOCK_STREAM;
1388	hints.ai_flags = AI_NUMERICHOST;
1389	if (getaddrinfo(s, NULL, &hints, &res))
1390		return (NULL);
1391	if (res->ai_next)
1392		err(1, "host_v6: numeric hostname expanded to multiple item");
1393
1394	ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1395	if (ipa == NULL)
1396		err(1, "host_v6: calloc");
1397	ipa->af = res->ai_family;
1398	memcpy(&ipa->address.v6,
1399	    &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1400	    sizeof(struct in6_addr));
1401	if (prefixlen > 128)
1402		prefixlen = 128;
1403	ipa->next = NULL;
1404	ipa->tail = ipa;
1405
1406	set_ipmask(ipa, prefixlen);
1407	if (getnameinfo(res->ai_addr, res->ai_addrlen,
1408	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)) {
1409		errx(1, "could not get a numeric hostname");
1410	}
1411
1412	if (prefixlen != 128) {
1413		ipa->netaddress = 1;
1414		asprintf(&ipa->name, "%s/%d", hbuf, prefixlen);
1415	} else
1416		ipa->name = strdup(hbuf);
1417	if (ipa->name == NULL)
1418		err(1, "host_v6: strdup");
1419
1420	freeaddrinfo(res);
1421
1422	return (ipa);
1423}
1424
1425struct ipsec_addr_wrap *
1426host_v4(const char *s, int mask)
1427{
1428	struct ipsec_addr_wrap	*ipa = NULL;
1429	struct in_addr		 ina;
1430	int			 bits = 32;
1431
1432	bzero(&ina, sizeof(struct in_addr));
1433	if (strrchr(s, '/') != NULL) {
1434		if ((bits = inet_net_pton(AF_INET, s, &ina, sizeof(ina))) == -1)
1435			return (NULL);
1436	} else {
1437		if (inet_pton(AF_INET, s, &ina) != 1)
1438			return (NULL);
1439	}
1440
1441	ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1442	if (ipa == NULL)
1443		err(1, "host_v4: calloc");
1444
1445	ipa->address.v4 = ina;
1446	ipa->name = strdup(s);
1447	if (ipa->name == NULL)
1448		err(1, "host_v4: strdup");
1449	ipa->af = AF_INET;
1450	ipa->next = NULL;
1451	ipa->tail = ipa;
1452
1453	set_ipmask(ipa, bits);
1454	if (bits != (ipa->af == AF_INET ? 32 : 128))
1455		ipa->netaddress = 1;
1456
1457	return (ipa);
1458}
1459
1460struct ipsec_addr_wrap *
1461host_dns(const char *s, int mask)
1462{
1463	struct ipsec_addr_wrap	*ipa = NULL;
1464	struct addrinfo		 hints, *res0, *res;
1465	int			 error;
1466	char			 hbuf[NI_MAXHOST];
1467
1468	bzero(&hints, sizeof(struct addrinfo));
1469	hints.ai_family = PF_UNSPEC;
1470	hints.ai_socktype = SOCK_STREAM;
1471	error = getaddrinfo(s, NULL, &hints, &res0);
1472	if (error)
1473		return (NULL);
1474
1475	for (res = res0; res; res = res->ai_next) {
1476		if (res->ai_family != AF_INET && res->ai_family != AF_INET6)
1477			continue;
1478
1479		ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1480		if (ipa == NULL)
1481			err(1, "host_dns: calloc");
1482		switch (res->ai_family) {
1483		case AF_INET:
1484			memcpy(&ipa->address.v4,
1485			    &((struct sockaddr_in *)res->ai_addr)->sin_addr,
1486			    sizeof(struct in_addr));
1487			break;
1488		case AF_INET6:
1489			/* XXX we do not support scoped IPv6 address yet */
1490			if (((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id) {
1491				free(ipa);
1492				continue;
1493			}
1494			memcpy(&ipa->address.v6,
1495			    &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1496			    sizeof(struct in6_addr));
1497			break;
1498		}
1499		error = getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
1500		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST);
1501		if (error)
1502			err(1, "host_dns: getnameinfo");
1503		ipa->name = strdup(hbuf);
1504		if (ipa->name == NULL)
1505			err(1, "host_dns: strdup");
1506		ipa->af = res->ai_family;
1507		ipa->next = NULL;
1508		ipa->tail = ipa;
1509
1510		/*
1511		 * XXX for now, no netmask support for IPv6.
1512		 * but since there's no way to specify address family, once you
1513		 * have IPv6 address on a host, you cannot use dns/netmask
1514		 * syntax.
1515		 */
1516		if (ipa->af == AF_INET)
1517			set_ipmask(ipa, mask == -1 ? 32 : mask);
1518		else
1519			if (mask != -1)
1520				err(1, "host_dns: cannot apply netmask "
1521				    "on non-IPv4 address");
1522		break;
1523	}
1524	freeaddrinfo(res0);
1525
1526	return (ipa);
1527}
1528
1529struct ipsec_addr_wrap *
1530host_if(const char *s, int mask)
1531{
1532	struct ipsec_addr_wrap *ipa = NULL;
1533
1534	if (ifa_exists(s))
1535		ipa = ifa_lookup(s);
1536
1537	return (ipa);
1538}
1539
1540/* interface lookup routintes */
1541
1542struct ipsec_addr_wrap	*iftab;
1543
1544void
1545ifa_load(void)
1546{
1547	struct ifaddrs		*ifap, *ifa;
1548	struct ipsec_addr_wrap	*n = NULL, *h = NULL;
1549
1550	if (getifaddrs(&ifap) < 0)
1551		err(1, "ifa_load: getifaddrs");
1552
1553	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1554		if (!(ifa->ifa_addr->sa_family == AF_INET ||
1555		    ifa->ifa_addr->sa_family == AF_INET6 ||
1556		    ifa->ifa_addr->sa_family == AF_LINK))
1557			continue;
1558		n = calloc(1, sizeof(struct ipsec_addr_wrap));
1559		if (n == NULL)
1560			err(1, "ifa_load: calloc");
1561		n->af = ifa->ifa_addr->sa_family;
1562		if ((n->name = strdup(ifa->ifa_name)) == NULL)
1563			err(1, "ifa_load: strdup");
1564		if (n->af == AF_INET) {
1565			n->af = AF_INET;
1566			memcpy(&n->address.v4, &((struct sockaddr_in *)
1567			    ifa->ifa_addr)->sin_addr,
1568			    sizeof(struct in_addr));
1569			memcpy(&n->mask.v4, &((struct sockaddr_in *)
1570			    ifa->ifa_netmask)->sin_addr,
1571			    sizeof(struct in_addr));
1572		} else if (n->af == AF_INET6) {
1573			n->af = AF_INET6;
1574			memcpy(&n->address.v6, &((struct sockaddr_in6 *)
1575			    ifa->ifa_addr)->sin6_addr,
1576			    sizeof(struct in6_addr));
1577			memcpy(&n->mask.v6, &((struct sockaddr_in6 *)
1578			    ifa->ifa_netmask)->sin6_addr,
1579			    sizeof(struct in6_addr));
1580		}
1581		n->next = NULL;
1582		n->tail = n;
1583		if (h == NULL)
1584			h = n;
1585		else {
1586			h->tail->next = n;
1587			h->tail = n;
1588		}
1589	}
1590
1591	iftab = h;
1592	freeifaddrs(ifap);
1593}
1594
1595int
1596ifa_exists(const char *ifa_name)
1597{
1598	struct ipsec_addr_wrap	*n;
1599	struct ifgroupreq	 ifgr;
1600	int			 s;
1601
1602	if (iftab == NULL)
1603		ifa_load();
1604
1605	/* check wether this is a group */
1606	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1607		err(1, "ifa_exists: socket");
1608	bzero(&ifgr, sizeof(ifgr));
1609	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1610	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == 0) {
1611		close(s);
1612		return (1);
1613	}
1614	close(s);
1615
1616	for (n = iftab; n; n = n->next) {
1617		if (n->af == AF_LINK && !strncmp(n->name, ifa_name,
1618		    IFNAMSIZ))
1619			return (1);
1620	}
1621
1622	return (0);
1623}
1624
1625struct ipsec_addr_wrap *
1626ifa_grouplookup(const char *ifa_name)
1627{
1628	struct ifg_req		*ifg;
1629	struct ifgroupreq	 ifgr;
1630	int			 s;
1631	size_t			 len;
1632	struct ipsec_addr_wrap	*n, *h = NULL, *hn;
1633
1634	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1635		err(1, "socket");
1636	bzero(&ifgr, sizeof(ifgr));
1637	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1638	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
1639		close(s);
1640		return (NULL);
1641	}
1642
1643	len = ifgr.ifgr_len;
1644	if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
1645		err(1, "calloc");
1646	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
1647		err(1, "ioctl");
1648
1649	for (ifg = ifgr.ifgr_groups; ifg && len >= sizeof(struct ifg_req);
1650	    ifg++) {
1651		len -= sizeof(struct ifg_req);
1652		if ((n = ifa_lookup(ifg->ifgrq_member)) == NULL)
1653			continue;
1654		if (h == NULL)
1655			h = n;
1656		else {
1657			for (hn = h; hn->next != NULL; hn = hn->next)
1658				;	/* nothing */
1659			hn->next = n;
1660			n->tail = hn;
1661		}
1662	}
1663	free(ifgr.ifgr_groups);
1664	close(s);
1665
1666	return (h);
1667}
1668
1669struct ipsec_addr_wrap *
1670ifa_lookup(const char *ifa_name)
1671{
1672	struct ipsec_addr_wrap	*p = NULL, *h = NULL, *n = NULL;
1673
1674	if (iftab == NULL)
1675		ifa_load();
1676
1677	if ((n = ifa_grouplookup(ifa_name)) != NULL)
1678		return (n);
1679
1680	for (p = iftab; p; p = p->next) {
1681		if (p->af != AF_INET && p->af != AF_INET6)
1682			continue;
1683		if (strncmp(p->name, ifa_name, IFNAMSIZ))
1684			continue;
1685		n = calloc(1, sizeof(struct ipsec_addr_wrap));
1686		if (n == NULL)
1687			err(1, "ifa_lookup: calloc");
1688		memcpy(n, p, sizeof(struct ipsec_addr_wrap));
1689		if ((n->name = strdup(p->name)) == NULL)
1690			err(1, "ifa_lookup: strdup");
1691		switch (n->af) {
1692		case AF_INET:
1693			set_ipmask(n, 32);
1694			break;
1695		case AF_INET6:
1696			/* route/show.c and bgpd/util.c give KAME credit */
1697			if (IN6_IS_ADDR_LINKLOCAL(&n->address.v6)) {
1698				u_int16_t tmp16;
1699				/* for now we can not handle link local,
1700				 * therefore bail for now
1701				 */
1702				free(n);
1703				continue;
1704
1705				memcpy(&tmp16, &n->address.v6.s6_addr[2],
1706				    sizeof(tmp16));
1707				/* use this when we support link-local
1708				 * n->??.scopeid = ntohs(tmp16);
1709				 */
1710				n->address.v6.s6_addr[2] = 0;
1711				n->address.v6.s6_addr[3] = 0;
1712			}
1713			set_ipmask(n, 128);
1714			break;
1715		}
1716
1717		n->next = NULL;
1718		n->tail = n;
1719		if (h == NULL)
1720			h = n;
1721		else {
1722			h->tail->next = n;
1723			h->tail = n;
1724		}
1725	}
1726
1727	return (h);
1728}
1729
1730void
1731set_ipmask(struct ipsec_addr_wrap *address, u_int8_t b)
1732{
1733	struct ipsec_addr	*ipa;
1734	int			 i, j = 0;
1735
1736	ipa = &address->mask;
1737	bzero(ipa, sizeof(struct ipsec_addr));
1738
1739	while (b >= 32) {
1740		ipa->addr32[j++] = 0xffffffff;
1741		b -= 32;
1742	}
1743	for (i = 31; i > 31 - b; --i)
1744		ipa->addr32[j] |= (1 << i);
1745	if (b)
1746		ipa->addr32[j] = htonl(ipa->addr32[j]);
1747}
1748
1749const struct ipsec_xf *
1750parse_xf(const char *name, const struct ipsec_xf xfs[])
1751{
1752	int		i;
1753
1754	for (i = 0; xfs[i].name != NULL; i++) {
1755		if (strncmp(name, xfs[i].name, strlen(name)))
1756			continue;
1757		return &xfs[i];
1758	}
1759	return (NULL);
1760}
1761
1762struct ipsec_life *
1763parse_life(int value)
1764{
1765	struct ipsec_life	*life;
1766
1767	life = calloc(1, sizeof(struct ipsec_life));
1768	if (life == NULL)
1769		err(1, "calloc");
1770
1771	life->lifetime = value;
1772
1773	return (life);
1774}
1775
1776struct ipsec_transforms *
1777copytransforms(const struct ipsec_transforms *xfs)
1778{
1779	struct ipsec_transforms *newxfs;
1780
1781	if (xfs == NULL)
1782		return (NULL);
1783
1784	newxfs = calloc(1, sizeof(struct ipsec_transforms));
1785	if (newxfs == NULL)
1786		err(1, "copytransforms: calloc");
1787
1788	memcpy(newxfs, xfs, sizeof(struct ipsec_transforms));
1789	return (newxfs);
1790}
1791
1792struct ipsec_life *
1793copylife(const struct ipsec_life *life)
1794{
1795	struct ipsec_life *newlife;
1796
1797	if (life == NULL)
1798		return (NULL);
1799
1800	newlife = calloc(1, sizeof(struct ipsec_life));
1801	if (newlife == NULL)
1802		err(1, "copylife: calloc");
1803
1804	memcpy(newlife, life, sizeof(struct ipsec_life));
1805	return (newlife);
1806}
1807
1808struct ipsec_auth *
1809copyipsecauth(const struct ipsec_auth *auth)
1810{
1811	struct ipsec_auth	*newauth;
1812
1813	if (auth == NULL)
1814		return (NULL);
1815
1816	if ((newauth = calloc(1, sizeof(struct ipsec_auth))) == NULL)
1817		err(1, "calloc");
1818	if (auth->srcid &&
1819	    asprintf(&newauth->srcid, "%s", auth->srcid) == -1)
1820		err(1, "asprintf");
1821	if (auth->dstid &&
1822	    asprintf(&newauth->dstid, "%s", auth->dstid) == -1)
1823		err(1, "asprintf");
1824
1825	newauth->srcid_type = auth->srcid_type;
1826	newauth->dstid_type = auth->dstid_type;
1827	newauth->type = auth->type;
1828
1829	return (newauth);
1830}
1831
1832struct ike_auth *
1833copyikeauth(const struct ike_auth *auth)
1834{
1835	struct ike_auth	*newauth;
1836
1837	if (auth == NULL)
1838		return (NULL);
1839
1840	if ((newauth = calloc(1, sizeof(struct ike_auth))) == NULL)
1841		err(1, "calloc");
1842	if (auth->string &&
1843	    asprintf(&newauth->string, "%s", auth->string) == -1)
1844		err(1, "asprintf");
1845
1846	newauth->type = auth->type;
1847
1848	return (newauth);
1849}
1850
1851struct ipsec_key *
1852copykey(struct ipsec_key *key)
1853{
1854	struct ipsec_key	*newkey;
1855
1856	if (key == NULL)
1857		return (NULL);
1858
1859	if ((newkey = calloc(1, sizeof(struct ipsec_key))) == NULL)
1860		err(1, "calloc");
1861	if ((newkey->data = calloc(key->len, sizeof(u_int8_t))) == NULL)
1862		err(1, "calloc");
1863	memcpy(newkey->data, key->data, key->len);
1864	newkey->len = key->len;
1865
1866	return (newkey);
1867}
1868
1869struct ipsec_addr_wrap *
1870copyhost(const struct ipsec_addr_wrap *src)
1871{
1872	struct ipsec_addr_wrap *dst;
1873
1874	if (src == NULL)
1875		return (NULL);
1876
1877	dst = calloc(1, sizeof(struct ipsec_addr_wrap));
1878	if (dst == NULL)
1879		err(1, "copyhost: calloc");
1880
1881	memcpy(dst, src, sizeof(struct ipsec_addr_wrap));
1882
1883	if (src->name != NULL && (dst->name = strdup(src->name)) == NULL)
1884		err(1, "copyhost: strdup");
1885
1886	return dst;
1887}
1888
1889char *
1890copytag(const char *src)
1891{
1892	char *tag;
1893
1894	if (src == NULL)
1895		return (NULL);
1896	if ((tag = strdup(src)) == NULL)
1897		err(1, "copytag: strdup");
1898
1899	return (tag);
1900}
1901
1902struct ipsec_rule *
1903copyrule(struct ipsec_rule *rule)
1904{
1905	struct ipsec_rule	*r;
1906
1907	if ((r = calloc(1, sizeof(struct ipsec_rule))) == NULL)
1908		err(1, "calloc");
1909
1910	r->src = copyhost(rule->src);
1911	r->dst = copyhost(rule->dst);
1912	r->local = copyhost(rule->local);
1913	r->peer = copyhost(rule->peer);
1914	r->auth = copyipsecauth(rule->auth);
1915	r->ikeauth = copyikeauth(rule->ikeauth);
1916	r->xfs = copytransforms(rule->xfs);
1917	r->p1xfs = copytransforms(rule->p1xfs);
1918	r->p2xfs = copytransforms(rule->p2xfs);
1919	r->p1life = copylife(rule->p1life);
1920	r->p2life = copylife(rule->p2life);
1921	r->authkey = copykey(rule->authkey);
1922	r->enckey = copykey(rule->enckey);
1923	r->tag = copytag(rule->tag);
1924
1925	r->p1ie = rule->p1ie;
1926	r->p2ie = rule->p2ie;
1927	r->type = rule->type;
1928	r->satype = rule->satype;
1929	r->proto = rule->proto;
1930	r->tmode = rule->tmode;
1931	r->direction = rule->direction;
1932	r->flowtype = rule->flowtype;
1933	r->sport = rule->sport;
1934	r->dport = rule->dport;
1935	r->ikemode = rule->ikemode;
1936	r->spi = rule->spi;
1937	r->nr = rule->nr;
1938
1939	return (r);
1940}
1941
1942int
1943validate_af(struct ipsec_addr_wrap *src, struct ipsec_addr_wrap *dst)
1944{
1945	struct ipsec_addr_wrap *ta;
1946	u_int8_t src_v4 = 0;
1947	u_int8_t dst_v4 = 0;
1948	u_int8_t src_v6 = 0;
1949	u_int8_t dst_v6 = 0;
1950
1951	for (ta = src; ta; ta = ta->next) {
1952		if (ta->af == AF_INET)
1953			src_v4 = 1;
1954		if (ta->af == AF_INET6)
1955			src_v6 = 1;
1956		if (ta->af == AF_UNSPEC)
1957			return 0;
1958		if (src_v4 && src_v6)
1959			break;
1960	}
1961	for (ta = dst; ta; ta = ta->next) {
1962		if (ta->af == AF_INET)
1963			dst_v4 = 1;
1964		if (ta->af == AF_INET6)
1965			dst_v6 = 1;
1966		if (ta->af == AF_UNSPEC)
1967			return 0;
1968		if (dst_v4 && dst_v6)
1969			break;
1970	}
1971	if (src_v4 != dst_v4 && src_v6 != dst_v6)
1972		return (1);
1973
1974	return (0);
1975}
1976
1977
1978int
1979validate_sa(u_int32_t spi, u_int8_t satype, struct ipsec_transforms *xfs,
1980    struct ipsec_key *authkey, struct ipsec_key *enckey, u_int8_t tmode)
1981{
1982	/* Sanity checks */
1983	if (spi == 0) {
1984		yyerror("no SPI specified");
1985		return (0);
1986	}
1987	if (satype == IPSEC_AH) {
1988		if (!xfs) {
1989			yyerror("no transforms specified");
1990			return (0);
1991		}
1992		if (!xfs->authxf)
1993			xfs->authxf = &authxfs[AUTHXF_HMAC_SHA2_256];
1994		if (xfs->encxf) {
1995			yyerror("ah does not provide encryption");
1996			return (0);
1997		}
1998		if (xfs->compxf) {
1999			yyerror("ah does not provide compression");
2000			return (0);
2001		}
2002	}
2003	if (satype == IPSEC_ESP) {
2004		if (!xfs) {
2005			yyerror("no transforms specified");
2006			return (0);
2007		}
2008		if (xfs->compxf) {
2009			yyerror("esp does not provide compression");
2010			return (0);
2011		}
2012		if (!xfs->authxf)
2013			xfs->authxf = &authxfs[AUTHXF_HMAC_SHA2_256];
2014		if (!xfs->encxf)
2015			xfs->encxf = &encxfs[ENCXF_AES];
2016	}
2017	if (satype == IPSEC_IPCOMP) {
2018		if (!xfs) {
2019			yyerror("no transform specified");
2020			return (0);
2021		}
2022		if (xfs->authxf || xfs->encxf) {
2023			yyerror("no encryption or authentication with ipcomp");
2024			return (0);
2025		}
2026		if (!xfs->compxf)
2027			xfs->compxf = &compxfs[COMPXF_DEFLATE];
2028	}
2029	if (satype == IPSEC_IPIP) {
2030		if (!xfs) {
2031			yyerror("no transform specified");
2032			return (0);
2033		}
2034		if (xfs->authxf || xfs->encxf || xfs->compxf) {
2035			yyerror("no encryption, authentication or compression"
2036			    " with ipip");
2037			return (0);
2038		}
2039	}
2040	if (satype == IPSEC_TCPMD5 && authkey == NULL && tmode !=
2041	    IPSEC_TRANSPORT) {
2042		yyerror("authentication key needed for tcpmd5");
2043		return (0);
2044	}
2045	if (xfs && xfs->authxf) {
2046		if (!authkey && xfs->authxf != &authxfs[AUTHXF_NONE]) {
2047			yyerror("no authentication key specified");
2048			return (0);
2049		}
2050		if (authkey && authkey->len != xfs->authxf->keymin) {
2051			yyerror("wrong authentication key length, needs to be "
2052			    "%d bits", xfs->authxf->keymin * 8);
2053			return (0);
2054		}
2055	}
2056	if (xfs && xfs->encxf) {
2057		if (!enckey && xfs->encxf != &encxfs[ENCXF_NULL]) {
2058			yyerror("no encryption key specified");
2059			return (0);
2060		}
2061		if (enckey) {
2062			if (enckey->len < xfs->encxf->keymin) {
2063				yyerror("encryption key too short (%d bits), "
2064				    "minimum %d bits", enckey->len * 8,
2065				    xfs->encxf->keymin * 8);
2066				return (0);
2067			}
2068			if (xfs->encxf->keymax < enckey->len) {
2069				yyerror("encryption key too long (%d bits), "
2070				    "maximum %d bits", enckey->len * 8,
2071				    xfs->encxf->keymax * 8);
2072				return (0);
2073			}
2074		}
2075	}
2076
2077	return 1;
2078}
2079
2080int
2081add_sagroup(struct ipsec_rule *r)
2082{
2083	struct ipsec_rule	*rp, *last, *group;
2084	int			 found = 0;
2085
2086	TAILQ_FOREACH(rp, &ipsec->group_queue, group_entry) {
2087		if ((strcmp(rp->src->name, r->src->name) == 0) &&
2088		    (strcmp(rp->dst->name, r->dst->name) == 0)) {
2089			found = 1;
2090			break;
2091		}
2092	}
2093	if (found) {
2094		last = TAILQ_LAST(&rp->dst_group_queue, dst_group_queue);
2095		TAILQ_INSERT_TAIL(&rp->dst_group_queue, r, dst_group_entry);
2096
2097		group = create_sagroup(last->dst, last->satype, last->spi,
2098		    r->dst, r->satype, r->spi);
2099		if (group == NULL)
2100			return (1);
2101		group->nr = ipsec->rule_nr++;
2102		if (ipsecctl_add_rule(ipsec, group))
2103			return (1);
2104	} else {
2105		TAILQ_INSERT_TAIL(&ipsec->group_queue, r, group_entry);
2106		TAILQ_INIT(&r->dst_group_queue);
2107		TAILQ_INSERT_TAIL(&r->dst_group_queue, r, dst_group_entry);
2108	}
2109
2110	return (0);
2111}
2112
2113struct ipsec_rule *
2114create_sa(u_int8_t satype, u_int8_t tmode, struct ipsec_hosts *hosts,
2115    u_int32_t spi, struct ipsec_transforms *xfs, struct ipsec_key *authkey,
2116    struct ipsec_key *enckey)
2117{
2118	struct ipsec_rule *r;
2119
2120	if (validate_sa(spi, satype, xfs, authkey, enckey, tmode) == 0)
2121		return (NULL);
2122
2123	r = calloc(1, sizeof(struct ipsec_rule));
2124	if (r == NULL)
2125		err(1, "create_sa: calloc");
2126
2127	r->type |= RULE_SA;
2128	r->satype = satype;
2129	r->tmode = tmode;
2130	r->src = hosts->src;
2131	r->dst = hosts->dst;
2132	r->spi = spi;
2133	r->xfs = xfs;
2134	r->authkey = authkey;
2135	r->enckey = enckey;
2136
2137	return r;
2138}
2139
2140struct ipsec_rule *
2141reverse_sa(struct ipsec_rule *rule, u_int32_t spi, struct ipsec_key *authkey,
2142    struct ipsec_key *enckey)
2143{
2144	struct ipsec_rule *reverse;
2145
2146	if (validate_sa(spi, rule->satype, rule->xfs, authkey, enckey,
2147	    rule->tmode) == 0)
2148		return (NULL);
2149
2150	reverse = calloc(1, sizeof(struct ipsec_rule));
2151	if (reverse == NULL)
2152		err(1, "reverse_sa: calloc");
2153
2154	reverse->type |= RULE_SA;
2155	reverse->satype = rule->satype;
2156	reverse->tmode = rule->tmode;
2157	reverse->src = copyhost(rule->dst);
2158	reverse->dst = copyhost(rule->src);
2159	reverse->spi = spi;
2160	reverse->xfs = copytransforms(rule->xfs);
2161	reverse->authkey = authkey;
2162	reverse->enckey = enckey;
2163
2164	return (reverse);
2165}
2166
2167struct ipsec_rule *
2168create_sagroup(struct ipsec_addr_wrap *dst, u_int8_t proto, u_int32_t spi,
2169    struct ipsec_addr_wrap *dst2, u_int8_t proto2, u_int32_t spi2)
2170{
2171	struct ipsec_rule *r;
2172
2173	r = calloc(1, sizeof(struct ipsec_rule));
2174	if (r == NULL)
2175		err(1, "create_sagroup: calloc");
2176
2177	r->type |= RULE_GROUP;
2178
2179	r->dst = copyhost(dst);
2180	r->dst2 = copyhost(dst2);
2181	r->proto = proto;
2182	r->proto2 = proto2;
2183	r->spi = spi;
2184	r->spi2 = spi2;
2185	r->satype = proto;
2186
2187	return (r);
2188}
2189
2190struct ipsec_rule *
2191create_flow(u_int8_t dir, u_int8_t proto, struct ipsec_hosts *hosts,
2192    struct ipsec_hosts *peers,
2193    u_int8_t satype, char *srcid, char *dstid, u_int8_t type)
2194{
2195	struct ipsec_rule *r;
2196
2197	r = calloc(1, sizeof(struct ipsec_rule));
2198	if (r == NULL)
2199		err(1, "create_flow: calloc");
2200
2201	r->type |= RULE_FLOW;
2202
2203	if (dir == IPSEC_INOUT)
2204		r->direction = IPSEC_OUT;
2205	else
2206		r->direction = dir;
2207
2208	r->satype = satype;
2209	r->proto = proto;
2210	r->src = hosts->src;
2211	r->sport = hosts->sport;
2212	r->dst = hosts->dst;
2213	r->dport = hosts->dport;
2214	if ((hosts->sport != 0 || hosts->dport != 0) &&
2215	    (proto != IPPROTO_TCP && proto != IPPROTO_UDP)) {
2216		yyerror("no protocol supplied with source/destination ports");
2217		goto errout;
2218	}
2219
2220	if (type == TYPE_DENY || type == TYPE_BYPASS) {
2221		r->flowtype = type;
2222		return (r);
2223	}
2224
2225	r->flowtype = type;
2226	r->local = peers->src;
2227	if (peers->dst == NULL) {
2228		/* Set peer to remote host.  Must be a host address. */
2229		if (r->direction == IPSEC_IN) {
2230			if (r->src->netaddress) {
2231				yyerror("no peer specified");
2232				goto errout;
2233			}
2234			r->peer = copyhost(r->src);
2235		} else {
2236			if (r->dst->netaddress) {
2237				yyerror("no peer specified");
2238				goto errout;
2239			}
2240			r->peer = copyhost(r->dst);
2241		}
2242	} else
2243		r->peer = peers->dst;
2244
2245	r->auth = calloc(1, sizeof(struct ipsec_auth));
2246	if (r->auth == NULL)
2247		err(1, "create_flow: calloc");
2248	r->auth->srcid = srcid;
2249	r->auth->dstid = dstid;
2250	r->auth->srcid_type = get_id_type(srcid);
2251	r->auth->dstid_type = get_id_type(dstid);
2252	return r;
2253
2254errout:
2255	free(r);
2256	if (srcid)
2257		free(srcid);
2258	if (dstid)
2259		free(dstid);
2260	free(hosts->src);
2261	hosts->src = NULL;
2262	free(hosts->dst);
2263	hosts->dst = NULL;
2264
2265	return NULL;
2266}
2267
2268void
2269expand_any(struct ipsec_addr_wrap *ipa_in)
2270{
2271	struct ipsec_addr_wrap *oldnext, *ipa;
2272
2273	for (ipa = ipa_in; ipa; ipa = ipa->next) {
2274		if (ipa->af != AF_UNSPEC)
2275			continue;
2276		oldnext = ipa->next;
2277
2278		ipa->af = AF_INET;
2279		ipa->netaddress = 1;
2280		if ((ipa->name = strdup("0.0.0.0/0")) == NULL)
2281			err(1, "expand_any: strdup");
2282
2283		ipa->next = calloc(1, sizeof(struct ipsec_addr_wrap));
2284		if (ipa->next == NULL)
2285			err(1, "expand_any: calloc");
2286		ipa->next->af = AF_INET6;
2287		ipa->next->netaddress = 1;
2288		if ((ipa->next->name = strdup("::/0")) == NULL)
2289			err(1, "expand_any: strdup");
2290
2291		ipa->next->next = oldnext;
2292	}
2293}
2294
2295int
2296expand_rule(struct ipsec_rule *rule, u_int8_t direction, u_int32_t spi,
2297    struct ipsec_key *authkey, struct ipsec_key *enckey, int group)
2298{
2299	struct ipsec_rule	*r, *revr;
2300	struct ipsec_addr_wrap	*src, *dst;
2301	int added = 0;
2302
2303	if (validate_af(rule->src, rule->dst)) {
2304		yyerror("source/destination address families do not match");
2305		goto errout;
2306	}
2307	expand_any(rule->src);
2308	expand_any(rule->dst);
2309	expand_any(rule->peer);
2310	for (src = rule->src; src; src = src->next) {
2311		for (dst = rule->dst; dst; dst = dst->next) {
2312			if (src->af != dst->af)
2313				continue;
2314			r = copyrule(rule);
2315
2316			r->src = copyhost(src);
2317			r->dst = copyhost(dst);
2318
2319			r->nr = ipsec->rule_nr++;
2320			if (ipsecctl_add_rule(ipsec, r))
2321				return (1);
2322			if (group && add_sagroup(r))
2323				return (1);
2324
2325			if (direction == IPSEC_INOUT) {
2326				/* Create and add reverse flow rule. */
2327				revr = reverse_rule(r);
2328				if (revr == NULL)
2329					return (1);
2330
2331				revr->nr = ipsec->rule_nr++;
2332				if (ipsecctl_add_rule(ipsec, revr))
2333					return (1);
2334				if (group && add_sagroup(revr))
2335					return (1);
2336			} else if (spi != 0 || authkey || enckey) {
2337				/* Create and add reverse sa rule. */
2338				revr = reverse_sa(r, spi, authkey, enckey);
2339				if (revr == NULL)
2340					return (1);
2341
2342				revr->nr = ipsec->rule_nr++;
2343				if (ipsecctl_add_rule(ipsec, revr))
2344					return (1);
2345				if (group && add_sagroup(revr))
2346					return (1);
2347			}
2348			added++;
2349		}
2350	}
2351	if (!added)
2352		yyerror("rule expands to no valid combination");
2353 errout:
2354	ipsecctl_free_rule(rule);
2355	return (0);
2356}
2357
2358struct ipsec_rule *
2359reverse_rule(struct ipsec_rule *rule)
2360{
2361	struct ipsec_rule *reverse;
2362
2363	reverse = calloc(1, sizeof(struct ipsec_rule));
2364	if (reverse == NULL)
2365		err(1, "reverse_rule: calloc");
2366
2367	reverse->type |= RULE_FLOW;
2368
2369	/* Reverse direction */
2370	if (rule->direction == (u_int8_t)IPSEC_OUT)
2371		reverse->direction = (u_int8_t)IPSEC_IN;
2372	else
2373		reverse->direction = (u_int8_t)IPSEC_OUT;
2374
2375	reverse->flowtype = rule->flowtype;
2376	reverse->src = copyhost(rule->dst);
2377	reverse->dst = copyhost(rule->src);
2378	reverse->sport = rule->dport;
2379	reverse->dport = rule->sport;
2380	if (rule->local)
2381		reverse->local = copyhost(rule->local);
2382	if (rule->peer)
2383		reverse->peer = copyhost(rule->peer);
2384	reverse->satype = rule->satype;
2385	reverse->proto = rule->proto;
2386
2387	if (rule->auth) {
2388		reverse->auth = calloc(1, sizeof(struct ipsec_auth));
2389		if (reverse->auth == NULL)
2390			err(1, "reverse_rule: calloc");
2391		if (rule->auth->dstid && (reverse->auth->dstid =
2392		    strdup(rule->auth->dstid)) == NULL)
2393			err(1, "reverse_rule: strdup");
2394		if (rule->auth->srcid && (reverse->auth->srcid =
2395		    strdup(rule->auth->srcid)) == NULL)
2396			err(1, "reverse_rule: strdup");
2397		reverse->auth->srcid_type = rule->auth->srcid_type;
2398		reverse->auth->dstid_type = rule->auth->dstid_type;
2399		reverse->auth->type = rule->auth->type;
2400	}
2401
2402	return reverse;
2403}
2404
2405struct ipsec_rule *
2406create_ike(u_int8_t proto, struct ipsec_hosts *hosts, struct ipsec_hosts *peers,
2407    struct ike_mode *phase1mode, struct ike_mode *phase2mode, u_int8_t satype,
2408    u_int8_t tmode, u_int8_t mode, char *srcid, char *dstid,
2409    struct ike_auth *authtype, char *tag)
2410{
2411	struct ipsec_rule *r;
2412
2413	r = calloc(1, sizeof(struct ipsec_rule));
2414	if (r == NULL)
2415		err(1, "create_ike: calloc");
2416
2417	r->type = RULE_IKE;
2418
2419	r->proto = proto;
2420	r->src = hosts->src;
2421	r->sport = hosts->sport;
2422	r->dst = hosts->dst;
2423	r->dport = hosts->dport;
2424	if ((hosts->sport != 0 || hosts->dport != 0) &&
2425	    (proto != IPPROTO_TCP && proto != IPPROTO_UDP)) {
2426		yyerror("no protocol supplied with source/destination ports");
2427		free(r);
2428		free(hosts->src);
2429		hosts->src = NULL;
2430		free(hosts->dst);
2431		hosts->dst = NULL;
2432		if (phase1mode) {
2433			free(phase1mode->xfs);
2434			phase1mode->xfs = NULL;
2435			free(phase1mode->life);
2436			phase1mode->life = NULL;
2437		}
2438		if (phase2mode) {
2439			free(phase2mode->xfs);
2440			phase2mode->xfs = NULL;
2441			free(phase2mode->life);
2442			phase2mode->life = NULL;
2443		}
2444		if (srcid)
2445			free(srcid);
2446		if (dstid)
2447			free(dstid);
2448		return NULL;
2449	}
2450
2451	if (peers->dst == NULL) {
2452		/* Set peer to remote host.  Must be a host address. */
2453		if (r->direction == IPSEC_IN) {
2454			if (r->src->netaddress)
2455				r->peer = NULL;
2456			else
2457				r->peer = copyhost(r->src);
2458		} else {
2459			if (r->dst->netaddress)
2460				r->peer = NULL;
2461			else
2462				r->peer = copyhost(r->dst);
2463		}
2464	} else
2465		r->peer = peers->dst;
2466
2467	if (peers->src)
2468		r->local = peers->src;
2469
2470	r->satype = satype;
2471	r->tmode = tmode;
2472	r->ikemode = mode;
2473	if (phase1mode) {
2474		r->p1xfs = phase1mode->xfs;
2475		r->p1life = phase1mode->life;
2476		r->p1ie = phase1mode->ike_exch;
2477	} else {
2478		r->p1ie = IKE_MM;
2479	}
2480	if (phase2mode) {
2481		r->p2xfs = phase2mode->xfs;
2482		r->p2life = phase2mode->life;
2483		r->p2ie = phase2mode->ike_exch;
2484	} else {
2485		r->p2ie = IKE_QM;
2486	}
2487
2488	r->auth = calloc(1, sizeof(struct ipsec_auth));
2489	if (r->auth == NULL)
2490		err(1, "create_ike: calloc");
2491	r->auth->srcid = srcid;
2492	r->auth->dstid = dstid;
2493	r->auth->srcid_type = get_id_type(srcid);
2494	r->auth->dstid_type = get_id_type(dstid);
2495	r->ikeauth = calloc(1, sizeof(struct ike_auth));
2496	if (r->ikeauth == NULL)
2497		err(1, "create_ike: calloc");
2498	r->ikeauth->type = authtype->type;
2499	r->ikeauth->string = authtype->string;
2500	r->tag = tag;
2501
2502	return (r);
2503}
2504