parse.y revision 1.169
1/*	$OpenBSD: parse.y,v 1.169 2017/10/27 08:29:32 mpi 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					YYERROR;
915				}
916			}
917			if (symset($1, $3, 0) == -1)
918				err(1, "cannot store variable");
919			free($1);
920			free($3);
921		}
922		;
923
924%%
925
926struct keywords {
927	const char	*k_name;
928	int		 k_val;
929};
930
931int
932yyerror(const char *fmt, ...)
933{
934	va_list		 ap;
935
936	file->errors++;
937	va_start(ap, fmt);
938	fprintf(stderr, "%s: %d: ", file->name, yylval.lineno);
939	vfprintf(stderr, fmt, ap);
940	fprintf(stderr, "\n");
941	va_end(ap);
942	return (0);
943}
944
945int
946yywarn(const char *fmt, ...)
947{
948	va_list		 ap;
949
950	va_start(ap, fmt);
951	fprintf(stderr, "%s: %d: ", file->name, yylval.lineno);
952	vfprintf(stderr, fmt, ap);
953	fprintf(stderr, "\n");
954	va_end(ap);
955	return (0);
956}
957
958int
959kw_cmp(const void *k, const void *e)
960{
961	return (strcmp(k, ((const struct keywords *)e)->k_name));
962}
963
964int
965lookup(char *s)
966{
967	/* this has to be sorted always */
968	static const struct keywords keywords[] = {
969		{ "acquire",		ACQUIRE },
970		{ "active",		ACTIVE },
971		{ "aggressive",		AGGRESSIVE },
972		{ "ah",			AH },
973		{ "any",		ANY },
974		{ "auth",		AUTHXF },
975		{ "authkey",		AUTHKEY },
976		{ "bundle",		BUNDLE },
977		{ "bypass",		BYPASS },
978		{ "comp",		COMPXF },
979		{ "deny",		DENY },
980		{ "dontacq",		DONTACQ },
981		{ "dstid",		DSTID },
982		{ "dynamic",		DYNAMIC },
983		{ "enc",		ENCXF },
984		{ "enckey",		ENCKEY },
985		{ "esp",		ESP },
986		{ "file",		FILENAME },
987		{ "flow",		FLOW },
988		{ "from",		FROM },
989		{ "group",		GROUP },
990		{ "ike",		IKE },
991		{ "in",			IN },
992		{ "include",		INCLUDE },
993		{ "ipcomp",		IPCOMP },
994		{ "ipip",		IPIP },
995		{ "lifetime",		LIFETIME },
996		{ "local",		LOCAL },
997		{ "main",		MAIN },
998		{ "out",		OUT },
999		{ "passive",		PASSIVE },
1000		{ "peer",		PEER },
1001		{ "port",		PORT },
1002		{ "proto",		PROTO },
1003		{ "psk",		PSK },
1004		{ "quick",		QUICK },
1005		{ "require",		REQUIRE },
1006		{ "rsa",		RSA },
1007		{ "spi",		SPI },
1008		{ "srcid",		SRCID },
1009		{ "tag",		TAG },
1010		{ "tcpmd5",		TCPMD5 },
1011		{ "to",			TO },
1012		{ "transport",		TRANSPORT },
1013		{ "tunnel",		TUNNEL },
1014		{ "type",		TYPE },
1015		{ "use",		USE }
1016	};
1017	const struct keywords	*p;
1018
1019	p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
1020	    sizeof(keywords[0]), kw_cmp);
1021
1022	if (p) {
1023		if (debug > 1)
1024			fprintf(stderr, "%s: %d\n", s, p->k_val);
1025		return (p->k_val);
1026	} else {
1027		if (debug > 1)
1028			fprintf(stderr, "string: %s\n", s);
1029		return (STRING);
1030	}
1031}
1032
1033#define MAXPUSHBACK	128
1034
1035u_char	*parsebuf;
1036int	 parseindex;
1037u_char	 pushback_buffer[MAXPUSHBACK];
1038int	 pushback_index = 0;
1039
1040int
1041lgetc(int quotec)
1042{
1043	int		c, next;
1044
1045	if (parsebuf) {
1046		/* Read character from the parsebuffer instead of input. */
1047		if (parseindex >= 0) {
1048			c = parsebuf[parseindex++];
1049			if (c != '\0')
1050				return (c);
1051			parsebuf = NULL;
1052		} else
1053			parseindex++;
1054	}
1055
1056	if (pushback_index)
1057		return (pushback_buffer[--pushback_index]);
1058
1059	if (quotec) {
1060		if ((c = getc(file->stream)) == EOF) {
1061			yyerror("reached end of file while parsing quoted string");
1062			if (popfile() == EOF)
1063				return (EOF);
1064			return (quotec);
1065		}
1066		return (c);
1067	}
1068
1069	while ((c = getc(file->stream)) == '\\') {
1070		next = getc(file->stream);
1071		if (next != '\n') {
1072			c = next;
1073			break;
1074		}
1075		yylval.lineno = file->lineno;
1076		file->lineno++;
1077	}
1078
1079	while (c == EOF) {
1080		if (popfile() == EOF)
1081			return (EOF);
1082		c = getc(file->stream);
1083	}
1084	return (c);
1085}
1086
1087int
1088lungetc(int c)
1089{
1090	if (c == EOF)
1091		return (EOF);
1092	if (parsebuf) {
1093		parseindex--;
1094		if (parseindex >= 0)
1095			return (c);
1096	}
1097	if (pushback_index < MAXPUSHBACK-1)
1098		return (pushback_buffer[pushback_index++] = c);
1099	else
1100		return (EOF);
1101}
1102
1103int
1104findeol(void)
1105{
1106	int	c;
1107
1108	parsebuf = NULL;
1109
1110	/* skip to either EOF or the first real EOL */
1111	while (1) {
1112		if (pushback_index)
1113			c = pushback_buffer[--pushback_index];
1114		else
1115			c = lgetc(0);
1116		if (c == '\n') {
1117			file->lineno++;
1118			break;
1119		}
1120		if (c == EOF)
1121			break;
1122	}
1123	return (ERROR);
1124}
1125
1126int
1127yylex(void)
1128{
1129	u_char	 buf[8096];
1130	u_char	*p, *val;
1131	int	 quotec, next, c;
1132	int	 token;
1133
1134top:
1135	p = buf;
1136	while ((c = lgetc(0)) == ' ' || c == '\t')
1137		; /* nothing */
1138
1139	yylval.lineno = file->lineno;
1140	if (c == '#')
1141		while ((c = lgetc(0)) != '\n' && c != EOF)
1142			; /* nothing */
1143	if (c == '$' && parsebuf == NULL) {
1144		while (1) {
1145			if ((c = lgetc(0)) == EOF)
1146				return (0);
1147
1148			if (p + 1 >= buf + sizeof(buf) - 1) {
1149				yyerror("string too long");
1150				return (findeol());
1151			}
1152			if (isalnum(c) || c == '_') {
1153				*p++ = c;
1154				continue;
1155			}
1156			*p = '\0';
1157			lungetc(c);
1158			break;
1159		}
1160		val = symget(buf);
1161		if (val == NULL) {
1162			yyerror("macro '%s' not defined", buf);
1163			return (findeol());
1164		}
1165		parsebuf = val;
1166		parseindex = 0;
1167		goto top;
1168	}
1169
1170	switch (c) {
1171	case '\'':
1172	case '"':
1173		quotec = c;
1174		while (1) {
1175			if ((c = lgetc(quotec)) == EOF)
1176				return (0);
1177			if (c == '\n') {
1178				file->lineno++;
1179				continue;
1180			} else if (c == '\\') {
1181				if ((next = lgetc(quotec)) == EOF)
1182					return (0);
1183				if (next == quotec || c == ' ' || c == '\t')
1184					c = next;
1185				else if (next == '\n') {
1186					file->lineno++;
1187					continue;
1188				} else
1189					lungetc(next);
1190			} else if (c == quotec) {
1191				*p = '\0';
1192				break;
1193			} else if (c == '\0') {
1194				yyerror("syntax error");
1195				return (findeol());
1196			}
1197			if (p + 1 >= buf + sizeof(buf) - 1) {
1198				yyerror("string too long");
1199				return (findeol());
1200			}
1201			*p++ = c;
1202		}
1203		yylval.v.string = strdup(buf);
1204		if (yylval.v.string == NULL)
1205			err(1, "yylex: strdup");
1206		return (STRING);
1207	}
1208
1209#define allowed_to_end_number(x) \
1210	(isspace(x) || x == ')' || x ==',' || x == '/' || x == '}' || x == '=')
1211
1212	if (c == '-' || isdigit(c)) {
1213		do {
1214			*p++ = c;
1215			if ((unsigned)(p-buf) >= sizeof(buf)) {
1216				yyerror("string too long");
1217				return (findeol());
1218			}
1219		} while ((c = lgetc(0)) != EOF && isdigit(c));
1220		lungetc(c);
1221		if (p == buf + 1 && buf[0] == '-')
1222			goto nodigits;
1223		if (c == EOF || allowed_to_end_number(c)) {
1224			const char *errstr = NULL;
1225
1226			*p = '\0';
1227			yylval.v.number = strtonum(buf, LLONG_MIN,
1228			    LLONG_MAX, &errstr);
1229			if (errstr) {
1230				yyerror("\"%s\" invalid number: %s",
1231				    buf, errstr);
1232				return (findeol());
1233			}
1234			return (NUMBER);
1235		} else {
1236nodigits:
1237			while (p > buf + 1)
1238				lungetc(*--p);
1239			c = *--p;
1240			if (c == '-')
1241				return (c);
1242		}
1243	}
1244
1245#define allowed_in_string(x) \
1246	(isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
1247	x != '{' && x != '}' && x != '<' && x != '>' && \
1248	x != '!' && x != '=' && x != '/' && x != '#' && \
1249	x != ','))
1250
1251	if (isalnum(c) || c == ':' || c == '_' || c == '*') {
1252		do {
1253			*p++ = c;
1254			if ((unsigned)(p-buf) >= sizeof(buf)) {
1255				yyerror("string too long");
1256				return (findeol());
1257			}
1258		} while ((c = lgetc(0)) != EOF && (allowed_in_string(c)));
1259		lungetc(c);
1260		*p = '\0';
1261		if ((token = lookup(buf)) == STRING)
1262			if ((yylval.v.string = strdup(buf)) == NULL)
1263				err(1, "yylex: strdup");
1264		return (token);
1265	}
1266	if (c == '\n') {
1267		yylval.lineno = file->lineno;
1268		file->lineno++;
1269	}
1270	if (c == EOF)
1271		return (0);
1272	return (c);
1273}
1274
1275int
1276check_file_secrecy(int fd, const char *fname)
1277{
1278	struct stat	st;
1279
1280	if (fstat(fd, &st)) {
1281		warn("cannot stat %s", fname);
1282		return (-1);
1283	}
1284	if (st.st_uid != 0 && st.st_uid != getuid()) {
1285		warnx("%s: owner not root or current user", fname);
1286		return (-1);
1287	}
1288	if (st.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO)) {
1289		warnx("%s: group writable or world read/writable", fname);
1290		return (-1);
1291	}
1292	return (0);
1293}
1294
1295struct file *
1296pushfile(const char *name, int secret)
1297{
1298	struct file	*nfile;
1299
1300	if ((nfile = calloc(1, sizeof(struct file))) == NULL) {
1301		warn("malloc");
1302		return (NULL);
1303	}
1304	if ((nfile->name = strdup(name)) == NULL) {
1305		warn("malloc");
1306		free(nfile);
1307		return (NULL);
1308	}
1309	if (TAILQ_FIRST(&files) == NULL && strcmp(nfile->name, "-") == 0) {
1310		nfile->stream = stdin;
1311		free(nfile->name);
1312		if ((nfile->name = strdup("stdin")) == NULL) {
1313			warn("strdup");
1314			free(nfile);
1315			return (NULL);
1316		}
1317	} else if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
1318		warn("%s", nfile->name);
1319		free(nfile->name);
1320		free(nfile);
1321		return (NULL);
1322	} else if (secret &&
1323	    check_file_secrecy(fileno(nfile->stream), nfile->name)) {
1324		fclose(nfile->stream);
1325		free(nfile->name);
1326		free(nfile);
1327		return (NULL);
1328	}
1329	nfile->lineno = 1;
1330	TAILQ_INSERT_TAIL(&files, nfile, entry);
1331	return (nfile);
1332}
1333
1334int
1335popfile(void)
1336{
1337	struct file	*prev;
1338
1339	if ((prev = TAILQ_PREV(file, files, entry)) != NULL) {
1340		prev->errors += file->errors;
1341		TAILQ_REMOVE(&files, file, entry);
1342		fclose(file->stream);
1343		free(file->name);
1344		free(file);
1345		file = prev;
1346		return (0);
1347	}
1348	return (EOF);
1349}
1350
1351int
1352parse_rules(const char *filename, struct ipsecctl *ipsecx)
1353{
1354	struct sym	*sym;
1355	int		 errors = 0;
1356
1357	ipsec = ipsecx;
1358
1359	if ((file = pushfile(filename, 1)) == NULL) {
1360		return (-1);
1361	}
1362
1363	yyparse();
1364	errors = file->errors;
1365	popfile();
1366
1367	/* Free macros and check which have not been used. */
1368	while ((sym = TAILQ_FIRST(&symhead))) {
1369		if ((ipsec->opts & IPSECCTL_OPT_VERBOSE2) && !sym->used)
1370			fprintf(stderr, "warning: macro '%s' not "
1371			    "used\n", sym->nam);
1372		free(sym->nam);
1373		free(sym->val);
1374		TAILQ_REMOVE(&symhead, sym, entry);
1375		free(sym);
1376	}
1377
1378	return (errors ? -1 : 0);
1379}
1380
1381int
1382symset(const char *nam, const char *val, int persist)
1383{
1384	struct sym	*sym;
1385
1386	TAILQ_FOREACH(sym, &symhead, entry) {
1387		if (strcmp(nam, sym->nam) == 0)
1388			break;
1389	}
1390
1391	if (sym != NULL) {
1392		if (sym->persist == 1)
1393			return (0);
1394		else {
1395			free(sym->nam);
1396			free(sym->val);
1397			TAILQ_REMOVE(&symhead, sym, entry);
1398			free(sym);
1399		}
1400	}
1401	if ((sym = calloc(1, sizeof(*sym))) == NULL)
1402		return (-1);
1403
1404	sym->nam = strdup(nam);
1405	if (sym->nam == NULL) {
1406		free(sym);
1407		return (-1);
1408	}
1409	sym->val = strdup(val);
1410	if (sym->val == NULL) {
1411		free(sym->nam);
1412		free(sym);
1413		return (-1);
1414	}
1415	sym->used = 0;
1416	sym->persist = persist;
1417	TAILQ_INSERT_TAIL(&symhead, sym, entry);
1418	return (0);
1419}
1420
1421int
1422cmdline_symset(char *s)
1423{
1424	char	*sym, *val;
1425	int	ret;
1426	size_t	len;
1427
1428	if ((val = strrchr(s, '=')) == NULL)
1429		return (-1);
1430
1431	len = strlen(s) - strlen(val) + 1;
1432	if ((sym = malloc(len)) == NULL)
1433		err(1, "cmdline_symset: malloc");
1434
1435	strlcpy(sym, s, len);
1436
1437	ret = symset(sym, val + 1, 1);
1438	free(sym);
1439
1440	return (ret);
1441}
1442
1443char *
1444symget(const char *nam)
1445{
1446	struct sym	*sym;
1447
1448	TAILQ_FOREACH(sym, &symhead, entry) {
1449		if (strcmp(nam, sym->nam) == 0) {
1450			sym->used = 1;
1451			return (sym->val);
1452		}
1453	}
1454	return (NULL);
1455}
1456
1457int
1458atoul(char *s, u_long *ulvalp)
1459{
1460	u_long	 ulval;
1461	char	*ep;
1462
1463	errno = 0;
1464	ulval = strtoul(s, &ep, 0);
1465	if (s[0] == '\0' || *ep != '\0')
1466		return (-1);
1467	if (errno == ERANGE && ulval == ULONG_MAX)
1468		return (-1);
1469	*ulvalp = ulval;
1470	return (0);
1471}
1472
1473int
1474atospi(char *s, u_int32_t *spivalp)
1475{
1476	unsigned long	ulval;
1477
1478	if (atoul(s, &ulval) == -1)
1479		return (-1);
1480	if (ulval > UINT_MAX) {
1481		yyerror("%lu not a valid spi", ulval);
1482		return (-1);
1483	}
1484	if (ulval >= SPI_RESERVED_MIN && ulval <= SPI_RESERVED_MAX) {
1485		yyerror("%lu within reserved spi range", ulval);
1486		return (-1);
1487	}
1488	*spivalp = ulval;
1489	return (0);
1490}
1491
1492u_int8_t
1493x2i(unsigned char *s)
1494{
1495	char	ss[3];
1496
1497	ss[0] = s[0];
1498	ss[1] = s[1];
1499	ss[2] = 0;
1500
1501	if (!isxdigit(s[0]) || !isxdigit(s[1])) {
1502		yyerror("keys need to be specified in hex digits");
1503		return (-1);
1504	}
1505	return ((u_int8_t)strtoul(ss, NULL, 16));
1506}
1507
1508struct ipsec_key *
1509parsekey(unsigned char *hexkey, size_t len)
1510{
1511	struct ipsec_key *key;
1512	int		  i;
1513
1514	key = calloc(1, sizeof(struct ipsec_key));
1515	if (key == NULL)
1516		err(1, "parsekey: calloc");
1517
1518	key->len = len / 2;
1519	key->data = calloc(key->len, sizeof(u_int8_t));
1520	if (key->data == NULL)
1521		err(1, "parsekey: calloc");
1522
1523	for (i = 0; i < (int)key->len; i++)
1524		key->data[i] = x2i(hexkey + 2 * i);
1525
1526	return (key);
1527}
1528
1529struct ipsec_key *
1530parsekeyfile(char *filename)
1531{
1532	struct stat	 sb;
1533	int		 fd;
1534	unsigned char	*hex;
1535
1536	if ((fd = open(filename, O_RDONLY)) < 0)
1537		err(1, "open %s", filename);
1538	if (fstat(fd, &sb) < 0)
1539		err(1, "parsekeyfile: stat %s", filename);
1540	if ((sb.st_size > KEYSIZE_LIMIT) || (sb.st_size == 0))
1541		errx(1, "%s: key too %s", filename, sb.st_size ? "large" :
1542		    "small");
1543	if ((hex = calloc(sb.st_size, sizeof(unsigned char))) == NULL)
1544		err(1, "parsekeyfile: calloc");
1545	if (read(fd, hex, sb.st_size) < sb.st_size)
1546		err(1, "parsekeyfile: read");
1547	close(fd);
1548	return (parsekey(hex, sb.st_size));
1549}
1550
1551int
1552get_id_type(char *string)
1553{
1554	struct in6_addr ia;
1555
1556	if (string == NULL)
1557		return (ID_UNKNOWN);
1558
1559	if (inet_pton(AF_INET, string, &ia) == 1)
1560		return (ID_IPV4);
1561	else if (inet_pton(AF_INET6, string, &ia) == 1)
1562		return (ID_IPV6);
1563	else if (strchr(string, '@'))
1564		return (ID_UFQDN);
1565	else
1566		return (ID_FQDN);
1567}
1568
1569struct ipsec_addr_wrap *
1570host(const char *s)
1571{
1572	struct ipsec_addr_wrap	*ipa = NULL;
1573	int			 mask, cont = 1;
1574	char			*p, *q, *ps;
1575
1576	if ((p = strrchr(s, '/')) != NULL) {
1577		errno = 0;
1578		mask = strtol(p + 1, &q, 0);
1579		if (errno == ERANGE || !q || *q || mask > 128 || q == (p + 1))
1580			errx(1, "host: invalid netmask '%s'", p);
1581		if ((ps = malloc(strlen(s) - strlen(p) + 1)) == NULL)
1582			err(1, "host: calloc");
1583		strlcpy(ps, s, strlen(s) - strlen(p) + 1);
1584	} else {
1585		if ((ps = strdup(s)) == NULL)
1586			err(1, "host: strdup");
1587		mask = -1;
1588	}
1589
1590	/* Does interface with this name exist? */
1591	if (cont && (ipa = host_if(ps, mask)) != NULL)
1592		cont = 0;
1593
1594	/* IPv4 address? */
1595	if (cont && (ipa = host_v4(s, mask == -1 ? 32 : mask)) != NULL)
1596		cont = 0;
1597
1598	/* IPv6 address? */
1599	if (cont && (ipa = host_v6(ps, mask == -1 ? 128 : mask)) != NULL)
1600		cont = 0;
1601
1602	/* dns lookup */
1603	if (cont && mask == -1 && (ipa = host_dns(s, mask)) != NULL)
1604		cont = 0;
1605	free(ps);
1606
1607	if (ipa == NULL || cont == 1) {
1608		fprintf(stderr, "no IP address found for %s\n", s);
1609		return (NULL);
1610	}
1611	return (ipa);
1612}
1613
1614struct ipsec_addr_wrap *
1615host_v6(const char *s, int prefixlen)
1616{
1617	struct ipsec_addr_wrap	*ipa = NULL;
1618	struct addrinfo		 hints, *res;
1619	char			 hbuf[NI_MAXHOST];
1620
1621	bzero(&hints, sizeof(struct addrinfo));
1622	hints.ai_family = AF_INET6;
1623	hints.ai_socktype = SOCK_STREAM;
1624	hints.ai_flags = AI_NUMERICHOST;
1625	if (getaddrinfo(s, NULL, &hints, &res))
1626		return (NULL);
1627	if (res->ai_next)
1628		err(1, "host_v6: numeric hostname expanded to multiple item");
1629
1630	ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1631	if (ipa == NULL)
1632		err(1, "host_v6: calloc");
1633	ipa->af = res->ai_family;
1634	memcpy(&ipa->address.v6,
1635	    &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1636	    sizeof(struct in6_addr));
1637	if (prefixlen > 128)
1638		prefixlen = 128;
1639	ipa->next = NULL;
1640	ipa->tail = ipa;
1641
1642	set_ipmask(ipa, prefixlen);
1643	if (getnameinfo(res->ai_addr, res->ai_addrlen,
1644	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)) {
1645		errx(1, "could not get a numeric hostname");
1646	}
1647
1648	if (prefixlen != 128) {
1649		ipa->netaddress = 1;
1650		if (asprintf(&ipa->name, "%s/%d", hbuf, prefixlen) == -1)
1651			err(1, "host_v6: asprintf");
1652	} else {
1653		if ((ipa->name = strdup(hbuf)) == NULL)
1654			err(1, "host_v6: strdup");
1655	}
1656
1657	freeaddrinfo(res);
1658
1659	return (ipa);
1660}
1661
1662struct ipsec_addr_wrap *
1663host_v4(const char *s, int mask)
1664{
1665	struct ipsec_addr_wrap	*ipa = NULL;
1666	struct in_addr		 ina;
1667	int			 bits = 32;
1668
1669	bzero(&ina, sizeof(struct in_addr));
1670	if (strrchr(s, '/') != NULL) {
1671		if ((bits = inet_net_pton(AF_INET, s, &ina, sizeof(ina))) == -1)
1672			return (NULL);
1673	} else {
1674		if (inet_pton(AF_INET, s, &ina) != 1)
1675			return (NULL);
1676	}
1677
1678	ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1679	if (ipa == NULL)
1680		err(1, "host_v4: calloc");
1681
1682	ipa->address.v4 = ina;
1683	ipa->name = strdup(s);
1684	if (ipa->name == NULL)
1685		err(1, "host_v4: strdup");
1686	ipa->af = AF_INET;
1687	ipa->next = NULL;
1688	ipa->tail = ipa;
1689
1690	set_ipmask(ipa, bits);
1691	if (strrchr(s, '/') != NULL)
1692		ipa->netaddress = 1;
1693
1694	return (ipa);
1695}
1696
1697struct ipsec_addr_wrap *
1698host_dns(const char *s, int mask)
1699{
1700	struct ipsec_addr_wrap	*ipa = NULL, *head = NULL;
1701	struct addrinfo		 hints, *res0, *res;
1702	int			 error;
1703	char			 hbuf[NI_MAXHOST];
1704
1705	bzero(&hints, sizeof(struct addrinfo));
1706	hints.ai_family = PF_UNSPEC;
1707	hints.ai_socktype = SOCK_STREAM;
1708	error = getaddrinfo(s, NULL, &hints, &res0);
1709	if (error)
1710		return (NULL);
1711
1712	for (res = res0; res; res = res->ai_next) {
1713		if (res->ai_family != AF_INET && res->ai_family != AF_INET6)
1714			continue;
1715
1716		ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1717		if (ipa == NULL)
1718			err(1, "host_dns: calloc");
1719		switch (res->ai_family) {
1720		case AF_INET:
1721			memcpy(&ipa->address.v4,
1722			    &((struct sockaddr_in *)res->ai_addr)->sin_addr,
1723			    sizeof(struct in_addr));
1724			break;
1725		case AF_INET6:
1726			/* XXX we do not support scoped IPv6 address yet */
1727			if (((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id) {
1728				free(ipa);
1729				continue;
1730			}
1731			memcpy(&ipa->address.v6,
1732			    &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1733			    sizeof(struct in6_addr));
1734			break;
1735		}
1736		error = getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
1737		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST);
1738		if (error)
1739			err(1, "host_dns: getnameinfo");
1740		ipa->name = strdup(hbuf);
1741		if (ipa->name == NULL)
1742			err(1, "host_dns: strdup");
1743		ipa->af = res->ai_family;
1744		ipa->next = NULL;
1745		ipa->tail = ipa;
1746		if (head == NULL)
1747			head = ipa;
1748		else {
1749			head->tail->next = ipa;
1750			head->tail = ipa;
1751		}
1752
1753		/*
1754		 * XXX for now, no netmask support for IPv6.
1755		 * but since there's no way to specify address family, once you
1756		 * have IPv6 address on a host, you cannot use dns/netmask
1757		 * syntax.
1758		 */
1759		if (ipa->af == AF_INET)
1760			set_ipmask(ipa, mask == -1 ? 32 : mask);
1761		else
1762			if (mask != -1)
1763				err(1, "host_dns: cannot apply netmask "
1764				    "on non-IPv4 address");
1765	}
1766	freeaddrinfo(res0);
1767
1768	return (head);
1769}
1770
1771struct ipsec_addr_wrap *
1772host_if(const char *s, int mask)
1773{
1774	struct ipsec_addr_wrap *ipa = NULL;
1775
1776	if (ifa_exists(s))
1777		ipa = ifa_lookup(s);
1778
1779	return (ipa);
1780}
1781
1782struct ipsec_addr_wrap *
1783host_any(void)
1784{
1785	struct ipsec_addr_wrap	*ipa;
1786
1787	ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1788	if (ipa == NULL)
1789		err(1, "host_any: calloc");
1790	ipa->af = AF_UNSPEC;
1791	ipa->netaddress = 1;
1792	ipa->tail = ipa;
1793	return (ipa);
1794}
1795
1796/* interface lookup routintes */
1797
1798struct ipsec_addr_wrap	*iftab;
1799
1800void
1801ifa_load(void)
1802{
1803	struct ifaddrs		*ifap, *ifa;
1804	struct ipsec_addr_wrap	*n = NULL, *h = NULL;
1805
1806	if (getifaddrs(&ifap) < 0)
1807		err(1, "ifa_load: getifaddrs");
1808
1809	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1810		if (!(ifa->ifa_addr->sa_family == AF_INET ||
1811		    ifa->ifa_addr->sa_family == AF_INET6 ||
1812		    ifa->ifa_addr->sa_family == AF_LINK))
1813			continue;
1814		n = calloc(1, sizeof(struct ipsec_addr_wrap));
1815		if (n == NULL)
1816			err(1, "ifa_load: calloc");
1817		n->af = ifa->ifa_addr->sa_family;
1818		if ((n->name = strdup(ifa->ifa_name)) == NULL)
1819			err(1, "ifa_load: strdup");
1820		if (n->af == AF_INET) {
1821			n->af = AF_INET;
1822			memcpy(&n->address.v4, &((struct sockaddr_in *)
1823			    ifa->ifa_addr)->sin_addr,
1824			    sizeof(struct in_addr));
1825			memcpy(&n->mask.v4, &((struct sockaddr_in *)
1826			    ifa->ifa_netmask)->sin_addr,
1827			    sizeof(struct in_addr));
1828		} else if (n->af == AF_INET6) {
1829			n->af = AF_INET6;
1830			memcpy(&n->address.v6, &((struct sockaddr_in6 *)
1831			    ifa->ifa_addr)->sin6_addr,
1832			    sizeof(struct in6_addr));
1833			memcpy(&n->mask.v6, &((struct sockaddr_in6 *)
1834			    ifa->ifa_netmask)->sin6_addr,
1835			    sizeof(struct in6_addr));
1836		}
1837		n->next = NULL;
1838		n->tail = n;
1839		if (h == NULL)
1840			h = n;
1841		else {
1842			h->tail->next = n;
1843			h->tail = n;
1844		}
1845	}
1846
1847	iftab = h;
1848	freeifaddrs(ifap);
1849}
1850
1851int
1852ifa_exists(const char *ifa_name)
1853{
1854	struct ipsec_addr_wrap	*n;
1855	struct ifgroupreq	 ifgr;
1856	int			 s;
1857
1858	if (iftab == NULL)
1859		ifa_load();
1860
1861	/* check whether this is a group */
1862	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1863		err(1, "ifa_exists: socket");
1864	bzero(&ifgr, sizeof(ifgr));
1865	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1866	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == 0) {
1867		close(s);
1868		return (1);
1869	}
1870	close(s);
1871
1872	for (n = iftab; n; n = n->next) {
1873		if (n->af == AF_LINK && !strncmp(n->name, ifa_name,
1874		    IFNAMSIZ))
1875			return (1);
1876	}
1877
1878	return (0);
1879}
1880
1881struct ipsec_addr_wrap *
1882ifa_grouplookup(const char *ifa_name)
1883{
1884	struct ifg_req		*ifg;
1885	struct ifgroupreq	 ifgr;
1886	int			 s;
1887	size_t			 len;
1888	struct ipsec_addr_wrap	*n, *h = NULL, *hn;
1889
1890	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1891		err(1, "socket");
1892	bzero(&ifgr, sizeof(ifgr));
1893	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1894	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
1895		close(s);
1896		return (NULL);
1897	}
1898
1899	len = ifgr.ifgr_len;
1900	if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
1901		err(1, "calloc");
1902	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
1903		err(1, "ioctl");
1904
1905	for (ifg = ifgr.ifgr_groups; ifg && len >= sizeof(struct ifg_req);
1906	    ifg++) {
1907		len -= sizeof(struct ifg_req);
1908		if ((n = ifa_lookup(ifg->ifgrq_member)) == NULL)
1909			continue;
1910		if (h == NULL)
1911			h = n;
1912		else {
1913			for (hn = h; hn->next != NULL; hn = hn->next)
1914				;	/* nothing */
1915			hn->next = n;
1916			n->tail = hn;
1917		}
1918	}
1919	free(ifgr.ifgr_groups);
1920	close(s);
1921
1922	return (h);
1923}
1924
1925struct ipsec_addr_wrap *
1926ifa_lookup(const char *ifa_name)
1927{
1928	struct ipsec_addr_wrap	*p = NULL, *h = NULL, *n = NULL;
1929
1930	if (iftab == NULL)
1931		ifa_load();
1932
1933	if ((n = ifa_grouplookup(ifa_name)) != NULL)
1934		return (n);
1935
1936	for (p = iftab; p; p = p->next) {
1937		if (p->af != AF_INET && p->af != AF_INET6)
1938			continue;
1939		if (strncmp(p->name, ifa_name, IFNAMSIZ))
1940			continue;
1941		n = calloc(1, sizeof(struct ipsec_addr_wrap));
1942		if (n == NULL)
1943			err(1, "ifa_lookup: calloc");
1944		memcpy(n, p, sizeof(struct ipsec_addr_wrap));
1945		if ((n->name = strdup(p->name)) == NULL)
1946			err(1, "ifa_lookup: strdup");
1947		switch (n->af) {
1948		case AF_INET:
1949			set_ipmask(n, 32);
1950			break;
1951		case AF_INET6:
1952			/* route/show.c and bgpd/util.c give KAME credit */
1953			if (IN6_IS_ADDR_LINKLOCAL(&n->address.v6)) {
1954				u_int16_t tmp16;
1955				/* for now we can not handle link local,
1956				 * therefore bail for now
1957				 */
1958				free(n);
1959				continue;
1960
1961				memcpy(&tmp16, &n->address.v6.s6_addr[2],
1962				    sizeof(tmp16));
1963				/* use this when we support link-local
1964				 * n->??.scopeid = ntohs(tmp16);
1965				 */
1966				n->address.v6.s6_addr[2] = 0;
1967				n->address.v6.s6_addr[3] = 0;
1968			}
1969			set_ipmask(n, 128);
1970			break;
1971		}
1972
1973		n->next = NULL;
1974		n->tail = n;
1975		if (h == NULL)
1976			h = n;
1977		else {
1978			h->tail->next = n;
1979			h->tail = n;
1980		}
1981	}
1982
1983	return (h);
1984}
1985
1986void
1987set_ipmask(struct ipsec_addr_wrap *address, u_int8_t b)
1988{
1989	struct ipsec_addr	*ipa;
1990	int			 i, j = 0;
1991
1992	ipa = &address->mask;
1993	bzero(ipa, sizeof(struct ipsec_addr));
1994
1995	while (b >= 32) {
1996		ipa->addr32[j++] = 0xffffffff;
1997		b -= 32;
1998	}
1999	for (i = 31; i > 31 - b; --i)
2000		ipa->addr32[j] |= (1 << i);
2001	if (b)
2002		ipa->addr32[j] = htonl(ipa->addr32[j]);
2003}
2004
2005const struct ipsec_xf *
2006parse_xf(const char *name, const struct ipsec_xf xfs[])
2007{
2008	int		i;
2009
2010	for (i = 0; xfs[i].name != NULL; i++) {
2011		if (strncmp(name, xfs[i].name, strlen(name)))
2012			continue;
2013		return &xfs[i];
2014	}
2015	return (NULL);
2016}
2017
2018struct ipsec_lifetime *
2019parse_life(const char *value)
2020{
2021	struct ipsec_lifetime	*life;
2022	int			ret;
2023	int			seconds = 0;
2024	char			unit = 0;
2025
2026	ret = sscanf(value, "%d%c", &seconds, &unit);
2027	if (ret == 2) {
2028		switch (tolower((unsigned char)unit)) {
2029		case 'm':
2030			seconds *= 60;
2031			break;
2032		case 'h':
2033			seconds *= 60 * 60;
2034			break;
2035		default:
2036			err(1, "invalid time unit");
2037		}
2038	} else if (ret != 1)
2039		err(1, "invalid time specification: %s", value);
2040
2041	life = calloc(1, sizeof(struct ipsec_lifetime));
2042	if (life == NULL)
2043		err(1, "calloc");
2044
2045	life->lt_seconds = seconds;
2046	life->lt_bytes = -1;
2047
2048	return (life);
2049}
2050
2051struct ipsec_transforms *
2052copytransforms(const struct ipsec_transforms *xfs)
2053{
2054	struct ipsec_transforms *newxfs;
2055
2056	if (xfs == NULL)
2057		return (NULL);
2058
2059	newxfs = calloc(1, sizeof(struct ipsec_transforms));
2060	if (newxfs == NULL)
2061		err(1, "copytransforms: calloc");
2062
2063	memcpy(newxfs, xfs, sizeof(struct ipsec_transforms));
2064	return (newxfs);
2065}
2066
2067struct ipsec_lifetime *
2068copylife(const struct ipsec_lifetime *life)
2069{
2070	struct ipsec_lifetime *newlife;
2071
2072	if (life == NULL)
2073		return (NULL);
2074
2075	newlife = calloc(1, sizeof(struct ipsec_lifetime));
2076	if (newlife == NULL)
2077		err(1, "copylife: calloc");
2078
2079	memcpy(newlife, life, sizeof(struct ipsec_lifetime));
2080	return (newlife);
2081}
2082
2083struct ipsec_auth *
2084copyipsecauth(const struct ipsec_auth *auth)
2085{
2086	struct ipsec_auth	*newauth;
2087
2088	if (auth == NULL)
2089		return (NULL);
2090
2091	if ((newauth = calloc(1, sizeof(struct ipsec_auth))) == NULL)
2092		err(1, "calloc");
2093	if (auth->srcid &&
2094	    asprintf(&newauth->srcid, "%s", auth->srcid) == -1)
2095		err(1, "asprintf");
2096	if (auth->dstid &&
2097	    asprintf(&newauth->dstid, "%s", auth->dstid) == -1)
2098		err(1, "asprintf");
2099
2100	newauth->srcid_type = auth->srcid_type;
2101	newauth->dstid_type = auth->dstid_type;
2102	newauth->type = auth->type;
2103
2104	return (newauth);
2105}
2106
2107struct ike_auth *
2108copyikeauth(const struct ike_auth *auth)
2109{
2110	struct ike_auth	*newauth;
2111
2112	if (auth == NULL)
2113		return (NULL);
2114
2115	if ((newauth = calloc(1, sizeof(struct ike_auth))) == NULL)
2116		err(1, "calloc");
2117	if (auth->string &&
2118	    asprintf(&newauth->string, "%s", auth->string) == -1)
2119		err(1, "asprintf");
2120
2121	newauth->type = auth->type;
2122
2123	return (newauth);
2124}
2125
2126struct ipsec_key *
2127copykey(struct ipsec_key *key)
2128{
2129	struct ipsec_key	*newkey;
2130
2131	if (key == NULL)
2132		return (NULL);
2133
2134	if ((newkey = calloc(1, sizeof(struct ipsec_key))) == NULL)
2135		err(1, "calloc");
2136	if ((newkey->data = calloc(key->len, sizeof(u_int8_t))) == NULL)
2137		err(1, "calloc");
2138	memcpy(newkey->data, key->data, key->len);
2139	newkey->len = key->len;
2140
2141	return (newkey);
2142}
2143
2144struct ipsec_addr_wrap *
2145copyhost(const struct ipsec_addr_wrap *src)
2146{
2147	struct ipsec_addr_wrap *dst;
2148
2149	if (src == NULL)
2150		return (NULL);
2151
2152	dst = calloc(1, sizeof(struct ipsec_addr_wrap));
2153	if (dst == NULL)
2154		err(1, "copyhost: calloc");
2155
2156	memcpy(dst, src, sizeof(struct ipsec_addr_wrap));
2157
2158	if (src->name != NULL && (dst->name = strdup(src->name)) == NULL)
2159		err(1, "copyhost: strdup");
2160
2161	return dst;
2162}
2163
2164char *
2165copytag(const char *src)
2166{
2167	char *tag;
2168
2169	if (src == NULL)
2170		return (NULL);
2171	if ((tag = strdup(src)) == NULL)
2172		err(1, "copytag: strdup");
2173
2174	return (tag);
2175}
2176
2177struct ipsec_rule *
2178copyrule(struct ipsec_rule *rule)
2179{
2180	struct ipsec_rule	*r;
2181
2182	if ((r = calloc(1, sizeof(struct ipsec_rule))) == NULL)
2183		err(1, "calloc");
2184
2185	r->src = copyhost(rule->src);
2186	r->dst = copyhost(rule->dst);
2187	r->local = copyhost(rule->local);
2188	r->peer = copyhost(rule->peer);
2189	r->auth = copyipsecauth(rule->auth);
2190	r->ikeauth = copyikeauth(rule->ikeauth);
2191	r->xfs = copytransforms(rule->xfs);
2192	r->p1xfs = copytransforms(rule->p1xfs);
2193	r->p2xfs = copytransforms(rule->p2xfs);
2194	r->p1life = copylife(rule->p1life);
2195	r->p2life = copylife(rule->p2life);
2196	r->authkey = copykey(rule->authkey);
2197	r->enckey = copykey(rule->enckey);
2198	r->tag = copytag(rule->tag);
2199
2200	r->p1ie = rule->p1ie;
2201	r->p2ie = rule->p2ie;
2202	r->type = rule->type;
2203	r->satype = rule->satype;
2204	r->proto = rule->proto;
2205	r->tmode = rule->tmode;
2206	r->direction = rule->direction;
2207	r->flowtype = rule->flowtype;
2208	r->sport = rule->sport;
2209	r->dport = rule->dport;
2210	r->ikemode = rule->ikemode;
2211	r->spi = rule->spi;
2212	r->nr = rule->nr;
2213
2214	return (r);
2215}
2216
2217int
2218validate_af(struct ipsec_addr_wrap *src, struct ipsec_addr_wrap *dst)
2219{
2220	struct ipsec_addr_wrap *ta;
2221	u_int8_t src_v4 = 0;
2222	u_int8_t dst_v4 = 0;
2223	u_int8_t src_v6 = 0;
2224	u_int8_t dst_v6 = 0;
2225
2226	for (ta = src; ta; ta = ta->next) {
2227		if (ta->af == AF_INET)
2228			src_v4 = 1;
2229		if (ta->af == AF_INET6)
2230			src_v6 = 1;
2231		if (ta->af == AF_UNSPEC)
2232			return 0;
2233		if (src_v4 && src_v6)
2234			break;
2235	}
2236	for (ta = dst; ta; ta = ta->next) {
2237		if (ta->af == AF_INET)
2238			dst_v4 = 1;
2239		if (ta->af == AF_INET6)
2240			dst_v6 = 1;
2241		if (ta->af == AF_UNSPEC)
2242			return 0;
2243		if (dst_v4 && dst_v6)
2244			break;
2245	}
2246	if (src_v4 != dst_v4 && src_v6 != dst_v6)
2247		return (1);
2248
2249	return (0);
2250}
2251
2252
2253int
2254validate_sa(u_int32_t spi, u_int8_t satype, struct ipsec_transforms *xfs,
2255    struct ipsec_key *authkey, struct ipsec_key *enckey, u_int8_t tmode)
2256{
2257	/* Sanity checks */
2258	if (spi == 0) {
2259		yyerror("no SPI specified");
2260		return (0);
2261	}
2262	if (satype == IPSEC_AH) {
2263		if (!xfs) {
2264			yyerror("no transforms specified");
2265			return (0);
2266		}
2267		if (!xfs->authxf)
2268			xfs->authxf = &authxfs[AUTHXF_HMAC_SHA2_256];
2269		if (xfs->encxf) {
2270			yyerror("ah does not provide encryption");
2271			return (0);
2272		}
2273		if (xfs->compxf) {
2274			yyerror("ah does not provide compression");
2275			return (0);
2276		}
2277	}
2278	if (satype == IPSEC_ESP) {
2279		if (!xfs) {
2280			yyerror("no transforms specified");
2281			return (0);
2282		}
2283		if (xfs->compxf) {
2284			yyerror("esp does not provide compression");
2285			return (0);
2286		}
2287		if (!xfs->encxf)
2288			xfs->encxf = &encxfs[ENCXF_AES];
2289		if (xfs->encxf->nostatic) {
2290			yyerror("%s is disallowed with static keys",
2291			    xfs->encxf->name);
2292			return 0;
2293		}
2294		if (xfs->encxf->noauth && xfs->authxf) {
2295			yyerror("authentication is implicit for %s",
2296			    xfs->encxf->name);
2297			return (0);
2298		} else if (!xfs->encxf->noauth && !xfs->authxf)
2299			xfs->authxf = &authxfs[AUTHXF_HMAC_SHA2_256];
2300	}
2301	if (satype == IPSEC_IPCOMP) {
2302		if (!xfs) {
2303			yyerror("no transform specified");
2304			return (0);
2305		}
2306		if (xfs->authxf || xfs->encxf) {
2307			yyerror("no encryption or authentication with ipcomp");
2308			return (0);
2309		}
2310		if (!xfs->compxf)
2311			xfs->compxf = &compxfs[COMPXF_DEFLATE];
2312	}
2313	if (satype == IPSEC_IPIP) {
2314		if (!xfs) {
2315			yyerror("no transform specified");
2316			return (0);
2317		}
2318		if (xfs->authxf || xfs->encxf || xfs->compxf) {
2319			yyerror("no encryption, authentication or compression"
2320			    " with ipip");
2321			return (0);
2322		}
2323	}
2324	if (satype == IPSEC_TCPMD5 && authkey == NULL && tmode !=
2325	    IPSEC_TRANSPORT) {
2326		yyerror("authentication key needed for tcpmd5");
2327		return (0);
2328	}
2329	if (xfs && xfs->authxf) {
2330		if (!authkey && xfs->authxf != &authxfs[AUTHXF_NONE]) {
2331			yyerror("no authentication key specified");
2332			return (0);
2333		}
2334		if (authkey && authkey->len != xfs->authxf->keymin) {
2335			yyerror("wrong authentication key length, needs to be "
2336			    "%zu bits", xfs->authxf->keymin * 8);
2337			return (0);
2338		}
2339	}
2340	if (xfs && xfs->encxf) {
2341		if (!enckey && xfs->encxf != &encxfs[ENCXF_NULL]) {
2342			yyerror("no encryption key specified");
2343			return (0);
2344		}
2345		if (enckey) {
2346			if (enckey->len < xfs->encxf->keymin) {
2347				yyerror("encryption key too short (%zu bits), "
2348				    "minimum %zu bits", enckey->len * 8,
2349				    xfs->encxf->keymin * 8);
2350				return (0);
2351			}
2352			if (xfs->encxf->keymax < enckey->len) {
2353				yyerror("encryption key too long (%zu bits), "
2354				    "maximum %zu bits", enckey->len * 8,
2355				    xfs->encxf->keymax * 8);
2356				return (0);
2357			}
2358		}
2359	}
2360
2361	return 1;
2362}
2363
2364int
2365add_sabundle(struct ipsec_rule *r, char *bundle)
2366{
2367	struct ipsec_rule	*rp, *last, *sabundle;
2368	int			 found = 0;
2369
2370	TAILQ_FOREACH(rp, &ipsec->bundle_queue, bundle_entry) {
2371		if ((strcmp(rp->src->name, r->src->name) == 0) &&
2372		    (strcmp(rp->dst->name, r->dst->name) == 0) &&
2373		    (strcmp(rp->bundle, bundle) == 0)) {
2374			found = 1;
2375			break;
2376		}
2377	}
2378	if (found) {
2379		last = TAILQ_LAST(&rp->dst_bundle_queue, dst_bundle_queue);
2380		TAILQ_INSERT_TAIL(&rp->dst_bundle_queue, r, dst_bundle_entry);
2381
2382		sabundle = create_sabundle(last->dst, last->satype, last->spi,
2383		    r->dst, r->satype, r->spi);
2384		if (sabundle == NULL)
2385			return (1);
2386		sabundle->nr = ipsec->rule_nr++;
2387		if (ipsecctl_add_rule(ipsec, sabundle))
2388			return (1);
2389	} else {
2390		TAILQ_INSERT_TAIL(&ipsec->bundle_queue, r, bundle_entry);
2391		TAILQ_INIT(&r->dst_bundle_queue);
2392		TAILQ_INSERT_TAIL(&r->dst_bundle_queue, r, dst_bundle_entry);
2393		r->bundle = bundle;
2394	}
2395
2396	return (0);
2397}
2398
2399struct ipsec_rule *
2400create_sa(u_int8_t satype, u_int8_t tmode, struct ipsec_hosts *hosts,
2401    u_int32_t spi, struct ipsec_transforms *xfs, struct ipsec_key *authkey,
2402    struct ipsec_key *enckey)
2403{
2404	struct ipsec_rule *r;
2405
2406	if (validate_sa(spi, satype, xfs, authkey, enckey, tmode) == 0)
2407		return (NULL);
2408
2409	r = calloc(1, sizeof(struct ipsec_rule));
2410	if (r == NULL)
2411		err(1, "create_sa: calloc");
2412
2413	r->type |= RULE_SA;
2414	r->satype = satype;
2415	r->tmode = tmode;
2416	r->src = hosts->src;
2417	r->dst = hosts->dst;
2418	r->spi = spi;
2419	r->xfs = xfs;
2420	r->authkey = authkey;
2421	r->enckey = enckey;
2422
2423	return r;
2424}
2425
2426struct ipsec_rule *
2427reverse_sa(struct ipsec_rule *rule, u_int32_t spi, struct ipsec_key *authkey,
2428    struct ipsec_key *enckey)
2429{
2430	struct ipsec_rule *reverse;
2431
2432	if (validate_sa(spi, rule->satype, rule->xfs, authkey, enckey,
2433	    rule->tmode) == 0)
2434		return (NULL);
2435
2436	reverse = calloc(1, sizeof(struct ipsec_rule));
2437	if (reverse == NULL)
2438		err(1, "reverse_sa: calloc");
2439
2440	reverse->type |= RULE_SA;
2441	reverse->satype = rule->satype;
2442	reverse->tmode = rule->tmode;
2443	reverse->src = copyhost(rule->dst);
2444	reverse->dst = copyhost(rule->src);
2445	reverse->spi = spi;
2446	reverse->xfs = copytransforms(rule->xfs);
2447	reverse->authkey = authkey;
2448	reverse->enckey = enckey;
2449
2450	return (reverse);
2451}
2452
2453struct ipsec_rule *
2454create_sabundle(struct ipsec_addr_wrap *dst, u_int8_t proto, u_int32_t spi,
2455    struct ipsec_addr_wrap *dst2, u_int8_t proto2, u_int32_t spi2)
2456{
2457	struct ipsec_rule *r;
2458
2459	r = calloc(1, sizeof(struct ipsec_rule));
2460	if (r == NULL)
2461		err(1, "create_sabundle: calloc");
2462
2463	r->type |= RULE_BUNDLE;
2464
2465	r->dst = copyhost(dst);
2466	r->dst2 = copyhost(dst2);
2467	r->proto = proto;
2468	r->proto2 = proto2;
2469	r->spi = spi;
2470	r->spi2 = spi2;
2471	r->satype = proto;
2472
2473	return (r);
2474}
2475
2476struct ipsec_rule *
2477create_flow(u_int8_t dir, u_int8_t proto, struct ipsec_hosts *hosts,
2478    u_int8_t satype, char *srcid, char *dstid, u_int8_t type)
2479{
2480	struct ipsec_rule *r;
2481
2482	r = calloc(1, sizeof(struct ipsec_rule));
2483	if (r == NULL)
2484		err(1, "create_flow: calloc");
2485
2486	r->type |= RULE_FLOW;
2487
2488	if (dir == IPSEC_INOUT)
2489		r->direction = IPSEC_OUT;
2490	else
2491		r->direction = dir;
2492
2493	r->satype = satype;
2494	r->proto = proto;
2495	r->src = hosts->src;
2496	r->sport = hosts->sport;
2497	r->dst = hosts->dst;
2498	r->dport = hosts->dport;
2499	if ((hosts->sport != 0 || hosts->dport != 0) &&
2500	    (proto != IPPROTO_TCP && proto != IPPROTO_UDP)) {
2501		yyerror("no protocol supplied with source/destination ports");
2502		goto errout;
2503	}
2504
2505	switch (satype) {
2506	case IPSEC_IPCOMP:
2507	case IPSEC_IPIP:
2508		if (type == TYPE_UNKNOWN)
2509			type = TYPE_USE;
2510		break;
2511	default:
2512		if (type == TYPE_UNKNOWN)
2513			type = TYPE_REQUIRE;
2514		break;
2515	}
2516
2517	r->flowtype = type;
2518	if (type == TYPE_DENY || type == TYPE_BYPASS)
2519		return (r);
2520
2521	r->auth = calloc(1, sizeof(struct ipsec_auth));
2522	if (r->auth == NULL)
2523		err(1, "create_flow: calloc");
2524	r->auth->srcid = srcid;
2525	r->auth->dstid = dstid;
2526	r->auth->srcid_type = get_id_type(srcid);
2527	r->auth->dstid_type = get_id_type(dstid);
2528	return r;
2529
2530errout:
2531	free(r);
2532	if (srcid)
2533		free(srcid);
2534	if (dstid)
2535		free(dstid);
2536	free(hosts->src);
2537	hosts->src = NULL;
2538	free(hosts->dst);
2539	hosts->dst = NULL;
2540
2541	return NULL;
2542}
2543
2544void
2545expand_any(struct ipsec_addr_wrap *ipa_in)
2546{
2547	struct ipsec_addr_wrap *oldnext, *ipa;
2548
2549	for (ipa = ipa_in; ipa; ipa = ipa->next) {
2550		if (ipa->af != AF_UNSPEC)
2551			continue;
2552		oldnext = ipa->next;
2553
2554		ipa->af = AF_INET;
2555		ipa->netaddress = 1;
2556		if ((ipa->name = strdup("0.0.0.0/0")) == NULL)
2557			err(1, "expand_any: strdup");
2558
2559		ipa->next = calloc(1, sizeof(struct ipsec_addr_wrap));
2560		if (ipa->next == NULL)
2561			err(1, "expand_any: calloc");
2562		ipa->next->af = AF_INET6;
2563		ipa->next->netaddress = 1;
2564		if ((ipa->next->name = strdup("::/0")) == NULL)
2565			err(1, "expand_any: strdup");
2566
2567		ipa->next->next = oldnext;
2568	}
2569}
2570
2571int
2572set_rule_peers(struct ipsec_rule *r, struct ipsec_hosts *peers)
2573{
2574	if (r->type == RULE_FLOW &&
2575	    (r->flowtype == TYPE_DENY || r->flowtype == TYPE_BYPASS))
2576		return (0);
2577
2578	r->local = copyhost(peers->src);
2579	r->peer = copyhost(peers->dst);
2580	if (r->peer == NULL) {
2581		/* Set peer to remote host.  Must be a host address. */
2582		if (r->direction == IPSEC_IN) {
2583			if (!r->src->netaddress)
2584				r->peer = copyhost(r->src);
2585		} else {
2586			if (!r->dst->netaddress)
2587				r->peer = copyhost(r->dst);
2588		}
2589	}
2590	if (r->type == RULE_FLOW && r->peer == NULL) {
2591		yyerror("no peer specified for destination %s",
2592		    r->dst->name);
2593		return (1);
2594	}
2595	if (r->peer != NULL && r->peer->af == AF_UNSPEC) {
2596		/* If peer has been specified as any, use the default peer. */
2597		free(r->peer);
2598		r->peer = NULL;
2599	}
2600	if (r->type == RULE_IKE && r->peer == NULL) {
2601		/*
2602                 * Check if the default peer is consistent for all
2603                 * rules.  Only warn to avoid breaking existing configs.
2604		 */
2605		static struct ipsec_rule *pdr = NULL;
2606
2607		if (pdr == NULL) {
2608			/* Remember first default peer rule for comparison. */
2609			pdr = r;
2610		} else {
2611			/* The new default peer must create the same config. */
2612			if ((pdr->local == NULL && r->local != NULL) ||
2613			    (pdr->local != NULL && r->local == NULL) ||
2614			    (pdr->local != NULL && r->local != NULL &&
2615			    strcmp(pdr->local->name, r->local->name)))
2616				yywarn("default peer local mismatch");
2617			if (pdr->ikeauth->type != r->ikeauth->type)
2618				yywarn("default peer phase 1 auth mismatch");
2619			if (pdr->ikeauth->type == IKE_AUTH_PSK &&
2620			    r->ikeauth->type == IKE_AUTH_PSK &&
2621			    strcmp(pdr->ikeauth->string, r->ikeauth->string))
2622				yywarn("default peer psk mismatch");
2623			if (pdr->p1ie != r->p1ie)
2624				yywarn("default peer phase 1 mode mismatch");
2625			/*
2626			 * Transforms have ADD insted of SET so they may be
2627			 * different and are not checked here.
2628			 */
2629			if ((pdr->auth->srcid == NULL &&
2630			    r->auth->srcid != NULL) ||
2631			    (pdr->auth->srcid != NULL &&
2632			    r->auth->srcid == NULL) ||
2633			    (pdr->auth->srcid != NULL &&
2634			    r->auth->srcid != NULL &&
2635			    strcmp(pdr->auth->srcid, r->auth->srcid)))
2636				yywarn("default peer srcid mismatch");
2637			if ((pdr->auth->dstid == NULL &&
2638			    r->auth->dstid != NULL) ||
2639			    (pdr->auth->dstid != NULL &&
2640			    r->auth->dstid == NULL) ||
2641			    (pdr->auth->dstid != NULL &&
2642			    r->auth->dstid != NULL &&
2643			    strcmp(pdr->auth->dstid, r->auth->dstid)))
2644				yywarn("default peer dstid mismatch");
2645		}
2646	}
2647	return (0);
2648}
2649
2650int
2651expand_rule(struct ipsec_rule *rule, struct ipsec_hosts *peers,
2652    u_int8_t direction, u_int32_t spi, struct ipsec_key *authkey,
2653    struct ipsec_key *enckey, char *bundle)
2654{
2655	struct ipsec_rule	*r, *revr;
2656	struct ipsec_addr_wrap	*src, *dst;
2657	int added = 0, ret = 1;
2658
2659	if (validate_af(rule->src, rule->dst)) {
2660		yyerror("source/destination address families do not match");
2661		goto errout;
2662	}
2663	expand_any(rule->src);
2664	expand_any(rule->dst);
2665	for (src = rule->src; src; src = src->next) {
2666		for (dst = rule->dst; dst; dst = dst->next) {
2667			if (src->af != dst->af)
2668				continue;
2669			r = copyrule(rule);
2670
2671			r->src = copyhost(src);
2672			r->dst = copyhost(dst);
2673
2674			if (peers && set_rule_peers(r, peers)) {
2675				ipsecctl_free_rule(r);
2676				goto errout;
2677			}
2678
2679			r->nr = ipsec->rule_nr++;
2680			if (ipsecctl_add_rule(ipsec, r))
2681				goto out;
2682			if (bundle && add_sabundle(r, bundle))
2683				goto out;
2684
2685			if (direction == IPSEC_INOUT) {
2686				/* Create and add reverse flow rule. */
2687				revr = reverse_rule(r);
2688				if (revr == NULL)
2689					goto out;
2690
2691				revr->nr = ipsec->rule_nr++;
2692				if (ipsecctl_add_rule(ipsec, revr))
2693					goto out;
2694				if (bundle && add_sabundle(revr, bundle))
2695					goto out;
2696			} else if (spi != 0 || authkey || enckey) {
2697				/* Create and add reverse sa rule. */
2698				revr = reverse_sa(r, spi, authkey, enckey);
2699				if (revr == NULL)
2700					goto out;
2701
2702				revr->nr = ipsec->rule_nr++;
2703				if (ipsecctl_add_rule(ipsec, revr))
2704					goto out;
2705				if (bundle && add_sabundle(revr, bundle))
2706					goto out;
2707			}
2708			added++;
2709		}
2710	}
2711	if (!added)
2712		yyerror("rule expands to no valid combination");
2713 errout:
2714	ret = 0;
2715	ipsecctl_free_rule(rule);
2716 out:
2717	if (peers) {
2718		if (peers->src)
2719			free(peers->src);
2720		if (peers->dst)
2721			free(peers->dst);
2722	}
2723	return (ret);
2724}
2725
2726struct ipsec_rule *
2727reverse_rule(struct ipsec_rule *rule)
2728{
2729	struct ipsec_rule *reverse;
2730
2731	reverse = calloc(1, sizeof(struct ipsec_rule));
2732	if (reverse == NULL)
2733		err(1, "reverse_rule: calloc");
2734
2735	reverse->type |= RULE_FLOW;
2736
2737	/* Reverse direction */
2738	if (rule->direction == (u_int8_t)IPSEC_OUT)
2739		reverse->direction = (u_int8_t)IPSEC_IN;
2740	else
2741		reverse->direction = (u_int8_t)IPSEC_OUT;
2742
2743	reverse->flowtype = rule->flowtype;
2744	reverse->src = copyhost(rule->dst);
2745	reverse->dst = copyhost(rule->src);
2746	reverse->sport = rule->dport;
2747	reverse->dport = rule->sport;
2748	if (rule->local)
2749		reverse->local = copyhost(rule->local);
2750	if (rule->peer)
2751		reverse->peer = copyhost(rule->peer);
2752	reverse->satype = rule->satype;
2753	reverse->proto = rule->proto;
2754
2755	if (rule->auth) {
2756		reverse->auth = calloc(1, sizeof(struct ipsec_auth));
2757		if (reverse->auth == NULL)
2758			err(1, "reverse_rule: calloc");
2759		if (rule->auth->dstid && (reverse->auth->dstid =
2760		    strdup(rule->auth->dstid)) == NULL)
2761			err(1, "reverse_rule: strdup");
2762		if (rule->auth->srcid && (reverse->auth->srcid =
2763		    strdup(rule->auth->srcid)) == NULL)
2764			err(1, "reverse_rule: strdup");
2765		reverse->auth->srcid_type = rule->auth->srcid_type;
2766		reverse->auth->dstid_type = rule->auth->dstid_type;
2767		reverse->auth->type = rule->auth->type;
2768	}
2769
2770	return reverse;
2771}
2772
2773struct ipsec_rule *
2774create_ike(u_int8_t proto, struct ipsec_hosts *hosts,
2775    struct ike_mode *phase1mode, struct ike_mode *phase2mode, u_int8_t satype,
2776    u_int8_t tmode, u_int8_t mode, char *srcid, char *dstid,
2777    struct ike_auth *authtype, char *tag)
2778{
2779	struct ipsec_rule *r;
2780
2781	r = calloc(1, sizeof(struct ipsec_rule));
2782	if (r == NULL)
2783		err(1, "create_ike: calloc");
2784
2785	r->type = RULE_IKE;
2786
2787	r->proto = proto;
2788	r->src = hosts->src;
2789	r->sport = hosts->sport;
2790	r->dst = hosts->dst;
2791	r->dport = hosts->dport;
2792	if ((hosts->sport != 0 || hosts->dport != 0) &&
2793	    (proto != IPPROTO_TCP && proto != IPPROTO_UDP)) {
2794		yyerror("no protocol supplied with source/destination ports");
2795		goto errout;
2796	}
2797
2798	r->satype = satype;
2799	r->tmode = tmode;
2800	r->ikemode = mode;
2801	if (phase1mode) {
2802		r->p1xfs = phase1mode->xfs;
2803		r->p1life = phase1mode->life;
2804		r->p1ie = phase1mode->ike_exch;
2805	} else {
2806		r->p1ie = IKE_MM;
2807	}
2808	if (phase2mode) {
2809		if (phase2mode->xfs && phase2mode->xfs->encxf &&
2810		    phase2mode->xfs->encxf->noauth &&
2811		    phase2mode->xfs->authxf) {
2812			yyerror("authentication is implicit for %s",
2813			    phase2mode->xfs->encxf->name);
2814			goto errout;
2815		}
2816		r->p2xfs = phase2mode->xfs;
2817		r->p2life = phase2mode->life;
2818		r->p2ie = phase2mode->ike_exch;
2819	} else {
2820		r->p2ie = IKE_QM;
2821	}
2822
2823	r->auth = calloc(1, sizeof(struct ipsec_auth));
2824	if (r->auth == NULL)
2825		err(1, "create_ike: calloc");
2826	r->auth->srcid = srcid;
2827	r->auth->dstid = dstid;
2828	r->auth->srcid_type = get_id_type(srcid);
2829	r->auth->dstid_type = get_id_type(dstid);
2830	r->ikeauth = calloc(1, sizeof(struct ike_auth));
2831	if (r->ikeauth == NULL)
2832		err(1, "create_ike: calloc");
2833	r->ikeauth->type = authtype->type;
2834	r->ikeauth->string = authtype->string;
2835	r->tag = tag;
2836
2837	return (r);
2838
2839errout:
2840	free(r);
2841	free(hosts->src);
2842	hosts->src = NULL;
2843	free(hosts->dst);
2844	hosts->dst = NULL;
2845	if (phase1mode) {
2846		free(phase1mode->xfs);
2847		phase1mode->xfs = NULL;
2848		free(phase1mode->life);
2849		phase1mode->life = NULL;
2850	}
2851	if (phase2mode) {
2852		free(phase2mode->xfs);
2853		phase2mode->xfs = NULL;
2854		free(phase2mode->life);
2855		phase2mode->life = NULL;
2856	}
2857	if (srcid)
2858		free(srcid);
2859	if (dstid)
2860		free(dstid);
2861	return NULL;
2862}
2863