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