xref: /openbsd/sbin/iked/parse.y (revision fc61954a)
1 /*	$OpenBSD: parse.y,v 1.58 2016/09/03 09:20:07 vgross Exp $	*/
2 
3 /*
4  * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org>
5  * Copyright (c) 2004, 2005 Hans-Joerg Hoexer <hshoexer@openbsd.org>
6  * Copyright (c) 2002, 2003, 2004 Henning Brauer <henning@openbsd.org>
7  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
8  * Copyright (c) 2001 Daniel Hartmeier.  All rights reserved.
9  * Copyright (c) 2001 Theo de Raadt.  All rights reserved.
10  *
11  * Permission to use, copy, modify, and distribute this software for any
12  * purpose with or without fee is hereby granted, provided that the above
13  * copyright notice and this permission notice appear in all copies.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
16  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
17  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
18  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
21  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  */
23 
24 %{
25 #include <sys/types.h>
26 #include <sys/ioctl.h>
27 #include <sys/queue.h>
28 #include <sys/socket.h>
29 #include <sys/stat.h>
30 #include <net/if.h>
31 #include <netinet/in.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 <stdlib.h>
44 #include <string.h>
45 #include <syslog.h>
46 #include <unistd.h>
47 #include <netdb.h>
48 #include <event.h>
49 
50 #include "iked.h"
51 #include "ikev2.h"
52 #include "eap.h"
53 
54 TAILQ_HEAD(files, file)		 files = TAILQ_HEAD_INITIALIZER(files);
55 static struct file {
56 	TAILQ_ENTRY(file)	 entry;
57 	FILE			*stream;
58 	char			*name;
59 	int			 lineno;
60 	int			 errors;
61 } *file;
62 struct file	*pushfile(const char *, int);
63 int		 popfile(void);
64 int		 check_file_secrecy(int, const char *);
65 int		 check_pubkey(char *, int );
66 int		 yyparse(void);
67 int		 yylex(void);
68 int		 yyerror(const char *, ...)
69     __attribute__((__format__ (printf, 1, 2)))
70     __attribute__((__nonnull__ (1)));
71 int		 kw_cmp(const void *, const void *);
72 int		 lookup(char *);
73 int		 lgetc(int);
74 int		 lungetc(int);
75 int		 findeol(void);
76 
77 TAILQ_HEAD(symhead, sym)	 symhead = TAILQ_HEAD_INITIALIZER(symhead);
78 struct sym {
79 	TAILQ_ENTRY(sym)	 entry;
80 	int			 used;
81 	int			 persist;
82 	char			*nam;
83 	char			*val;
84 };
85 int		 symset(const char *, const char *, int);
86 char		*symget(const char *);
87 
88 #define KEYSIZE_LIMIT	1024
89 
90 static struct iked	*env = NULL;
91 static int		 debug = 0;
92 static int		 rules = 0;
93 static int		 passive = 0;
94 static int		 decouple = 0;
95 static char		*ocsp_url = NULL;
96 
97 struct ipsec_xf {
98 	const char	*name;
99 	unsigned int	 id;
100 	unsigned int	 length;
101 	unsigned int	 keylength;
102 	unsigned int	 nonce;
103 	unsigned int	 noauth;
104 };
105 
106 struct ipsec_transforms {
107 	const struct ipsec_xf *authxf;
108 	const struct ipsec_xf *prfxf;
109 	const struct ipsec_xf *encxf;
110 	const struct ipsec_xf *groupxf;
111 	const struct ipsec_xf *esnxf;
112 };
113 
114 struct ipsec_mode {
115 	struct ipsec_transforms	*xfs;
116 	uint8_t			 ike_exch;
117 };
118 
119 struct iked_transform ikev2_default_ike_transforms[] = {
120 	{ IKEV2_XFORMTYPE_ENCR, IKEV2_XFORMENCR_AES_CBC, 256 },
121 	{ IKEV2_XFORMTYPE_ENCR, IKEV2_XFORMENCR_AES_CBC, 192 },
122 	{ IKEV2_XFORMTYPE_ENCR, IKEV2_XFORMENCR_AES_CBC, 128 },
123 	{ IKEV2_XFORMTYPE_ENCR, IKEV2_XFORMENCR_3DES },
124 	{ IKEV2_XFORMTYPE_PRF,	IKEV2_XFORMPRF_HMAC_SHA2_256 },
125 	{ IKEV2_XFORMTYPE_PRF,	IKEV2_XFORMPRF_HMAC_SHA1 },
126 	{ IKEV2_XFORMTYPE_INTEGR, IKEV2_XFORMAUTH_HMAC_SHA2_256_128 },
127 	{ IKEV2_XFORMTYPE_INTEGR, IKEV2_XFORMAUTH_HMAC_SHA1_96 },
128 	{ IKEV2_XFORMTYPE_DH,	IKEV2_XFORMDH_MODP_2048_256 },
129 	{ IKEV2_XFORMTYPE_DH,	IKEV2_XFORMDH_MODP_2048 },
130 	{ IKEV2_XFORMTYPE_DH,	IKEV2_XFORMDH_MODP_1536 },
131 	{ IKEV2_XFORMTYPE_DH,	IKEV2_XFORMDH_MODP_1024 },
132 	{ 0 }
133 };
134 size_t ikev2_default_nike_transforms = ((sizeof(ikev2_default_ike_transforms) /
135     sizeof(ikev2_default_ike_transforms[0])) - 1);
136 
137 struct iked_transform ikev2_default_esp_transforms[] = {
138 	{ IKEV2_XFORMTYPE_ENCR, IKEV2_XFORMENCR_AES_CBC, 256 },
139 	{ IKEV2_XFORMTYPE_ENCR, IKEV2_XFORMENCR_AES_CBC, 192 },
140 	{ IKEV2_XFORMTYPE_ENCR, IKEV2_XFORMENCR_AES_CBC, 128 },
141 	{ IKEV2_XFORMTYPE_INTEGR, IKEV2_XFORMAUTH_HMAC_SHA2_256_128 },
142 	{ IKEV2_XFORMTYPE_INTEGR, IKEV2_XFORMAUTH_HMAC_SHA1_96 },
143 	{ IKEV2_XFORMTYPE_ESN,	IKEV2_XFORMESN_ESN },
144 	{ IKEV2_XFORMTYPE_ESN,	IKEV2_XFORMESN_NONE },
145 	{ 0 }
146 };
147 size_t ikev2_default_nesp_transforms = ((sizeof(ikev2_default_esp_transforms) /
148     sizeof(ikev2_default_esp_transforms[0])) - 1);
149 
150 const struct ipsec_xf authxfs[] = {
151 	{ "hmac-md5",		IKEV2_XFORMAUTH_HMAC_MD5_96,		16 },
152 	{ "hmac-sha1",		IKEV2_XFORMAUTH_HMAC_SHA1_96,		20 },
153 	{ "hmac-sha2-256",	IKEV2_XFORMAUTH_HMAC_SHA2_256_128,	32 },
154 	{ "hmac-sha2-384",	IKEV2_XFORMAUTH_HMAC_SHA2_384_192,	48 },
155 	{ "hmac-sha2-512",	IKEV2_XFORMAUTH_HMAC_SHA2_512_256,	64 },
156 	{ NULL }
157 };
158 
159 const struct ipsec_xf prfxfs[] = {
160 	{ "hmac-md5",		IKEV2_XFORMPRF_HMAC_MD5,	16 },
161 	{ "hmac-sha1",		IKEV2_XFORMPRF_HMAC_SHA1,	20 },
162 	{ "hmac-sha2-256",	IKEV2_XFORMPRF_HMAC_SHA2_256,	32 },
163 	{ "hmac-sha2-384",	IKEV2_XFORMPRF_HMAC_SHA2_384,	48 },
164 	{ "hmac-sha2-512",	IKEV2_XFORMPRF_HMAC_SHA2_512,	64 },
165 	{ NULL }
166 };
167 
168 const struct ipsec_xf *encxfs = NULL;
169 
170 const struct ipsec_xf ikeencxfs[] = {
171 	{ "3des",		IKEV2_XFORMENCR_3DES,		24 },
172 	{ "3des-cbc",		IKEV2_XFORMENCR_3DES,		24 },
173 	{ "aes-128",		IKEV2_XFORMENCR_AES_CBC,	16, 16 },
174 	{ "aes-192",		IKEV2_XFORMENCR_AES_CBC,	24, 24 },
175 	{ "aes-256",		IKEV2_XFORMENCR_AES_CBC,	32, 32 },
176 	{ NULL }
177 };
178 
179 const struct ipsec_xf ipsecencxfs[] = {
180 	{ "3des",		IKEV2_XFORMENCR_3DES,		24 },
181 	{ "3des-cbc",		IKEV2_XFORMENCR_3DES,		24 },
182 	{ "aes-128",		IKEV2_XFORMENCR_AES_CBC,	16, 16 },
183 	{ "aes-192",		IKEV2_XFORMENCR_AES_CBC,	24, 24 },
184 	{ "aes-256",		IKEV2_XFORMENCR_AES_CBC,	32, 32 },
185 	{ "aes-128-ctr",	IKEV2_XFORMENCR_AES_CTR,	16, 16, 4 },
186 	{ "aes-192-ctr",	IKEV2_XFORMENCR_AES_CTR,	24, 24, 4 },
187 	{ "aes-256-ctr",	IKEV2_XFORMENCR_AES_CTR,	32, 32, 4 },
188 	{ "aes-128-gcm",	IKEV2_XFORMENCR_AES_GCM_16,	16, 16, 4, 1 },
189 	{ "aes-192-gcm",	IKEV2_XFORMENCR_AES_GCM_16,	24, 24, 4, 1 },
190 	{ "aes-256-gcm",	IKEV2_XFORMENCR_AES_GCM_16,	32, 32, 4, 1 },
191 	{ "aes-128-gmac",	IKEV2_XFORMENCR_NULL_AES_GMAC,	16, 16, 4, 1 },
192 	{ "aes-192-gmac",	IKEV2_XFORMENCR_NULL_AES_GMAC,	24, 24, 4, 1 },
193 	{ "aes-256-gmac",	IKEV2_XFORMENCR_NULL_AES_GMAC,	32, 32, 4, 1 },
194 	{ "blowfish",		IKEV2_XFORMENCR_BLOWFISH,	20, 20 },
195 	{ "cast",		IKEV2_XFORMENCR_CAST,		16, 16 },
196 	{ "chacha20-poly1305",	IKEV2_XFORMENCR_CHACHA20_POLY1305,
197 								32, 32, 4, 1 },
198 	{ "null",		IKEV2_XFORMENCR_NULL,		0, 0 },
199 	{ NULL }
200 };
201 
202 const struct ipsec_xf groupxfs[] = {
203 	{ "modp768",		IKEV2_XFORMDH_MODP_768 },
204 	{ "grp1",		IKEV2_XFORMDH_MODP_768 },
205 	{ "modp1024",		IKEV2_XFORMDH_MODP_1024 },
206 	{ "grp2",		IKEV2_XFORMDH_MODP_1024 },
207 	{ "ec2n155",		IKEV2_XFORMDH_EC2N_155 },
208 	{ "grp3",		IKEV2_XFORMDH_EC2N_155 },
209 	{ "ec2n185",		IKEV2_XFORMDH_EC2N_185 },
210 	{ "grp4",		IKEV2_XFORMDH_EC2N_185 },
211 	{ "modp1536",		IKEV2_XFORMDH_MODP_1536 },
212 	{ "grp5",		IKEV2_XFORMDH_MODP_1536 },
213 	{ "modp2048",		IKEV2_XFORMDH_MODP_2048 },
214 	{ "grp14",		IKEV2_XFORMDH_MODP_2048 },
215 	{ "modp3072",		IKEV2_XFORMDH_MODP_3072 },
216 	{ "grp15",		IKEV2_XFORMDH_MODP_3072 },
217 	{ "modp4096",		IKEV2_XFORMDH_MODP_4096 },
218 	{ "grp16",		IKEV2_XFORMDH_MODP_4096 },
219 	{ "modp6144",		IKEV2_XFORMDH_MODP_6144 },
220 	{ "grp17",		IKEV2_XFORMDH_MODP_6144 },
221 	{ "modp8192",		IKEV2_XFORMDH_MODP_8192 },
222 	{ "grp18",		IKEV2_XFORMDH_MODP_8192 },
223 	{ "ecp256",		IKEV2_XFORMDH_ECP_256 },
224 	{ "grp19",		IKEV2_XFORMDH_ECP_256 },
225 	{ "ecp384",		IKEV2_XFORMDH_ECP_384 },
226 	{ "grp20",		IKEV2_XFORMDH_ECP_384 },
227 	{ "ecp521",		IKEV2_XFORMDH_ECP_521 },
228 	{ "grp21",		IKEV2_XFORMDH_ECP_521 },
229 	{ "modp1024-160",	IKEV2_XFORMDH_MODP_1024_160 },
230 	{ "grp22",		IKEV2_XFORMDH_MODP_1024_160 },
231 	{ "modp2048-224",	IKEV2_XFORMDH_MODP_2048_224 },
232 	{ "grp23",		IKEV2_XFORMDH_MODP_2048_224 },
233 	{ "modp2048-256",	IKEV2_XFORMDH_MODP_2048_256 },
234 	{ "grp24",		IKEV2_XFORMDH_MODP_2048_256 },
235 	{ "ecp192",		IKEV2_XFORMDH_ECP_192 },
236 	{ "grp25",		IKEV2_XFORMDH_ECP_192 },
237 	{ "ecp224",		IKEV2_XFORMDH_ECP_224 },
238 	{ "grp26",		IKEV2_XFORMDH_ECP_224 },
239 	{ "brainpool224",	IKEV2_XFORMDH_BRAINPOOL_P224R1 },
240 	{ "grp27",		IKEV2_XFORMDH_BRAINPOOL_P224R1 },
241 	{ "brainpool256",	IKEV2_XFORMDH_BRAINPOOL_P256R1 },
242 	{ "grp28",		IKEV2_XFORMDH_BRAINPOOL_P256R1 },
243 	{ "brainpool384",	IKEV2_XFORMDH_BRAINPOOL_P384R1 },
244 	{ "grp29",		IKEV2_XFORMDH_BRAINPOOL_P384R1 },
245 	{ "brainpool512",	IKEV2_XFORMDH_BRAINPOOL_P512R1 },
246 	{ "grp30",		IKEV2_XFORMDH_BRAINPOOL_P512R1 },
247 	{ "curve25519",		IKEV2_XFORMDH_X_CURVE25519 },
248 	{ NULL }
249 };
250 
251 const struct ipsec_xf methodxfs[] = {
252 	{ "rsa",		IKEV2_AUTH_RSA_SIG },
253 	{ "dss",		IKEV2_AUTH_DSS_SIG },
254 	{ "ecdsa-256",		IKEV2_AUTH_ECDSA_256 },
255 	{ "ecdsa-384",		IKEV2_AUTH_ECDSA_384 },
256 	{ "ecdsa-521",		IKEV2_AUTH_ECDSA_521 },
257 	{ NULL }
258 };
259 
260 const struct ipsec_xf saxfs[] = {
261 	{ "esp",		IKEV2_SAPROTO_ESP },
262 	{ "ah",			IKEV2_SAPROTO_AH },
263 	{ NULL }
264 };
265 
266 const struct ipsec_xf cpxfs[] = {
267 	{ "address", IKEV2_CFG_INTERNAL_IP4_ADDRESS,		AF_INET },
268 	{ "netmask", IKEV2_CFG_INTERNAL_IP4_NETMASK,		AF_INET },
269 	{ "name-server", IKEV2_CFG_INTERNAL_IP4_DNS,		AF_INET },
270 	{ "netbios-server", IKEV2_CFG_INTERNAL_IP4_NBNS,	AF_INET },
271 	{ "dhcp-server", IKEV2_CFG_INTERNAL_IP4_DHCP,		AF_INET },
272 	{ "address", IKEV2_CFG_INTERNAL_IP6_ADDRESS,		AF_INET6 },
273 	{ "name-server", IKEV2_CFG_INTERNAL_IP6_DNS,		AF_INET6 },
274 	{ "netbios-server", IKEV2_CFG_INTERNAL_IP6_NBNS,	AF_INET6 },
275 	{ "dhcp-server", IKEV2_CFG_INTERNAL_IP6_DHCP,		AF_INET6 },
276 	{ "protected-subnet", IKEV2_CFG_INTERNAL_IP4_SUBNET,	AF_INET },
277 	{ "protected-subnet", IKEV2_CFG_INTERNAL_IP6_SUBNET,	AF_INET6 },
278 	{ "access-server", IKEV2_CFG_INTERNAL_IP4_SERVER,	AF_INET },
279 	{ "access-server", IKEV2_CFG_INTERNAL_IP6_SERVER,	AF_INET6 },
280 	{ NULL }
281 };
282 
283 const struct iked_lifetime deflifetime = {
284 	IKED_LIFETIME_BYTES,
285 	IKED_LIFETIME_SECONDS
286 };
287 
288 struct ipsec_addr_wrap {
289 	struct sockaddr_storage	 address;
290 	uint8_t			 mask;
291 	int			 netaddress;
292 	sa_family_t		 af;
293 	unsigned int		 type;
294 	unsigned int		 action;
295 	char			*name;
296 	struct ipsec_addr_wrap	*next;
297 	struct ipsec_addr_wrap	*tail;
298 	struct ipsec_addr_wrap	*srcnat;
299 };
300 
301 struct ipsec_hosts {
302 	struct ipsec_addr_wrap	*src;
303 	struct ipsec_addr_wrap	*dst;
304 	uint16_t		 sport;
305 	uint16_t		 dport;
306 };
307 
308 struct ipsec_filters {
309 	char			*tag;
310 	unsigned int		 tap;
311 };
312 
313 struct ipsec_addr_wrap	*host(const char *);
314 struct ipsec_addr_wrap	*host_v6(const char *, int);
315 struct ipsec_addr_wrap	*host_v4(const char *, int);
316 struct ipsec_addr_wrap	*host_dns(const char *, int);
317 struct ipsec_addr_wrap	*host_if(const char *, int);
318 struct ipsec_addr_wrap	*host_any(void);
319 void			 ifa_load(void);
320 int			 ifa_exists(const char *);
321 struct ipsec_addr_wrap	*ifa_lookup(const char *ifa_name);
322 struct ipsec_addr_wrap	*ifa_grouplookup(const char *);
323 void			 set_ipmask(struct ipsec_addr_wrap *, uint8_t);
324 const struct ipsec_xf	*parse_xf(const char *, unsigned int,
325 			    const struct ipsec_xf *);
326 const char		*print_xf(unsigned int, unsigned int,
327 			    const struct ipsec_xf *);
328 void			 copy_transforms(unsigned int, const struct ipsec_xf *,
329 			    const struct ipsec_xf *,
330 			    struct iked_transform *, size_t,
331 			    unsigned int *, struct iked_transform *, size_t);
332 int			 create_ike(char *, int, uint8_t, struct ipsec_hosts *,
333 			    struct ipsec_hosts *, struct ipsec_mode *,
334 			    struct ipsec_mode *, uint8_t,
335 			    uint8_t, char *, char *,
336 			    uint32_t, struct iked_lifetime *,
337 			    struct iked_auth *, struct ipsec_filters *,
338 			    struct ipsec_addr_wrap *);
339 int			 create_user(const char *, const char *);
340 int			 get_id_type(char *);
341 uint8_t			 x2i(unsigned char *);
342 int			 parsekey(unsigned char *, size_t, struct iked_auth *);
343 int			 parsekeyfile(char *, struct iked_auth *);
344 
345 struct ipsec_transforms *ipsec_transforms;
346 struct ipsec_filters *ipsec_filters;
347 
348 typedef struct {
349 	union {
350 		int64_t			 number;
351 		uint8_t			 ikemode;
352 		uint8_t			 dir;
353 		uint8_t			 satype;
354 		uint8_t			 proto;
355 		char			*string;
356 		uint16_t		 port;
357 		struct ipsec_hosts	*hosts;
358 		struct ipsec_hosts	 peers;
359 		struct ipsec_addr_wrap	*anyhost;
360 		struct ipsec_addr_wrap	*host;
361 		struct ipsec_addr_wrap	*cfg;
362 		struct {
363 			char		*srcid;
364 			char		*dstid;
365 		} ids;
366 		char			*id;
367 		uint8_t			 type;
368 		struct iked_lifetime	 lifetime;
369 		struct iked_auth	 ikeauth;
370 		struct iked_auth	 ikekey;
371 		struct ipsec_transforms	*transforms;
372 		struct ipsec_filters	*filters;
373 		struct ipsec_mode	*mode;
374 	} v;
375 	int lineno;
376 } YYSTYPE;
377 
378 %}
379 
380 %token	FROM ESP AH IN PEER ON OUT TO SRCID DSTID RSA PSK PORT
381 %token	FILENAME AUTHXF PRFXF ENCXF ERROR IKEV2 IKESA CHILDSA
382 %token	PASSIVE ACTIVE ANY TAG TAP PROTO LOCAL GROUP NAME CONFIG EAP USER
383 %token	IKEV1 FLOW SA TCPMD5 TUNNEL TRANSPORT COUPLE DECOUPLE SET
384 %token	INCLUDE LIFETIME BYTES INET INET6 QUICK SKIP DEFAULT
385 %token	IPCOMP OCSP IKELIFETIME
386 %token	<v.string>		STRING
387 %token	<v.number>		NUMBER
388 %type	<v.string>		string
389 %type	<v.satype>		satype
390 %type	<v.proto>		proto
391 %type	<v.number>		protoval
392 %type	<v.hosts>		hosts hosts_list
393 %type	<v.port>		port
394 %type	<v.number>		portval af
395 %type	<v.peers>		peers
396 %type	<v.anyhost>		anyhost
397 %type	<v.host>		host host_spec
398 %type	<v.ids>			ids
399 %type	<v.id>			id
400 %type	<v.transforms>		transforms
401 %type	<v.filters>		filters
402 %type	<v.ikemode>		ikeflags ikematch ikemode ipcomp
403 %type	<v.ikeauth>		ikeauth
404 %type	<v.ikekey>		keyspec
405 %type	<v.mode>		ike_sa child_sa
406 %type	<v.lifetime>		lifetime
407 %type	<v.number>		byte_spec time_spec ikelifetime
408 %type	<v.string>		name
409 %type	<v.cfg>			cfg ikecfg ikecfgvals
410 %%
411 
412 grammar		: /* empty */
413 		| grammar include '\n'
414 		| grammar '\n'
415 		| grammar set '\n'
416 		| grammar user '\n'
417 		| grammar ikev2rule '\n'
418 		| grammar varset '\n'
419 		| grammar otherrule skipline '\n'
420 		| grammar error '\n'		{ file->errors++; }
421 		;
422 
423 comma		: ','
424 		| /* empty */
425 		;
426 
427 include		: INCLUDE STRING		{
428 			struct file	*nfile;
429 
430 			if ((nfile = pushfile($2, 0)) == NULL) {
431 				yyerror("failed to include file %s", $2);
432 				free($2);
433 				YYERROR;
434 			}
435 			free($2);
436 
437 			file = nfile;
438 			lungetc('\n');
439 		}
440 		;
441 
442 set		: SET ACTIVE	{ passive = 0; }
443 		| SET PASSIVE	{ passive = 1; }
444 		| SET COUPLE	{ decouple = 0; }
445 		| SET DECOUPLE	{ decouple = 1; }
446 		| SET OCSP STRING		{
447 			if ((ocsp_url = strdup($3)) == NULL) {
448 				yyerror("cannot set ocsp_url");
449 				YYERROR;
450 			}
451 		}
452 		;
453 
454 user		: USER STRING STRING		{
455 			if (create_user($2, $3) == -1)
456 				YYERROR;
457 		}
458 		;
459 
460 ikev2rule	: IKEV2 name ikeflags satype af proto hosts_list peers
461 		    ike_sa child_sa ids ikelifetime lifetime ikeauth ikecfg
462 		    filters {
463 			if (create_ike($2, $5, $6, $7, &$8, $9, $10, $4, $3,
464 			    $11.srcid, $11.dstid, $12, &$13, &$14,
465 			    $16, $15) == -1)
466 				YYERROR;
467 		}
468 		;
469 
470 ikecfg		: /* empty */			{ $$ = NULL; }
471 		| ikecfgvals			{ $$ = $1; }
472 		;
473 
474 ikecfgvals	: cfg				{ $$ = $1; }
475 		| ikecfgvals cfg		{
476 			if ($2 == NULL)
477 				$$ = $1;
478 			else if ($1 == NULL)
479 				$$ = $2;
480 			else {
481 				$1->tail->next = $2;
482 				$1->tail = $2->tail;
483 				$$ = $1;
484 			}
485 		}
486 		;
487 
488 cfg		: CONFIG STRING host_spec	{
489 			const struct ipsec_xf	*xf;
490 
491 			if ((xf = parse_xf($2, $3->af, cpxfs)) == NULL) {
492 				yyerror("not a valid ikecfg option");
493 				free($2);
494 				free($3);
495 				YYERROR;
496 			}
497 			$$ = $3;
498 			$$->type = xf->id;
499 			$$->action = IKEV2_CP_REPLY;	/* XXX */
500 		}
501 		;
502 
503 name		: /* empty */			{ $$ = NULL; }
504 		| STRING			{
505 			$$ = $1;
506 		}
507 
508 satype		: /* empty */			{ $$ = IKEV2_SAPROTO_ESP; }
509 		| ESP				{ $$ = IKEV2_SAPROTO_ESP; }
510 		| AH				{ $$ = IKEV2_SAPROTO_AH; }
511 		;
512 
513 af		: /* empty */			{ $$ = AF_UNSPEC; }
514 		| INET				{ $$ = AF_INET; }
515 		| INET6				{ $$ = AF_INET6; }
516 		;
517 
518 proto		: /* empty */			{ $$ = 0; }
519 		| PROTO protoval		{ $$ = $2; }
520 		| PROTO ESP			{ $$ = IPPROTO_ESP; }
521 		| PROTO AH			{ $$ = IPPROTO_AH; }
522 		;
523 
524 protoval	: STRING			{
525 			struct protoent *p;
526 
527 			p = getprotobyname($1);
528 			if (p == NULL) {
529 				yyerror("unknown protocol: %s", $1);
530 				YYERROR;
531 			}
532 			$$ = p->p_proto;
533 			free($1);
534 		}
535 		| NUMBER			{
536 			if ($1 > 255 || $1 < 0) {
537 				yyerror("protocol outside range");
538 				YYERROR;
539 			}
540 		}
541 		;
542 
543 hosts_list	: hosts				{ $$ = $1; }
544 		| hosts_list comma hosts	{
545 			if ($3 == NULL)
546 				$$ = $1;
547 			else if ($1 == NULL)
548 				$$ = $3;
549 			else {
550 				$1->src->tail->next = $3->src;
551 				$1->src->tail = $3->src->tail;
552 				$1->dst->tail->next = $3->dst;
553 				$1->dst->tail = $3->dst->tail;
554 				$$ = $1;
555 			}
556 		}
557 		;
558 
559 hosts		: FROM host port TO host port		{
560 			struct ipsec_addr_wrap *ipa;
561 			for (ipa = $5; ipa; ipa = ipa->next) {
562 				if (ipa->srcnat) {
563 					yyerror("no flow NAT support for"
564 					    " destination network: %s",
565 					    ipa->name);
566 					YYERROR;
567 				}
568 			}
569 
570 			if (($$ = calloc(1, sizeof(*$$))) == NULL)
571 				err(1, "hosts: calloc");
572 
573 			$$->src = $2;
574 			$$->sport = $3;
575 			$$->dst = $5;
576 			$$->dport = $6;
577 		}
578 		| TO host port FROM host port		{
579 			struct ipsec_addr_wrap *ipa;
580 			for (ipa = $2; ipa; ipa = ipa->next) {
581 				if (ipa->srcnat) {
582 					yyerror("no flow NAT support for"
583 					    " destination network: %s",
584 					    ipa->name);
585 					YYERROR;
586 				}
587 			}
588 			if (($$ = calloc(1, sizeof(*$$))) == NULL)
589 				err(1, "hosts: calloc");
590 
591 			$$->src = $5;
592 			$$->sport = $6;
593 			$$->dst = $2;
594 			$$->dport = $3;
595 		}
596 		;
597 
598 port		: /* empty */				{ $$ = 0; }
599 		| PORT portval				{ $$ = $2; }
600 		;
601 
602 portval		: STRING				{
603 			struct servent *s;
604 
605 			if ((s = getservbyname($1, "tcp")) != NULL ||
606 			    (s = getservbyname($1, "udp")) != NULL) {
607 				$$ = s->s_port;
608 			} else {
609 				yyerror("unknown port: %s", $1);
610 				YYERROR;
611 			}
612 		}
613 		| NUMBER				{
614 			if ($1 > USHRT_MAX || $1 < 0) {
615 				yyerror("port outside range");
616 				YYERROR;
617 			}
618 			$$ = htons($1);
619 		}
620 		;
621 
622 peers		: /* empty */				{
623 			$$.dst = NULL;
624 			$$.src = NULL;
625 		}
626 		| PEER anyhost LOCAL anyhost		{
627 			$$.dst = $2;
628 			$$.src = $4;
629 		}
630 		| LOCAL anyhost PEER anyhost		{
631 			$$.dst = $4;
632 			$$.src = $2;
633 		}
634 		| PEER anyhost				{
635 			$$.dst = $2;
636 			$$.src = NULL;
637 		}
638 		| LOCAL anyhost				{
639 			$$.dst = NULL;
640 			$$.src = $2;
641 		}
642 		;
643 
644 anyhost		: host_spec			{ $$ = $1; }
645 		| ANY				{
646 			$$ = host_any();
647 		}
648 
649 host_spec	: STRING			{
650 			if (($$ = host($1)) == NULL) {
651 				free($1);
652 				yyerror("could not parse host specification");
653 				YYERROR;
654 			}
655 			free($1);
656 		}
657 		| STRING '/' NUMBER		{
658 			char	*buf;
659 
660 			if (asprintf(&buf, "%s/%lld", $1, $3) == -1)
661 				err(1, "host: asprintf");
662 			free($1);
663 			if (($$ = host(buf)) == NULL)	{
664 				free(buf);
665 				yyerror("could not parse host specification");
666 				YYERROR;
667 			}
668 			free(buf);
669 		}
670 		;
671 
672 host		: host_spec			{ $$ = $1; }
673 		| host_spec '(' host_spec ')'   {
674 			if (($1->af != AF_UNSPEC) && ($3->af != AF_UNSPEC) &&
675 			    ($3->af != $1->af)) {
676 				yyerror("Flow NAT address family mismatch");
677 				YYERROR;
678 			}
679 			$$ = $1;
680 			$$->srcnat = $3;
681 		}
682 		| ANY				{
683 			$$ = host_any();
684 		}
685 		;
686 
687 ids		: /* empty */			{
688 			$$.srcid = NULL;
689 			$$.dstid = NULL;
690 		}
691 		| SRCID id DSTID id		{
692 			$$.srcid = $2;
693 			$$.dstid = $4;
694 		}
695 		| SRCID id			{
696 			$$.srcid = $2;
697 			$$.dstid = NULL;
698 		}
699 		| DSTID id			{
700 			$$.srcid = NULL;
701 			$$.dstid = $2;
702 		}
703 		;
704 
705 id		: STRING			{ $$ = $1; }
706 		;
707 
708 transforms	:					{
709 			if ((ipsec_transforms = calloc(1,
710 			    sizeof(struct ipsec_transforms))) == NULL)
711 				err(1, "transforms: calloc");
712 		}
713 		    transforms_l			{
714 			$$ = ipsec_transforms;
715 		}
716 		| /* empty */				{
717 			$$ = NULL;
718 		}
719 		;
720 
721 transforms_l	: transforms_l transform
722 		| transform
723 		;
724 
725 transform	: AUTHXF STRING			{
726 			if (ipsec_transforms->authxf)
727 				yyerror("auth already set");
728 			else {
729 				ipsec_transforms->authxf = parse_xf($2, 0,
730 				    authxfs);
731 				if (!ipsec_transforms->authxf)
732 					yyerror("%s not a valid transform", $2);
733 			}
734 		}
735 		| ENCXF STRING			{
736 			if (ipsec_transforms->encxf)
737 				yyerror("enc already set");
738 			else {
739 				ipsec_transforms->encxf = parse_xf($2, 0,
740 				    encxfs);
741 				if (!ipsec_transforms->encxf)
742 					yyerror("%s not a valid transform",
743 					    $2);
744 			}
745 		}
746 		| PRFXF STRING			{
747 			if (ipsec_transforms->prfxf)
748 				yyerror("prf already set");
749 			else {
750 				ipsec_transforms->prfxf = parse_xf($2, 0,
751 				    prfxfs);
752 				if (!ipsec_transforms->prfxf)
753 					yyerror("%s not a valid transform",
754 					    $2);
755 			}
756 		}
757 		| GROUP STRING			{
758 			if (ipsec_transforms->groupxf)
759 				yyerror("group already set");
760 			else {
761 				ipsec_transforms->groupxf = parse_xf($2, 0,
762 				    groupxfs);
763 				if (!ipsec_transforms->groupxf)
764 					yyerror("%s not a valid transform",
765 					    $2);
766 			}
767 		}
768 		;
769 
770 ike_sa		: /* empty */	{
771 			$$ = NULL;
772 		}
773 		| IKESA		{
774 			encxfs = ikeencxfs;
775 		} transforms	{
776 			if (($$ = calloc(1, sizeof(*$$))) == NULL)
777 				err(1, "ike_sa: calloc");
778 			$$->xfs = $3;
779 		}
780 		;
781 
782 child_sa	: /* empty */	{
783 			$$ = NULL;
784 		}
785 		| CHILDSA	{
786 			encxfs = ipsecencxfs;
787 		} transforms	{
788 			if (($$ = calloc(1, sizeof(*$$))) == NULL)
789 				err(1, "child_sa: calloc");
790 			$$->xfs = $3;
791 		}
792 		;
793 
794 ikeflags	: ikematch ikemode ipcomp	{ $$ = $1 | $2 | $3; }
795 		;
796 
797 ikematch	: /* empty */			{ $$ = 0; }
798 		| QUICK				{ $$ = IKED_POLICY_QUICK; }
799 		| SKIP				{ $$ = IKED_POLICY_SKIP; }
800 		| DEFAULT			{ $$ = IKED_POLICY_DEFAULT; }
801 		;
802 
803 ikemode		: /* empty */			{ $$ = IKED_POLICY_PASSIVE; }
804 		| PASSIVE			{ $$ = IKED_POLICY_PASSIVE; }
805 		| ACTIVE			{ $$ = IKED_POLICY_ACTIVE; }
806 		;
807 
808 ipcomp		: /* empty */			{ $$ = 0; }
809 		| IPCOMP			{ $$ = IKED_POLICY_IPCOMP; }
810 		;
811 
812 ikeauth		: /* empty */			{
813 			$$.auth_method = IKEV2_AUTH_RSA_SIG;
814 			$$.auth_eap = 0;
815 			$$.auth_length = 0;
816 		}
817 		| RSA				{
818 			$$.auth_method = IKEV2_AUTH_RSA_SIG;
819 			$$.auth_eap = 0;
820 			$$.auth_length = 0;
821 		}
822 		| PSK keyspec			{
823 			memcpy(&$$, &$2, sizeof($$));
824 			$$.auth_method = IKEV2_AUTH_SHARED_KEY_MIC;
825 			$$.auth_eap = 0;
826 		}
827 		| EAP STRING			{
828 			unsigned int i;
829 
830 			for (i = 0; i < strlen($2); i++)
831 				if ($2[i] == '-')
832 					$2[i] = '_';
833 
834 			if (strcasecmp("mschap_v2", $2) != 0) {
835 				yyerror("unsupported EAP method: %s", $2);
836 				free($2);
837 				YYERROR;
838 			}
839 			free($2);
840 
841 			$$.auth_method = IKEV2_AUTH_RSA_SIG;
842 			$$.auth_eap = EAP_TYPE_MSCHAP_V2;
843 			$$.auth_length = 0;
844 		}
845 		;
846 
847 byte_spec	: NUMBER			{
848 			$$ = $1;
849 		}
850 		| STRING			{
851 			uint64_t	 bytes = 0;
852 			char		 unit = 0;
853 
854 			if (sscanf($1, "%llu%c", &bytes, &unit) != 2) {
855 				yyerror("invalid byte specification: %s", $1);
856 				YYERROR;
857 			}
858 			switch (toupper((unsigned char)unit)) {
859 			case 'K':
860 				bytes *= 1024;
861 				break;
862 			case 'M':
863 				bytes *= 1024 * 1024;
864 				break;
865 			case 'G':
866 				bytes *= 1024 * 1024 * 1024;
867 				break;
868 			default:
869 				yyerror("invalid byte unit");
870 				YYERROR;
871 			}
872 			$$ = bytes;
873 		}
874 		;
875 
876 time_spec	: NUMBER			{
877 			$$ = $1;
878 		}
879 		| STRING			{
880 			uint64_t	 seconds = 0;
881 			char		 unit = 0;
882 
883 			if (sscanf($1, "%llu%c", &seconds, &unit) != 2) {
884 				yyerror("invalid time specification: %s", $1);
885 				YYERROR;
886 			}
887 			switch (tolower((unsigned char)unit)) {
888 			case 'm':
889 				seconds *= 60;
890 				break;
891 			case 'h':
892 				seconds *= 60 * 60;
893 				break;
894 			default:
895 				yyerror("invalid time unit");
896 				YYERROR;
897 			}
898 			$$ = seconds;
899 		}
900 		;
901 
902 lifetime	: /* empty */				{
903 			$$ = deflifetime;
904 		}
905 		| LIFETIME time_spec			{
906 			$$.lt_seconds = $2;
907 			$$.lt_bytes = deflifetime.lt_bytes;
908 		}
909 		| LIFETIME time_spec BYTES byte_spec	{
910 			$$.lt_seconds = $2;
911 			$$.lt_bytes = $4;
912 		}
913 		;
914 
915 ikelifetime	: /* empty */				{
916 			$$ = 0;
917 		}
918 		| IKELIFETIME time_spec			{
919 			$$ = $2;
920 		}
921 
922 keyspec		: STRING			{
923 			uint8_t		*hex;
924 
925 			bzero(&$$, sizeof($$));
926 
927 			hex = $1;
928 			if (strncmp(hex, "0x", 2) == 0) {
929 				hex += 2;
930 				if (parsekey(hex, strlen(hex), &$$) != 0) {
931 					free($1);
932 					YYERROR;
933 				}
934 			} else {
935 				if (strlen($1) > sizeof($$.auth_data)) {
936 					yyerror("psk too long");
937 					free($1);
938 					YYERROR;
939 				}
940 				strlcpy($$.auth_data, $1,
941 				    sizeof($$.auth_data));
942 				$$.auth_length = strlen($1);
943 			}
944 			free($1);
945 		}
946 		| FILENAME STRING		{
947 			if (parsekeyfile($2, &$$) != 0) {
948 				free($2);
949 				YYERROR;
950 			}
951 			free($2);
952 		}
953 		;
954 
955 filters		:					{
956 			if ((ipsec_filters = calloc(1,
957 			    sizeof(struct ipsec_filters))) == NULL)
958 				err(1, "filters: calloc");
959 		}
960 		    filters_l			{
961 			$$ = ipsec_filters;
962 		}
963 		| /* empty */				{
964 			$$ = NULL;
965 		}
966 		;
967 
968 filters_l	: filters_l filter
969 		| filter
970 		;
971 
972 filter		: TAG STRING
973 		{
974 			ipsec_filters->tag = $2;
975 		}
976 		| TAP STRING
977 		{
978 			const char	*errstr = NULL;
979 			size_t		 len;
980 
981 			len = strcspn($2, "0123456789");
982 			if (strlen("enc") != len ||
983 			    strncmp("enc", $2, len) != 0) {
984 				yyerror("invalid tap interface name: %s", $2);
985 				free($2);
986 				YYERROR;
987 			}
988 			ipsec_filters->tap =
989 			    strtonum($2 + len, 0, UINT_MAX, &errstr);
990 			free($2);
991 			if (errstr != NULL) {
992 				yyerror("invalid tap interface unit: %s",
993 				    errstr);
994 				YYERROR;
995 			}
996 		}
997 		;
998 
999 string		: string STRING
1000 		{
1001 			if (asprintf(&$$, "%s %s", $1, $2) == -1)
1002 				err(1, "string: asprintf");
1003 			free($1);
1004 			free($2);
1005 		}
1006 		| STRING
1007 		;
1008 
1009 varset		: STRING '=' string
1010 		{
1011 			char *s = $1;
1012 			log_debug("%s = \"%s\"\n", $1, $3);
1013 			while (*s++) {
1014 				if (isspace((unsigned char)*s)) {
1015 					yyerror("macro name cannot contain "
1016 					    "whitespace");
1017 					YYERROR;
1018 				}
1019 			}
1020 			if (symset($1, $3, 0) == -1)
1021 				err(1, "cannot store variable");
1022 			free($1);
1023 			free($3);
1024 		}
1025 		;
1026 
1027 /*
1028  * ignore IKEv1/manual keying rules in ipsec.conf
1029  */
1030 otherrule	: IKEV1
1031 		| sarule
1032 		| FLOW
1033 		| TCPMD5
1034 		;
1035 
1036 /* manual keying SAs might start with the following keywords */
1037 sarule		: SA
1038 		| FROM
1039 		| TO
1040 		| TUNNEL
1041 		| TRANSPORT
1042 		;
1043 
1044 /* ignore everything to the end of the line */
1045 skipline	:
1046 		{
1047 			int	 c;
1048 
1049 			while ((c = lgetc(0)) != '\n' && c != EOF)
1050 				; /* nothing */
1051 			if (c == '\n')
1052 				lungetc(c);
1053 		}
1054 		;
1055 %%
1056 
1057 struct keywords {
1058 	const char	*k_name;
1059 	int		 k_val;
1060 };
1061 
1062 int
1063 yyerror(const char *fmt, ...)
1064 {
1065 	va_list		 ap;
1066 
1067 	file->errors++;
1068 	va_start(ap, fmt);
1069 	fprintf(stderr, "%s: %d: ", file->name, yylval.lineno);
1070 	vfprintf(stderr, fmt, ap);
1071 	fprintf(stderr, "\n");
1072 	va_end(ap);
1073 	return (0);
1074 }
1075 
1076 int
1077 kw_cmp(const void *k, const void *e)
1078 {
1079 	return (strcmp(k, ((const struct keywords *)e)->k_name));
1080 }
1081 
1082 int
1083 lookup(char *s)
1084 {
1085 	/* this has to be sorted always */
1086 	static const struct keywords keywords[] = {
1087 		{ "active",		ACTIVE },
1088 		{ "ah",			AH },
1089 		{ "any",		ANY },
1090 		{ "auth",		AUTHXF },
1091 		{ "bytes",		BYTES },
1092 		{ "childsa",		CHILDSA },
1093 		{ "config",		CONFIG },
1094 		{ "couple",		COUPLE },
1095 		{ "decouple",		DECOUPLE },
1096 		{ "default",		DEFAULT },
1097 		{ "dstid",		DSTID },
1098 		{ "eap",		EAP },
1099 		{ "enc",		ENCXF },
1100 		{ "esp",		ESP },
1101 		{ "file",		FILENAME },
1102 		{ "flow",		FLOW },
1103 		{ "from",		FROM },
1104 		{ "group",		GROUP },
1105 		{ "ike",		IKEV1 },
1106 		{ "ikelifetime",	IKELIFETIME },
1107 		{ "ikesa",		IKESA },
1108 		{ "ikev2",		IKEV2 },
1109 		{ "include",		INCLUDE },
1110 		{ "inet",		INET },
1111 		{ "inet6",		INET6 },
1112 		{ "ipcomp",		IPCOMP },
1113 		{ "lifetime",		LIFETIME },
1114 		{ "local",		LOCAL },
1115 		{ "name",		NAME },
1116 		{ "ocsp",		OCSP },
1117 		{ "passive",		PASSIVE },
1118 		{ "peer",		PEER },
1119 		{ "port",		PORT },
1120 		{ "prf",		PRFXF },
1121 		{ "proto",		PROTO },
1122 		{ "psk",		PSK },
1123 		{ "quick",		QUICK },
1124 		{ "rsa",		RSA },
1125 		{ "sa",			SA },
1126 		{ "set",		SET },
1127 		{ "skip",		SKIP },
1128 		{ "srcid",		SRCID },
1129 		{ "tag",		TAG },
1130 		{ "tap",		TAP },
1131 		{ "tcpmd5",		TCPMD5 },
1132 		{ "to",			TO },
1133 		{ "transport",		TRANSPORT },
1134 		{ "tunnel",		TUNNEL },
1135 		{ "user",		USER }
1136 	};
1137 	const struct keywords	*p;
1138 
1139 	p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
1140 	    sizeof(keywords[0]), kw_cmp);
1141 
1142 	if (p) {
1143 		if (debug > 1)
1144 			fprintf(stderr, "%s: %d\n", s, p->k_val);
1145 		return (p->k_val);
1146 	} else {
1147 		if (debug > 1)
1148 			fprintf(stderr, "string: %s\n", s);
1149 		return (STRING);
1150 	}
1151 }
1152 
1153 #define MAXPUSHBACK	128
1154 
1155 unsigned char	*parsebuf;
1156 int		 parseindex;
1157 unsigned char	 pushback_buffer[MAXPUSHBACK];
1158 int		 pushback_index = 0;
1159 
1160 int
1161 lgetc(int quotec)
1162 {
1163 	int		c, next;
1164 
1165 	if (parsebuf) {
1166 		/* Read character from the parsebuffer instead of input. */
1167 		if (parseindex >= 0) {
1168 			c = parsebuf[parseindex++];
1169 			if (c != '\0')
1170 				return (c);
1171 			parsebuf = NULL;
1172 		} else
1173 			parseindex++;
1174 	}
1175 
1176 	if (pushback_index)
1177 		return (pushback_buffer[--pushback_index]);
1178 
1179 	if (quotec) {
1180 		if ((c = getc(file->stream)) == EOF) {
1181 			yyerror("reached end of file while parsing "
1182 			    "quoted string");
1183 			if (popfile() == EOF)
1184 				return (EOF);
1185 			return (quotec);
1186 		}
1187 		return (c);
1188 	}
1189 
1190 	while ((c = getc(file->stream)) == '\\') {
1191 		next = getc(file->stream);
1192 		if (next != '\n') {
1193 			c = next;
1194 			break;
1195 		}
1196 		yylval.lineno = file->lineno;
1197 		file->lineno++;
1198 	}
1199 
1200 	while (c == EOF) {
1201 		if (popfile() == EOF)
1202 			return (EOF);
1203 		c = getc(file->stream);
1204 	}
1205 	return (c);
1206 }
1207 
1208 int
1209 lungetc(int c)
1210 {
1211 	if (c == EOF)
1212 		return (EOF);
1213 	if (parsebuf) {
1214 		parseindex--;
1215 		if (parseindex >= 0)
1216 			return (c);
1217 	}
1218 	if (pushback_index < MAXPUSHBACK-1)
1219 		return (pushback_buffer[pushback_index++] = c);
1220 	else
1221 		return (EOF);
1222 }
1223 
1224 int
1225 findeol(void)
1226 {
1227 	int	c;
1228 
1229 	parsebuf = NULL;
1230 
1231 	/* skip to either EOF or the first real EOL */
1232 	while (1) {
1233 		if (pushback_index)
1234 			c = pushback_buffer[--pushback_index];
1235 		else
1236 			c = lgetc(0);
1237 		if (c == '\n') {
1238 			file->lineno++;
1239 			break;
1240 		}
1241 		if (c == EOF)
1242 			break;
1243 	}
1244 	return (ERROR);
1245 }
1246 
1247 int
1248 yylex(void)
1249 {
1250 	unsigned char	 buf[8096];
1251 	unsigned char	*p, *val;
1252 	int		 quotec, next, c;
1253 	int		 token;
1254 
1255 top:
1256 	p = buf;
1257 	while ((c = lgetc(0)) == ' ' || c == '\t')
1258 		; /* nothing */
1259 
1260 	yylval.lineno = file->lineno;
1261 	if (c == '#')
1262 		while ((c = lgetc(0)) != '\n' && c != EOF)
1263 			; /* nothing */
1264 	if (c == '$' && parsebuf == NULL) {
1265 		while (1) {
1266 			if ((c = lgetc(0)) == EOF)
1267 				return (0);
1268 
1269 			if (p + 1 >= buf + sizeof(buf) - 1) {
1270 				yyerror("string too long");
1271 				return (findeol());
1272 			}
1273 			if (isalnum(c) || c == '_') {
1274 				*p++ = c;
1275 				continue;
1276 			}
1277 			*p = '\0';
1278 			lungetc(c);
1279 			break;
1280 		}
1281 		val = symget(buf);
1282 		if (val == NULL) {
1283 			yyerror("macro '%s' not defined", buf);
1284 			return (findeol());
1285 		}
1286 		parsebuf = val;
1287 		parseindex = 0;
1288 		goto top;
1289 	}
1290 
1291 	switch (c) {
1292 	case '\'':
1293 	case '"':
1294 		quotec = c;
1295 		while (1) {
1296 			if ((c = lgetc(quotec)) == EOF)
1297 				return (0);
1298 			if (c == '\n') {
1299 				file->lineno++;
1300 				continue;
1301 			} else if (c == '\\') {
1302 				if ((next = lgetc(quotec)) == EOF)
1303 					return (0);
1304 				if (next == quotec || c == ' ' || c == '\t')
1305 					c = next;
1306 				else if (next == '\n') {
1307 					file->lineno++;
1308 					continue;
1309 				} else
1310 					lungetc(next);
1311 			} else if (c == quotec) {
1312 				*p = '\0';
1313 				break;
1314 			} else if (c == '\0') {
1315 				yyerror("syntax error");
1316 				return (findeol());
1317 			}
1318 			if (p + 1 >= buf + sizeof(buf) - 1) {
1319 				yyerror("string too long");
1320 				return (findeol());
1321 			}
1322 			*p++ = c;
1323 		}
1324 		yylval.v.string = strdup(buf);
1325 		if (yylval.v.string == NULL)
1326 			err(1, "yylex: strdup");
1327 		return (STRING);
1328 	}
1329 
1330 #define allowed_to_end_number(x) \
1331 	(isspace(x) || x == ')' || x ==',' || x == '/' || x == '}' || x == '=')
1332 
1333 	if (c == '-' || isdigit(c)) {
1334 		do {
1335 			*p++ = c;
1336 			if ((unsigned)(p-buf) >= sizeof(buf)) {
1337 				yyerror("string too long");
1338 				return (findeol());
1339 			}
1340 		} while ((c = lgetc(0)) != EOF && isdigit(c));
1341 		lungetc(c);
1342 		if (p == buf + 1 && buf[0] == '-')
1343 			goto nodigits;
1344 		if (c == EOF || allowed_to_end_number(c)) {
1345 			const char *errstr = NULL;
1346 
1347 			*p = '\0';
1348 			yylval.v.number = strtonum(buf, LLONG_MIN,
1349 			    LLONG_MAX, &errstr);
1350 			if (errstr) {
1351 				yyerror("\"%s\" invalid number: %s",
1352 				    buf, errstr);
1353 				return (findeol());
1354 			}
1355 			return (NUMBER);
1356 		} else {
1357 nodigits:
1358 			while (p > buf + 1)
1359 				lungetc(*--p);
1360 			c = *--p;
1361 			if (c == '-')
1362 				return (c);
1363 		}
1364 	}
1365 
1366 #define allowed_in_string(x) \
1367 	(isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
1368 	x != '{' && x != '}' && x != '<' && x != '>' && \
1369 	x != '!' && x != '=' && x != '/' && x != '#' && \
1370 	x != ','))
1371 
1372 	if (isalnum(c) || c == ':' || c == '_' || c == '*') {
1373 		do {
1374 			*p++ = c;
1375 			if ((unsigned)(p-buf) >= sizeof(buf)) {
1376 				yyerror("string too long");
1377 				return (findeol());
1378 			}
1379 		} while ((c = lgetc(0)) != EOF && (allowed_in_string(c)));
1380 		lungetc(c);
1381 		*p = '\0';
1382 		if ((token = lookup(buf)) == STRING)
1383 			if ((yylval.v.string = strdup(buf)) == NULL)
1384 				err(1, "yylex: strdup");
1385 		return (token);
1386 	}
1387 	if (c == '\n') {
1388 		yylval.lineno = file->lineno;
1389 		file->lineno++;
1390 	}
1391 	if (c == EOF)
1392 		return (0);
1393 	return (c);
1394 }
1395 
1396 int
1397 check_file_secrecy(int fd, const char *fname)
1398 {
1399 	struct stat	st;
1400 
1401 	if (fstat(fd, &st)) {
1402 		warn("cannot stat %s", fname);
1403 		return (-1);
1404 	}
1405 	if (st.st_uid != 0 && st.st_uid != getuid()) {
1406 		warnx("%s: owner not root or current user", fname);
1407 		return (-1);
1408 	}
1409 	if (st.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO)) {
1410 		warnx("%s: group writable or world read/writable", fname);
1411 		return (-1);
1412 	}
1413 	return (0);
1414 }
1415 
1416 struct file *
1417 pushfile(const char *name, int secret)
1418 {
1419 	struct file	*nfile;
1420 
1421 	if ((nfile = calloc(1, sizeof(struct file))) == NULL) {
1422 		warn("malloc");
1423 		return (NULL);
1424 	}
1425 	if ((nfile->name = strdup(name)) == NULL) {
1426 		warn("malloc");
1427 		free(nfile);
1428 		return (NULL);
1429 	}
1430 	if (TAILQ_FIRST(&files) == NULL && strcmp(nfile->name, "-") == 0) {
1431 		nfile->stream = stdin;
1432 		free(nfile->name);
1433 		if ((nfile->name = strdup("stdin")) == NULL) {
1434 			warn("strdup");
1435 			free(nfile);
1436 			return (NULL);
1437 		}
1438 	} else if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
1439 		warn("%s", nfile->name);
1440 		free(nfile->name);
1441 		free(nfile);
1442 		return (NULL);
1443 	} else if (secret &&
1444 	    check_file_secrecy(fileno(nfile->stream), nfile->name)) {
1445 		fclose(nfile->stream);
1446 		free(nfile->name);
1447 		free(nfile);
1448 		return (NULL);
1449 	}
1450 	nfile->lineno = 1;
1451 	TAILQ_INSERT_TAIL(&files, nfile, entry);
1452 	return (nfile);
1453 }
1454 
1455 int
1456 popfile(void)
1457 {
1458 	struct file	*prev;
1459 
1460 	if ((prev = TAILQ_PREV(file, files, entry)) != NULL) {
1461 		prev->errors += file->errors;
1462 		TAILQ_REMOVE(&files, file, entry);
1463 		fclose(file->stream);
1464 		free(file->name);
1465 		free(file);
1466 		file = prev;
1467 		return (0);
1468 	}
1469 	return (EOF);
1470 }
1471 
1472 int
1473 parse_config(const char *filename, struct iked *x_env)
1474 {
1475 	struct sym	*sym;
1476 	int		 errors = 0;
1477 
1478 	env = x_env;
1479 	rules = 0;
1480 
1481 	if ((file = pushfile(filename, 1)) == NULL)
1482 		return (-1);
1483 
1484 	decouple = passive = 0;
1485 
1486 	if (env->sc_opts & IKED_OPT_PASSIVE)
1487 		passive = 1;
1488 
1489 	yyparse();
1490 	errors = file->errors;
1491 	popfile();
1492 
1493 	env->sc_passive = passive ? 1 : 0;
1494 	env->sc_decoupled = decouple ? 1 : 0;
1495 	env->sc_ocsp_url = ocsp_url;
1496 
1497 	if (!rules)
1498 		log_warnx("%s: no valid configuration rules found",
1499 		    filename);
1500 	else
1501 		log_debug("%s: loaded %d configuration rules",
1502 		    filename, rules);
1503 
1504 	/* Free macros and check which have not been used. */
1505 	while ((sym = TAILQ_FIRST(&symhead))) {
1506 		if (!sym->used)
1507 			log_debug("warning: macro '%s' not "
1508 			    "used\n", sym->nam);
1509 		free(sym->nam);
1510 		free(sym->val);
1511 		TAILQ_REMOVE(&symhead, sym, entry);
1512 		free(sym);
1513 	}
1514 
1515 	return (errors ? -1 : 0);
1516 }
1517 
1518 int
1519 symset(const char *nam, const char *val, int persist)
1520 {
1521 	struct sym	*sym;
1522 
1523 	for (sym = TAILQ_FIRST(&symhead); sym && strcmp(nam, sym->nam);
1524 	    sym = TAILQ_NEXT(sym, entry))
1525 		;	/* nothing */
1526 
1527 	if (sym != NULL) {
1528 		if (sym->persist == 1)
1529 			return (0);
1530 		else {
1531 			free(sym->nam);
1532 			free(sym->val);
1533 			TAILQ_REMOVE(&symhead, sym, entry);
1534 			free(sym);
1535 		}
1536 	}
1537 	if ((sym = calloc(1, sizeof(*sym))) == NULL)
1538 		return (-1);
1539 
1540 	sym->nam = strdup(nam);
1541 	if (sym->nam == NULL) {
1542 		free(sym);
1543 		return (-1);
1544 	}
1545 	sym->val = strdup(val);
1546 	if (sym->val == NULL) {
1547 		free(sym->nam);
1548 		free(sym);
1549 		return (-1);
1550 	}
1551 	sym->used = 0;
1552 	sym->persist = persist;
1553 	TAILQ_INSERT_TAIL(&symhead, sym, entry);
1554 	return (0);
1555 }
1556 
1557 int
1558 cmdline_symset(char *s)
1559 {
1560 	char	*sym, *val;
1561 	int	ret;
1562 	size_t	len;
1563 
1564 	if ((val = strrchr(s, '=')) == NULL)
1565 		return (-1);
1566 
1567 	len = strlen(s) - strlen(val) + 1;
1568 	if ((sym = malloc(len)) == NULL)
1569 		err(1, "cmdline_symset: malloc");
1570 
1571 	strlcpy(sym, s, len);
1572 
1573 	ret = symset(sym, val + 1, 1);
1574 	free(sym);
1575 
1576 	return (ret);
1577 }
1578 
1579 char *
1580 symget(const char *nam)
1581 {
1582 	struct sym	*sym;
1583 
1584 	TAILQ_FOREACH(sym, &symhead, entry)
1585 		if (strcmp(nam, sym->nam) == 0) {
1586 			sym->used = 1;
1587 			return (sym->val);
1588 		}
1589 	return (NULL);
1590 }
1591 
1592 uint8_t
1593 x2i(unsigned char *s)
1594 {
1595 	char	ss[3];
1596 
1597 	ss[0] = s[0];
1598 	ss[1] = s[1];
1599 	ss[2] = 0;
1600 
1601 	if (!isxdigit(s[0]) || !isxdigit(s[1])) {
1602 		yyerror("keys need to be specified in hex digits");
1603 		return (-1);
1604 	}
1605 	return ((uint8_t)strtoul(ss, NULL, 16));
1606 }
1607 
1608 int
1609 parsekey(unsigned char *hexkey, size_t len, struct iked_auth *auth)
1610 {
1611 	unsigned int	  i;
1612 
1613 	bzero(auth, sizeof(*auth));
1614 	if ((len / 2) > sizeof(auth->auth_data))
1615 		return (-1);
1616 	auth->auth_length = len / 2;
1617 
1618 	for (i = 0; i < auth->auth_length; i++)
1619 		auth->auth_data[i] = x2i(hexkey + 2 * i);
1620 
1621 	return (0);
1622 }
1623 
1624 int
1625 parsekeyfile(char *filename, struct iked_auth *auth)
1626 {
1627 	struct stat	 sb;
1628 	int		 fd, ret;
1629 	unsigned char	*hex;
1630 
1631 	if ((fd = open(filename, O_RDONLY)) < 0)
1632 		err(1, "open %s", filename);
1633 	if (fstat(fd, &sb) < 0)
1634 		err(1, "parsekeyfile: stat %s", filename);
1635 	if ((sb.st_size > KEYSIZE_LIMIT) || (sb.st_size == 0))
1636 		errx(1, "%s: key too %s", filename, sb.st_size ? "large" :
1637 		    "small");
1638 	if ((hex = calloc(sb.st_size, sizeof(unsigned char))) == NULL)
1639 		err(1, "parsekeyfile: calloc");
1640 	if (read(fd, hex, sb.st_size) < sb.st_size)
1641 		err(1, "parsekeyfile: read");
1642 	close(fd);
1643 	ret = parsekey(hex, sb.st_size, auth);
1644 	free(hex);
1645 	return (ret);
1646 }
1647 
1648 int
1649 get_id_type(char *string)
1650 {
1651 	struct in6_addr ia;
1652 
1653 	if (string == NULL)
1654 		return (IKEV2_ID_NONE);
1655 
1656 	if (*string == '/')
1657 		return (IKEV2_ID_ASN1_DN);
1658 	else if (inet_pton(AF_INET, string, &ia) == 1)
1659 		return (IKEV2_ID_IPV4);
1660 	else if (inet_pton(AF_INET6, string, &ia) == 1)
1661 		return (IKEV2_ID_IPV6);
1662 	else if (strchr(string, '@'))
1663 		return (IKEV2_ID_UFQDN);
1664 	else
1665 		return (IKEV2_ID_FQDN);
1666 }
1667 
1668 int
1669 check_pubkey(char *idstr, int type)
1670 {
1671 	char		 keyfile[PATH_MAX];
1672 	FILE		*fp = NULL;
1673 	const char	*suffix = NULL;
1674 
1675 	switch (type) {
1676 	case IKEV2_ID_IPV4:
1677 		suffix = "ipv4";
1678 		break;
1679 	case IKEV2_ID_IPV6:
1680 		suffix = "ipv6";
1681 		break;
1682 	case IKEV2_ID_FQDN:
1683 		suffix = "fqdn";
1684 		break;
1685 	case IKEV2_ID_UFQDN:
1686 		suffix = "ufqdn";
1687 		break;
1688 	default:
1689 		/* Unspecified ID or public key not supported for this type */
1690 		return (-1);
1691 	}
1692 
1693 	lc_string(idstr);
1694 	if ((size_t)snprintf(keyfile, sizeof(keyfile),
1695 	    IKED_CA IKED_PUBKEY_DIR "%s/%s", suffix,
1696 	    idstr) >= sizeof(keyfile)) {
1697 		log_warnx("%s: public key path is too long", __func__);
1698 		return (-1);
1699 	}
1700 
1701 	if ((fp = fopen(keyfile, "r")) == NULL)
1702 		return (-1);
1703 	fclose(fp);
1704 
1705 	log_debug("%s: found public key file %s", __func__, keyfile);
1706 
1707 	return (0);
1708 }
1709 
1710 struct ipsec_addr_wrap *
1711 host(const char *s)
1712 {
1713 	struct ipsec_addr_wrap	*ipa = NULL;
1714 	int			 mask, cont = 1;
1715 	char			*p, *q, *ps;
1716 
1717 	if ((p = strrchr(s, '/')) != NULL) {
1718 		errno = 0;
1719 		mask = strtol(p + 1, &q, 0);
1720 		if (errno == ERANGE || !q || *q || mask > 128 || q == (p + 1))
1721 			errx(1, "host: invalid netmask '%s'", p);
1722 		if ((ps = malloc(strlen(s) - strlen(p) + 1)) == NULL)
1723 			err(1, "host: calloc");
1724 		strlcpy(ps, s, strlen(s) - strlen(p) + 1);
1725 	} else {
1726 		if ((ps = strdup(s)) == NULL)
1727 			err(1, "host: strdup");
1728 		mask = -1;
1729 	}
1730 
1731 	/* Does interface with this name exist? */
1732 	if (cont && (ipa = host_if(ps, mask)) != NULL)
1733 		cont = 0;
1734 
1735 	/* IPv4 address? */
1736 	if (cont && (ipa = host_v4(s, mask == -1 ? 32 : mask)) != NULL)
1737 		cont = 0;
1738 
1739 	/* IPv6 address? */
1740 	if (cont && (ipa = host_v6(ps, mask == -1 ? 128 : mask)) != NULL)
1741 		cont = 0;
1742 
1743 	/* dns lookup */
1744 	if (cont && mask == -1 && (ipa = host_dns(s, mask)) != NULL)
1745 		cont = 0;
1746 	free(ps);
1747 
1748 	if (ipa == NULL || cont == 1) {
1749 		fprintf(stderr, "no IP address found for %s\n", s);
1750 		return (NULL);
1751 	}
1752 	return (ipa);
1753 }
1754 
1755 struct ipsec_addr_wrap *
1756 host_v6(const char *s, int prefixlen)
1757 {
1758 	struct ipsec_addr_wrap	*ipa = NULL;
1759 	struct addrinfo		 hints, *res;
1760 	char			 hbuf[NI_MAXHOST];
1761 
1762 	bzero(&hints, sizeof(struct addrinfo));
1763 	hints.ai_family = AF_INET6;
1764 	hints.ai_socktype = SOCK_STREAM;
1765 	hints.ai_flags = AI_NUMERICHOST;
1766 	if (getaddrinfo(s, NULL, &hints, &res))
1767 		return (NULL);
1768 	if (res->ai_next)
1769 		err(1, "host_v6: numeric hostname expanded to multiple item");
1770 
1771 	ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1772 	if (ipa == NULL)
1773 		err(1, "host_v6: calloc");
1774 	ipa->af = res->ai_family;
1775 	memcpy(&ipa->address, res->ai_addr, sizeof(struct sockaddr_in6));
1776 	if (prefixlen > 128)
1777 		prefixlen = 128;
1778 	ipa->next = NULL;
1779 	ipa->tail = ipa;
1780 
1781 	set_ipmask(ipa, prefixlen);
1782 	if (getnameinfo(res->ai_addr, res->ai_addrlen,
1783 	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST)) {
1784 		errx(1, "could not get a numeric hostname");
1785 	}
1786 
1787 	if (prefixlen != 128) {
1788 		ipa->netaddress = 1;
1789 		if (asprintf(&ipa->name, "%s/%d", hbuf, prefixlen) == -1)
1790 			err(1, "host_v6: asprintf");
1791 	} else {
1792 		if ((ipa->name = strdup(hbuf)) == NULL)
1793 			err(1, "host_v6: strdup");
1794 	}
1795 
1796 	freeaddrinfo(res);
1797 
1798 	return (ipa);
1799 }
1800 
1801 struct ipsec_addr_wrap *
1802 host_v4(const char *s, int mask)
1803 {
1804 	struct ipsec_addr_wrap	*ipa = NULL;
1805 	struct sockaddr_in	 ina;
1806 	int			 bits = 32;
1807 
1808 	bzero(&ina, sizeof(ina));
1809 	if (strrchr(s, '/') != NULL) {
1810 		if ((bits = inet_net_pton(AF_INET, s, &ina.sin_addr,
1811 		    sizeof(ina.sin_addr))) == -1)
1812 			return (NULL);
1813 	} else {
1814 		if (inet_pton(AF_INET, s, &ina.sin_addr) != 1)
1815 			return (NULL);
1816 	}
1817 
1818 	ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1819 	if (ipa == NULL)
1820 		err(1, "host_v4: calloc");
1821 
1822 	ina.sin_family = AF_INET;
1823 	ina.sin_len = sizeof(ina);
1824 	memcpy(&ipa->address, &ina, sizeof(ina));
1825 
1826 	ipa->name = strdup(s);
1827 	if (ipa->name == NULL)
1828 		err(1, "host_v4: strdup");
1829 	ipa->af = AF_INET;
1830 	ipa->next = NULL;
1831 	ipa->tail = ipa;
1832 
1833 	set_ipmask(ipa, bits);
1834 	if (strrchr(s, '/') != NULL)
1835 		ipa->netaddress = 1;
1836 
1837 	return (ipa);
1838 }
1839 
1840 struct ipsec_addr_wrap *
1841 host_dns(const char *s, int mask)
1842 {
1843 	struct ipsec_addr_wrap	*ipa = NULL, *head = NULL;
1844 	struct addrinfo		 hints, *res0, *res;
1845 	int			 error;
1846 	char			 hbuf[NI_MAXHOST];
1847 
1848 	bzero(&hints, sizeof(struct addrinfo));
1849 	hints.ai_family = PF_UNSPEC;
1850 	hints.ai_socktype = SOCK_STREAM;
1851 	hints.ai_flags = AI_ADDRCONFIG;
1852 	error = getaddrinfo(s, NULL, &hints, &res0);
1853 	if (error)
1854 		return (NULL);
1855 
1856 	for (res = res0; res; res = res->ai_next) {
1857 		if (res->ai_family != AF_INET && res->ai_family != AF_INET6)
1858 			continue;
1859 
1860 		ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1861 		if (ipa == NULL)
1862 			err(1, "host_dns: calloc");
1863 		switch (res->ai_family) {
1864 		case AF_INET:
1865 			memcpy(&ipa->address, res->ai_addr,
1866 			    sizeof(struct sockaddr_in));
1867 			break;
1868 		case AF_INET6:
1869 			memcpy(&ipa->address, res->ai_addr,
1870 			    sizeof(struct sockaddr_in6));
1871 			break;
1872 		}
1873 		error = getnameinfo(res->ai_addr, res->ai_addrlen, hbuf,
1874 		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST);
1875 		if (error)
1876 			err(1, "host_dns: getnameinfo");
1877 		ipa->name = strdup(hbuf);
1878 		if (ipa->name == NULL)
1879 			err(1, "host_dns: strdup");
1880 		ipa->af = res->ai_family;
1881 		ipa->next = NULL;
1882 		ipa->tail = ipa;
1883 		if (head == NULL)
1884 			head = ipa;
1885 		else {
1886 			head->tail->next = ipa;
1887 			head->tail = ipa;
1888 		}
1889 
1890 		/*
1891 		 * XXX for now, no netmask support for IPv6.
1892 		 * but since there's no way to specify address family, once you
1893 		 * have IPv6 address on a host, you cannot use dns/netmask
1894 		 * syntax.
1895 		 */
1896 		if (ipa->af == AF_INET)
1897 			set_ipmask(ipa, mask == -1 ? 32 : mask);
1898 		else
1899 			if (mask != -1)
1900 				err(1, "host_dns: cannot apply netmask "
1901 				    "on non-IPv4 address");
1902 	}
1903 	freeaddrinfo(res0);
1904 
1905 	return (head);
1906 }
1907 
1908 struct ipsec_addr_wrap *
1909 host_if(const char *s, int mask)
1910 {
1911 	struct ipsec_addr_wrap *ipa = NULL;
1912 
1913 	if (ifa_exists(s))
1914 		ipa = ifa_lookup(s);
1915 
1916 	return (ipa);
1917 }
1918 
1919 struct ipsec_addr_wrap *
1920 host_any(void)
1921 {
1922 	struct ipsec_addr_wrap	*ipa;
1923 
1924 	ipa = calloc(1, sizeof(struct ipsec_addr_wrap));
1925 	if (ipa == NULL)
1926 		err(1, "host_any: calloc");
1927 	ipa->af = AF_UNSPEC;
1928 	ipa->netaddress = 1;
1929 	ipa->tail = ipa;
1930 	return (ipa);
1931 }
1932 
1933 /* interface lookup routintes */
1934 
1935 struct ipsec_addr_wrap	*iftab;
1936 
1937 void
1938 ifa_load(void)
1939 {
1940 	struct ifaddrs		*ifap, *ifa;
1941 	struct ipsec_addr_wrap	*n = NULL, *h = NULL;
1942 	struct sockaddr_in	*sa_in;
1943 	struct sockaddr_in6	*sa_in6;
1944 
1945 	if (getifaddrs(&ifap) < 0)
1946 		err(1, "ifa_load: getifaddrs");
1947 
1948 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1949 		if (!(ifa->ifa_addr->sa_family == AF_INET ||
1950 		    ifa->ifa_addr->sa_family == AF_INET6 ||
1951 		    ifa->ifa_addr->sa_family == AF_LINK))
1952 			continue;
1953 		n = calloc(1, sizeof(struct ipsec_addr_wrap));
1954 		if (n == NULL)
1955 			err(1, "ifa_load: calloc");
1956 		n->af = ifa->ifa_addr->sa_family;
1957 		if ((n->name = strdup(ifa->ifa_name)) == NULL)
1958 			err(1, "ifa_load: strdup");
1959 		if (n->af == AF_INET) {
1960 			sa_in = (struct sockaddr_in *)ifa->ifa_addr;
1961 			memcpy(&n->address, sa_in, sizeof(*sa_in));
1962 			sa_in = (struct sockaddr_in *)ifa->ifa_netmask;
1963 			n->mask = mask2prefixlen((struct sockaddr *)sa_in);
1964 		} else if (n->af == AF_INET6) {
1965 			sa_in6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1966 			memcpy(&n->address, sa_in6, sizeof(*sa_in6));
1967 			sa_in6 = (struct sockaddr_in6 *)ifa->ifa_netmask;
1968 			n->mask = mask2prefixlen6((struct sockaddr *)sa_in6);
1969 		}
1970 		n->next = NULL;
1971 		n->tail = n;
1972 		if (h == NULL)
1973 			h = n;
1974 		else {
1975 			h->tail->next = n;
1976 			h->tail = n;
1977 		}
1978 	}
1979 
1980 	iftab = h;
1981 	freeifaddrs(ifap);
1982 }
1983 
1984 int
1985 ifa_exists(const char *ifa_name)
1986 {
1987 	struct ipsec_addr_wrap	*n;
1988 	struct ifgroupreq	 ifgr;
1989 	int			 s;
1990 
1991 	if (iftab == NULL)
1992 		ifa_load();
1993 
1994 	/* check wether this is a group */
1995 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1996 		err(1, "ifa_exists: socket");
1997 	bzero(&ifgr, sizeof(ifgr));
1998 	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1999 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == 0) {
2000 		close(s);
2001 		return (1);
2002 	}
2003 	close(s);
2004 
2005 	for (n = iftab; n; n = n->next) {
2006 		if (n->af == AF_LINK && !strncmp(n->name, ifa_name,
2007 		    IFNAMSIZ))
2008 			return (1);
2009 	}
2010 
2011 	return (0);
2012 }
2013 
2014 struct ipsec_addr_wrap *
2015 ifa_grouplookup(const char *ifa_name)
2016 {
2017 	struct ifg_req		*ifg;
2018 	struct ifgroupreq	 ifgr;
2019 	int			 s;
2020 	size_t			 len;
2021 	struct ipsec_addr_wrap	*n, *h = NULL, *hn;
2022 
2023 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
2024 		err(1, "socket");
2025 	bzero(&ifgr, sizeof(ifgr));
2026 	strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
2027 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
2028 		close(s);
2029 		return (NULL);
2030 	}
2031 
2032 	len = ifgr.ifgr_len;
2033 	if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
2034 		err(1, "calloc");
2035 	if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
2036 		err(1, "ioctl");
2037 
2038 	for (ifg = ifgr.ifgr_groups; ifg && len >= sizeof(struct ifg_req);
2039 	    ifg++) {
2040 		len -= sizeof(struct ifg_req);
2041 		if ((n = ifa_lookup(ifg->ifgrq_member)) == NULL)
2042 			continue;
2043 		if (h == NULL)
2044 			h = n;
2045 		else {
2046 			for (hn = h; hn->next != NULL; hn = hn->next)
2047 				;	/* nothing */
2048 			hn->next = n;
2049 			n->tail = hn;
2050 		}
2051 	}
2052 	free(ifgr.ifgr_groups);
2053 	close(s);
2054 
2055 	return (h);
2056 }
2057 
2058 struct ipsec_addr_wrap *
2059 ifa_lookup(const char *ifa_name)
2060 {
2061 	struct ipsec_addr_wrap	*p = NULL, *h = NULL, *n = NULL;
2062 	struct sockaddr_in6	*in6;
2063 	uint8_t			*s6;
2064 
2065 	if (iftab == NULL)
2066 		ifa_load();
2067 
2068 	if ((n = ifa_grouplookup(ifa_name)) != NULL)
2069 		return (n);
2070 
2071 	for (p = iftab; p; p = p->next) {
2072 		if (p->af != AF_INET && p->af != AF_INET6)
2073 			continue;
2074 		if (strncmp(p->name, ifa_name, IFNAMSIZ))
2075 			continue;
2076 		n = calloc(1, sizeof(struct ipsec_addr_wrap));
2077 		if (n == NULL)
2078 			err(1, "ifa_lookup: calloc");
2079 		memcpy(n, p, sizeof(struct ipsec_addr_wrap));
2080 		if ((n->name = strdup(p->name)) == NULL)
2081 			err(1, "ifa_lookup: strdup");
2082 		switch (n->af) {
2083 		case AF_INET:
2084 			set_ipmask(n, 32);
2085 			break;
2086 		case AF_INET6:
2087 			in6 = (struct sockaddr_in6 *)&n->address;
2088 			s6 = (uint8_t *)&in6->sin6_addr.s6_addr;
2089 
2090 			/* route/show.c and bgpd/util.c give KAME credit */
2091 			if (IN6_IS_ADDR_LINKLOCAL(&in6->sin6_addr)) {
2092 				uint16_t	 tmp16;
2093 
2094 				/* for now we can not handle link local,
2095 				 * therefore bail for now
2096 				 */
2097 				free(n);
2098 				continue;
2099 
2100 				memcpy(&tmp16, &s6[2], sizeof(tmp16));
2101 				/* use this when we support link-local
2102 				 * n->??.scopeid = ntohs(tmp16);
2103 				 */
2104 				s6[2] = 0;
2105 				s6[3] = 0;
2106 			}
2107 			set_ipmask(n, 128);
2108 			break;
2109 		}
2110 
2111 		n->next = NULL;
2112 		n->tail = n;
2113 		if (h == NULL)
2114 			h = n;
2115 		else {
2116 			h->tail->next = n;
2117 			h->tail = n;
2118 		}
2119 	}
2120 
2121 	return (h);
2122 }
2123 
2124 void
2125 set_ipmask(struct ipsec_addr_wrap *address, uint8_t b)
2126 {
2127 	address->mask = b;
2128 }
2129 
2130 const struct ipsec_xf *
2131 parse_xf(const char *name, unsigned int length, const struct ipsec_xf xfs[])
2132 {
2133 	int		i;
2134 
2135 	for (i = 0; xfs[i].name != NULL; i++) {
2136 		if (strncmp(name, xfs[i].name, strlen(name)))
2137 			continue;
2138 		if (length == 0 || length == xfs[i].length)
2139 			return &xfs[i];
2140 	}
2141 	return (NULL);
2142 }
2143 
2144 const char *
2145 print_xf(unsigned int id, unsigned int length, const struct ipsec_xf xfs[])
2146 {
2147 	int		i;
2148 
2149 	for (i = 0; xfs[i].name != NULL; i++) {
2150 		if (xfs[i].id == id) {
2151 			if (length == 0 || length == xfs[i].length)
2152 				return (xfs[i].name);
2153 		}
2154 	}
2155 	return ("unknown");
2156 }
2157 
2158 size_t
2159 keylength_xf(unsigned int saproto, unsigned int type, unsigned int id)
2160 {
2161 	int			 i;
2162 	const struct ipsec_xf	*xfs;
2163 
2164 	switch (type) {
2165 	case IKEV2_XFORMTYPE_ENCR:
2166 		if (saproto == IKEV2_SAPROTO_IKE)
2167 			xfs = ikeencxfs;
2168 		else
2169 			xfs = ipsecencxfs;
2170 		break;
2171 	case IKEV2_XFORMTYPE_INTEGR:
2172 		xfs = authxfs;
2173 		break;
2174 	default:
2175 		return (0);
2176 	}
2177 
2178 	for (i = 0; xfs[i].name != NULL; i++) {
2179 		if (xfs[i].id == id)
2180 			return (xfs[i].length * 8);
2181 	}
2182 	return (0);
2183 }
2184 
2185 size_t
2186 noncelength_xf(unsigned int type, unsigned int id)
2187 {
2188 	const struct ipsec_xf	*xfs = ipsecencxfs;
2189 	int			 i;
2190 
2191 	if (type != IKEV2_XFORMTYPE_ENCR)
2192 		return (0);
2193 
2194 	for (i = 0; xfs[i].name != NULL; i++)
2195 		if (xfs[i].id == id)
2196 			return (xfs[i].nonce * 8);
2197 	return (0);
2198 }
2199 
2200 void
2201 print_user(struct iked_user *usr)
2202 {
2203 	print_verbose("user \"%s\" \"%s\"\n", usr->usr_name, usr->usr_pass);
2204 }
2205 
2206 void
2207 print_policy(struct iked_policy *pol)
2208 {
2209 	struct iked_proposal	*pp;
2210 	struct iked_transform	*xform;
2211 	struct iked_flow	*flow;
2212 	struct iked_cfg		*cfg;
2213 	unsigned int		 i, j;
2214 	const struct ipsec_xf	*xfs = NULL;
2215 
2216 	print_verbose("ikev2");
2217 
2218 	if (pol->pol_name[0] != '\0')
2219 		print_verbose(" \"%s\"", pol->pol_name);
2220 
2221 	if (pol->pol_flags & IKED_POLICY_DEFAULT)
2222 		print_verbose(" default");
2223 	else if (pol->pol_flags & IKED_POLICY_QUICK)
2224 		print_verbose(" quick");
2225 	else if (pol->pol_flags & IKED_POLICY_SKIP)
2226 		print_verbose(" skip");
2227 
2228 	if (pol->pol_flags & IKED_POLICY_ACTIVE)
2229 		print_verbose(" active");
2230 	else
2231 		print_verbose(" passive");
2232 
2233 	print_verbose(" %s", print_xf(pol->pol_saproto, 0, saxfs));
2234 
2235 	if (pol->pol_ipproto)
2236 		print_verbose(" proto %s", print_proto(pol->pol_ipproto));
2237 
2238 	if (pol->pol_af) {
2239 		if (pol->pol_af == AF_INET)
2240 			print_verbose(" inet");
2241 		else
2242 			print_verbose(" inet6");
2243 	}
2244 
2245 	RB_FOREACH(flow, iked_flows, &pol->pol_flows) {
2246 		print_verbose(" from %s",
2247 		    print_host((struct sockaddr *)&flow->flow_src.addr, NULL,
2248 		    0));
2249 		if (flow->flow_src.addr_af != AF_UNSPEC &&
2250 		    flow->flow_src.addr_net)
2251 			print_verbose("/%d", flow->flow_src.addr_mask);
2252 		if (flow->flow_src.addr_port)
2253 			print_verbose(" port %d",
2254 			    ntohs(flow->flow_src.addr_port));
2255 
2256 		print_verbose(" to %s",
2257 		    print_host((struct sockaddr *)&flow->flow_dst.addr, NULL,
2258 		    0));
2259 		if (flow->flow_dst.addr_af != AF_UNSPEC &&
2260 		    flow->flow_dst.addr_net)
2261 			print_verbose("/%d", flow->flow_dst.addr_mask);
2262 		if (flow->flow_dst.addr_port)
2263 			print_verbose(" port %d",
2264 			    ntohs(flow->flow_dst.addr_port));
2265 	}
2266 
2267 	if ((pol->pol_flags & IKED_POLICY_DEFAULT) == 0) {
2268 		print_verbose(" local %s",
2269 		    print_host((struct sockaddr *)&pol->pol_local.addr, NULL,
2270 		    0));
2271 		if (pol->pol_local.addr.ss_family != AF_UNSPEC &&
2272 		    pol->pol_local.addr_net)
2273 			print_verbose("/%d", pol->pol_local.addr_mask);
2274 
2275 		print_verbose(" peer %s",
2276 		    print_host((struct sockaddr *)&pol->pol_peer.addr, NULL,
2277 		    0));
2278 		if (pol->pol_peer.addr.ss_family != AF_UNSPEC &&
2279 		    pol->pol_peer.addr_net)
2280 			print_verbose("/%d", pol->pol_peer.addr_mask);
2281 	}
2282 
2283 	TAILQ_FOREACH(pp, &pol->pol_proposals, prop_entry) {
2284 		if (!pp->prop_nxforms)
2285 			continue;
2286 		if (pp->prop_protoid == IKEV2_SAPROTO_IKE)
2287 			print_verbose(" ikesa");
2288 		else
2289 			print_verbose(" childsa");
2290 
2291 		for (j = 0; ikev2_xformtype_map[j].cm_type != 0; j++) {
2292 			xfs = NULL;
2293 
2294 			for (i = 0; i < pp->prop_nxforms; i++) {
2295 				xform = pp->prop_xforms + i;
2296 
2297 				if (xform->xform_type !=
2298 				    ikev2_xformtype_map[j].cm_type)
2299 					continue;
2300 
2301 				if (xfs != NULL) {
2302 					print_verbose(",");
2303 				} else {
2304 					switch (xform->xform_type) {
2305 					case IKEV2_XFORMTYPE_INTEGR:
2306 						print_verbose(" auth ");
2307 						xfs = authxfs;
2308 						break;
2309 					case IKEV2_XFORMTYPE_ENCR:
2310 						print_verbose(" enc ");
2311 						if (pp->prop_protoid ==
2312 						    IKEV2_SAPROTO_IKE)
2313 							xfs = ikeencxfs;
2314 						else
2315 							xfs = ipsecencxfs;
2316 						break;
2317 					case IKEV2_XFORMTYPE_PRF:
2318 						print_verbose(" prf ");
2319 						xfs = prfxfs;
2320 						break;
2321 					case IKEV2_XFORMTYPE_DH:
2322 						print_verbose(" group ");
2323 						xfs = groupxfs;
2324 						break;
2325 					default:
2326 						continue;
2327 					}
2328 				}
2329 
2330 				print_verbose("%s", print_xf(xform->xform_id,
2331 				    xform->xform_length / 8, xfs));
2332 			}
2333 		}
2334 	}
2335 
2336 	if (pol->pol_localid.id_length != 0)
2337 		print_verbose(" srcid %s", pol->pol_localid.id_data);
2338 	if (pol->pol_peerid.id_length != 0)
2339 		print_verbose(" dstid %s", pol->pol_peerid.id_data);
2340 
2341 	if (pol->pol_rekey)
2342 		print_verbose(" ikelifetime %u", pol->pol_rekey);
2343 
2344 	print_verbose(" lifetime %llu bytes %llu",
2345 	    pol->pol_lifetime.lt_seconds, pol->pol_lifetime.lt_bytes);
2346 
2347 	if (pol->pol_auth.auth_method == IKEV2_AUTH_SHARED_KEY_MIC) {
2348 			print_verbose(" psk 0x");
2349 			for (i = 0; i < pol->pol_auth.auth_length; i++)
2350 				print_verbose("%02x",
2351 				    pol->pol_auth.auth_data[i]);
2352 	} else {
2353 		if (pol->pol_auth.auth_eap)
2354 			print_verbose(" eap \"%s\"",
2355 			    print_map(pol->pol_auth.auth_eap, eap_type_map));
2356 		else
2357 			print_verbose(" %s",
2358 			    print_xf(pol->pol_auth.auth_method, 0, methodxfs));
2359 	}
2360 
2361 	for (i = 0; i < pol->pol_ncfg; i++) {
2362 		cfg = &pol->pol_cfg[i];
2363 		print_verbose(" config %s %s", print_xf(cfg->cfg_type,
2364 		    cfg->cfg.address.addr_af, cpxfs),
2365 		    print_host((struct sockaddr *)&cfg->cfg.address.addr, NULL,
2366 		    0));
2367 	}
2368 
2369 	if (pol->pol_tag[0] != '\0')
2370 		print_verbose(" tag \"%s\"", pol->pol_tag);
2371 
2372 	if (pol->pol_tap != 0)
2373 		print_verbose(" tap \"enc%u\"", pol->pol_tap);
2374 
2375 	print_verbose("\n");
2376 }
2377 
2378 void
2379 copy_transforms(unsigned int type, const struct ipsec_xf *xf,
2380     const struct ipsec_xf *xfs,
2381     struct iked_transform *dst, size_t ndst,
2382     unsigned int *n, struct iked_transform *src, size_t nsrc)
2383 {
2384 	unsigned int		 i;
2385 	struct iked_transform	*a, *b;
2386 
2387 	if (xf != NULL) {
2388 		if (*n >= ndst)
2389 			return;
2390 		b = dst + (*n)++;
2391 
2392 		b->xform_type = type;
2393 		b->xform_id = xf->id;
2394 		b->xform_keylength = xf->length * 8;
2395 		b->xform_length = xf->keylength * 8;
2396 		return;
2397 	}
2398 
2399 	for (i = 0; i < nsrc; i++) {
2400 		a = src + i;
2401 		if (a->xform_type != type)
2402 			continue;
2403 		if (*n >= ndst)
2404 			return;
2405 		b = dst + (*n)++;
2406 		memcpy(b, a, sizeof(*b));
2407 	}
2408 }
2409 
2410 int
2411 create_ike(char *name, int af, uint8_t ipproto, struct ipsec_hosts *hosts,
2412     struct ipsec_hosts *peers, struct ipsec_mode *ike_sa,
2413     struct ipsec_mode *ipsec_sa, uint8_t saproto,
2414     uint8_t flags, char *srcid, char *dstid,
2415     uint32_t ikelifetime, struct iked_lifetime *lt,
2416     struct iked_auth *authtype, struct ipsec_filters *filter,
2417     struct ipsec_addr_wrap *ikecfg)
2418 {
2419 	char			 idstr[IKED_ID_SIZE];
2420 	unsigned int		 idtype = IKEV2_ID_NONE;
2421 	struct ipsec_addr_wrap	*ipa, *ipb, *ippn;
2422 	struct iked_policy	 pol;
2423 	struct iked_proposal	 prop[2];
2424 	unsigned int		 j;
2425 	struct iked_transform	 ikexforms[64], ipsecxforms[64];
2426 	struct iked_flow	 flows[64];
2427 	static unsigned int	 policy_id = 0;
2428 	struct iked_cfg		*cfg;
2429 
2430 	bzero(&pol, sizeof(pol));
2431 	bzero(&prop, sizeof(prop));
2432 	bzero(idstr, sizeof(idstr));
2433 
2434 	pol.pol_id = ++policy_id;
2435 	pol.pol_certreqtype = env->sc_certreqtype;
2436 	pol.pol_af = af;
2437 	pol.pol_saproto = saproto;
2438 	pol.pol_ipproto = ipproto;
2439 	pol.pol_flags = flags;
2440 	memcpy(&pol.pol_auth, authtype, sizeof(struct iked_auth));
2441 
2442 	if (name != NULL) {
2443 		if (strlcpy(pol.pol_name, name,
2444 		    sizeof(pol.pol_name)) >= sizeof(pol.pol_name)) {
2445 			yyerror("name too long");
2446 			return (-1);
2447 		}
2448 	} else {
2449 		snprintf(pol.pol_name, sizeof(pol.pol_name),
2450 		    "policy%d", policy_id);
2451 	}
2452 
2453 	if (srcid) {
2454 		pol.pol_localid.id_type = get_id_type(srcid);
2455 		pol.pol_localid.id_length = strlen(srcid);
2456 		if (strlcpy((char *)pol.pol_localid.id_data,
2457 		    srcid, IKED_ID_SIZE) >= IKED_ID_SIZE) {
2458 			yyerror("srcid too long");
2459 			return (-1);
2460 		}
2461 	}
2462 	if (dstid) {
2463 		pol.pol_peerid.id_type = get_id_type(dstid);
2464 		pol.pol_peerid.id_length = strlen(dstid);
2465 		if (strlcpy((char *)pol.pol_peerid.id_data,
2466 		    dstid, IKED_ID_SIZE) >= IKED_ID_SIZE) {
2467 			yyerror("dstid too long");
2468 			return (-1);
2469 		}
2470 	}
2471 
2472 	if (filter != NULL) {
2473 		if (filter->tag)
2474 			strlcpy(pol.pol_tag, filter->tag, sizeof(pol.pol_tag));
2475 		pol.pol_tap = filter->tap;
2476 	}
2477 
2478 	if (peers == NULL) {
2479 		if (pol.pol_flags & IKED_POLICY_ACTIVE) {
2480 			yyerror("active mode requires peer specification");
2481 			return (-1);
2482 		}
2483 		pol.pol_flags |= IKED_POLICY_DEFAULT|IKED_POLICY_SKIP;
2484 	}
2485 
2486 	if (peers && peers->src && peers->dst &&
2487 	    (peers->src->af != AF_UNSPEC) && (peers->dst->af != AF_UNSPEC) &&
2488 	    (peers->src->af != peers->dst->af))
2489 		fatalx("create_ike: peer address family mismatch");
2490 
2491 	if (peers && (pol.pol_af != AF_UNSPEC) &&
2492 	    ((peers->src && (peers->src->af != AF_UNSPEC) &&
2493 	    (peers->src->af != pol.pol_af)) ||
2494 	    (peers->dst && (peers->dst->af != AF_UNSPEC) &&
2495 	    (peers->dst->af != pol.pol_af))))
2496 		fatalx("create_ike: policy address family mismatch");
2497 
2498 	ipa = ipb = NULL;
2499 	if (peers) {
2500 		if (peers->src)
2501 			ipa = peers->src;
2502 		if (peers->dst)
2503 			ipb = peers->dst;
2504 		if (ipa == NULL && ipb == NULL) {
2505 			if (hosts->src && hosts->src->next == NULL)
2506 				ipa = hosts->src;
2507 			if (hosts->dst && hosts->dst->next == NULL)
2508 				ipb = hosts->dst;
2509 		}
2510 	}
2511 	if (ipa == NULL && ipb == NULL) {
2512 		yyerror("could not get local/peer specification");
2513 		return (-1);
2514 	}
2515 	if (pol.pol_flags & IKED_POLICY_ACTIVE) {
2516 		if (ipb == NULL || ipb->netaddress ||
2517 		    (ipa != NULL && ipa->netaddress)) {
2518 			yyerror("active mode requires local/peer address");
2519 			return (-1);
2520 		}
2521 	}
2522 	if (ipa) {
2523 		memcpy(&pol.pol_local.addr, &ipa->address,
2524 		    sizeof(ipa->address));
2525 		pol.pol_local.addr_af = ipa->af;
2526 		pol.pol_local.addr_mask = ipa->mask;
2527 		pol.pol_local.addr_net = ipa->netaddress;
2528 		if (pol.pol_af == AF_UNSPEC)
2529 			pol.pol_af = ipa->af;
2530 	}
2531 	if (ipb) {
2532 		memcpy(&pol.pol_peer.addr, &ipb->address,
2533 		    sizeof(ipb->address));
2534 		pol.pol_peer.addr_af = ipb->af;
2535 		pol.pol_peer.addr_mask = ipb->mask;
2536 		pol.pol_peer.addr_net = ipb->netaddress;
2537 		if (pol.pol_af == AF_UNSPEC)
2538 			pol.pol_af = ipb->af;
2539 	}
2540 
2541 	if (ikelifetime)
2542 		pol.pol_rekey = ikelifetime;
2543 
2544 	if (lt)
2545 		pol.pol_lifetime = *lt;
2546 	else
2547 		pol.pol_lifetime = deflifetime;
2548 
2549 	TAILQ_INIT(&pol.pol_proposals);
2550 	RB_INIT(&pol.pol_flows);
2551 
2552 	prop[0].prop_id = ++pol.pol_nproposals;
2553 	prop[0].prop_protoid = IKEV2_SAPROTO_IKE;
2554 	if (ike_sa == NULL || ike_sa->xfs == NULL) {
2555 		prop[0].prop_nxforms = ikev2_default_nike_transforms;
2556 		prop[0].prop_xforms = ikev2_default_ike_transforms;
2557 	} else {
2558 		j = 0;
2559 		copy_transforms(IKEV2_XFORMTYPE_INTEGR,
2560 		    ike_sa->xfs->authxf, authxfs,
2561 		    ikexforms, nitems(ikexforms), &j,
2562 		    ikev2_default_ike_transforms,
2563 		    ikev2_default_nike_transforms);
2564 		copy_transforms(IKEV2_XFORMTYPE_ENCR,
2565 		    ike_sa->xfs->encxf, ikeencxfs,
2566 		    ikexforms, nitems(ikexforms), &j,
2567 		    ikev2_default_ike_transforms,
2568 		    ikev2_default_nike_transforms);
2569 		copy_transforms(IKEV2_XFORMTYPE_DH,
2570 		    ike_sa->xfs->groupxf, groupxfs,
2571 		    ikexforms, nitems(ikexforms), &j,
2572 		    ikev2_default_ike_transforms,
2573 		    ikev2_default_nike_transforms);
2574 		copy_transforms(IKEV2_XFORMTYPE_PRF,
2575 		    ike_sa->xfs->prfxf, prfxfs,
2576 		    ikexforms, nitems(ikexforms), &j,
2577 		    ikev2_default_ike_transforms,
2578 		    ikev2_default_nike_transforms);
2579 		prop[0].prop_nxforms = j;
2580 		prop[0].prop_xforms = ikexforms;
2581 	}
2582 	TAILQ_INSERT_TAIL(&pol.pol_proposals, &prop[0], prop_entry);
2583 
2584 	prop[1].prop_id = ++pol.pol_nproposals;
2585 	prop[1].prop_protoid = saproto;
2586 	if (ipsec_sa == NULL || ipsec_sa->xfs == NULL) {
2587 		prop[1].prop_nxforms = ikev2_default_nesp_transforms;
2588 		prop[1].prop_xforms = ikev2_default_esp_transforms;
2589 	} else {
2590 		j = 0;
2591 		if (ipsec_sa->xfs->encxf && ipsec_sa->xfs->encxf->noauth &&
2592 		    ipsec_sa->xfs->authxf) {
2593 			yyerror("authentication is implicit for %s",
2594 			    ipsec_sa->xfs->encxf->name);
2595 			return (-1);
2596 		}
2597 		if (ipsec_sa->xfs->encxf == NULL ||
2598 		    (ipsec_sa->xfs->encxf && !ipsec_sa->xfs->encxf->noauth))
2599 			copy_transforms(IKEV2_XFORMTYPE_INTEGR,
2600 			    ipsec_sa->xfs->authxf, authxfs,
2601 			    ipsecxforms, nitems(ipsecxforms), &j,
2602 			    ikev2_default_esp_transforms,
2603 			    ikev2_default_nesp_transforms);
2604 		copy_transforms(IKEV2_XFORMTYPE_ENCR,
2605 		    ipsec_sa->xfs->encxf, ipsecencxfs,
2606 		    ipsecxforms, nitems(ipsecxforms), &j,
2607 		    ikev2_default_esp_transforms,
2608 		    ikev2_default_nesp_transforms);
2609 		copy_transforms(IKEV2_XFORMTYPE_DH,
2610 		    ipsec_sa->xfs->groupxf, groupxfs,
2611 		    ipsecxforms, nitems(ipsecxforms), &j,
2612 		    ikev2_default_esp_transforms,
2613 		    ikev2_default_nesp_transforms);
2614 		copy_transforms(IKEV2_XFORMTYPE_ESN,
2615 		    NULL, NULL,
2616 		    ipsecxforms, nitems(ipsecxforms), &j,
2617 		    ikev2_default_esp_transforms,
2618 		    ikev2_default_nesp_transforms);
2619 		prop[1].prop_nxforms = j;
2620 		prop[1].prop_xforms = ipsecxforms;
2621 	}
2622 	TAILQ_INSERT_TAIL(&pol.pol_proposals, &prop[1], prop_entry);
2623 
2624 	if (hosts == NULL || hosts->src == NULL || hosts->dst == NULL)
2625 		fatalx("create_ike: no traffic selectors/flows");
2626 
2627 	for (j = 0, ipa = hosts->src, ipb = hosts->dst; ipa && ipb;
2628 	    ipa = ipa->next, ipb = ipb->next, j++) {
2629 		memcpy(&flows[j].flow_src.addr, &ipa->address,
2630 		    sizeof(ipa->address));
2631 		flows[j].flow_src.addr_af = ipa->af;
2632 		flows[j].flow_src.addr_mask = ipa->mask;
2633 		flows[j].flow_src.addr_net = ipa->netaddress;
2634 		flows[j].flow_src.addr_port = hosts->sport;
2635 
2636 		memcpy(&flows[j].flow_dst.addr, &ipb->address,
2637 		    sizeof(ipb->address));
2638 		flows[j].flow_dst.addr_af = ipb->af;
2639 		flows[j].flow_dst.addr_mask = ipb->mask;
2640 		flows[j].flow_dst.addr_net = ipb->netaddress;
2641 		flows[j].flow_dst.addr_port = hosts->dport;
2642 
2643 		ippn = ipa->srcnat;
2644 		if (ippn) {
2645 			memcpy(&flows[j].flow_prenat.addr, &ippn->address,
2646 			    sizeof(ippn->address));
2647 			flows[j].flow_prenat.addr_af = ippn->af;
2648 			flows[j].flow_prenat.addr_mask = ippn->mask;
2649 			flows[j].flow_prenat.addr_net = ippn->netaddress;
2650 		} else {
2651 			flows[j].flow_prenat.addr_af = 0;
2652 		}
2653 
2654 		flows[j].flow_ipproto = ipproto;
2655 
2656 		pol.pol_nflows++;
2657 		RB_INSERT(iked_flows, &pol.pol_flows, &flows[j]);
2658 	}
2659 
2660 	for (j = 0, ipa = ikecfg; ipa; ipa = ipa->next, j++) {
2661 		if (j >= IKED_CFG_MAX)
2662 			break;
2663 		cfg = &pol.pol_cfg[j];
2664 		pol.pol_ncfg++;
2665 
2666 		cfg->cfg_action = ipa->action;
2667 		cfg->cfg_type = ipa->type;
2668 		memcpy(&cfg->cfg.address.addr, &ipa->address,
2669 		    sizeof(ipa->address));
2670 		cfg->cfg.address.addr_mask = ipa->mask;
2671 		cfg->cfg.address.addr_net = ipa->netaddress;
2672 		cfg->cfg.address.addr_af = ipa->af;
2673 	}
2674 
2675 	if (dstid) {
2676 		strlcpy(idstr, dstid, sizeof(idstr));
2677 		idtype = pol.pol_peerid.id_type;
2678 	} else if (!pol.pol_peer.addr_net) {
2679 		print_host((struct sockaddr *)&pol.pol_peer.addr, idstr,
2680 		    sizeof(idstr));
2681 		switch (pol.pol_peer.addr.ss_family) {
2682 		case AF_INET:
2683 			idtype = IKEV2_ID_IPV4;
2684 			break;
2685 		case AF_INET6:
2686 			idtype = IKEV2_ID_IPV6;
2687 			break;
2688 		default:
2689 			log_warnx("%s: unknown address family", __func__);
2690 			break;
2691 		}
2692 	}
2693 
2694 	/* Check if we have a raw public key for this peer */
2695 	if (check_pubkey(idstr, idtype) != -1)
2696 		pol.pol_certreqtype = IKEV2_CERT_RSA_KEY;
2697 
2698 	config_setpolicy(env, &pol, PROC_IKEV2);
2699 
2700 	rules++;
2701 	return (0);
2702 }
2703 
2704 int
2705 create_user(const char *user, const char *pass)
2706 {
2707 	struct iked_user	 usr;
2708 
2709 	bzero(&usr, sizeof(usr));
2710 
2711 	if (*user == '\0' || (strlcpy(usr.usr_name, user,
2712 	    sizeof(usr.usr_name)) >= sizeof(usr.usr_name))) {
2713 		yyerror("invalid user name");
2714 		return (-1);
2715 	}
2716 	if (*pass == '\0' || (strlcpy(usr.usr_pass, pass,
2717 	    sizeof(usr.usr_pass)) >= sizeof(usr.usr_pass))) {
2718 		yyerror("invalid password");
2719 		return (-1);
2720 	}
2721 
2722 	config_setuser(env, &usr, PROC_IKEV2);
2723 
2724 	rules++;
2725 	return (0);
2726 }
2727