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