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