1 /*        $NetBSD: pfkey.c,v 1.63 2025/03/07 15:55:29 christos Exp $  */
2 
3 /* $Id: pfkey.c,v 1.63 2025/03/07 15:55:29 christos Exp $ */
4 
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include "config.h"
35 
36 #include <stdlib.h>
37 #include <string.h>
38 #include <stdio.h>
39 #include <netdb.h>
40 #include <errno.h>
41 #ifdef HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44 #include <netdb.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 
48 #ifdef ENABLE_NATT
49 # ifdef __linux__
50 #  include <linux/udp.h>
51 # endif
52 # if defined(__NetBSD__) || defined(__FreeBSD__) ||         \
53   (defined(__APPLE__) && defined(__MACH__))
54 #  include <netinet/udp.h>
55 # endif
56 #endif
57 
58 #include <sys/types.h>
59 #include <sys/param.h>
60 #include <sys/socket.h>
61 #include <sys/queue.h>
62 #include <sys/sysctl.h>
63 
64 #include <net/route.h>
65 #include <net/pfkeyv2.h>
66 
67 #include <netinet/in.h>
68 #include PATH_IPSEC_H
69 #include <fcntl.h>
70 
71 #include "libpfkey.h"
72 
73 #include "var.h"
74 #include "misc.h"
75 #include "vmbuf.h"
76 #include "plog.h"
77 #include "sockmisc.h"
78 #include "session.h"
79 #include "debug.h"
80 
81 #include "schedule.h"
82 #include "localconf.h"
83 #include "remoteconf.h"
84 #include "handler.h"
85 #include "policy.h"
86 #include "proposal.h"
87 #include "isakmp_var.h"
88 #include "isakmp.h"
89 #include "isakmp_inf.h"
90 #include "ipsec_doi.h"
91 #include "oakley.h"
92 #include "pfkey.h"
93 #include "algorithm.h"
94 #include "sainfo.h"
95 #include "admin.h"
96 #include "evt.h"
97 #include "privsep.h"
98 #include "strnames.h"
99 #include "backupsa.h"
100 #include "gcmalloc.h"
101 #include "nattraversal.h"
102 #include "crypto_openssl.h"
103 #include "grabmyaddr.h"
104 
105 #if defined(SADB_X_EALG_RIJNDAELCBC) && !defined(SADB_X_EALG_AESCBC)
106 #define SADB_X_EALG_AESCBC  SADB_X_EALG_RIJNDAELCBC
107 #endif
108 
109 /* prototype */
110 static u_int ipsecdoi2pfkey_aalg(u_int);
111 static u_int ipsecdoi2pfkey_ealg(u_int);
112 static u_int ipsecdoi2pfkey_calg(u_int);
113 static u_int ipsecdoi2pfkey_alg(u_int, u_int);
114 static u_int keylen_aalg(u_int);
115 static u_int keylen_ealg(u_int, int);
116 
117 static int pk_recvgetspi(caddr_t *);
118 static int pk_recvupdate(caddr_t *);
119 static int pk_recvadd(caddr_t *);
120 static int pk_recvdelete(caddr_t *);
121 static int pk_recvacquire(caddr_t *);
122 static int pk_recvexpire(caddr_t *);
123 static int pk_recvflush(caddr_t *);
124 static int getsadbpolicy(caddr_t *, int *, int, struct ph2handle *);
125 static int pk_recvspdupdate(caddr_t *);
126 static int pk_recvspdadd(caddr_t *);
127 static int pk_recvspddelete(caddr_t *);
128 static int pk_recvspdexpire(caddr_t *);
129 static int pk_recvspdget(caddr_t *);
130 static int pk_recvspddump(caddr_t *);
131 static int pk_recvspdflush(caddr_t *);
132 #if defined(SADB_X_MIGRATE) && defined(SADB_X_EXT_KMADDRESS)
133 static int pk_recvmigrate(caddr_t *);
134 #endif
135 static struct sadb_msg *pk_recv(int, int *);
136 
137 static int (*pkrecvf[])(caddr_t *) = {
138 NULL,
139 pk_recvgetspi,
140 pk_recvupdate,
141 pk_recvadd,
142 pk_recvdelete,
143 NULL,     /* SADB_GET */
144 pk_recvacquire,
145 NULL,     /* SABD_REGISTER */
146 pk_recvexpire,
147 pk_recvflush,
148 NULL,     /* SADB_DUMP */
149 NULL,     /* SADB_X_PROMISC */
150 NULL,     /* SADB_X_PCHANGE */
151 pk_recvspdupdate,
152 pk_recvspdadd,
153 pk_recvspddelete,
154 pk_recvspdget,
155 NULL,     /* SADB_X_SPDACQUIRE */
156 pk_recvspddump,
157 pk_recvspdflush,
158 NULL,     /* SADB_X_SPDSETIDX */
159 pk_recvspdexpire,
160 NULL,     /* SADB_X_SPDDELETE2 */
161 NULL,     /* SADB_X_NAT_T_NEW_MAPPING */
162 #if defined(SADB_X_MIGRATE) && defined(SADB_X_EXT_KMADDRESS)
163 pk_recvmigrate,
164 #else
165 NULL,     /* SADB_X_MIGRATE */
166 #endif
167 #if (SADB_MAX > 24)
168 #error "SADB extra message?"
169 #endif
170 };
171 
172 static int addnewsp(caddr_t *, struct sockaddr *, struct sockaddr *);
173 
174 /* cope with old kame headers - ugly */
175 #ifndef SADB_X_AALG_MD5
176 #define SADB_X_AALG_MD5                 SADB_AALG_MD5
177 #endif
178 #ifndef SADB_X_AALG_SHA
179 #define SADB_X_AALG_SHA                 SADB_AALG_SHA
180 #endif
181 #ifndef SADB_X_AALG_NULL
182 #define SADB_X_AALG_NULL      SADB_AALG_NULL
183 #endif
184 
185 #ifndef SADB_X_EALG_BLOWFISHCBC
186 #define SADB_X_EALG_BLOWFISHCBC         SADB_EALG_BLOWFISHCBC
187 #endif
188 #ifndef SADB_X_EALG_CAST128CBC
189 #define SADB_X_EALG_CAST128CBC          SADB_EALG_CAST128CBC
190 #endif
191 #ifndef SADB_X_EALG_RC5CBC
192 #ifdef SADB_EALG_RC5CBC
193 #define SADB_X_EALG_RC5CBC    SADB_EALG_RC5CBC
194 #endif
195 #endif
196 
197 /*
198  * PF_KEY packet handler
199  *        0: success
200  *        -1: fail
201  */
202 /*ARGSUSED*/
203 static int
pfkey_handler(void * ctx __unused,int fd)204 pfkey_handler(void *ctx __unused, int fd)
205 {
206           struct sadb_msg *msg;
207           int len;
208           caddr_t mhp[SADB_EXT_MAX + 1];
209           int error = -1;
210 
211           /* receive pfkey message. */
212           len = 0;
213           msg = (struct sadb_msg *) pk_recv(fd, &len);
214           if (msg == NULL) {
215                     if (len < 0) {
216                             /* do not report EAGAIN as error; well get
217                              * called from main loop later. and it's normal
218                              * when spd dump is received during reload and
219                              * this function is called in loop. */
220                             if (errno == EAGAIN)
221                                     goto end;
222 
223                               plog(LLV_ERROR, LOCATION, NULL,
224                                         "failed to recv from pfkey (%s)\n",
225                                         strerror(errno));
226                               goto end;
227                     } else {
228                               /* short message - msg not ready */
229                               return 0;
230                     }
231           }
232 
233           plog(LLV_DEBUG, LOCATION, NULL, "got pfkey %s message\n",
234                     s_pfkey_type(msg->sadb_msg_type));
235           plogdump(LLV_DEBUG2, msg, msg->sadb_msg_len << 3);
236 
237           /* validity check */
238           if (msg->sadb_msg_errno) {
239                     int pri;
240 
241                     /* when SPD is empty, treat the state as no error. */
242                     if (msg->sadb_msg_type == SADB_X_SPDDUMP &&
243                         msg->sadb_msg_errno == ENOENT)
244                               pri = LLV_DEBUG;
245                     else
246                               pri = LLV_ERROR;
247 
248                     plog(pri, LOCATION, NULL,
249                               "pfkey %s failed: %s\n",
250                               s_pfkey_type(msg->sadb_msg_type),
251                               strerror(msg->sadb_msg_errno));
252 
253                     goto end;
254           }
255 
256           /* check pfkey message. */
257           if (pfkey_align(msg, mhp)) {
258                     plog(LLV_ERROR, LOCATION, NULL,
259                               "libipsec failed pfkey align (%s)\n",
260                               ipsec_strerror());
261                     goto end;
262           }
263           if (pfkey_check(mhp)) {
264                     plog(LLV_ERROR, LOCATION, NULL,
265                               "libipsec failed pfkey check (%s)\n",
266                               ipsec_strerror());
267                     goto end;
268           }
269           msg = (struct sadb_msg *)mhp[0];
270 
271           /* safety check */
272           if (msg->sadb_msg_type >= ARRAYLEN(pkrecvf)) {
273                     plog(LLV_ERROR, LOCATION, NULL,
274                               "unknown PF_KEY message type=%u\n",
275                               msg->sadb_msg_type);
276                     goto end;
277           }
278 
279           if (pkrecvf[msg->sadb_msg_type] == NULL) {
280                     plog(LLV_INFO, LOCATION, NULL,
281                               "unsupported PF_KEY message %s\n",
282                               s_pfkey_type(msg->sadb_msg_type));
283                     goto end;
284           }
285 
286           if ((pkrecvf[msg->sadb_msg_type])(mhp) < 0)
287                     goto end;
288 
289           error = 1;
290 end:
291           if (msg)
292                     racoon_free(msg);
293           return(error);
294 }
295 
296 /*
297  * dump SADB
298  */
299 vchar_t *
pfkey_dump_sadb(int satype)300 pfkey_dump_sadb(int satype)
301 {
302           int s;
303           vchar_t *buf = NULL;
304           pid_t pid = getpid();
305           struct sadb_msg *msg = NULL;
306           size_t bl, ml;
307           int len;
308           int bufsiz;
309 
310           if ((s = privsep_socket(PF_KEY, SOCK_RAW, PF_KEY_V2)) < 0) {
311                     plog(LLV_ERROR, LOCATION, NULL,
312                               "libipsec failed pfkey open: %s\n",
313                               ipsec_strerror());
314                     return NULL;
315           }
316 
317           if ((bufsiz = pfkey_set_buffer_size(s, lcconf->pfkey_buffer_size)) < 0) {
318                     plog(LLV_ERROR, LOCATION, NULL,
319                          "libipsec failed pfkey set buffer size to %d: %s\n",
320                          lcconf->pfkey_buffer_size, ipsec_strerror());
321                     return NULL;
322           } else if (bufsiz < lcconf->pfkey_buffer_size) {
323                     plog(LLV_WARNING, LOCATION, NULL,
324                          "pfkey socket receive buffer set to %dKB, instead of %d\n",
325                          bufsiz, lcconf->pfkey_buffer_size);
326           }
327 
328           plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_dump\n");
329           if (pfkey_send_dump(s, satype) < 0) {
330                     plog(LLV_ERROR, LOCATION, NULL,
331                               "libipsec failed dump: %s\n", ipsec_strerror());
332                     goto fail;
333           }
334 
335           for (;;) {
336                     if (msg)
337                               racoon_free(msg);
338                     msg = pk_recv(s, &len);
339                     if (msg == NULL) {
340                               if (len < 0)
341                                         goto done;
342                               else
343                                         continue;
344                     }
345 
346                     if (msg->sadb_msg_type != SADB_DUMP || msg->sadb_msg_pid != pid)
347                     {
348                         plog(LLV_DEBUG, LOCATION, NULL,
349                                "discarding non-sadb dump msg %p, our pid=%i\n", msg, pid);
350                         plog(LLV_DEBUG, LOCATION, NULL,
351                                "type %i, pid %i\n", msg->sadb_msg_type, msg->sadb_msg_pid);
352                         continue;
353                     }
354 
355 
356                     ml = msg->sadb_msg_len << 3;
357                     bl = buf ? buf->l : 0;
358                     buf = vrealloc(buf, bl + ml);
359                     if (buf == NULL) {
360                               plog(LLV_ERROR, LOCATION, NULL,
361                                         "failed to reallocate buffer to dump.\n");
362                               goto fail;
363                     }
364                     memcpy(buf->v + bl, msg, ml);
365 
366                     if (msg->sadb_msg_seq == 0)
367                               break;
368           }
369           goto done;
370 
371 fail:
372           if (buf)
373                     vfree(buf);
374           buf = NULL;
375 done:
376           if (msg)
377                     racoon_free(msg);
378           close(s);
379           return buf;
380 }
381 
382 #ifdef ENABLE_ADMINPORT
383 /*
384  * flush SADB
385  */
386 void
pfkey_flush_sadb(u_int proto)387 pfkey_flush_sadb(u_int proto)
388 {
389           int satype;
390 
391           /* convert to SADB_SATYPE */
392           if ((satype = admin2pfkey_proto(proto)) < 0)
393                     return;
394 
395           plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_flush\n");
396           if (pfkey_send_flush(lcconf->sock_pfkey, satype) < 0) {
397                     plog(LLV_ERROR, LOCATION, NULL,
398                               "libipsec failed send flush (%s)\n", ipsec_strerror());
399                     return;
400           }
401 
402           return;
403 }
404 #endif
405 
406 /*
407  * These are the SATYPEs that we manage.  We register to get
408  * PF_KEY messages related to these SATYPEs, and we also use
409  * this list to determine which SATYPEs to delete SAs for when
410  * we receive an INITIAL-CONTACT.
411  */
412 const struct pfkey_satype pfkey_satypes[] = {
413           { SADB_SATYPE_AH,   "AH" },
414           { SADB_SATYPE_ESP,  "ESP" },
415           { SADB_X_SATYPE_IPCOMP,       "IPCOMP" },
416 };
417 const int pfkey_nsatypes =
418     sizeof(pfkey_satypes) / sizeof(pfkey_satypes[0]);
419 
420 /*
421  * PF_KEY initialization
422  */
423 int
pfkey_init()424 pfkey_init()
425 {
426           int i, reg_fail;
427           int bufsiz;
428 
429           if ((lcconf->sock_pfkey = pfkey_open()) < 0) {
430                     plog(LLV_ERROR, LOCATION, NULL,
431                               "libipsec failed pfkey open (%s)\n", ipsec_strerror());
432                     return -1;
433           }
434           if ((bufsiz = pfkey_set_buffer_size(lcconf->sock_pfkey,
435                                                       lcconf->pfkey_buffer_size)) < 0) {
436                     plog(LLV_ERROR, LOCATION, NULL,
437                          "libipsec failed to set pfkey buffer size to %d (%s)\n",
438                          lcconf->pfkey_buffer_size, ipsec_strerror());
439                     return -1;
440           } else if (bufsiz < lcconf->pfkey_buffer_size) {
441                     plog(LLV_WARNING, LOCATION, NULL,
442                          "pfkey socket receive buffer set to %dKB, instead of %d\n",
443                          bufsiz, lcconf->pfkey_buffer_size);
444           }
445 
446           if (fcntl(lcconf->sock_pfkey, F_SETFL, O_NONBLOCK) == -1)
447                     plog(LLV_WARNING, LOCATION, NULL,
448                         "failed to set the pfkey socket to NONBLOCK\n");
449 
450           for (i = 0, reg_fail = 0; i < pfkey_nsatypes; i++) {
451                     plog(LLV_DEBUG, LOCATION, NULL,
452                         "call pfkey_send_register for %s\n",
453                         pfkey_satypes[i].ps_name);
454                     if (pfkey_send_register(lcconf->sock_pfkey,
455                                                   pfkey_satypes[i].ps_satype) < 0 ||
456                         pfkey_recv_register(lcconf->sock_pfkey) < 0) {
457                               plog(LLV_WARNING, LOCATION, NULL,
458                                   "failed to register %s (%s)\n",
459                                   pfkey_satypes[i].ps_name,
460                                   ipsec_strerror());
461                               reg_fail++;
462                     }
463           }
464 
465           if (reg_fail == pfkey_nsatypes) {
466                     plog(LLV_ERROR, LOCATION, NULL,
467                               "failed to regist any protocol.\n");
468                     pfkey_close(lcconf->sock_pfkey);
469                     return -1;
470           }
471 
472           initsp();
473 
474           if (pfkey_send_spddump(lcconf->sock_pfkey) < 0) {
475                     plog(LLV_ERROR, LOCATION, NULL,
476                               "libipsec sending spddump failed: %s\n",
477                               ipsec_strerror());
478                     pfkey_close(lcconf->sock_pfkey);
479                     return -1;
480           }
481 #if 0
482           if (pfkey_promisc_toggle(1) < 0) {
483                     pfkey_close(lcconf->sock_pfkey);
484                     return -1;
485           }
486 #endif
487           monitor_fd(lcconf->sock_pfkey, pfkey_handler, NULL, 0);
488           return 0;
489 }
490 
491 int
pfkey_reload()492 pfkey_reload()
493 {
494           flushsp();
495 
496           if (pfkey_send_spddump(lcconf->sock_pfkey) < 0) {
497                     plog(LLV_ERROR, LOCATION, NULL,
498                               "libipsec sending spddump failed: %s\n",
499                               ipsec_strerror());
500                     return -1;
501           }
502 
503           while (pfkey_handler(NULL, lcconf->sock_pfkey) > 0)
504                     continue;
505 
506           return 0;
507 }
508 
509 /* %%% for conversion */
510 /* IPSECDOI_ATTR_AUTH -> SADB_AALG */
511 static u_int
ipsecdoi2pfkey_aalg(u_int hashtype)512 ipsecdoi2pfkey_aalg(u_int hashtype)
513 {
514           switch (hashtype) {
515           case IPSECDOI_ATTR_AUTH_HMAC_MD5:
516                     return SADB_AALG_MD5HMAC;
517           case IPSECDOI_ATTR_AUTH_HMAC_SHA1:
518                     return SADB_AALG_SHA1HMAC;
519           case IPSECDOI_ATTR_AUTH_HMAC_SHA2_256:
520 #if (defined SADB_X_AALG_SHA2_256) && !defined(SADB_X_AALG_SHA2_256HMAC)
521                     return SADB_X_AALG_SHA2_256;
522 #else
523                     return SADB_X_AALG_SHA2_256HMAC;
524 #endif
525           case IPSECDOI_ATTR_AUTH_HMAC_SHA2_384:
526 #if (defined SADB_X_AALG_SHA2_384) && !defined(SADB_X_AALG_SHA2_384HMAC)
527                     return SADB_X_AALG_SHA2_384;
528 #else
529                     return SADB_X_AALG_SHA2_384HMAC;
530 #endif
531           case IPSECDOI_ATTR_AUTH_HMAC_SHA2_512:
532 #if (defined SADB_X_AALG_SHA2_512) && !defined(SADB_X_AALG_SHA2_512HMAC)
533                     return SADB_X_AALG_SHA2_512;
534 #else
535                     return SADB_X_AALG_SHA2_512HMAC;
536 #endif
537           case IPSECDOI_ATTR_AUTH_KPDK:           /* need special care */
538                     return SADB_AALG_NONE;
539 
540           /* not supported */
541           case IPSECDOI_ATTR_AUTH_DES_MAC:
542                     plog(LLV_ERROR, LOCATION, NULL,
543                               "Not supported hash type: %u\n", hashtype);
544                     return ~0u;
545 
546           case 0: /* reserved */
547           default:
548                     return SADB_AALG_NONE;
549 
550                     plog(LLV_ERROR, LOCATION, NULL,
551                               "Invalid hash type: %u\n", hashtype);
552                     return ~0u;
553           }
554           /*NOTREACHED*/
555 }
556 
557 /* IPSECDOI_ESP -> SADB_EALG */
558 static u_int
ipsecdoi2pfkey_ealg(u_int t_id)559 ipsecdoi2pfkey_ealg(u_int t_id)
560 {
561           switch (t_id) {
562           case IPSECDOI_ESP_DES_IV64:             /* sa_flags |= SADB_X_EXT_OLD */
563                     return SADB_EALG_DESCBC;
564           case IPSECDOI_ESP_DES:
565                     return SADB_EALG_DESCBC;
566           case IPSECDOI_ESP_3DES:
567                     return SADB_EALG_3DESCBC;
568 #ifdef SADB_X_EALG_RC5CBC
569           case IPSECDOI_ESP_RC5:
570                     return SADB_X_EALG_RC5CBC;
571 #endif
572           case IPSECDOI_ESP_CAST:
573                     return SADB_X_EALG_CAST128CBC;
574           case IPSECDOI_ESP_BLOWFISH:
575                     return SADB_X_EALG_BLOWFISHCBC;
576           case IPSECDOI_ESP_DES_IV32:   /* flags |= (SADB_X_EXT_OLD|
577                                                                       SADB_X_EXT_IV4B)*/
578                     return SADB_EALG_DESCBC;
579           case IPSECDOI_ESP_NULL:
580                     return SADB_EALG_NULL;
581 #ifdef SADB_X_EALG_AESCBC
582           case IPSECDOI_ESP_AES:
583                     return SADB_X_EALG_AESCBC;
584 #endif
585 #ifdef SADB_X_EALG_AESGCM16
586           case IPSECDOI_ESP_AESGCM16:
587                     return SADB_X_EALG_AESGCM16;
588 #endif
589 #ifdef SADB_X_EALG_TWOFISHCBC
590           case IPSECDOI_ESP_TWOFISH:
591                     return SADB_X_EALG_TWOFISHCBC;
592 #endif
593 #ifdef SADB_X_EALG_CAMELLIACBC
594           case IPSECDOI_ESP_CAMELLIA:
595                     return SADB_X_EALG_CAMELLIACBC;
596 #endif
597 
598           /* not supported */
599           case IPSECDOI_ESP_3IDEA:
600           case IPSECDOI_ESP_IDEA:
601           case IPSECDOI_ESP_RC4:
602                     plog(LLV_ERROR, LOCATION, NULL,
603                               "Not supported transform: %u\n", t_id);
604                     return ~0u;
605 
606           case 0: /* reserved */
607           default:
608                     plog(LLV_ERROR, LOCATION, NULL,
609                               "Invalid transform id: %u\n", t_id);
610                     return ~0u;
611           }
612           /*NOTREACHED*/
613 }
614 
615 /* IPCOMP -> SADB_CALG */
616 static u_int
ipsecdoi2pfkey_calg(u_int t_id)617 ipsecdoi2pfkey_calg(u_int t_id)
618 {
619           switch (t_id) {
620           case IPSECDOI_IPCOMP_OUI:
621                     return SADB_X_CALG_OUI;
622           case IPSECDOI_IPCOMP_DEFLATE:
623                     return SADB_X_CALG_DEFLATE;
624           case IPSECDOI_IPCOMP_LZS:
625                     return SADB_X_CALG_LZS;
626 
627           case 0: /* reserved */
628           default:
629                     plog(LLV_ERROR, LOCATION, NULL,
630                               "Invalid transform id: %u\n", t_id);
631                     return ~0u;
632           }
633           /*NOTREACHED*/
634 }
635 
636 /* IPSECDOI_PROTO -> SADB_SATYPE */
637 u_int
ipsecdoi2pfkey_proto(u_int proto)638 ipsecdoi2pfkey_proto(u_int proto)
639 {
640           switch (proto) {
641           case IPSECDOI_PROTO_IPSEC_AH:
642                     return SADB_SATYPE_AH;
643           case IPSECDOI_PROTO_IPSEC_ESP:
644                     return SADB_SATYPE_ESP;
645           case IPSECDOI_PROTO_IPCOMP:
646                     return SADB_X_SATYPE_IPCOMP;
647 
648           default:
649                     plog(LLV_ERROR, LOCATION, NULL,
650                               "Invalid ipsec_doi proto: %u\n", proto);
651                     return ~0u;
652           }
653           /*NOTREACHED*/
654 }
655 
656 static u_int
ipsecdoi2pfkey_alg(u_int algclass,u_int type)657 ipsecdoi2pfkey_alg(u_int algclass, u_int type)
658 {
659           switch (algclass) {
660           case IPSECDOI_ATTR_AUTH:
661                     return ipsecdoi2pfkey_aalg(type);
662           case IPSECDOI_PROTO_IPSEC_ESP:
663                     return ipsecdoi2pfkey_ealg(type);
664           case IPSECDOI_PROTO_IPCOMP:
665                     return ipsecdoi2pfkey_calg(type);
666           default:
667                     plog(LLV_ERROR, LOCATION, NULL,
668                               "Invalid ipsec_doi algclass: %u\n", algclass);
669                     return ~0u;
670           }
671           /*NOTREACHED*/
672 }
673 
674 /* SADB_SATYPE -> IPSECDOI_PROTO */
675 u_int
pfkey2ipsecdoi_proto(u_int satype)676 pfkey2ipsecdoi_proto(u_int satype)
677 {
678           switch (satype) {
679           case SADB_SATYPE_AH:
680                     return IPSECDOI_PROTO_IPSEC_AH;
681           case SADB_SATYPE_ESP:
682                     return IPSECDOI_PROTO_IPSEC_ESP;
683           case SADB_X_SATYPE_IPCOMP:
684                     return IPSECDOI_PROTO_IPCOMP;
685 
686           default:
687                     plog(LLV_ERROR, LOCATION, NULL,
688                               "Invalid pfkey proto: %u\n", satype);
689                     return ~0u;
690           }
691           /*NOTREACHED*/
692 }
693 
694 /* IPSECDOI_ATTR_ENC_MODE -> IPSEC_MODE */
695 u_int
ipsecdoi2pfkey_mode(u_int mode)696 ipsecdoi2pfkey_mode(u_int mode)
697 {
698           switch (mode) {
699           case IPSECDOI_ATTR_ENC_MODE_TUNNEL:
700 #ifdef ENABLE_NATT
701           case IPSECDOI_ATTR_ENC_MODE_UDPTUNNEL_RFC:
702           case IPSECDOI_ATTR_ENC_MODE_UDPTUNNEL_DRAFT:
703 #endif
704                     return IPSEC_MODE_TUNNEL;
705           case IPSECDOI_ATTR_ENC_MODE_TRNS:
706 #ifdef ENABLE_NATT
707           case IPSECDOI_ATTR_ENC_MODE_UDPTRNS_RFC:
708           case IPSECDOI_ATTR_ENC_MODE_UDPTRNS_DRAFT:
709 #endif
710                     return IPSEC_MODE_TRANSPORT;
711           default:
712                     plog(LLV_ERROR, LOCATION, NULL, "Invalid mode type: %u\n", mode);
713                     return ~0u;
714           }
715           /*NOTREACHED*/
716 }
717 
718 /* IPSECDOI_ATTR_ENC_MODE -> IPSEC_MODE */
719 u_int
pfkey2ipsecdoi_mode(u_int mode)720 pfkey2ipsecdoi_mode(u_int mode)
721 {
722           switch (mode) {
723           case IPSEC_MODE_TUNNEL:
724                     return IPSECDOI_ATTR_ENC_MODE_TUNNEL;
725           case IPSEC_MODE_TRANSPORT:
726                     return IPSECDOI_ATTR_ENC_MODE_TRNS;
727           case IPSEC_MODE_ANY:
728                     return IPSECDOI_ATTR_ENC_MODE_ANY;
729           default:
730                     plog(LLV_ERROR, LOCATION, NULL, "Invalid mode type: %u\n", mode);
731                     return ~0u;
732           }
733           /*NOTREACHED*/
734 }
735 
736 /* default key length for encryption algorithm */
737 static u_int
keylen_aalg(u_int hashtype)738 keylen_aalg(u_int hashtype)
739 {
740           int res;
741 
742           if (hashtype == 0)
743                     return SADB_AALG_NONE;
744 
745           res = alg_ipsec_hmacdef_hashlen(hashtype);
746           if (res == -1) {
747                     plog(LLV_ERROR, LOCATION, NULL,
748                               "invalid hmac algorithm %u.\n", hashtype);
749                     return ~0u;
750           }
751           return res;
752 }
753 
754 /* default key length for encryption algorithm */
755 static u_int
keylen_ealg(u_int enctype,int encklen)756 keylen_ealg(u_int enctype, int encklen)
757 {
758           int res;
759 
760           res = alg_ipsec_encdef_keylen(enctype, encklen);
761           if (res == -1) {
762                     plog(LLV_ERROR, LOCATION, NULL,
763                               "invalid encryption algorithm %u.\n", enctype);
764                     return ~0u;
765           }
766           return res;
767 }
768 
769 void
pk_fixup_sa_addresses(caddr_t * mhp)770 pk_fixup_sa_addresses(caddr_t *mhp)
771 {
772           struct sockaddr *src, *dst;
773 
774           src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
775           dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
776           set_port(src, PORT_ISAKMP);
777           set_port(dst, PORT_ISAKMP);
778 
779 #ifdef ENABLE_NATT
780           if (PFKEY_ADDR_X_NATTYPE(mhp[SADB_X_EXT_NAT_T_TYPE])) {
781                     /* NAT-T is enabled for this SADB entry; copy
782                      * the ports from NAT-T extensions */
783                     if(mhp[SADB_X_EXT_NAT_T_SPORT] != NULL)
784                               set_port(src, PFKEY_ADDR_X_PORT(mhp[SADB_X_EXT_NAT_T_SPORT]));
785                     if(mhp[SADB_X_EXT_NAT_T_DPORT] != NULL)
786                               set_port(dst, PFKEY_ADDR_X_PORT(mhp[SADB_X_EXT_NAT_T_DPORT]));
787           }
788 #endif
789 }
790 
791 int
pfkey_convertfromipsecdoi(u_int proto_id,u_int t_id,u_int hashtype,u_int * e_type,u_int * e_keylen,u_int * a_type,u_int * a_keylen,u_int * flags)792 pfkey_convertfromipsecdoi(u_int proto_id, u_int t_id, u_int hashtype,
793     u_int *e_type, u_int *e_keylen, u_int *a_type, u_int *a_keylen,
794     u_int *flags)
795 {
796           *flags = 0;
797           switch (proto_id) {
798           case IPSECDOI_PROTO_IPSEC_ESP:
799                     if ((*e_type = ipsecdoi2pfkey_ealg(t_id)) == ~0u)
800                               goto bad;
801                     if ((*e_keylen = keylen_ealg(t_id, *e_keylen)) == ~0u)
802                               goto bad;
803                     *e_keylen >>= 3;
804 
805                     if ((*a_type = ipsecdoi2pfkey_aalg(hashtype)) == ~0u)
806                               goto bad;
807                     if ((*a_keylen = keylen_aalg(hashtype)) == ~0u)
808                               goto bad;
809                     *a_keylen >>= 3;
810 
811                     if (*e_type == SADB_EALG_NONE) {
812                               plog(LLV_ERROR, LOCATION, NULL, "no ESP algorithm.\n");
813                               goto bad;
814                     }
815                     break;
816 
817           case IPSECDOI_PROTO_IPSEC_AH:
818                     if ((*a_type = ipsecdoi2pfkey_aalg(hashtype)) == ~0u)
819                               goto bad;
820                     if ((*a_keylen = keylen_aalg(hashtype)) == ~0u)
821                               goto bad;
822                     *a_keylen >>= 3;
823 
824                     if (t_id == IPSECDOI_ATTR_AUTH_HMAC_MD5
825                      && hashtype == IPSECDOI_ATTR_AUTH_KPDK) {
826                               /* AH_MD5 + Auth(KPDK) = RFC1826 keyed-MD5 */
827                               *a_type = SADB_X_AALG_MD5;
828                               *flags |= SADB_X_EXT_OLD;
829                     }
830                     *e_type = SADB_EALG_NONE;
831                     *e_keylen = 0;
832                     if (*a_type == SADB_AALG_NONE) {
833                               plog(LLV_ERROR, LOCATION, NULL, "no AH algorithm.\n");
834                               goto bad;
835                     }
836                     break;
837 
838           case IPSECDOI_PROTO_IPCOMP:
839                     if ((*e_type = ipsecdoi2pfkey_calg(t_id)) == ~0u)
840                               goto bad;
841                     *e_keylen = 0;
842 
843                     *flags = SADB_X_EXT_RAWCPI;
844 
845                     *a_type = SADB_AALG_NONE;
846                     *a_keylen = 0;
847                     if (*e_type == SADB_X_CALG_NONE) {
848                               plog(LLV_ERROR, LOCATION, NULL, "no IPCOMP algorithm.\n");
849                               goto bad;
850                     }
851                     break;
852 
853           default:
854                     plog(LLV_ERROR, LOCATION, NULL, "unknown IPsec protocol.\n");
855                     goto bad;
856           }
857 
858           return 0;
859 
860     bad:
861           errno = EINVAL;
862           return -1;
863 }
864 
865 /*%%%*/
866 /* send getspi message per ipsec protocol per remote address */
867 /*
868  * the local address and remote address in ph1handle are dealed
869  * with destination address and source address respectively.
870  * Because SPI is decided by responder.
871  */
872 int
pk_sendgetspi(struct ph2handle * iph2)873 pk_sendgetspi(struct ph2handle *iph2)
874 {
875           struct sockaddr *src = NULL, *dst = NULL;
876           u_int satype, mode;
877           struct saprop *pp;
878           struct saproto *pr;
879           uint32_t minspi, maxspi;
880           uint8_t natt_type = 0;
881           uint16_t sport = 0, dport = 0;
882 
883           if (iph2->side == INITIATOR)
884                     pp = iph2->proposal;
885           else
886                     pp = iph2->approval;
887 
888           if (iph2->sa_src && iph2->sa_dst) {
889                     /* MIPv6: Use SA addresses, not IKE ones */
890                     src = dupsaddr(iph2->sa_src);
891                     dst = dupsaddr(iph2->sa_dst);
892           } else {
893                     /* Common case: SA addresses and IKE ones are the same */
894                     src = dupsaddr(iph2->src);
895                     dst = dupsaddr(iph2->dst);
896           }
897 
898           if (src == NULL || dst == NULL) {
899                     racoon_free(src);
900                     racoon_free(dst);
901                     return -1;
902           }
903 
904           for (pr = pp->head; pr != NULL; pr = pr->next) {
905 
906                     /* validity check */
907                     satype = ipsecdoi2pfkey_proto(pr->proto_id);
908                     if (satype == ~0u) {
909                               plog(LLV_ERROR, LOCATION, NULL,
910                                         "invalid proto_id %d\n", pr->proto_id);
911                               racoon_free(src);
912                               racoon_free(dst);
913                               return -1;
914                     }
915                     /* this works around a bug in Linux kernel where it allocates 4 byte
916                        spi's for IPCOMP */
917                     else if (satype == SADB_X_SATYPE_IPCOMP) {
918                               minspi = 0x100;
919                               maxspi = 0xffff;
920                     }
921                     else {
922                               minspi = 0;
923                               maxspi = 0;
924                     }
925                     mode = ipsecdoi2pfkey_mode(pr->encmode);
926                     if (mode == ~0u) {
927                               plog(LLV_ERROR, LOCATION, NULL,
928                                         "invalid encmode %d\n", pr->encmode);
929                               racoon_free(src);
930                               racoon_free(dst);
931                               return -1;
932                     }
933 
934 #ifdef ENABLE_NATT
935                     if (pr->udp_encap) {
936                               natt_type = iph2->ph1->natt_options->encaps_type;
937                               sport=extract_port(src);
938                               dport=extract_port(dst);
939                     }
940 #endif
941 
942                     plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_getspi\n");
943                     if (pfkey_send_getspi_nat(
944                                         lcconf->sock_pfkey,
945                                         satype,
946                                         mode,
947                                         dst,                          /* src of SA */
948                                         src,                          /* dst of SA */
949                                         natt_type,
950                                         dport,
951                                         sport,
952                                         minspi, maxspi,
953                                         pr->reqid_in, iph2->seq) < 0) {
954                               plog(LLV_ERROR, LOCATION, NULL,
955                                         "ipseclib failed send getspi (%s)\n",
956                                         ipsec_strerror());
957                               racoon_free(src);
958                               racoon_free(dst);
959                               return -1;
960                     }
961                     plog(LLV_DEBUG, LOCATION, NULL,
962                               "pfkey GETSPI sent: %s\n",
963                               sadbsecas2str(dst, src, satype, 0, mode));
964           }
965 
966           racoon_free(src);
967           racoon_free(dst);
968           return 0;
969 }
970 
971 /*
972  * receive GETSPI from kernel.
973  */
974 static int
pk_recvgetspi(caddr_t * mhp)975 pk_recvgetspi(caddr_t *mhp)
976 {
977           struct sadb_msg *msg;
978           struct sadb_sa *sa;
979           struct ph2handle *iph2;
980           struct sockaddr *src, *dst;
981           int proto_id;
982           int allspiok, notfound;
983           struct saprop *pp;
984           struct saproto *pr;
985 
986           /* validity check */
987           if (mhp[SADB_EXT_SA] == NULL
988            || mhp[SADB_EXT_ADDRESS_DST] == NULL
989            || mhp[SADB_EXT_ADDRESS_SRC] == NULL) {
990                     plog(LLV_ERROR, LOCATION, NULL,
991                               "inappropriate sadb getspi message passed.\n");
992                     return -1;
993           }
994           msg = (struct sadb_msg *)mhp[0];
995           sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
996           pk_fixup_sa_addresses(mhp);
997           dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]); /* note SA dir */
998           src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
999 
1000           /* the message has to be processed or not ? */
1001           if (msg->sadb_msg_pid != getpid()) {
1002                     plog(LLV_DEBUG, LOCATION, NULL,
1003                               "%s message is not interesting "
1004                               "because pid %d is not mine.\n",
1005                               s_pfkey_type(msg->sadb_msg_type),
1006                               msg->sadb_msg_pid);
1007                     return -1;
1008           }
1009 
1010           iph2 = getph2byseq(msg->sadb_msg_seq);
1011           if (iph2 == NULL) {
1012                     plog(LLV_DEBUG, LOCATION, NULL,
1013                               "seq %d of %s message not interesting.\n",
1014                               msg->sadb_msg_seq,
1015                               s_pfkey_type(msg->sadb_msg_type));
1016                     return -1;
1017           }
1018 
1019           if (iph2->status != PHASE2ST_GETSPISENT) {
1020                     plog(LLV_ERROR, LOCATION, NULL,
1021                               "status mismatch (db:%d msg:%d)\n",
1022                               iph2->status, PHASE2ST_GETSPISENT);
1023                     return -1;
1024           }
1025 
1026           /* set SPI, and check to get all spi whether or not */
1027           allspiok = 1;
1028           notfound = 1;
1029           proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1030           pp = iph2->side == INITIATOR ? iph2->proposal : iph2->approval;
1031 
1032           for (pr = pp->head; pr != NULL; pr = pr->next) {
1033                     if (pr->proto_id == proto_id && pr->spi == 0) {
1034                               pr->spi = sa->sadb_sa_spi;
1035                               notfound = 0;
1036                               plog(LLV_DEBUG, LOCATION, NULL,
1037                                         "pfkey GETSPI succeeded: %s\n",
1038                                         sadbsecas2str(dst, src,
1039                                             msg->sadb_msg_satype,
1040                                             sa->sadb_sa_spi,
1041                                             ipsecdoi2pfkey_mode(pr->encmode)));
1042                     }
1043                     if (pr->spi == 0)
1044                               allspiok = 0;       /* not get all spi */
1045           }
1046 
1047           if (notfound) {
1048                     plog(LLV_ERROR, LOCATION, NULL,
1049                               "get spi for unknown address %s\n",
1050                               saddrwop2str(dst));
1051                     return -1;
1052           }
1053 
1054           if (allspiok) {
1055                     /* update status */
1056                     iph2->status = PHASE2ST_GETSPIDONE;
1057                     if (isakmp_post_getspi(iph2) < 0) {
1058                               plog(LLV_ERROR, LOCATION, NULL,
1059                                         "failed to start post getspi.\n");
1060                               remph2(iph2);
1061                               delph2(iph2);
1062                               iph2 = NULL;
1063                               return -1;
1064                     }
1065           }
1066 
1067           return 0;
1068 }
1069 
1070 /*
1071  * set inbound SA
1072  */
1073 int
pk_sendupdate(struct ph2handle * iph2)1074 pk_sendupdate(struct ph2handle *iph2)
1075 {
1076           struct saproto *pr;
1077           struct pfkey_send_sa_args sa_args;
1078 
1079           /* sanity check */
1080           if (iph2->approval == NULL) {
1081                     plog(LLV_ERROR, LOCATION, NULL,
1082                               "no approvaled SAs found.\n");
1083                     return -1;
1084           }
1085 
1086           /* fill in some needed for pfkey_send_update2 */
1087           memset (&sa_args, 0, sizeof (sa_args));
1088           sa_args.so = lcconf->sock_pfkey;
1089           if (iph2->lifetime_secs)
1090                     sa_args.l_addtime = iph2->lifetime_secs;
1091           else
1092                     sa_args.l_addtime = iph2->approval->lifetime;
1093           sa_args.seq = iph2->seq;
1094           sa_args.wsize = 4;
1095 
1096           if (iph2->sa_src && iph2->sa_dst) {
1097                     /* MIPv6: Use SA addresses, not IKE ones */
1098                     sa_args.dst = dupsaddr(iph2->sa_src);
1099                     sa_args.src = dupsaddr(iph2->sa_dst);
1100           } else {
1101                     /* Common case: SA addresses and IKE ones are the same */
1102                     sa_args.dst = dupsaddr(iph2->src);
1103                     sa_args.src = dupsaddr(iph2->dst);
1104           }
1105 
1106           if (sa_args.src == NULL || sa_args.dst == NULL) {
1107                     racoon_free(sa_args.src);
1108                     racoon_free(sa_args.dst);
1109                     return -1;
1110           }
1111 
1112           for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1113                     /* validity check */
1114                     sa_args.satype = ipsecdoi2pfkey_proto(pr->proto_id);
1115                     if (sa_args.satype == ~0u) {
1116                               plog(LLV_ERROR, LOCATION, NULL,
1117                                         "invalid proto_id %d\n", pr->proto_id);
1118                               racoon_free(sa_args.src);
1119                               racoon_free(sa_args.dst);
1120                               return -1;
1121                     }
1122                     else if (sa_args.satype == SADB_X_SATYPE_IPCOMP) {
1123                               /* IPCOMP has no replay window */
1124                               sa_args.wsize = 0;
1125                     }
1126 #ifdef ENABLE_SAMODE_UNSPECIFIED
1127                     sa_args.mode = IPSEC_MODE_ANY;
1128 #else
1129                     sa_args.mode = ipsecdoi2pfkey_mode(pr->encmode);
1130                     if (sa_args.mode == ~0u) {
1131                               plog(LLV_ERROR, LOCATION, NULL,
1132                                         "invalid encmode %d\n", pr->encmode);
1133                               racoon_free(sa_args.src);
1134                               racoon_free(sa_args.dst);
1135                               return -1;
1136                     }
1137 #endif
1138                     /* set algorithm type and key length */
1139                     sa_args.e_keylen = pr->head->encklen;
1140                     if (pfkey_convertfromipsecdoi(
1141                                         pr->proto_id,
1142                                         pr->head->trns_id,
1143                                         pr->head->authtype,
1144                                         &sa_args.e_type, &sa_args.e_keylen,
1145                                         &sa_args.a_type, &sa_args.a_keylen,
1146                                         &sa_args.flags) < 0){
1147                               racoon_free(sa_args.src);
1148                               racoon_free(sa_args.dst);
1149                               return -1;
1150                     }
1151 
1152 #if 0
1153                     sa_args.l_bytes = iph2->approval->lifebyte * 1024,
1154 #else
1155                     sa_args.l_bytes = 0;
1156 #endif
1157 
1158 #ifdef HAVE_SECCTX
1159                     if (*iph2->approval->sctx.ctx_str) {
1160                               sa_args.ctxdoi = iph2->approval->sctx.ctx_doi;
1161                               sa_args.ctxalg = iph2->approval->sctx.ctx_alg;
1162                               sa_args.ctxstrlen = iph2->approval->sctx.ctx_strlen;
1163                               sa_args.ctxstr = iph2->approval->sctx.ctx_str;
1164                     }
1165 #endif /* HAVE_SECCTX */
1166 
1167 #ifdef ENABLE_NATT
1168                     if (pr->udp_encap) {
1169                               sa_args.l_natt_type = iph2->ph1->natt_options->encaps_type;
1170                               sa_args.l_natt_sport = extract_port(iph2->ph1->remote);
1171                               sa_args.l_natt_dport = extract_port(iph2->ph1->local);
1172                               sa_args.l_natt_oa = iph2->natoa_src;
1173 #ifdef SADB_X_EXT_NAT_T_FRAG
1174                               sa_args.l_natt_frag = iph2->ph1->rmconf->esp_frag;
1175 #endif
1176                     }
1177 #endif
1178 
1179                     /* more info to fill in */
1180                     sa_args.spi = pr->spi;
1181                     sa_args.reqid = pr->reqid_in;
1182                     sa_args.keymat = pr->keymat->v;
1183 
1184                     plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_update2\n");
1185                     if (pfkey_send_update2(&sa_args) < 0) {
1186                               plog(LLV_ERROR, LOCATION, NULL,
1187                                         "libipsec failed send update (%s)\n",
1188                                         ipsec_strerror());
1189                               racoon_free(sa_args.src);
1190                               racoon_free(sa_args.dst);
1191                               return -1;
1192                     }
1193 
1194                     if (!lcconf->pathinfo[LC_PATHTYPE_BACKUPSA])
1195                               continue;
1196 
1197                     /*
1198                      * It maybe good idea to call backupsa_to_file() after
1199                      * racoon will receive the sadb_update messages.
1200                      * But it is impossible because there is not key in the
1201                      * information from the kernel.
1202                      */
1203 
1204                     /* change some things before backing up */
1205                     sa_args.wsize = 4;
1206                     sa_args.l_bytes = iph2->approval->lifebyte * 1024;
1207 
1208                     if (backupsa_to_file(&sa_args) < 0) {
1209                               plog(LLV_ERROR, LOCATION, NULL,
1210                                         "backuped SA failed: %s\n",
1211                                         sadbsecas2str(sa_args.src, sa_args.dst,
1212                                         sa_args.satype, sa_args.spi, sa_args.mode));
1213                     }
1214                     plog(LLV_DEBUG, LOCATION, NULL,
1215                               "backuped SA: %s\n",
1216                               sadbsecas2str(sa_args.src, sa_args.dst,
1217                               sa_args.satype, sa_args.spi, sa_args.mode));
1218           }
1219 
1220           racoon_free(sa_args.src);
1221           racoon_free(sa_args.dst);
1222           return 0;
1223 }
1224 
1225 static int
pk_recvupdate(caddr_t * mhp)1226 pk_recvupdate(caddr_t *mhp)
1227 {
1228           struct sadb_msg *msg;
1229           struct sadb_sa *sa;
1230           struct sockaddr *src, *dst;
1231           struct ph2handle *iph2;
1232           u_int proto_id, encmode, sa_mode;
1233           int incomplete = 0;
1234           struct saproto *pr;
1235 
1236           /* ignore this message because of local test mode. */
1237           if (f_local)
1238                     return 0;
1239 
1240           /* sanity check */
1241           if (mhp[0] == NULL
1242            || mhp[SADB_EXT_SA] == NULL
1243            || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1244            || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1245                     plog(LLV_ERROR, LOCATION, NULL,
1246                               "inappropriate sadb update message passed.\n");
1247                     return -1;
1248           }
1249           msg = (struct sadb_msg *)mhp[0];
1250           pk_fixup_sa_addresses(mhp);
1251           src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1252           dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1253           sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1254 
1255           sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1256                     ? IPSEC_MODE_ANY
1257                     : ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1258 
1259           /* the message has to be processed or not ? */
1260           if (msg->sadb_msg_pid != getpid()) {
1261                     plog(LLV_DEBUG, LOCATION, NULL,
1262                               "%s message is not interesting "
1263                               "because pid %d is not mine.\n",
1264                               s_pfkey_type(msg->sadb_msg_type),
1265                               msg->sadb_msg_pid);
1266                     return -1;
1267           }
1268 
1269           iph2 = getph2byseq(msg->sadb_msg_seq);
1270           if (iph2 == NULL) {
1271                     plog(LLV_DEBUG, LOCATION, NULL,
1272                               "seq %d of %s message not interesting.\n",
1273                               msg->sadb_msg_seq,
1274                               s_pfkey_type(msg->sadb_msg_type));
1275                     return -1;
1276           }
1277 
1278           if (iph2->status != PHASE2ST_ADDSA) {
1279                     plog(LLV_ERROR, LOCATION, NULL,
1280                               "status mismatch (db:%d msg:%d)\n",
1281                               iph2->status, PHASE2ST_ADDSA);
1282                     return -1;
1283           }
1284 
1285           /* check to complete all keys ? */
1286           for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1287                     proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1288                     if (proto_id == ~0u) {
1289                               plog(LLV_ERROR, LOCATION, NULL,
1290                                         "invalid proto_id %d\n", msg->sadb_msg_satype);
1291                               return -1;
1292                     }
1293                     encmode = pfkey2ipsecdoi_mode(sa_mode);
1294                     if (encmode == ~0u) {
1295                               plog(LLV_ERROR, LOCATION, NULL,
1296                                         "invalid encmode %d\n", sa_mode);
1297                               return -1;
1298                     }
1299 
1300                     if (pr->proto_id == proto_id
1301                      && pr->spi == sa->sadb_sa_spi) {
1302                               pr->ok = 1;
1303                               plog(LLV_DEBUG, LOCATION, NULL,
1304                                         "pfkey UPDATE succeeded: %s\n",
1305                                         sadbsecas2str(dst, src,
1306                                             msg->sadb_msg_satype,
1307                                             sa->sadb_sa_spi,
1308                                             sa_mode));
1309 
1310                               plog(LLV_INFO, LOCATION, NULL,
1311                                         "IPsec-SA established: %s\n",
1312                                         sadbsecas2str(dst, src,
1313                                                   msg->sadb_msg_satype, sa->sadb_sa_spi,
1314                                                   sa_mode));
1315                     }
1316 
1317                     if (pr->ok == 0)
1318                               incomplete = 1;
1319           }
1320 
1321           if (incomplete)
1322                     return 0;
1323 
1324           /* turn off the timer for calling pfkey_timeover() */
1325           sched_cancel(&iph2->sce);
1326 
1327           /* update status */
1328           iph2->status = PHASE2ST_ESTABLISHED;
1329           evt_phase2(iph2, EVT_PHASE2_UP, NULL);
1330 
1331 #ifdef ENABLE_STATS
1332           gettimeofday(&iph2->end, NULL);
1333           syslog(LOG_NOTICE, "%s(%s): %8.6f",
1334                     "phase2", "quick", timedelta(&iph2->start, &iph2->end));
1335 #endif
1336 
1337           /* turn off schedule */
1338           sched_cancel(&iph2->scr);
1339 
1340           /*
1341            * since we are going to reuse the phase2 handler, we need to
1342            * remain it and refresh all the references between ph1 and ph2 to use.
1343            */
1344           sched_schedule(&iph2->sce, iph2->approval->lifetime,
1345                            isakmp_ph2expire_stub);
1346 
1347           plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1348           return 0;
1349 }
1350 
1351 /*
1352  * set outbound SA
1353  */
1354 int
pk_sendadd(struct ph2handle * iph2)1355 pk_sendadd(struct ph2handle *iph2)
1356 {
1357           struct saproto *pr;
1358           struct pfkey_send_sa_args sa_args;
1359 
1360           /* sanity check */
1361           if (iph2->approval == NULL) {
1362                     plog(LLV_ERROR, LOCATION, NULL,
1363                               "no approvaled SAs found.\n");
1364                     return -1;
1365           }
1366 
1367           /* fill in some needed for pfkey_send_update2 */
1368           memset (&sa_args, 0, sizeof (sa_args));
1369           sa_args.so = lcconf->sock_pfkey;
1370           if (iph2->lifetime_secs)
1371                     sa_args.l_addtime = iph2->lifetime_secs;
1372           else
1373                     sa_args.l_addtime = iph2->approval->lifetime;
1374           sa_args.seq = iph2->seq;
1375           sa_args.wsize = 4;
1376 
1377           if (iph2->sa_src && iph2->sa_dst) {
1378                     /* MIPv6: Use SA addresses, not IKE ones */
1379                     sa_args.src = dupsaddr(iph2->sa_src);
1380                     sa_args.dst = dupsaddr(iph2->sa_dst);
1381           } else {
1382                     /* Common case: SA addresses and IKE ones are the same */
1383                     sa_args.src = dupsaddr(iph2->src);
1384                     sa_args.dst = dupsaddr(iph2->dst);
1385           }
1386 
1387           if (sa_args.src == NULL || sa_args.dst == NULL) {
1388                     racoon_free(sa_args.src);
1389                     racoon_free(sa_args.dst);
1390                     return -1;
1391           }
1392 
1393           for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1394                     /* validity check */
1395                     sa_args.satype = ipsecdoi2pfkey_proto(pr->proto_id);
1396                     if (sa_args.satype == ~0u) {
1397                               plog(LLV_ERROR, LOCATION, NULL,
1398                                         "invalid proto_id %d\n", pr->proto_id);
1399                               racoon_free(sa_args.src);
1400                               racoon_free(sa_args.dst);
1401                               return -1;
1402                     }
1403                     else if (sa_args.satype == SADB_X_SATYPE_IPCOMP) {
1404                               /* no replay window for IPCOMP */
1405                               sa_args.wsize = 0;
1406                     }
1407 #ifdef ENABLE_SAMODE_UNSPECIFIED
1408                     sa_args.mode = IPSEC_MODE_ANY;
1409 #else
1410                     sa_args.mode = ipsecdoi2pfkey_mode(pr->encmode);
1411                     if (sa_args.mode == ~0u) {
1412                               plog(LLV_ERROR, LOCATION, NULL,
1413                                         "invalid encmode %d\n", pr->encmode);
1414                               racoon_free(sa_args.src);
1415                               racoon_free(sa_args.dst);
1416                               return -1;
1417                     }
1418 #endif
1419 
1420                     /* set algorithm type and key length */
1421                     sa_args.e_keylen = pr->head->encklen;
1422                     if (pfkey_convertfromipsecdoi(
1423                                         pr->proto_id,
1424                                         pr->head->trns_id,
1425                                         pr->head->authtype,
1426                                         &sa_args.e_type, &sa_args.e_keylen,
1427                                         &sa_args.a_type, &sa_args.a_keylen,
1428                                         &sa_args.flags) < 0){
1429                               racoon_free(sa_args.src);
1430                               racoon_free(sa_args.dst);
1431                               return -1;
1432                     }
1433 
1434 #if 0
1435                     sa_args.l_bytes = iph2->approval->lifebyte * 1024,
1436 #else
1437                     sa_args.l_bytes = 0;
1438 #endif
1439 
1440 #ifdef HAVE_SECCTX
1441                     if (*iph2->approval->sctx.ctx_str) {
1442                               sa_args.ctxdoi = iph2->approval->sctx.ctx_doi;
1443                               sa_args.ctxalg = iph2->approval->sctx.ctx_alg;
1444                               sa_args.ctxstrlen = iph2->approval->sctx.ctx_strlen;
1445                               sa_args.ctxstr = iph2->approval->sctx.ctx_str;
1446                     }
1447 #endif /* HAVE_SECCTX */
1448 
1449 #ifdef ENABLE_NATT
1450                     plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_add2 "
1451                         "(NAT flavor)\n");
1452 
1453                     if (pr->udp_encap) {
1454                               sa_args.l_natt_type = UDP_ENCAP_ESPINUDP;
1455                               sa_args.l_natt_sport = extract_port(iph2->ph1->local);
1456                               sa_args.l_natt_dport = extract_port(iph2->ph1->remote);
1457                               sa_args.l_natt_oa = iph2->natoa_dst;
1458 #ifdef SADB_X_EXT_NAT_T_FRAG
1459                               sa_args.l_natt_frag = iph2->ph1->rmconf->esp_frag;
1460 #endif
1461                     }
1462 #endif
1463                     /* more info to fill in */
1464                     sa_args.spi = pr->spi_p;
1465                     sa_args.reqid = pr->reqid_out;
1466                     sa_args.keymat = pr->keymat_p->v;
1467 
1468                     plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_add2\n");
1469                     if (pfkey_send_add2(&sa_args) < 0) {
1470                               plog(LLV_ERROR, LOCATION, NULL,
1471                                         "libipsec failed send add (%s)\n",
1472                                         ipsec_strerror());
1473                               racoon_free(sa_args.src);
1474                               racoon_free(sa_args.dst);
1475                               return -1;
1476                     }
1477 
1478                     if (!lcconf->pathinfo[LC_PATHTYPE_BACKUPSA])
1479                               continue;
1480 
1481                     /*
1482                      * It maybe good idea to call backupsa_to_file() after
1483                      * racoon will receive the sadb_update messages.
1484                      * But it is impossible because there is not key in the
1485                      * information from the kernel.
1486                      */
1487                     if (backupsa_to_file(&sa_args) < 0) {
1488                               plog(LLV_ERROR, LOCATION, NULL,
1489                                         "backuped SA failed: %s\n",
1490                                         sadbsecas2str(sa_args.src, sa_args.dst,
1491                                         sa_args.satype, sa_args.spi, sa_args.mode));
1492                     }
1493                     plog(LLV_DEBUG, LOCATION, NULL,
1494                               "backuped SA: %s\n",
1495                               sadbsecas2str(sa_args.src, sa_args.dst,
1496                               sa_args.satype, sa_args.spi, sa_args.mode));
1497           }
1498           racoon_free(sa_args.src);
1499           racoon_free(sa_args.dst);
1500           return 0;
1501 }
1502 
1503 static int
pk_recvadd(caddr_t * mhp)1504 pk_recvadd(caddr_t *mhp)
1505 {
1506           struct sadb_msg *msg;
1507           struct sadb_sa *sa;
1508           struct sockaddr *src, *dst;
1509           struct ph2handle *iph2;
1510           u_int sa_mode;
1511 
1512           /* ignore this message because of local test mode. */
1513           if (f_local)
1514                     return 0;
1515 
1516           /* sanity check */
1517           if (mhp[0] == NULL
1518            || mhp[SADB_EXT_SA] == NULL
1519            || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1520            || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1521                     plog(LLV_ERROR, LOCATION, NULL,
1522                               "inappropriate sadb add message passed.\n");
1523                     return -1;
1524           }
1525           msg = (struct sadb_msg *)mhp[0];
1526           pk_fixup_sa_addresses(mhp);
1527           src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1528           dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1529           sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1530 
1531           sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1532                     ? IPSEC_MODE_ANY
1533                     : ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1534 
1535           /* the message has to be processed or not ? */
1536           if (msg->sadb_msg_pid != getpid()) {
1537                     plog(LLV_DEBUG, LOCATION, NULL,
1538                               "%s message is not interesting "
1539                               "because pid %d is not mine.\n",
1540                               s_pfkey_type(msg->sadb_msg_type),
1541                               msg->sadb_msg_pid);
1542                     return -1;
1543           }
1544 
1545           iph2 = getph2byseq(msg->sadb_msg_seq);
1546           if (iph2 == NULL) {
1547                     plog(LLV_DEBUG, LOCATION, NULL,
1548                               "seq %d of %s message not interesting.\n",
1549                               msg->sadb_msg_seq,
1550                               s_pfkey_type(msg->sadb_msg_type));
1551                     return -1;
1552           }
1553 
1554           /*
1555            * NOTE don't update any status of phase2 handle
1556            * because they must be updated by SADB_UPDATE message
1557            */
1558 
1559           plog(LLV_INFO, LOCATION, NULL,
1560                     "IPsec-SA established: %s\n",
1561                     sadbsecas2str(src, dst,
1562                               msg->sadb_msg_satype, sa->sadb_sa_spi, sa_mode));
1563 
1564           plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1565           return 0;
1566 }
1567 
1568 static int
pk_recvexpire(caddr_t * mhp)1569 pk_recvexpire(caddr_t *mhp)
1570 {
1571           struct sadb_msg *msg;
1572           struct sadb_sa *sa;
1573           struct sockaddr *src, *dst;
1574           struct ph2handle *iph2;
1575           u_int proto_id, sa_mode;
1576 
1577           /* sanity check */
1578           if (mhp[0] == NULL
1579            || mhp[SADB_EXT_SA] == NULL
1580            || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1581            || mhp[SADB_EXT_ADDRESS_DST] == NULL
1582            || (mhp[SADB_EXT_LIFETIME_HARD] != NULL
1583             && mhp[SADB_EXT_LIFETIME_SOFT] != NULL)) {
1584                     plog(LLV_ERROR, LOCATION, NULL,
1585                               "inappropriate sadb expire message passed.\n");
1586                     return -1;
1587           }
1588           msg = (struct sadb_msg *)mhp[0];
1589           sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1590           pk_fixup_sa_addresses(mhp);
1591           src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1592           dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1593 
1594           sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1595                     ? IPSEC_MODE_ANY
1596                     : ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1597 
1598           proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1599           if (proto_id == ~0u) {
1600                     plog(LLV_ERROR, LOCATION, NULL,
1601                               "invalid proto_id %d\n", msg->sadb_msg_satype);
1602                     return -1;
1603           }
1604 
1605           plog(LLV_INFO, LOCATION, NULL,
1606                     "IPsec-SA expired: %s\n",
1607                     sadbsecas2str(src, dst,
1608                               msg->sadb_msg_satype, sa->sadb_sa_spi, sa_mode));
1609 
1610           iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
1611           if (iph2 == NULL) {
1612                     /*
1613                      * Ignore it because two expire messages are come up.
1614                      * phase2 handler has been deleted already when 2nd message
1615                      * is received.
1616                      */
1617                     plog(LLV_DEBUG, LOCATION, NULL,
1618                               "no such a SA found: %s\n",
1619                               sadbsecas2str(src, dst,
1620                                   msg->sadb_msg_satype, sa->sadb_sa_spi,
1621                                   sa_mode));
1622                     return 0;
1623           }
1624 
1625           /* resent expiry message? */
1626           if (iph2->status > PHASE2ST_ESTABLISHED)
1627                     return 0;
1628 
1629           /* still negotiating? */
1630           if (iph2->status < PHASE2ST_ESTABLISHED) {
1631                     /* not a hard timeout? */
1632                     if (mhp[SADB_EXT_LIFETIME_HARD] == NULL)
1633                               return 0;
1634 
1635                     /*
1636                      * We were negotiating for that SA (w/o much success
1637                      * from current status) and kernel has decided our time
1638                      * is over trying (xfrm_larval_drop controls that and
1639                      * is enabled by default on Linux >= 2.6.28 kernels).
1640                      */
1641                     plog(LLV_WARNING, LOCATION, NULL,
1642                          "PF_KEY EXPIRE message received from kernel for SA"
1643                          " being negotiated. Stopping negotiation.\n");
1644           }
1645 
1646           /* turn off the timer for calling isakmp_ph2expire() */
1647           sched_cancel(&iph2->sce);
1648 
1649           if (iph2->status == PHASE2ST_ESTABLISHED &&
1650               iph2->side == INITIATOR) {
1651                     struct ph1handle *iph1hint;
1652                     /*
1653                      * Active phase 2 expired and we were initiator.
1654                      * Begin new phase 2 exchange, so we can keep on sending
1655                      * traffic.
1656                      */
1657 
1658                     /* update status for re-use */
1659                     iph1hint = iph2->ph1;
1660                     initph2(iph2);
1661                     iph2->status = PHASE2ST_STATUS2;
1662 
1663                     /* start quick exchange */
1664                     if (isakmp_post_acquire(iph2, iph1hint, FALSE) < 0) {
1665                               plog(LLV_ERROR, LOCATION, iph2->dst,
1666                                         "failed to begin ipsec sa "
1667                                         "re-negotication.\n");
1668                               remph2(iph2);
1669                               delph2(iph2);
1670                               return -1;
1671                     }
1672 
1673                     return 0;
1674           }
1675 
1676           /*
1677            * We are responder or the phase 2 was not established.
1678            * Just remove the ph2handle to reflect SADB.
1679            */
1680           iph2->status = PHASE2ST_EXPIRED;
1681           remph2(iph2);
1682           delph2(iph2);
1683 
1684           return 0;
1685 }
1686 
1687 static int
pk_recvacquire(caddr_t * mhp)1688 pk_recvacquire(caddr_t *mhp)
1689 {
1690           struct sadb_msg *msg;
1691           struct sadb_x_policy *xpl;
1692           struct secpolicy *sp_out = NULL, *sp_in = NULL;
1693           struct ph2handle *iph2;
1694           struct sockaddr *src, *dst;     /* IKE addresses (for exchanges) */
1695           struct sockaddr *sp_src, *sp_dst;   /* SP addresses (selectors). */
1696           struct sockaddr *sa_src = NULL, *sa_dst = NULL ; /* SA addresses */
1697 #ifdef HAVE_SECCTX
1698           struct sadb_x_sec_ctx *m_sec_ctx;
1699 #endif /* HAVE_SECCTX */
1700           struct policyindex spidx;
1701 
1702           /* ignore this message because of local test mode. */
1703           if (f_local)
1704                     return 0;
1705 
1706           /* sanity check */
1707           if (mhp[0] == NULL
1708            || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1709            || mhp[SADB_EXT_ADDRESS_DST] == NULL
1710            || mhp[SADB_X_EXT_POLICY] == NULL) {
1711                     plog(LLV_ERROR, LOCATION, NULL,
1712                               "inappropriate sadb acquire message passed.\n");
1713                     return -1;
1714           }
1715           msg = (struct sadb_msg *)mhp[0];
1716           xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
1717           /* acquire does not have nat-t ports; so do not bother setting
1718            * the default port 500; just use the port zero for wildcard
1719            * matching the get a valid natted destination */
1720           sp_src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1721           sp_dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1722 
1723 #ifdef HAVE_SECCTX
1724           m_sec_ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
1725 
1726           if (m_sec_ctx != NULL) {
1727                     plog(LLV_INFO, LOCATION, NULL, "security context doi: %u\n",
1728                          m_sec_ctx->sadb_x_ctx_doi);
1729                     plog(LLV_INFO, LOCATION, NULL,
1730                          "security context algorithm: %u\n",
1731                          m_sec_ctx->sadb_x_ctx_alg);
1732                     plog(LLV_INFO, LOCATION, NULL, "security context length: %u\n",
1733                          m_sec_ctx->sadb_x_ctx_len);
1734                     plog(LLV_INFO, LOCATION, NULL, "security context: %s\n",
1735                          ((char *)m_sec_ctx + sizeof(struct sadb_x_sec_ctx)));
1736           }
1737 #endif /* HAVE_SECCTX */
1738 
1739           /* ignore if type is not IPSEC_POLICY_IPSEC */
1740           if (xpl->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
1741                     plog(LLV_DEBUG, LOCATION, NULL,
1742                               "ignore ACQUIRE message. type is not IPsec.\n");
1743                     return 0;
1744           }
1745 
1746           /* ignore it if src or dst are multicast addresses. */
1747           if ((sp_dst->sa_family == AF_INET
1748             && IN_MULTICAST(ntohl(((struct sockaddr_in *)sp_dst)->sin_addr.s_addr)))
1749 #ifdef INET6
1750            || (sp_dst->sa_family == AF_INET6
1751             && IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)sp_dst)->sin6_addr))
1752 #endif
1753           ) {
1754                     plog(LLV_DEBUG, LOCATION, NULL,
1755                               "ignore due to multicast destination address: %s.\n",
1756                               saddrwop2str(sp_dst));
1757                     return 0;
1758           }
1759 
1760           if ((sp_src->sa_family == AF_INET
1761             && IN_MULTICAST(ntohl(((struct sockaddr_in *)sp_src)->sin_addr.s_addr)))
1762 #ifdef INET6
1763            || (sp_src->sa_family == AF_INET6
1764             && IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)sp_src)->sin6_addr))
1765 #endif
1766           ) {
1767                     plog(LLV_DEBUG, LOCATION, NULL,
1768                               "ignore due to multicast source address: %s.\n",
1769                               saddrwop2str(sp_src));
1770                     return 0;
1771           }
1772 
1773           /* search for proper policyindex */
1774           sp_out = getspbyspid(xpl->sadb_x_policy_id);
1775           if (sp_out == NULL) {
1776                     plog(LLV_ERROR, LOCATION, NULL, "no policy found: id:%d.\n",
1777                               xpl->sadb_x_policy_id);
1778                     return -1;
1779           }
1780           plog(LLV_DEBUG, LOCATION, NULL,
1781                     "suitable outbound SP found: %s.\n", spidx2str(&sp_out->spidx));
1782 
1783           /* Before going further, let first get the source and destination
1784            * address that would be used for IKE negotiation. The logic is:
1785            * - if SP from SPD image contains local and remote hints, we
1786            *   use them (provided by MIGRATE).
1787            * - otherwise, we use the ones from the ipsecrequest, which means:
1788            *   - the addresses from the request for transport mode
1789            *   - the endpoints addresses for tunnel mode
1790            *
1791            * Note that:
1792            * 1) racoon does not support negotiation of bundles which
1793            *    simplifies the lookup for the addresses in the ipsecrequest
1794            *    list, as we expect only one.
1795            * 2) We do source and destination parts all together and do not
1796            *    accept semi-defined information. This is just a decision,
1797            *    there might be needs.
1798            *
1799            * --arno
1800            */
1801           if (sp_out->req && sp_out->req->saidx.mode == IPSEC_MODE_TUNNEL) {
1802                     /* For Tunnel mode, SA addresses are the endpoints */
1803                     src = (struct sockaddr *) &sp_out->req->saidx.src;
1804                     dst = (struct sockaddr *) &sp_out->req->saidx.dst;
1805           } else {
1806                     /* Otherwise use requested addresses.
1807                      *
1808                      * We need to explicitly setup sa_src and sa_dst too,
1809                      * since the SA ports are different from IKE port. And
1810                      * src/dst ports will be overwritten when the matching
1811                      * phase1 is found. */
1812                     src = sa_src = sp_src;
1813                     dst = sa_dst = sp_dst;
1814           }
1815           if (sp_out->local && sp_out->remote) {
1816                     /* hints available, let's use them */
1817                     sa_src = src;
1818                     sa_dst = dst;
1819                     src = (struct sockaddr *) sp_out->local;
1820                     dst = (struct sockaddr *) sp_out->remote;
1821           }
1822 
1823           /*
1824            * If there is a phase 2 handler against the policy identifier in
1825            * the acquire message, and if
1826            *    1. its state is less than PHASE2ST_ESTABLISHED, then racoon
1827            *       should ignore such a acquire message because the phase 2
1828            *       is just negotiating.
1829            *    2. its state is equal to PHASE2ST_ESTABLISHED, then racoon
1830            *       has to process such an acquire message because racoon may
1831            *       have lost the expire message.
1832            */
1833           iph2 = getph2byid(src, dst, xpl->sadb_x_policy_id);
1834           if (iph2 != NULL) {
1835                     if (iph2->status < PHASE2ST_ESTABLISHED) {
1836                               plog(LLV_DEBUG, LOCATION, NULL,
1837                                         "ignore the acquire because ph2 found\n");
1838                               return -1;
1839                     }
1840                     if (iph2->status == PHASE2ST_EXPIRED)
1841                               iph2 = NULL;
1842                     /*FALLTHROUGH*/
1843           }
1844 
1845           /* Check we are listening on source address. If not, ignore. */
1846           if (myaddr_getsport(src) == -1) {
1847                     plog(LLV_DEBUG, LOCATION, NULL,
1848                          "Not listening on source address %s. Ignoring ACQUIRE.\n",
1849                          saddrwop2str(src));
1850                     return 0;
1851           }
1852 
1853           /* get inbound policy */
1854     {
1855 
1856           memset(&spidx, 0, sizeof(spidx));
1857           spidx.dir = IPSEC_DIR_INBOUND;
1858           memcpy(&spidx.src, &sp_out->spidx.dst, sizeof(spidx.src));
1859           memcpy(&spidx.dst, &sp_out->spidx.src, sizeof(spidx.dst));
1860           spidx.prefs = sp_out->spidx.prefd;
1861           spidx.prefd = sp_out->spidx.prefs;
1862           spidx.ul_proto = sp_out->spidx.ul_proto;
1863 
1864 #ifdef HAVE_SECCTX
1865           if (m_sec_ctx) {
1866                     spidx.sec_ctx.ctx_doi = m_sec_ctx->sadb_x_ctx_doi;
1867                     spidx.sec_ctx.ctx_alg = m_sec_ctx->sadb_x_ctx_alg;
1868                     spidx.sec_ctx.ctx_strlen = m_sec_ctx->sadb_x_ctx_len;
1869                     memcpy(spidx.sec_ctx.ctx_str,
1870                           ((char *)m_sec_ctx + sizeof(struct sadb_x_sec_ctx)),
1871                           spidx.sec_ctx.ctx_strlen);
1872           }
1873 #endif /* HAVE_SECCTX */
1874 
1875           sp_in = getsp(&spidx);
1876           if (sp_in) {
1877                     plog(LLV_DEBUG, LOCATION, NULL,
1878                               "suitable inbound SP found: %s.\n",
1879                               spidx2str(&sp_in->spidx));
1880           } else {
1881                     plog(LLV_NOTIFY, LOCATION, NULL,
1882                               "no in-bound policy found: %s\n",
1883                               spidx2str(&spidx));
1884           }
1885     }
1886 
1887           /* allocate a phase 2 */
1888           iph2 = newph2();
1889           if (iph2 == NULL) {
1890                     plog(LLV_ERROR, LOCATION, NULL,
1891                               "failed to allocate phase2 entry.\n");
1892                     return -1;
1893           }
1894           iph2->side = INITIATOR;
1895           iph2->spid = xpl->sadb_x_policy_id;
1896           iph2->satype = msg->sadb_msg_satype;
1897           iph2->seq = msg->sadb_msg_seq;
1898           iph2->status = PHASE2ST_STATUS2;
1899 
1900           /* set address used by IKE for the negotiation (might differ from
1901            * SA address, i.e. might not be tunnel endpoints or addresses
1902            * of transport mode SA) */
1903           iph2->dst = dupsaddr(dst);
1904           if (iph2->dst == NULL) {
1905                     delph2(iph2);
1906                     return -1;
1907           }
1908           iph2->src = dupsaddr(src);
1909           if (iph2->src == NULL) {
1910                     delph2(iph2);
1911                     return -1;
1912           }
1913 
1914           /* If sa_src and sa_dst have been set, this mean we have to
1915            * set iph2->sa_src and iph2->sa_dst to provide the addresses
1916            * of the SA because iph2->src and iph2->dst are only the ones
1917            * used for the IKE exchanges. Those that need these addresses
1918            * are for instance pk_sendupdate() or pk_sendgetspi() */
1919           if (sa_src) {
1920                     iph2->sa_src = dupsaddr(sa_src);
1921                     iph2->sa_dst = dupsaddr(sa_dst);
1922           }
1923 
1924           if (isakmp_get_sainfo(iph2, sp_out, sp_in) < 0) {
1925                     delph2(iph2);
1926                     return -1;
1927           }
1928 
1929 #ifdef HAVE_SECCTX
1930           if (m_sec_ctx) {
1931                     set_secctx_in_proposal(iph2, spidx);
1932           }
1933 #endif /* HAVE_SECCTX */
1934 
1935           insph2(iph2);
1936 
1937           /* start isakmp initiation by using ident exchange */
1938           /* XXX should be looped if there are multiple phase 2 handler. */
1939           if (isakmp_post_acquire(iph2, NULL, TRUE) < 0) {
1940                     plog(LLV_ERROR, LOCATION, NULL,
1941                               "failed to begin ipsec sa negotication.\n");
1942                     remph2(iph2);
1943                     delph2(iph2);
1944                     return -1;
1945           }
1946 
1947           return 0;
1948 }
1949 
1950 static int
pk_recvdelete(caddr_t * mhp)1951 pk_recvdelete(caddr_t *mhp)
1952 {
1953           struct sadb_msg *msg;
1954           struct sadb_sa *sa;
1955           struct sockaddr *src, *dst;
1956           struct ph2handle *iph2 = NULL;
1957           u_int proto_id;
1958 
1959           /* ignore this message because of local test mode. */
1960           if (f_local)
1961                     return 0;
1962 
1963           /* sanity check */
1964           if (mhp[0] == NULL
1965            || mhp[SADB_EXT_SA] == NULL
1966            || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1967            || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1968                     plog(LLV_ERROR, LOCATION, NULL,
1969                               "inappropriate sadb delete message passed.\n");
1970                     return -1;
1971           }
1972           msg = (struct sadb_msg *)mhp[0];
1973           sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1974           pk_fixup_sa_addresses(mhp);
1975           src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1976           dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1977 
1978           /* the message has to be processed or not ? */
1979           if (msg->sadb_msg_pid == getpid()) {
1980                     plog(LLV_DEBUG, LOCATION, NULL,
1981                               "%s message is not interesting "
1982                               "because the message was originated by me.\n",
1983                               s_pfkey_type(msg->sadb_msg_type));
1984                     return -1;
1985           }
1986 
1987           proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1988           if (proto_id == ~0u) {
1989                     plog(LLV_ERROR, LOCATION, NULL,
1990                               "invalid proto_id %d\n", msg->sadb_msg_satype);
1991                     return -1;
1992           }
1993 
1994           iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
1995           if (iph2 == NULL) {
1996                     /* ignore */
1997                     plog(LLV_ERROR, LOCATION, NULL,
1998                               "no iph2 found: %s\n",
1999                               sadbsecas2str(src, dst, msg->sadb_msg_satype,
2000                                         sa->sadb_sa_spi, IPSEC_MODE_ANY));
2001                     return 0;
2002           }
2003 
2004           plog(LLV_ERROR, LOCATION, NULL,
2005                     "pfkey DELETE received: %s\n",
2006                     sadbsecas2str(src, dst,
2007                               msg->sadb_msg_satype, sa->sadb_sa_spi, IPSEC_MODE_ANY));
2008 
2009           /* send delete information */
2010           if (iph2->status == PHASE2ST_ESTABLISHED)
2011                     isakmp_info_send_d2(iph2);
2012 
2013           remph2(iph2);
2014           delph2(iph2);
2015 
2016           return 0;
2017 }
2018 
2019 static int
pk_recvflush(caddr_t * mhp)2020 pk_recvflush(caddr_t *mhp)
2021 {
2022           /* ignore this message because of local test mode. */
2023           if (f_local)
2024                     return 0;
2025 
2026           /* sanity check */
2027           if (mhp[0] == NULL) {
2028                     plog(LLV_ERROR, LOCATION, NULL,
2029                               "inappropriate sadb flush message passed.\n");
2030                     return -1;
2031           }
2032 
2033           flushph2();
2034 
2035           return 0;
2036 }
2037 
2038 static int
getsadbpolicy(caddr_t * policy0,int * policylen0,int type,struct ph2handle * iph2)2039 getsadbpolicy(caddr_t *policy0, int *policylen0, int type,
2040     struct ph2handle *iph2)
2041 {
2042           struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2043           struct sockaddr *src = NULL, *dst = NULL;
2044           struct sadb_x_policy *xpl;
2045           struct sadb_x_ipsecrequest *xisr;
2046           struct saproto *pr;
2047           struct saproto **pr_rlist;
2048           int rlist_len = 0;
2049           caddr_t policy, p;
2050           int policylen;
2051           int xisrlen;
2052           u_int satype, mode;
2053           int len = 0;
2054 #ifdef HAVE_SECCTX
2055           int ctxlen = 0;
2056 #endif /* HAVE_SECCTX */
2057 
2058 
2059           /* get policy buffer size */
2060           policylen = sizeof(struct sadb_x_policy);
2061           if (type != SADB_X_SPDDELETE) {
2062                     if (iph2->sa_src && iph2->sa_dst) {
2063                               src = iph2->sa_src; /* MIPv6: Use SA addresses, */
2064                               dst = iph2->sa_dst; /* not IKE ones             */
2065                     } else {
2066                               src = iph2->src; /* Common case: SA addresses */
2067                               dst = iph2->dst; /* and IKE ones are the same */
2068                     }
2069 
2070                     for (pr = iph2->approval->head; pr; pr = pr->next) {
2071                               xisrlen = sizeof(*xisr);
2072                               if (pr->encmode == IPSECDOI_ATTR_ENC_MODE_TUNNEL) {
2073                                         xisrlen += (sysdep_sa_len(src) +
2074                                                       sysdep_sa_len(dst));
2075                               }
2076 
2077                               policylen += PFKEY_ALIGN8(xisrlen);
2078                     }
2079           }
2080 
2081 #ifdef HAVE_SECCTX
2082           if (*spidx->sec_ctx.ctx_str) {
2083                     ctxlen = sizeof(struct sadb_x_sec_ctx)
2084                                         + PFKEY_ALIGN8(spidx->sec_ctx.ctx_strlen);
2085                     policylen += ctxlen;
2086           }
2087 #endif /* HAVE_SECCTX */
2088 
2089           /* make policy structure */
2090           policy = racoon_malloc(policylen);
2091           memset((void*)policy, 0xcd, policylen);
2092           if (!policy) {
2093                     plog(LLV_ERROR, LOCATION, NULL,
2094                               "buffer allocation failed.\n");
2095                     return -1;
2096           }
2097 
2098           xpl = (struct sadb_x_policy *)policy;
2099           xpl->sadb_x_policy_len = PFKEY_UNIT64(policylen);
2100           xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2101           xpl->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2102           xpl->sadb_x_policy_dir = spidx->dir;
2103           xpl->sadb_x_policy_id = 0;
2104 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2105           xpl->sadb_x_policy_priority = PRIORITY_DEFAULT;
2106 #endif
2107           len++;
2108 
2109 #ifdef HAVE_SECCTX
2110           if (*spidx->sec_ctx.ctx_str) {
2111                     struct sadb_x_sec_ctx *p;
2112 
2113                     p = (struct sadb_x_sec_ctx *)(xpl + len);
2114                     memset(p, 0, ctxlen);
2115                     p->sadb_x_sec_len = PFKEY_UNIT64(ctxlen);
2116                     p->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
2117                     p->sadb_x_ctx_len = spidx->sec_ctx.ctx_strlen;
2118                     p->sadb_x_ctx_doi = spidx->sec_ctx.ctx_doi;
2119                     p->sadb_x_ctx_alg = spidx->sec_ctx.ctx_alg;
2120 
2121                     memcpy(p + 1,spidx->sec_ctx.ctx_str,spidx->sec_ctx.ctx_strlen);
2122                     len += ctxlen;
2123           }
2124 #endif /* HAVE_SECCTX */
2125 
2126           /* no need to append policy information any more if type is SPDDELETE */
2127           if (type == SADB_X_SPDDELETE)
2128                     goto end;
2129 
2130           xisr = (struct sadb_x_ipsecrequest *)(xpl + len);
2131 
2132           /* The order of things is reversed for use in add policy messages */
2133           for (pr = iph2->approval->head; pr; pr = pr->next) rlist_len++;
2134           pr_rlist = racoon_malloc((rlist_len+1)*sizeof(struct saproto*));
2135           if (!pr_rlist) {
2136                     plog(LLV_ERROR, LOCATION, NULL,
2137                               "buffer allocation failed.\n");
2138                     return -1;
2139           }
2140           pr_rlist[rlist_len--] = NULL;
2141           for (pr = iph2->approval->head; pr; pr = pr->next) pr_rlist[rlist_len--] = pr;
2142           rlist_len = 0;
2143 
2144           for (pr = pr_rlist[rlist_len++]; pr; pr = pr_rlist[rlist_len++]) {
2145 
2146                     satype = doi2ipproto(pr->proto_id);
2147                     if (satype == ~0u) {
2148                               plog(LLV_ERROR, LOCATION, NULL,
2149                                         "invalid proto_id %d\n", pr->proto_id);
2150                               goto err;
2151                     }
2152                     mode = ipsecdoi2pfkey_mode(pr->encmode);
2153                     if (mode == ~0u) {
2154                               plog(LLV_ERROR, LOCATION, NULL,
2155                                         "invalid encmode %d\n", pr->encmode);
2156                               goto err;
2157                     }
2158 
2159                     /*
2160                      * the policy level cannot be unique because the policy
2161                      * is defined later than SA, so req_id cannot be bound to SA.
2162                      */
2163                     xisr->sadb_x_ipsecrequest_proto = satype;
2164                     xisr->sadb_x_ipsecrequest_mode = mode;
2165                     if(iph2->proposal->head->reqid_in > 0){
2166                               xisr->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2167                               xisr->sadb_x_ipsecrequest_reqid = iph2->proposal->head->reqid_in;
2168                     }else{
2169                               xisr->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE;
2170                               xisr->sadb_x_ipsecrequest_reqid = 0;
2171                     }
2172                     p = (caddr_t)(xisr + 1);
2173 
2174                     xisrlen = sizeof(*xisr);
2175 
2176                     if (pr->encmode == IPSECDOI_ATTR_ENC_MODE_TUNNEL) {
2177                               int src_len, dst_len;
2178 
2179                               src_len = sysdep_sa_len(src);
2180                               dst_len = sysdep_sa_len(dst);
2181                               xisrlen += src_len + dst_len;
2182 
2183                               memcpy(p, src, src_len);
2184                               p += src_len;
2185 
2186                               memcpy(p, dst, dst_len);
2187                               p += dst_len;
2188                     }
2189 
2190                     xisr->sadb_x_ipsecrequest_len = PFKEY_ALIGN8(xisrlen);
2191                     xisr = (struct sadb_x_ipsecrequest *)p;
2192 
2193           }
2194           racoon_free(pr_rlist);
2195 
2196 end:
2197           *policy0 = policy;
2198           *policylen0 = policylen;
2199 
2200           return 0;
2201 
2202 err:
2203           if (policy)
2204                     racoon_free(policy);
2205           if (pr_rlist) racoon_free(pr_rlist);
2206 
2207           return -1;
2208 }
2209 
2210 int
pk_sendspdupdate2(struct ph2handle * iph2)2211 pk_sendspdupdate2(struct ph2handle *iph2)
2212 {
2213           struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2214           caddr_t policy = NULL;
2215           int policylen = 0;
2216           u_int64_t ltime, vtime;
2217 
2218           ltime = iph2->approval->lifetime;
2219           vtime = 0;
2220 
2221           if (getsadbpolicy(&policy, &policylen, SADB_X_SPDUPDATE, iph2)) {
2222                     plog(LLV_ERROR, LOCATION, NULL,
2223                               "getting sadb policy failed.\n");
2224                     return -1;
2225           }
2226 
2227           if (pfkey_send_spdupdate2(
2228                               lcconf->sock_pfkey,
2229                               (struct sockaddr *)&spidx->src,
2230                               spidx->prefs,
2231                               (struct sockaddr *)&spidx->dst,
2232                               spidx->prefd,
2233                               spidx->ul_proto,
2234                               ltime, vtime,
2235                               policy, policylen, 0) < 0) {
2236                     plog(LLV_ERROR, LOCATION, NULL,
2237                               "libipsec failed send spdupdate2 (%s)\n",
2238                               ipsec_strerror());
2239                     goto end;
2240           }
2241           plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spdupdate2\n");
2242 
2243 end:
2244           if (policy)
2245                     racoon_free(policy);
2246 
2247           return 0;
2248 }
2249 
2250 static int
pk_recvspdupdate(caddr_t * mhp)2251 pk_recvspdupdate(caddr_t *mhp)
2252 {
2253           struct sadb_address *saddr, *daddr;
2254           struct sadb_x_policy *xpl;
2255           struct sadb_lifetime *lt;
2256           struct policyindex spidx;
2257           struct secpolicy *sp;
2258           struct sockaddr *local=NULL, *remote=NULL;
2259           u_int64_t created;
2260           int ret;
2261 
2262           /* sanity check */
2263           if (mhp[0] == NULL
2264            || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2265            || mhp[SADB_EXT_ADDRESS_DST] == NULL
2266            || mhp[SADB_X_EXT_POLICY] == NULL) {
2267                     plog(LLV_ERROR, LOCATION, NULL,
2268                               "inappropriate sadb spdupdate message passed.\n");
2269                     return -1;
2270           }
2271           saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2272           daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2273           xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2274           lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2275           if(lt != NULL)
2276                     created = lt->sadb_lifetime_addtime;
2277           else
2278                     created = 0;
2279 
2280 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2281           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2282                               saddr + 1,
2283                               daddr + 1,
2284                               saddr->sadb_address_prefixlen,
2285                               daddr->sadb_address_prefixlen,
2286                               saddr->sadb_address_proto,
2287                               xpl->sadb_x_policy_priority,
2288                               created,
2289                               &spidx);
2290 #else
2291           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2292                               saddr + 1,
2293                               daddr + 1,
2294                               saddr->sadb_address_prefixlen,
2295                               daddr->sadb_address_prefixlen,
2296                               saddr->sadb_address_proto,
2297                               created,
2298                               &spidx);
2299 #endif
2300 
2301 #ifdef HAVE_SECCTX
2302           if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2303                     struct sadb_x_sec_ctx *ctx;
2304 
2305                     ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2306                     spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2307                     spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2308                     spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2309                     memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2310           }
2311 #endif /* HAVE_SECCTX */
2312 
2313           sp = getsp(&spidx);
2314           if (sp == NULL) {
2315                     plog(LLV_DEBUG, LOCATION, NULL,
2316                               "this policy did not exist for removal: \"%s\"\n",
2317                               spidx2str(&spidx));
2318           } else {
2319                     /* preserve hints before deleting the SP */
2320                     local = sp->local;
2321                     remote = sp->remote;
2322                     sp->local = NULL;
2323                     sp->remote = NULL;
2324 
2325                     remsp(sp);
2326                     delsp(sp);
2327           }
2328 
2329           /* Add new SP (with old hints) */
2330           ret = addnewsp(mhp, local, remote);
2331 
2332           if (local != NULL)
2333                     racoon_free(local);
2334           if (remote != NULL)
2335                     racoon_free(remote);
2336 
2337           if (ret < 0)
2338                     return -1;
2339 
2340           return 0;
2341 }
2342 
2343 /*
2344  * this function has to be used by responder side.
2345  */
2346 int
pk_sendspdadd2(struct ph2handle * iph2)2347 pk_sendspdadd2(struct ph2handle *iph2)
2348 {
2349           struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2350           caddr_t policy = NULL;
2351           int policylen = 0;
2352           u_int64_t ltime, vtime;
2353 
2354           ltime = iph2->approval->lifetime;
2355           vtime = 0;
2356 
2357           if (getsadbpolicy(&policy, &policylen, SADB_X_SPDADD, iph2)) {
2358                     plog(LLV_ERROR, LOCATION, NULL,
2359                               "getting sadb policy failed.\n");
2360                     return -1;
2361           }
2362 
2363           if (pfkey_send_spdadd2(
2364                               lcconf->sock_pfkey,
2365                               (struct sockaddr *)&spidx->src,
2366                               spidx->prefs,
2367                               (struct sockaddr *)&spidx->dst,
2368                               spidx->prefd,
2369                               spidx->ul_proto,
2370                               ltime, vtime,
2371                               policy, policylen, 0) < 0) {
2372                     plog(LLV_ERROR, LOCATION, NULL,
2373                               "libipsec failed send spdadd2 (%s)\n",
2374                               ipsec_strerror());
2375                     goto end;
2376           }
2377           plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spdadd2\n");
2378 
2379 end:
2380           if (policy)
2381                     racoon_free(policy);
2382 
2383           return 0;
2384 }
2385 
2386 static int
pk_recvspdadd(caddr_t * mhp)2387 pk_recvspdadd(caddr_t *mhp)
2388 {
2389           struct sadb_address *saddr, *daddr;
2390           struct sadb_x_policy *xpl;
2391           struct sadb_lifetime *lt;
2392           struct policyindex spidx;
2393           struct secpolicy *sp;
2394           struct sockaddr *local = NULL, *remote = NULL;
2395           u_int64_t created;
2396           int ret;
2397 
2398           /* sanity check */
2399           if (mhp[0] == NULL
2400            || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2401            || mhp[SADB_EXT_ADDRESS_DST] == NULL
2402            || mhp[SADB_X_EXT_POLICY] == NULL) {
2403                     plog(LLV_ERROR, LOCATION, NULL,
2404                               "inappropriate sadb spdadd message passed.\n");
2405                     return -1;
2406           }
2407           saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2408           daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2409           xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2410           lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2411           if(lt != NULL)
2412                     created = lt->sadb_lifetime_addtime;
2413           else
2414                     created = 0;
2415 
2416 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2417           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2418                               saddr + 1,
2419                               daddr + 1,
2420                               saddr->sadb_address_prefixlen,
2421                               daddr->sadb_address_prefixlen,
2422                               saddr->sadb_address_proto,
2423                               xpl->sadb_x_policy_priority,
2424                               created,
2425                               &spidx);
2426 #else
2427           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2428                               saddr + 1,
2429                               daddr + 1,
2430                               saddr->sadb_address_prefixlen,
2431                               daddr->sadb_address_prefixlen,
2432                               saddr->sadb_address_proto,
2433                               created,
2434                               &spidx);
2435 #endif
2436 
2437 #ifdef HAVE_SECCTX
2438           if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2439                     struct sadb_x_sec_ctx *ctx;
2440 
2441                     ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2442                     spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2443                     spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2444                     spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2445                     memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2446           }
2447 #endif /* HAVE_SECCTX */
2448 
2449           sp = getsp(&spidx);
2450           if (sp != NULL) {
2451                     plog(LLV_ERROR, LOCATION, NULL,
2452                               "such policy already exists. "
2453                               "anyway replace it: %s\n",
2454                               spidx2str(&spidx));
2455 
2456                     /* preserve hints before deleting the SP */
2457                     local = sp->local;
2458                     remote = sp->remote;
2459                     sp->local = NULL;
2460                     sp->remote = NULL;
2461 
2462                     remsp(sp);
2463                     delsp(sp);
2464           }
2465 
2466           /* Add new SP (with old hints) */
2467           ret = addnewsp(mhp, local, remote);
2468 
2469           if (local != NULL)
2470                     racoon_free(local);
2471           if (remote != NULL)
2472                     racoon_free(remote);
2473 
2474           if (ret < 0)
2475                     return -1;
2476 
2477           return 0;
2478 }
2479 
2480 /*
2481  * this function has to be used by responder side.
2482  */
2483 int
pk_sendspddelete(struct ph2handle * iph2)2484 pk_sendspddelete(struct ph2handle *iph2)
2485 {
2486           struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
2487           caddr_t policy = NULL;
2488           int policylen;
2489 
2490           if (getsadbpolicy(&policy, &policylen, SADB_X_SPDDELETE, iph2)) {
2491                     plog(LLV_ERROR, LOCATION, NULL,
2492                               "getting sadb policy failed.\n");
2493                     return -1;
2494           }
2495 
2496           if (pfkey_send_spddelete(
2497                               lcconf->sock_pfkey,
2498                               (struct sockaddr *)&spidx->src,
2499                               spidx->prefs,
2500                               (struct sockaddr *)&spidx->dst,
2501                               spidx->prefd,
2502                               spidx->ul_proto,
2503                               policy, policylen, 0) < 0) {
2504                     plog(LLV_ERROR, LOCATION, NULL,
2505                               "libipsec failed send spddelete (%s)\n",
2506                               ipsec_strerror());
2507                     goto end;
2508           }
2509           plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spddelete\n");
2510 
2511 end:
2512           if (policy)
2513                     racoon_free(policy);
2514 
2515           return 0;
2516 }
2517 
2518 static int
pk_recvspddelete(caddr_t * mhp)2519 pk_recvspddelete(caddr_t *mhp)
2520 {
2521           struct sadb_address *saddr, *daddr;
2522           struct sadb_x_policy *xpl;
2523           struct sadb_lifetime *lt;
2524           struct policyindex spidx;
2525           struct secpolicy *sp;
2526           u_int64_t created;
2527 
2528           /* sanity check */
2529           if (mhp[0] == NULL
2530            || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2531            || mhp[SADB_EXT_ADDRESS_DST] == NULL
2532            || mhp[SADB_X_EXT_POLICY] == NULL) {
2533                     plog(LLV_ERROR, LOCATION, NULL,
2534                               "inappropriate sadb spddelete message passed.\n");
2535                     return -1;
2536           }
2537           saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2538           daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2539           xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2540           lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2541           if(lt != NULL)
2542                     created = lt->sadb_lifetime_addtime;
2543           else
2544                     created = 0;
2545 
2546 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2547           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2548                               saddr + 1,
2549                               daddr + 1,
2550                               saddr->sadb_address_prefixlen,
2551                               daddr->sadb_address_prefixlen,
2552                               saddr->sadb_address_proto,
2553                               xpl->sadb_x_policy_priority,
2554                               created,
2555                               &spidx);
2556 #else
2557           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2558                               saddr + 1,
2559                               daddr + 1,
2560                               saddr->sadb_address_prefixlen,
2561                               daddr->sadb_address_prefixlen,
2562                               saddr->sadb_address_proto,
2563                               created,
2564                               &spidx);
2565 #endif
2566 
2567 #ifdef HAVE_SECCTX
2568           if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2569                     struct sadb_x_sec_ctx *ctx;
2570 
2571                     ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2572                     spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2573                     spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2574                     spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2575                     memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2576           }
2577 #endif /* HAVE_SECCTX */
2578 
2579           sp = getsp(&spidx);
2580           if (sp == NULL) {
2581                     plog(LLV_ERROR, LOCATION, NULL,
2582                               "no policy found: %s\n",
2583                               spidx2str(&spidx));
2584                     return -1;
2585           }
2586 
2587           remsp(sp);
2588           delsp(sp);
2589 
2590           return 0;
2591 }
2592 
2593 static int
pk_recvspdexpire(caddr_t * mhp)2594 pk_recvspdexpire(caddr_t *mhp)
2595 {
2596           struct sadb_address *saddr, *daddr;
2597           struct sadb_x_policy *xpl;
2598           struct sadb_lifetime *lt;
2599           struct policyindex spidx;
2600           struct secpolicy *sp;
2601           u_int64_t created;
2602 
2603           /* sanity check */
2604           if (mhp[0] == NULL
2605            || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2606            || mhp[SADB_EXT_ADDRESS_DST] == NULL
2607            || mhp[SADB_X_EXT_POLICY] == NULL) {
2608                     plog(LLV_ERROR, LOCATION, NULL,
2609                               "inappropriate sadb spdexpire message passed.\n");
2610                     return -1;
2611           }
2612           saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2613           daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2614           xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2615           lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2616           if(lt != NULL)
2617                     created = lt->sadb_lifetime_addtime;
2618           else
2619                     created = 0;
2620 
2621 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2622           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2623                               saddr + 1,
2624                               daddr + 1,
2625                               saddr->sadb_address_prefixlen,
2626                               daddr->sadb_address_prefixlen,
2627                               saddr->sadb_address_proto,
2628                               xpl->sadb_x_policy_priority,
2629                               created,
2630                               &spidx);
2631 #else
2632           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2633                               saddr + 1,
2634                               daddr + 1,
2635                               saddr->sadb_address_prefixlen,
2636                               daddr->sadb_address_prefixlen,
2637                               saddr->sadb_address_proto,
2638                               created,
2639                               &spidx);
2640 #endif
2641 
2642 #ifdef HAVE_SECCTX
2643           if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2644                     struct sadb_x_sec_ctx *ctx;
2645 
2646                     ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2647                     spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2648                     spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2649                     spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2650                     memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2651           }
2652 #endif /* HAVE_SECCTX */
2653 
2654           sp = getsp(&spidx);
2655           if (sp == NULL) {
2656                     plog(LLV_ERROR, LOCATION, NULL,
2657                               "no policy found: %s\n",
2658                               spidx2str(&spidx));
2659                     return -1;
2660           }
2661 
2662           remsp(sp);
2663           delsp(sp);
2664 
2665           return 0;
2666 }
2667 
2668 static int
pk_recvspdget(caddr_t * mhp)2669 pk_recvspdget(caddr_t *mhp)
2670 {
2671           /* sanity check */
2672           if (mhp[0] == NULL) {
2673                     plog(LLV_ERROR, LOCATION, NULL,
2674                               "inappropriate sadb spdget message passed.\n");
2675                     return -1;
2676           }
2677 
2678           return 0;
2679 }
2680 
2681 static int
pk_recvspddump(caddr_t * mhp)2682 pk_recvspddump(caddr_t *mhp)
2683 {
2684           struct sadb_address *saddr, *daddr;
2685           struct sadb_x_policy *xpl;
2686           struct sadb_lifetime *lt;
2687           struct policyindex spidx;
2688           struct secpolicy *sp;
2689           struct sockaddr *local=NULL, *remote=NULL;
2690           u_int64_t created;
2691           int ret;
2692 
2693           /* sanity check */
2694           if (mhp[0] == NULL) {
2695                     plog(LLV_ERROR, LOCATION, NULL,
2696                               "inappropriate sadb spddump message passed.\n");
2697                     return -1;
2698           }
2699           saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2700           daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2701           xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2702           lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
2703           if(lt != NULL)
2704                     created = lt->sadb_lifetime_addtime;
2705           else
2706                     created = 0;
2707 
2708           if (saddr == NULL || daddr == NULL || xpl == NULL) {
2709                     plog(LLV_ERROR, LOCATION, NULL,
2710                               "inappropriate sadb spddump message passed.\n");
2711                     return -1;
2712           }
2713 
2714 #ifdef HAVE_PFKEY_POLICY_PRIORITY
2715           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2716                               saddr + 1,
2717                               daddr + 1,
2718                               saddr->sadb_address_prefixlen,
2719                               daddr->sadb_address_prefixlen,
2720                               saddr->sadb_address_proto,
2721                               xpl->sadb_x_policy_priority,
2722                               created,
2723                               &spidx);
2724 #else
2725           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2726                               saddr + 1,
2727                               daddr + 1,
2728                               saddr->sadb_address_prefixlen,
2729                               daddr->sadb_address_prefixlen,
2730                               saddr->sadb_address_proto,
2731                               created,
2732                               &spidx);
2733 #endif
2734 
2735 #ifdef HAVE_SECCTX
2736           if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
2737                     struct sadb_x_sec_ctx *ctx;
2738 
2739                     ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
2740                     spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
2741                     spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
2742                     spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
2743                     memcpy(spidx.sec_ctx.ctx_str, ctx + 1, ctx->sadb_x_ctx_len);
2744           }
2745 #endif /* HAVE_SECCTX */
2746 
2747           sp = getsp(&spidx);
2748           if (sp != NULL) {
2749                     plog(LLV_ERROR, LOCATION, NULL,
2750                               "such policy already exists. "
2751                               "anyway replace it: %s\n",
2752                               spidx2str(&spidx));
2753 
2754                     /* preserve hints before deleting the SP */
2755                     local = sp->local;
2756                     remote = sp->remote;
2757                     sp->local = NULL;
2758                     sp->remote = NULL;
2759 
2760                     remsp(sp);
2761                     delsp(sp);
2762           }
2763 
2764           /* Add new SP (with old hints) */
2765           ret = addnewsp(mhp, local, remote);
2766 
2767           if (local != NULL)
2768                     racoon_free(local);
2769           if (remote != NULL)
2770                     racoon_free(remote);
2771 
2772           if (ret < 0)
2773                     return -1;
2774 
2775           return 0;
2776 }
2777 
2778 static int
pk_recvspdflush(caddr_t * mhp)2779 pk_recvspdflush(caddr_t *mhp)
2780 {
2781           /* sanity check */
2782           if (mhp[0] == NULL) {
2783                     plog(LLV_ERROR, LOCATION, NULL,
2784                               "inappropriate sadb spdflush message passed.\n");
2785                     return -1;
2786           }
2787 
2788           flushsp();
2789 
2790           return 0;
2791 }
2792 
2793 #if defined(SADB_X_MIGRATE) && defined(SADB_X_EXT_KMADDRESS)
2794 
2795 /* MIGRATE support (pk_recvmigrate() is the handler of MIGRATE message).
2796  *
2797  * pk_recvmigrate()
2798  *   1) some preprocessing and checks
2799  *   2) parsing of sadb_x_kmaddress extension
2800  *   3) SP lookup using selectors and content of policy extension from MIGRATE
2801  *   4) resolution of current local and remote IKE addresses
2802  *   5) Use of addresses to get Phase 1 handler if any
2803  *   6) Update of IKE addresses in Phase 1 (iph1->local and iph1->remote)
2804  *   7) Update of IKE addresses in Phase 2 (iph2->src and iph2->dst)
2805  *   8) Update of IKE addresses in SP (sp->local and sp->remote)
2806  *   9) Loop on sadb_x_ipsecrequests pairs from MIGRATE
2807  *      - update of associated ipsecrequests entries in sp->req (should be
2808  *        only one as racoon does not support bundles), i.e. update of
2809  *        tunnel endpoints when required.
2810  *      - If tunnel mode endpoints have been updated, lookup of associated
2811  *        Phase 2 handle to also update sa_src and sa_dst entries
2812  *
2813  * XXX Note that we do not support yet the update of SA addresses for transport
2814  *     mode, but only the update of SA addresses for tunnel mode (endpoints).
2815  *     Reasons are:
2816  *      - there is no initial need for MIPv6
2817  *      - racoon does not support bundles
2818  *      - this would imply more work to deal with sainfo update (if feasible).
2819  */
2820 
2821 /* Generic argument structure for migration callbacks */
2822 struct migrate_args {
2823           struct sockaddr *local;
2824           struct sockaddr *remote;
2825 };
2826 
2827 /*
2828  * Update local and remote addresses of given Phase 1. Schedule removal
2829  * if negotiation was going on and restart a one from updated address.
2830  *
2831  * -1 is returned on error. 0 if everything went right.
2832  */
2833 static int
migrate_ph1_ike_addresses(iph1,arg)2834 migrate_ph1_ike_addresses(iph1, arg)
2835         struct ph1handle *iph1;
2836         void *arg;
2837 {
2838           struct migrate_args *ma = (struct migrate_args *) arg;
2839           struct remoteconf *rmconf;
2840           uint16_t port;
2841 
2842           /* Already up-to-date? */
2843           if (cmpsaddr(iph1->local, ma->local) == CMPSADDR_MATCH &&
2844               cmpsaddr(iph1->remote, ma->remote) == CMPSADDR_MATCH)
2845                     return 0;
2846 
2847           if (iph1->status < PHASE1ST_ESTABLISHED) {
2848                     /* Bad luck! We received a MIGRATE *while* negotiating
2849                      * Phase 1 (i.e. it was not established yet). If we act as
2850                      * initiator we need to restart the negotiation. As
2851                      * responder, our best bet is to update our addresses
2852                      * and wait for the initiator to do something */
2853                     plog(LLV_WARNING, LOCATION, NULL, "MIGRATE received *during* "
2854                          "Phase 1 negotiation (%s).\n",
2855                          saddr2str_fromto("%s => %s", ma->local, ma->remote));
2856 
2857                     /* If we are not acting as initiator, let's just leave and
2858                      * let the remote peer handle the restart */
2859                     rmconf = getrmconf(ma->remote, 0);
2860                     if (rmconf == NULL || !rmconf->passive) {
2861                               iph1->status = PHASE1ST_EXPIRED;
2862                               isakmp_ph1delete(iph1);
2863 
2864                               /* This is unlikely, but let's just check if a Phase 1
2865                                * for the new addresses already exist */
2866                               if (getph1byaddr(ma->local, ma->remote, 0)) {
2867                                         plog(LLV_WARNING, LOCATION, NULL, "No need "
2868                                              "to start a new Phase 1 negotiation. One "
2869                                              "already exists.\n");
2870                                         return 0;
2871                               }
2872 
2873                               plog(LLV_WARNING, LOCATION, NULL, "As initiator, "
2874                                    "restarting it.\n");
2875                                /* Note that the insertion of the new Phase 1 will not
2876                                 * interfere with the fact we are called from enumph1,
2877                                 * because it is inserted as first element. --arno */
2878                               isakmp_ph1begin_i(rmconf, ma->local, ma->remote);
2879 
2880                               return 0;
2881                     }
2882           }
2883 
2884           if (iph1->local != NULL) {
2885                     plog(LLV_DEBUG, LOCATION, NULL, "Migrating Phase 1 local "
2886                          "address from %s\n",
2887                          saddr2str_fromto("%s to %s", iph1->local, ma->local));
2888                     port = extract_port(iph1->local);
2889                     racoon_free(iph1->local);
2890           } else
2891                     port = 0;
2892 
2893           iph1->local = dupsaddr(ma->local);
2894           if (iph1->local == NULL) {
2895                     plog(LLV_ERROR, LOCATION, NULL, "unable to allocate "
2896                          "Phase 1 local address.\n");
2897                     return -1;
2898           }
2899           set_port(iph1->local, port);
2900 
2901           if (iph1->remote != NULL) {
2902                     plog(LLV_DEBUG, LOCATION, NULL, "Migrating Phase 1 remote "
2903                          "address from %s\n",
2904                          saddr2str_fromto("%s to %s", iph1->remote, ma->remote));
2905                     port = extract_port(iph1->remote);
2906                     racoon_free(iph1->remote);
2907           } else
2908                     port = 0;
2909 
2910           iph1->remote = dupsaddr(ma->remote);
2911           if (iph1->remote == NULL) {
2912                     plog(LLV_ERROR, LOCATION, NULL, "unable to allocate "
2913                          "Phase 1 remote address.\n");
2914                     return -1;
2915           }
2916           set_port(iph1->remote, port);
2917 
2918           return 0;
2919 }
2920 
2921 /* Update src and dst of all current Phase 2 handles.
2922  * with provided local and remote addresses.
2923  * Our intent is NOT to modify IPsec SA endpoints but IKE
2924  * addresses so we need to take care to separate those if
2925  * they are different. -1 is returned on error. 0 if everything
2926  * went right.
2927  *
2928  * Note: we do not maintain port information as it is not
2929  *       expected to be meaningful --arno
2930  */
2931 static int
migrate_ph2_ike_addresses(iph2,arg)2932 migrate_ph2_ike_addresses(iph2, arg)
2933           struct ph2handle *iph2;
2934           void *arg;
2935 {
2936           struct migrate_args *ma = (struct migrate_args *) arg;
2937           struct ph1handle *iph1;
2938 
2939           /* If Phase 2 has an associated Phase 1, migrate addresses */
2940           if (iph2->ph1)
2941                     migrate_ph1_ike_addresses(iph2->ph1, arg);
2942 
2943           /* Already up-to-date? */
2944           if (cmpsaddr(iph2->src, ma->local) == CMPSADDR_MATCH &&
2945               cmpsaddr(iph2->dst, ma->remote) == CMPSADDR_MATCH)
2946                     return 0;
2947 
2948           /* save src/dst as sa_src/sa_dst before rewriting */
2949           if (iph2->sa_src == NULL && iph2->sa_dst == NULL) {
2950                     iph2->sa_src = iph2->src;
2951                     iph2->sa_dst = iph2->dst;
2952                     iph2->src = NULL;
2953                     iph2->dst = NULL;
2954           }
2955 
2956           if (iph2->src != NULL)
2957                     racoon_free(iph2->src);
2958           iph2->src = dupsaddr(ma->local);
2959           if (iph2->src == NULL) {
2960                     plog(LLV_ERROR, LOCATION, NULL,
2961                          "unable to allocate Phase 2 src address.\n");
2962                     return -1;
2963           }
2964 
2965           if (iph2->dst != NULL)
2966                     racoon_free(iph2->dst);
2967           iph2->dst = dupsaddr(ma->remote);
2968           if (iph2->dst == NULL) {
2969                     plog(LLV_ERROR, LOCATION, NULL,
2970                          "unable to allocate Phase 2 dst address.\n");
2971                     return -1;
2972           }
2973 
2974           return 0;
2975 }
2976 
2977 /* Consider existing Phase 2 handles with given spid and update their source
2978  * and destination addresses for SA. As racoon does not support bundles, if
2979  * we modify multiple occurrences, this probably imply rekeying has happened.
2980  *
2981  * Both addresses passed to the function are expected not to be NULL and of
2982  * same family. -1 is returned on error. 0 if everything went right.
2983  *
2984  * Specific care is needed to support Phase 2 for which negotiation has
2985  * already started but are which not yet established.
2986  */
2987 static int
migrate_ph2_sa_addresses(iph2,args)2988 migrate_ph2_sa_addresses(iph2, args)
2989           struct ph2handle *iph2;
2990           void *args;
2991 {
2992           struct migrate_args *ma = (struct migrate_args *) args;
2993 
2994           if (iph2->sa_src != NULL) {
2995                     racoon_free(iph2->sa_src);
2996                     iph2->sa_src = NULL;
2997           }
2998 
2999           if (iph2->sa_dst != NULL) {
3000                     racoon_free(iph2->sa_dst);
3001                     iph2->sa_dst = NULL;
3002           }
3003 
3004           iph2->sa_src = dupsaddr(ma->local);
3005           if (iph2->sa_src == NULL) {
3006                     plog(LLV_ERROR, LOCATION, NULL,
3007                          "unable to allocate Phase 2 sa_src address.\n");
3008                     return -1;
3009           }
3010 
3011           iph2->sa_dst = dupsaddr(ma->remote);
3012           if (iph2->sa_dst == NULL) {
3013                     plog(LLV_ERROR, LOCATION, NULL,
3014                          "unable to allocate Phase 2 sa_dst address.\n");
3015                     return -1;
3016           }
3017 
3018           if (iph2->status < PHASE2ST_ESTABLISHED) {
3019                     struct remoteconf *rmconf;
3020                     /* We were negotiating for that SA when we received the MIGRATE.
3021                      * We cannot simply update the addresses and let the exchange
3022                      * go on. We have to restart the whole negotiation if we are
3023                      * the initiator. Otherwise (acting as responder), we just need
3024                      * to delete our ph2handle and wait for the initiator to start
3025                      * a new negotiation. */
3026 
3027                     if (iph2->ph1 && iph2->ph1->rmconf)
3028                               rmconf = iph2->ph1->rmconf;
3029                     else
3030                               rmconf = getrmconf(iph2->dst, 0);
3031 
3032                     if (rmconf && !rmconf->passive) {
3033                               struct ph1handle *iph1hint;
3034 
3035                               plog(LLV_WARNING, LOCATION, iph2->dst, "MIGRATE received "
3036                                    "*during* IPsec SA negotiation. As initiator, "
3037                                    "restarting it.\n");
3038 
3039                               /* Turn off expiration timer ...*/
3040                               sched_cancel(&iph2->sce);
3041                               iph2->status = PHASE2ST_EXPIRED;
3042 
3043                               /* ... clean Phase 2 handle ... */
3044                               iph1hint = iph2->ph1;
3045                               initph2(iph2);
3046                               iph2->status = PHASE2ST_STATUS2;
3047 
3048                               /* and start a new negotiation */
3049                               if (isakmp_post_acquire(iph2, iph1hint, FALSE) < 0) {
3050                                         plog(LLV_ERROR, LOCATION, iph2->dst, "failed "
3051                                              "to begin IPsec SA renegotiation after "
3052                                              "MIGRATE reception.\n");
3053                                         remph2(iph2);
3054                                         delph2(iph2);
3055                                         return -1;
3056                               }
3057                     } else {
3058                               plog(LLV_WARNING, LOCATION, iph2->dst, "MIGRATE received "
3059                                    "*during* IPsec SA negotiation. As responder, let's"
3060                                    "wait for the initiator to act.\n");
3061 
3062                               /* Simply schedule deletion */
3063                               isakmp_ph2expire(iph2);
3064                     }
3065           }
3066 
3067           return 0;
3068 }
3069 
3070 /* Update SP hints (local and remote addresses) for future IKE
3071  * negotiations of SA associated with that SP. -1 is returned
3072  * on error. 0 if everything went right.
3073  *
3074  * Note: we do not maintain port information as it is not
3075  *       expected to be meaningful --arno
3076  */
3077 static int
migrate_sp_ike_addresses(sp,local,remote)3078 migrate_sp_ike_addresses(sp, local, remote)
3079         struct secpolicy *sp;
3080         struct sockaddr *local, *remote;
3081 {
3082           if (sp == NULL || local == NULL || remote == NULL)
3083                     return -1;
3084 
3085           if (sp->local != NULL)
3086                     racoon_free(sp->local);
3087 
3088           sp->local = dupsaddr(local);
3089           if (sp->local == NULL) {
3090                     plog(LLV_ERROR, LOCATION, NULL, "unable to allocate "
3091                          "local hint for SP.\n");
3092                     return -1;
3093           }
3094 
3095           if (sp->remote != NULL)
3096                     racoon_free(sp->remote);
3097 
3098           sp->remote = dupsaddr(remote);
3099           if (sp->remote == NULL) {
3100                     plog(LLV_ERROR, LOCATION, NULL, "unable to allocate "
3101                          "remote hint for SP.\n");
3102                     return -1;
3103           }
3104 
3105           return 0;
3106 }
3107 
3108 /* Given current ipsecrequest (isr_cur) to be migrated in considered
3109    tree, the function first checks that it matches the expected one
3110    (xisr_old) provided in MIGRATE message and then updates the addresses
3111    if it is tunnel mode (with content of xisr_new). Various other checks
3112    are performed. For transport mode, structures are not modified, only
3113    the checks are done. -1 is returned on error. */
3114 static int
migrate_ph2_one_isr(spid,isr_cur,xisr_old,xisr_new)3115 migrate_ph2_one_isr(spid, isr_cur, xisr_old, xisr_new)
3116         uint32_t spid;
3117         struct ipsecrequest *isr_cur;
3118           struct sadb_x_ipsecrequest *xisr_old, *xisr_new;
3119 {
3120           struct secasindex *saidx = &isr_cur->saidx;
3121           struct sockaddr *osaddr, *odaddr, *nsaddr, *ndaddr;
3122           struct ph2selector ph2sel;
3123           struct migrate_args ma;
3124 
3125           /* First, check that mode and proto do match */
3126           if (xisr_old->sadb_x_ipsecrequest_proto != saidx->proto ||
3127               xisr_old->sadb_x_ipsecrequest_mode != saidx->mode ||
3128               xisr_new->sadb_x_ipsecrequest_proto != saidx->proto ||
3129               xisr_new->sadb_x_ipsecrequest_mode != saidx->mode)
3130                     return -1;
3131 
3132           /* Then, verify reqid if necessary */
3133           if (isr_cur->saidx.reqid &&
3134               (xisr_old->sadb_x_ipsecrequest_level != IPSEC_LEVEL_UNIQUE ||
3135                xisr_new->sadb_x_ipsecrequest_level != IPSEC_LEVEL_UNIQUE ||
3136                isr_cur->saidx.reqid != xisr_old->sadb_x_ipsecrequest_reqid ||
3137                isr_cur->saidx.reqid != xisr_new->sadb_x_ipsecrequest_reqid))
3138                     return -1;
3139 
3140           /* If not tunnel mode, our work is over */
3141           if (saidx->mode != IPSEC_MODE_TUNNEL) {
3142                     plog(LLV_DEBUG, LOCATION, NULL, "SADB_X_MIGRATE: "
3143                          "non tunnel mode isr, skipping SA address migration.\n");
3144                     return 0;
3145           }
3146 
3147           /* Tunnel mode: let's check addresses do match and then update them. */
3148           osaddr = (struct sockaddr *)(xisr_old + 1);
3149           odaddr = (struct sockaddr *)(((uint8_t *)osaddr) + sysdep_sa_len(osaddr));
3150           nsaddr = (struct sockaddr *)(xisr_new + 1);
3151           ndaddr = (struct sockaddr *)(((uint8_t *)nsaddr) + sysdep_sa_len(nsaddr));
3152 
3153           /* Check family does match */
3154           if (osaddr->sa_family != odaddr->sa_family ||
3155               nsaddr->sa_family != ndaddr->sa_family)
3156                     return -1;
3157 
3158           /* Check family does match */
3159           if (saidx->src.ss_family != osaddr->sa_family)
3160                     return -1;
3161 
3162           /* We log IPv4 to IPv6 and IPv6 to IPv4 switches */
3163           if (nsaddr->sa_family != osaddr->sa_family)
3164                     plog(LLV_INFO, LOCATION, NULL, "SADB_X_MIGRATE: "
3165                          "changing address families (%d to %d) for endpoints.\n",
3166                          osaddr->sa_family, nsaddr->sa_family);
3167 
3168           if (cmpsaddr(osaddr, (struct sockaddr *) &saidx->src) != CMPSADDR_MATCH ||
3169               cmpsaddr(odaddr, (struct sockaddr *) &saidx->dst) != CMPSADDR_MATCH) {
3170                     plog(LLV_DEBUG, LOCATION, NULL, "SADB_X_MIGRATE: "
3171                          "mismatch of addresses in saidx and xisr.\n");
3172                     return -1;
3173           }
3174 
3175           /* Excellent. Let's grab associated Phase 2 handle (if any)
3176            * and update its sa_src and sa_dst entries.  Note that we
3177            * make the assumption that racoon does not support bundles
3178            * and make the lookup using spid: we blindly update
3179            * sa_src and sa_dst for _all_ found Phase 2 handles */
3180           memset(&ph2sel, 0, sizeof(ph2sel));
3181           ph2sel.spid = spid;
3182 
3183           memset(&ma, 0, sizeof(ma));
3184           ma.local = nsaddr;
3185           ma.remote = ndaddr;
3186 
3187           if (enumph2(&ph2sel, migrate_ph2_sa_addresses, &ma) < 0)
3188                     return -1;
3189 
3190           /* Now we can do the update of endpoints in secasindex */
3191           memcpy(&saidx->src, nsaddr, sysdep_sa_len(nsaddr));
3192           memcpy(&saidx->dst, ndaddr, sysdep_sa_len(ndaddr));
3193 
3194           return 0;
3195 }
3196 
3197 /* Process the raw (unparsed yet) list of sadb_x_ipsecrequests of MIGRATE
3198  * message. For each sadb_x_ipsecrequest pair (old followed by new),
3199  * the corresponding ipsecrequest entry in the SP is updated. Associated
3200  * existing Phase 2 handle is also updated (if any) */
3201 static int
migrate_sp_isr_list(sp,xisr_list,xisr_list_len)3202 migrate_sp_isr_list(sp, xisr_list, xisr_list_len)
3203         struct secpolicy *sp;
3204           struct sadb_x_ipsecrequest *xisr_list;
3205           int xisr_list_len;
3206 {
3207           struct sadb_x_ipsecrequest *xisr_new, *xisr_old = xisr_list;
3208           int xisr_old_len, xisr_new_len;
3209           struct ipsecrequest *isr_cur;
3210 
3211           isr_cur = sp->req; /* ipsecrequest list from sp */
3212 
3213           while (xisr_list_len > 0 && isr_cur != NULL) {
3214                     /* Get old xisr (length field is in bytes) */
3215                     xisr_old_len = xisr_old->sadb_x_ipsecrequest_len;
3216                     if (xisr_old_len < sizeof(*xisr_old) ||
3217                         xisr_old_len + sizeof(*xisr_new) > xisr_list_len) {
3218                               plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3219                                    "invalid ipsecrequest length. Exiting.\n");
3220                               return -1;
3221                     }
3222 
3223                     /* Get new xisr with updated info */
3224                     xisr_new = (struct sadb_x_ipsecrequest *)(((uint8_t *)xisr_old) + xisr_old_len);
3225                     xisr_new_len = xisr_new->sadb_x_ipsecrequest_len;
3226                     if (xisr_new_len < sizeof(*xisr_new) ||
3227                         xisr_new_len + xisr_old_len > xisr_list_len) {
3228                               plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3229                                    "invalid ipsecrequest length. Exiting.\n");
3230                               return -1;
3231                     }
3232 
3233                     /* Start by migrating current ipsecrequest from SP */
3234                     if (migrate_ph2_one_isr(sp->id, isr_cur, xisr_old, xisr_new) == -1) {
3235                               plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3236                                    "Unable to match and migrate isr. Exiting.\n");
3237                               return -1;
3238                     }
3239 
3240                     /* Update pointers for next round */
3241                     xisr_list_len -= xisr_old_len + xisr_new_len;
3242                     xisr_old = (struct sadb_x_ipsecrequest *)(((uint8_t *)xisr_new) +
3243                                                                         xisr_new_len);
3244 
3245                     isr_cur = isr_cur->next; /* Get next ipsecrequest from SP */
3246           }
3247 
3248           /* Check we had the same amount of pairs in the MIGRATE
3249              as the number of ipsecrequests in the SP */
3250           if ((xisr_list_len != 0) || isr_cur != NULL) {
3251                     plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3252                          "number of ipsecrequest does not match the one in SP.\n");
3253                     return -1;
3254           }
3255 
3256           return 0;
3257 }
3258 
3259 /* Parse sadb_x_kmaddress extension and make local and remote
3260  * parameters point to the new addresses (zero copy). -1 is
3261  * returned on error, meaning that addresses are not usable */
3262 static int
parse_kmaddress(kmaddr,local,remote)3263 parse_kmaddress(kmaddr, local, remote)
3264         struct sadb_x_kmaddress *kmaddr;
3265           struct sockaddr **local, **remote;
3266 {
3267           int addrslen, local_len=0;
3268           struct ph1handle *iph1;
3269 
3270           if (kmaddr == NULL)
3271                     return -1;
3272 
3273           /* Grab addresses in sadb_x_kmaddress extension */
3274           addrslen = PFKEY_EXTLEN(kmaddr) - sizeof(*kmaddr);
3275           if (addrslen < sizeof(struct sockaddr))
3276                     return -1;
3277 
3278           *local = (struct sockaddr *)(kmaddr + 1);
3279 
3280           switch ((*local)->sa_family) {
3281           case AF_INET:
3282                     local_len = sizeof(struct sockaddr_in);
3283                     break;
3284 #ifdef INET6
3285           case AF_INET6:
3286                     local_len = sizeof(struct sockaddr_in6);
3287                     break;
3288 #endif
3289           default:
3290                     return -1;
3291           }
3292 
3293           if (addrslen != PFKEY_ALIGN8(2*local_len))
3294                     return -1;
3295 
3296           *remote = (struct sockaddr *)(((uint8_t *)(*local)) + local_len);
3297 
3298           if ((*local)->sa_family != (*remote)->sa_family)
3299                     return -1;
3300 
3301           return 0;
3302 }
3303 
3304 /* Handler of PF_KEY MIGRATE message. Helpers are above */
3305 static int
pk_recvmigrate(mhp)3306 pk_recvmigrate(mhp)
3307           caddr_t *mhp;
3308 {
3309           struct sadb_address *saddr, *daddr;
3310           struct sockaddr *old_saddr, *new_saddr;
3311           struct sockaddr *old_daddr, *new_daddr;
3312           struct sockaddr *old_local, *old_remote;
3313           struct sockaddr *local, *remote;
3314           struct sadb_x_kmaddress *kmaddr;
3315           struct sadb_x_policy *xpl;
3316           struct sadb_x_ipsecrequest *xisr_list;
3317           struct sadb_lifetime *lt;
3318           struct policyindex spidx;
3319           struct secpolicy *sp;
3320           struct ipsecrequest *isr_cur;
3321           struct secasindex *oldsaidx;
3322           struct ph2handle *iph2;
3323           struct ph1handle *iph1;
3324           struct ph2selector ph2sel;
3325           struct ph1selector ph1sel;
3326           uint32_t spid;
3327           u_int64_t created;
3328           int xisr_list_len;
3329           int ulproto;
3330           struct migrate_args ma;
3331 
3332           /* Some sanity checks */
3333 
3334           if (mhp[0] == NULL
3335            || mhp[SADB_EXT_ADDRESS_SRC] == NULL
3336            || mhp[SADB_EXT_ADDRESS_DST] == NULL
3337            || mhp[SADB_X_EXT_KMADDRESS] == NULL
3338            || mhp[SADB_X_EXT_POLICY] == NULL) {
3339                     plog(LLV_ERROR, LOCATION, NULL,
3340                               "SADB_X_MIGRATE: invalid MIGRATE message received.\n");
3341                     return -1;
3342           }
3343           kmaddr = (struct sadb_x_kmaddress *)mhp[SADB_X_EXT_KMADDRESS];
3344           saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
3345           daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
3346           xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
3347           lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
3348           if (lt != NULL)
3349                     created = lt->sadb_lifetime_addtime;
3350           else
3351                     created = 0;
3352 
3353           if (xpl->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
3354                     plog(LLV_WARNING, LOCATION, NULL,"SADB_X_MIGRATE: "
3355                          "found non IPsec policy in MIGRATE message. Exiting.\n");
3356                     return -1;
3357           }
3358 
3359           if (PFKEY_EXTLEN(xpl) < sizeof(*xpl)) {
3360                     plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3361                          "invalid size for sadb_x_policy. Exiting.\n");
3362                     return -1;
3363           }
3364 
3365           /* Some logging to help debbugging */
3366           if (xpl->sadb_x_policy_dir == IPSEC_DIR_OUTBOUND)
3367                     plog(LLV_DEBUG, LOCATION, NULL,
3368                          "SADB_X_MIGRATE: Outbound SA being migrated.\n");
3369           else
3370                     plog(LLV_DEBUG, LOCATION, NULL,
3371                          "SADB_X_MIGRATE: Inbound SA being migrated.\n");
3372 
3373           /* validity check */
3374           xisr_list = (struct sadb_x_ipsecrequest *)(xpl + 1);
3375           xisr_list_len = PFKEY_EXTLEN(xpl) - sizeof(*xpl);
3376           if (xisr_list_len < sizeof(*xisr_list)) {
3377                     plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3378                          "invalid sadb_x_policy message length. Exiting.\n");
3379                     return -1;
3380           }
3381 
3382           if (parse_kmaddress(kmaddr, &local, &remote) == -1) {
3383                     plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: "
3384                          "invalid sadb_x_kmaddress extension. Exiting.\n");
3385                     return -1;
3386           }
3387 
3388           /* 0 means ANY */
3389           if (saddr->sadb_address_proto == 0)
3390                     ulproto = IPSEC_ULPROTO_ANY;
3391           else
3392                     ulproto = saddr->sadb_address_proto;
3393 
3394 #ifdef HAVE_PFKEY_POLICY_PRIORITY
3395           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
3396                               saddr + 1,
3397                               daddr + 1,
3398                               saddr->sadb_address_prefixlen,
3399                               daddr->sadb_address_prefixlen,
3400                               ulproto,
3401                               xpl->sadb_x_policy_priority,
3402                               created,
3403                               &spidx);
3404 #else
3405           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
3406                               saddr + 1,
3407                               daddr + 1,
3408                               saddr->sadb_address_prefixlen,
3409                               daddr->sadb_address_prefixlen,
3410                               ulproto,
3411                               created,
3412                               &spidx);
3413 #endif
3414 
3415           /* Everything seems ok, let's get the SP.
3416            *
3417            * XXX We could also do the lookup using the spid from xpl.
3418            *     I don't know which one is better.  --arno */
3419           sp = getsp(&spidx);
3420           if (sp == NULL) {
3421                     plog(LLV_ERROR, LOCATION, NULL,
3422                               "SADB_X_MIGRATE: Passed policy does not exist: %s\n",
3423                               spidx2str(&spidx));
3424                     return -1;
3425           }
3426 
3427           /* Get the best source and destination addresses used for IKE
3428            * negotiation, to find and migrate existing Phase 1 */
3429           if (sp->local && sp->remote) {
3430                     /* hints available, let's use them */
3431                     old_local  = (struct sockaddr *)sp->local;
3432                     old_remote = (struct sockaddr *)sp->remote;
3433           } else if (sp->req && sp->req->saidx.mode == IPSEC_MODE_TUNNEL) {
3434                     /* Tunnel mode and no hint, use endpoints */
3435                     old_local  = (struct sockaddr *)&sp->req->saidx.src;
3436                     old_remote = (struct sockaddr *)&sp->req->saidx.dst;
3437           } else {
3438                     /* default, use selectors as fallback */
3439                     old_local  = (struct sockaddr *)&sp->spidx.src;
3440                     old_remote = (struct sockaddr *)&sp->spidx.dst;
3441           }
3442 
3443           /* We migrate all Phase 1 that match our old local and remote
3444            * addresses (no matter their state).
3445            *
3446            * XXX In fact, we should probably havea special treatment for
3447            * Phase 1 that are being established when we receive a MIGRATE.
3448            * This can happen if a movement occurs during the initial IKE
3449            * negotiation. In that case, I wonder if should restart the
3450            * negotiation from the new address or just update things like
3451            * we do it now.
3452            *
3453            * XXX while looking at getph1byaddr(), the comment at the
3454            * beginning of the function expects comparison to happen
3455            * without ports considerations but it uses CMPSADDR() which
3456            * relies either on cmpsaddrstrict() or cmpsaddrwop() based
3457            * on NAT-T support being activated. That make me wonder if I
3458            * should force ports to 0 (ANY) in local and remote values
3459            * used below.
3460            *
3461            * -- arno */
3462 
3463           /* Apply callback data ...*/
3464           memset(&ma, 0, sizeof(ma));
3465           ma.local = local;
3466           ma.remote = remote;
3467 
3468           /* Fill phase1 match criteria ... */
3469           memset(&ph1sel, 0, sizeof(ph1sel));
3470           ph1sel.local = old_local;
3471           ph1sel.remote = old_remote;
3472 
3473 
3474           /* Have matching Phase 1 found and addresses updated. As this is a
3475            * time consuming task on a busy responder, and MIGRATE messages
3476            * are always sent for *both* inbound and outbound (and possibly
3477            * forward), we only do that for outbound SP. */
3478           if (xpl->sadb_x_policy_dir == IPSEC_DIR_OUTBOUND &&
3479               enumph1(&ph1sel, migrate_ph1_ike_addresses, &ma) < 0) {
3480                     plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: Unable "
3481                          "to migrate Phase 1 addresses.\n");
3482                     return -1;
3483           }
3484 
3485           /* We can now update IKE addresses in Phase 2 handle. */
3486           memset(&ph2sel, 0, sizeof(ph2sel));
3487           ph2sel.spid = sp->id;
3488           if (enumph2(&ph2sel, migrate_ph2_ike_addresses, &ma) < 0) {
3489                     plog(LLV_ERROR, LOCATION, NULL, "SADB_X_MIGRATE: Unable "
3490                          "to migrate Phase 2 IKE addresses.\n");
3491                     return -1;
3492           }
3493 
3494           /* and _then_ in SP. */
3495           if (migrate_sp_ike_addresses(sp, local, remote) < 0) {
3496                     plog(LLV_ERROR, LOCATION, NULL,
3497                          "SADB_X_MIGRATE: Unable to migrate SP IKE addresses.\n");
3498                     return -1;
3499           }
3500 
3501           /* Loop on sadb_x_ipsecrequest list to possibly update sp->req
3502            * entries and associated live Phase 2 handles (their sa_src
3503            * and sa_dst) */
3504           if (migrate_sp_isr_list(sp, xisr_list, xisr_list_len) < 0) {
3505                     plog(LLV_ERROR, LOCATION, NULL,
3506                          "SADB_X_MIGRATE: Unable to migrate isr list.\n");
3507                     return -1;
3508           }
3509 
3510           return 0;
3511 }
3512 #endif
3513 
3514 /*
3515  * send error against acquire message to kernel.
3516  */
3517 int
pk_sendeacquire(struct ph2handle * iph2)3518 pk_sendeacquire(struct ph2handle *iph2)
3519 {
3520           struct sadb_msg *newmsg;
3521           int len;
3522 
3523           len = sizeof(struct sadb_msg);
3524           newmsg = racoon_calloc(1, len);
3525           if (newmsg == NULL) {
3526                     plog(LLV_ERROR, LOCATION, NULL,
3527                               "failed to get buffer to send acquire.\n");
3528                     return -1;
3529           }
3530 
3531           memset(newmsg, 0, len);
3532           newmsg->sadb_msg_version = PF_KEY_V2;
3533           newmsg->sadb_msg_type = SADB_ACQUIRE;
3534           newmsg->sadb_msg_errno = ENOENT;        /* XXX */
3535           newmsg->sadb_msg_satype = iph2->satype;
3536           newmsg->sadb_msg_len = PFKEY_UNIT64(len);
3537           newmsg->sadb_msg_reserved = 0;
3538           newmsg->sadb_msg_seq = iph2->seq;
3539           newmsg->sadb_msg_pid = (uint32_t)getpid();
3540 
3541           /* send message */
3542           len = pfkey_send(lcconf->sock_pfkey, newmsg, len);
3543 
3544           racoon_free(newmsg);
3545 
3546           return 0;
3547 }
3548 
3549 /*
3550  * check if the algorithm is supported or not.
3551  * OUT     0: ok
3552  *        -1: ng
3553  */
3554 int
pk_checkalg(int class,int calg,int keylen)3555 pk_checkalg(int class, int calg, int keylen)
3556 {
3557           int sup, error;
3558           u_int alg;
3559           struct sadb_alg alg0;
3560 
3561           switch (algclass2doi(class)) {
3562           case IPSECDOI_PROTO_IPSEC_ESP:
3563                     sup = SADB_EXT_SUPPORTED_ENCRYPT;
3564                     break;
3565           case IPSECDOI_ATTR_AUTH:
3566                     sup = SADB_EXT_SUPPORTED_AUTH;
3567                     break;
3568           case IPSECDOI_PROTO_IPCOMP:
3569                     plog(LLV_DEBUG, LOCATION, NULL,
3570                               "no check of compression algorithm; "
3571                               "not supported in sadb message.\n");
3572                     return 0;
3573           default:
3574                     plog(LLV_ERROR, LOCATION, NULL,
3575                               "invalid algorithm class.\n");
3576                     return -1;
3577           }
3578           alg = ipsecdoi2pfkey_alg(algclass2doi(class), algtype2doi(class, calg));
3579           if (alg == ~0u)
3580                     return -1;
3581 
3582           if (keylen == 0) {
3583                     if (ipsec_get_keylen(sup, alg, &alg0)) {
3584                               plog(LLV_ERROR, LOCATION, NULL,
3585                                         "%s.\n", ipsec_strerror());
3586                               return -1;
3587                     }
3588                     keylen = alg0.sadb_alg_minbits;
3589           }
3590 
3591           error = ipsec_check_keylen(sup, alg, keylen);
3592           if (error)
3593                     plog(LLV_ERROR, LOCATION, NULL,
3594                               "%s.\n", ipsec_strerror());
3595 
3596           return error;
3597 }
3598 
3599 /*
3600  * differences with pfkey_recv() in libipsec/pfkey.c:
3601  * - never performs busy wait loop.
3602  * - returns NULL and set *lenp to negative on fatal failures
3603  * - returns NULL and set *lenp to non-negative on non-fatal failures
3604  * - returns non-NULL on success
3605  */
3606 static struct sadb_msg *
pk_recv(int so,int * lenp)3607 pk_recv(int so, int *lenp)
3608 {
3609           struct sadb_msg buf, *newmsg;
3610           int reallen;
3611           int retry = 0;
3612 
3613           *lenp = -1;
3614           do
3615           {
3616               plog(LLV_DEBUG, LOCATION, NULL, "pk_recv: retry[%d] recv() \n", retry );
3617               *lenp = recv(so, (caddr_t)&buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT);
3618               retry++;
3619           }
3620           while (*lenp < 0 && errno == EAGAIN && retry < 3);
3621 
3622           if (*lenp < 0)
3623                     return NULL;        /*fatal*/
3624 
3625           else if (*lenp < sizeof(buf))
3626                     return NULL;
3627 
3628           reallen = PFKEY_UNUNIT64(buf.sadb_msg_len);
3629           if (reallen < sizeof(buf)) {
3630                     *lenp = -1;
3631                     errno = EIO;
3632                     return NULL;    /*fatal*/
3633           }
3634           if ((newmsg = racoon_calloc(1, reallen)) == NULL)
3635                     return NULL;
3636 
3637           *lenp = recv(so, (caddr_t)newmsg, reallen, MSG_PEEK);
3638           if (*lenp < 0) {
3639                     racoon_free(newmsg);
3640                     return NULL;        /*fatal*/
3641           } else if (*lenp != reallen) {
3642                     racoon_free(newmsg);
3643                     return NULL;
3644           }
3645 
3646           *lenp = recv(so, (caddr_t)newmsg, reallen, 0);
3647           if (*lenp < 0) {
3648                     racoon_free(newmsg);
3649                     return NULL;        /*fatal*/
3650           } else if (*lenp != reallen) {
3651                     racoon_free(newmsg);
3652                     return NULL;
3653           }
3654 
3655           return newmsg;
3656 }
3657 
3658 /* see handler.h */
3659 uint32_t
pk_getseq(void)3660 pk_getseq(void)
3661 {
3662           return eay_random();
3663 }
3664 
3665 static int
addnewsp(caddr_t * mhp,struct sockaddr * local,struct sockaddr * remote)3666 addnewsp(caddr_t *mhp, struct sockaddr *local, struct sockaddr *remote)
3667 {
3668           struct secpolicy *new = NULL;
3669           struct sadb_address *saddr, *daddr;
3670           struct sadb_x_policy *xpl;
3671           struct sadb_lifetime *lt;
3672           u_int64_t created;
3673 
3674           /* sanity check */
3675           if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
3676            || mhp[SADB_EXT_ADDRESS_DST] == NULL
3677            || mhp[SADB_X_EXT_POLICY] == NULL) {
3678                     plog(LLV_ERROR, LOCATION, NULL,
3679                               "inappropriate sadb spd management message passed.\n");
3680                     goto bad;
3681           }
3682 
3683           saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
3684           daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
3685           xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
3686           lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
3687           if(lt != NULL)
3688                     created = lt->sadb_lifetime_addtime;
3689           else
3690                     created = 0;
3691           lt = (struct sadb_lifetime*)mhp[SADB_EXT_LIFETIME_HARD];
3692           if(lt != NULL)
3693                     created = lt->sadb_lifetime_addtime;
3694           else
3695                     created = 0;
3696 
3697 #ifdef __linux__
3698           /* bsd skips over per-socket policies because there will be no
3699            * src and dst extensions in spddump messages. On Linux the only
3700            * way to achieve the same is check for policy id.
3701            */
3702           if (xpl->sadb_x_policy_id % 8 >= 3) return 0;
3703 #endif
3704 
3705           new = newsp();
3706           if (new == NULL) {
3707                     plog(LLV_ERROR, LOCATION, NULL,
3708                               "failed to allocate buffer\n");
3709                     goto bad;
3710           }
3711 
3712           new->spidx.dir = xpl->sadb_x_policy_dir;
3713           new->id = xpl->sadb_x_policy_id;
3714           new->policy = xpl->sadb_x_policy_type;
3715           new->req = NULL;
3716 
3717           /* check policy */
3718           switch (xpl->sadb_x_policy_type) {
3719           case IPSEC_POLICY_DISCARD:
3720           case IPSEC_POLICY_NONE:
3721           case IPSEC_POLICY_ENTRUST:
3722           case IPSEC_POLICY_BYPASS:
3723                     break;
3724 
3725           case IPSEC_POLICY_IPSEC:
3726               {
3727                     int tlen;
3728                     struct sadb_x_ipsecrequest *xisr;
3729                     struct ipsecrequest **p_isr = &new->req;
3730 
3731                     /* validity check */
3732                     if (PFKEY_EXTLEN(xpl) < sizeof(*xpl)) {
3733                               plog(LLV_ERROR, LOCATION, NULL,
3734                                         "invalid msg length.\n");
3735                               goto bad;
3736                     }
3737 
3738                     tlen = PFKEY_EXTLEN(xpl) - sizeof(*xpl);
3739                     xisr = (struct sadb_x_ipsecrequest *)(xpl + 1);
3740 
3741                     while (tlen > 0) {
3742 
3743                               /* length check */
3744                               if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
3745                                         plog(LLV_ERROR, LOCATION, NULL,
3746                                                   "invalid msg length.\n");
3747                                         goto bad;
3748                               }
3749 
3750                               /* allocate request buffer */
3751                               *p_isr = newipsecreq();
3752                               if (*p_isr == NULL) {
3753                                         plog(LLV_ERROR, LOCATION, NULL,
3754                                                   "failed to get new ipsecreq.\n");
3755                                         goto bad;
3756                               }
3757 
3758                               /* set values */
3759                               (*p_isr)->next = NULL;
3760 
3761                               switch (xisr->sadb_x_ipsecrequest_proto) {
3762                               case IPPROTO_ESP:
3763                               case IPPROTO_AH:
3764                               case IPPROTO_IPCOMP:
3765                                         break;
3766                               default:
3767                                         plog(LLV_ERROR, LOCATION, NULL,
3768                                                   "invalid proto type: %u\n",
3769                                                   xisr->sadb_x_ipsecrequest_proto);
3770                                         goto bad;
3771                               }
3772                               (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
3773 
3774                               switch (xisr->sadb_x_ipsecrequest_mode) {
3775                               case IPSEC_MODE_TRANSPORT:
3776                               case IPSEC_MODE_TUNNEL:
3777                                         break;
3778                               case IPSEC_MODE_ANY:
3779                               default:
3780                                         plog(LLV_ERROR, LOCATION, NULL,
3781                                                   "invalid mode: %u\n",
3782                                                   xisr->sadb_x_ipsecrequest_mode);
3783                                         goto bad;
3784                               }
3785                               (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
3786 
3787                               switch (xisr->sadb_x_ipsecrequest_level) {
3788                               case IPSEC_LEVEL_DEFAULT:
3789                               case IPSEC_LEVEL_USE:
3790                               case IPSEC_LEVEL_REQUIRE:
3791                                         break;
3792                               case IPSEC_LEVEL_UNIQUE:
3793                                         (*p_isr)->saidx.reqid =
3794                                                   xisr->sadb_x_ipsecrequest_reqid;
3795                                         break;
3796 
3797                               default:
3798                                         plog(LLV_ERROR, LOCATION, NULL,
3799                                                   "invalid level: %u\n",
3800                                                   xisr->sadb_x_ipsecrequest_level);
3801                                         goto bad;
3802                               }
3803                               (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
3804 
3805                               /* set IP addresses if there */
3806                               if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
3807                                         struct sockaddr *paddr;
3808 
3809                                         paddr = (struct sockaddr *)(xisr + 1);
3810                                         bcopy(paddr, &(*p_isr)->saidx.src,
3811                                                   sysdep_sa_len(paddr));
3812 
3813                                         paddr = (struct sockaddr *)((caddr_t)paddr
3814                                                                       + sysdep_sa_len(paddr));
3815                                         bcopy(paddr, &(*p_isr)->saidx.dst,
3816                                                   sysdep_sa_len(paddr));
3817                               }
3818 
3819                               (*p_isr)->sp = new;
3820 
3821                               /* initialization for the next. */
3822                               p_isr = &(*p_isr)->next;
3823                               tlen -= xisr->sadb_x_ipsecrequest_len;
3824 
3825                               /* validity check */
3826                               if (tlen < 0) {
3827                                         plog(LLV_ERROR, LOCATION, NULL,
3828                                                   "becoming tlen < 0\n");
3829                               }
3830 
3831                               xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
3832                                                + xisr->sadb_x_ipsecrequest_len);
3833                     }
3834               }
3835                     break;
3836           default:
3837                     plog(LLV_ERROR, LOCATION, NULL,
3838                               "invalid policy type.\n");
3839                     goto bad;
3840           }
3841 
3842 #ifdef HAVE_PFKEY_POLICY_PRIORITY
3843           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
3844                               saddr + 1,
3845                               daddr + 1,
3846                               saddr->sadb_address_prefixlen,
3847                               daddr->sadb_address_prefixlen,
3848                               saddr->sadb_address_proto,
3849                               xpl->sadb_x_policy_priority,
3850                               created,
3851                               &new->spidx);
3852 #else
3853           KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
3854                               saddr + 1,
3855                               daddr + 1,
3856                               saddr->sadb_address_prefixlen,
3857                               daddr->sadb_address_prefixlen,
3858                               saddr->sadb_address_proto,
3859                               created,
3860                               &new->spidx);
3861 #endif
3862 
3863 #ifdef HAVE_SECCTX
3864           if (mhp[SADB_X_EXT_SEC_CTX] != NULL) {
3865                     struct sadb_x_sec_ctx *ctx;
3866 
3867                     ctx = (struct sadb_x_sec_ctx *)mhp[SADB_X_EXT_SEC_CTX];
3868                     new->spidx.sec_ctx.ctx_alg = ctx->sadb_x_ctx_alg;
3869                     new->spidx.sec_ctx.ctx_doi = ctx->sadb_x_ctx_doi;
3870                     new->spidx.sec_ctx.ctx_strlen = ctx->sadb_x_ctx_len;
3871                     memcpy(new->spidx.sec_ctx.ctx_str,ctx + 1,ctx->sadb_x_ctx_len);
3872           }
3873 #endif /* HAVE_SECCTX */
3874 
3875           /* Set local and remote hints for that SP, if available */
3876           if (local && remote) {
3877                     new->local = dupsaddr(local);
3878                     new->remote = dupsaddr(remote);
3879           }
3880 
3881           inssp(new);
3882 
3883           return 0;
3884 bad:
3885           if (new != NULL) {
3886                     if (new->req != NULL)
3887                               racoon_free(new->req);
3888                     racoon_free(new);
3889           }
3890           return -1;
3891 }
3892 
3893 /* proto/mode/src->dst spi */
3894 const char *
sadbsecas2str(struct sockaddr * src,struct sockaddr * dst,int proto,uint32_t spi,int mode)3895 sadbsecas2str(struct sockaddr *src, struct sockaddr *dst, int proto,
3896     uint32_t spi, int mode)
3897 {
3898           static char buf[256];
3899           u_int doi_proto, doi_mode = 0;
3900           char *p;
3901           int blen, i;
3902 
3903           doi_proto = pfkey2ipsecdoi_proto(proto);
3904           if (doi_proto == ~0u)
3905                     return NULL;
3906           if (mode) {
3907                     doi_mode = pfkey2ipsecdoi_mode(mode);
3908                     if (doi_mode == ~0u)
3909                               return NULL;
3910           }
3911 
3912           blen = sizeof(buf) - 1;
3913           p = buf;
3914 
3915           i = snprintf(p, blen, "%s%s%s ",
3916                     s_ipsecdoi_proto(doi_proto),
3917                     mode ? "/" : "",
3918                     mode ? s_ipsecdoi_encmode(doi_mode) : "");
3919           if (i < 0 || i >= blen)
3920                     return NULL;
3921           p += i;
3922           blen -= i;
3923 
3924           i = snprintf(p, blen, "%s->", saddr2str(src));
3925           if (i < 0 || i >= blen)
3926                     return NULL;
3927           p += i;
3928           blen -= i;
3929 
3930           i = snprintf(p, blen, "%s ", saddr2str(dst));
3931           if (i < 0 || i >= blen)
3932                     return NULL;
3933           p += i;
3934           blen -= i;
3935 
3936           if (spi) {
3937                     snprintf(p, blen, "spi=%lu(0x%lx)", (unsigned long)ntohl(spi),
3938                         (unsigned long)ntohl(spi));
3939           }
3940 
3941           return buf;
3942 }
3943