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