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