1/*	$KAME: pfkey.c,v 1.133 2001/11/16 04:07:41 sakane Exp $	*/
2
3/*
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the project nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#define _PFKEY_C_
33
34#include <sys/types.h>
35#include <sys/param.h>
36#include <sys/socket.h>
37#include <sys/queue.h>
38
39#include <net/route.h>
40#include <net/pfkeyv2.h>
41
42#include <netinet/in.h>
43#ifdef IPV6_INRIA_VERSION
44#include <netinet/ipsec.h>
45#else
46#include <netinet6/ipsec.h>
47#endif
48
49#include <stdlib.h>
50#include <string.h>
51#include <stdio.h>
52#include <netdb.h>
53#include <errno.h>
54#ifdef HAVE_UNISTD_H
55#include <unistd.h>
56#endif
57#include <netdb.h>
58
59#include "libpfkey.h"
60
61#include "var.h"
62#include "misc.h"
63#include "vmbuf.h"
64#include "plog.h"
65#include "sockmisc.h"
66#include "debug.h"
67
68#include "schedule.h"
69#include "localconf.h"
70#include "remoteconf.h"
71#include "isakmp_var.h"
72#include "isakmp.h"
73#include "isakmp_inf.h"
74#include "ipsec_doi.h"
75#include "oakley.h"
76#include "pfkey.h"
77#include "handler.h"
78#include "policy.h"
79#include "algorithm.h"
80#include "sainfo.h"
81#include "proposal.h"
82#include "admin.h"
83#include "strnames.h"
84#include "backupsa.h"
85#include "gcmalloc.h"
86
87/* prototype */
88static u_int ipsecdoi2pfkey_aalg __P((u_int));
89static u_int ipsecdoi2pfkey_ealg __P((u_int));
90static u_int ipsecdoi2pfkey_calg __P((u_int));
91static u_int ipsecdoi2pfkey_alg __P((u_int, u_int));
92static u_int keylen_aalg __P((u_int));
93static u_int keylen_ealg __P((u_int, int));
94
95static int pk_recvgetspi __P((caddr_t *));
96static int pk_recvupdate __P((caddr_t *));
97static int pk_recvadd __P((caddr_t *));
98static int pk_recvdelete __P((caddr_t *));
99static int pk_recvacquire __P((caddr_t *));
100static int pk_recvexpire __P((caddr_t *));
101static int pk_recvflush __P((caddr_t *));
102static int getsadbpolicy __P((caddr_t *, int *, int, struct ph2handle *));
103static int pk_recvspdupdate __P((caddr_t *));
104static int pk_recvspdadd __P((caddr_t *));
105static int pk_recvspddelete __P((caddr_t *));
106static int pk_recvspdexpire __P((caddr_t *));
107static int pk_recvspdget __P((caddr_t *));
108static int pk_recvspddump __P((caddr_t *));
109static int pk_recvspdflush __P((caddr_t *));
110static struct sadb_msg *pk_recv __P((int, int *));
111
112static int (*pkrecvf[]) __P((caddr_t *)) = {
113NULL,
114pk_recvgetspi,
115pk_recvupdate,
116pk_recvadd,
117pk_recvdelete,
118NULL,	/* SADB_GET */
119pk_recvacquire,
120NULL,	/* SABD_REGISTER */
121pk_recvexpire,
122pk_recvflush,
123NULL,	/* SADB_DUMP */
124NULL,	/* SADB_X_PROMISC */
125NULL,	/* SADB_X_PCHANGE */
126pk_recvspdupdate,
127pk_recvspdadd,
128pk_recvspddelete,
129pk_recvspdget,
130NULL,	/* SADB_X_SPDACQUIRE */
131pk_recvspddump,
132pk_recvspdflush,
133NULL,	/* SADB_X_SPDSETIDX */
134pk_recvspdexpire,
135NULL,	/* SADB_X_SPDDELETE2 */
136};
137
138static int addnewsp __P((caddr_t *));
139
140/* cope with old kame headers - ugly */
141#ifndef SADB_X_AALG_MD5
142#define SADB_X_AALG_MD5		SADB_AALG_MD5
143#endif
144#ifndef SADB_X_AALG_SHA
145#define SADB_X_AALG_SHA		SADB_AALG_SHA
146#endif
147#ifndef SADB_X_AALG_NULL
148#define SADB_X_AALG_NULL	SADB_AALG_NULL
149#endif
150
151#ifndef SADB_X_EALG_BLOWFISHCBC
152#define SADB_X_EALG_BLOWFISHCBC	SADB_EALG_BLOWFISHCBC
153#endif
154#ifndef SADB_X_EALG_CAST128CBC
155#define SADB_X_EALG_CAST128CBC	SADB_EALG_CAST128CBC
156#endif
157#ifndef SADB_X_EALG_RC5CBC
158#ifdef SADB_EALG_RC5CBC
159#define SADB_X_EALG_RC5CBC	SADB_EALG_RC5CBC
160#endif
161#endif
162
163/*
164 * PF_KEY packet handler
165 *	0: success
166 *	-1: fail
167 */
168int
169pfkey_handler()
170{
171	struct sadb_msg *msg;
172	int len;
173	caddr_t mhp[SADB_EXT_MAX + 1];
174	int error = -1;
175
176	/* receive pfkey message. */
177	len = 0;
178	msg = (struct sadb_msg *)pk_recv(lcconf->sock_pfkey, &len);
179	if (msg == NULL) {
180		if (len < 0) {
181			plog(LLV_ERROR, LOCATION, NULL,
182				"failed to recv from pfkey (%s)\n",
183				strerror(errno));
184			goto end;
185		} else {
186			/* short message - msg not ready */
187			return 0;
188		}
189	}
190
191	plog(LLV_DEBUG, LOCATION, NULL, "get pfkey %s message\n",
192		s_pfkey_type(msg->sadb_msg_type));
193	plogdump(LLV_DEBUG2, msg, msg->sadb_msg_len << 3);
194
195	/* validity check */
196	if (msg->sadb_msg_errno) {
197		int pri;
198
199		/* when SPD is empty, treat the state as no error. */
200		if (msg->sadb_msg_type == SADB_X_SPDDUMP &&
201		    msg->sadb_msg_errno == ENOENT)
202			pri = LLV_DEBUG;
203		else
204			pri = LLV_ERROR;
205
206		plog(pri, LOCATION, NULL,
207			"pfkey %s failed: %s\n",
208			s_pfkey_type(msg->sadb_msg_type),
209			strerror(msg->sadb_msg_errno));
210
211		goto end;
212	}
213
214	/* check pfkey message. */
215	if (pfkey_align(msg, mhp)) {
216		plog(LLV_ERROR, LOCATION, NULL,
217			"libipsec failed pfkey align (%s)\n",
218			ipsec_strerror());
219		goto end;
220	}
221	if (pfkey_check(mhp)) {
222		plog(LLV_ERROR, LOCATION, NULL,
223			"libipsec failed pfkey check (%s)\n",
224			ipsec_strerror());
225		goto end;
226	}
227	msg = (struct sadb_msg *)mhp[0];
228
229	if (pkrecvf[msg->sadb_msg_type] == NULL) {
230		plog(LLV_DEBUG, LOCATION, NULL,
231			"not supported command %s\n",
232			s_pfkey_type(msg->sadb_msg_type));
233		goto end;
234	}
235
236	if ((pkrecvf[msg->sadb_msg_type])(mhp) < 0)
237		goto end;
238
239	error = 0;
240end:
241	if (msg)
242		racoon_free(msg);
243	return(error);
244}
245
246/*
247 * dump SADB
248 */
249vchar_t *
250pfkey_dump_sadb(satype)
251	int satype;
252{
253	int s = -1;
254	vchar_t *buf = NULL;
255	pid_t pid = getpid();
256	struct sadb_msg *msg = NULL;
257	size_t bl, ml;
258	int len;
259
260	if ((s = pfkey_open()) < 0) {
261		plog(LLV_ERROR, LOCATION, NULL,
262			"libipsec failed pfkey open: %s\n",
263			ipsec_strerror());
264		return NULL;
265	}
266
267	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_dump\n");
268	if (pfkey_send_dump(s, satype) < 0) {
269		plog(LLV_ERROR, LOCATION, NULL,
270			"libipsec failed dump: %s\n", ipsec_strerror());
271		goto fail;
272	}
273
274	while (1) {
275		if (msg)
276			racoon_free(msg);
277		msg = pk_recv(s, &len);
278		if (msg == NULL) {
279			if (len < 0)
280				goto done;
281			else
282				continue;
283		}
284
285		if (msg->sadb_msg_type != SADB_DUMP || msg->sadb_msg_pid != pid)
286			continue;
287
288		ml = msg->sadb_msg_len << 3;
289		bl = buf ? buf->l : 0;
290		buf = vrealloc(buf, bl + ml);
291		if (buf == NULL) {
292			plog(LLV_ERROR, LOCATION, NULL,
293				"failed to reallocate buffer to dump.\n");
294			goto fail;
295		}
296		memcpy(buf->v + bl, msg, ml);
297
298		if (msg->sadb_msg_seq == 0)
299			break;
300	}
301	goto done;
302
303fail:
304	if (buf)
305		vfree(buf);
306	buf = NULL;
307done:
308	if (msg)
309		racoon_free(msg);
310	if (s >= 0)
311		close(s);
312	return buf;
313}
314
315/*
316 * flush SADB
317 */
318void
319pfkey_flush_sadb(proto)
320	u_int proto;
321{
322	int satype;
323
324	/* convert to SADB_SATYPE */
325	if ((satype = admin2pfkey_proto(proto)) < 0)
326		return;
327
328	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_flush\n");
329	if (pfkey_send_flush(lcconf->sock_pfkey, satype) < 0) {
330		plog(LLV_ERROR, LOCATION, NULL,
331			"libipsec failed send flush (%s)\n", ipsec_strerror());
332		return;
333	}
334
335	return;
336}
337
338/*
339 * These are the SATYPEs that we manage.  We register to get
340 * PF_KEY messages related to these SATYPEs, and we also use
341 * this list to determine which SATYPEs to delete SAs for when
342 * we receive an INITIAL-CONTACT.
343 */
344const struct pfkey_satype pfkey_satypes[] = {
345	{ SADB_SATYPE_AH,	"AH" },
346	{ SADB_SATYPE_ESP,	"ESP" },
347	{ SADB_X_SATYPE_IPCOMP,	"IPCOMP" },
348};
349const int pfkey_nsatypes =
350    sizeof(pfkey_satypes) / sizeof(pfkey_satypes[0]);
351
352/*
353 * PF_KEY initialization
354 */
355int
356pfkey_init()
357{
358	int i, reg_fail;
359
360	if ((lcconf->sock_pfkey = pfkey_open()) < 0) {
361		plog(LLV_ERROR, LOCATION, NULL,
362			"libipsec failed pfkey open (%s)", ipsec_strerror());
363		return -1;
364	}
365
366	for (i = 0, reg_fail = 0; i < pfkey_nsatypes; i++) {
367		plog(LLV_DEBUG, LOCATION, NULL,
368		    "call pfkey_send_register for %s\n",
369		    pfkey_satypes[i].ps_name);
370		if (pfkey_send_register(lcconf->sock_pfkey,
371					pfkey_satypes[i].ps_satype) < 0 ||
372		    pfkey_recv_register(lcconf->sock_pfkey) < 0) {
373			plog(LLV_WARNING, LOCATION, NULL,
374			    "failed to register %s (%s)",
375			    pfkey_satypes[i].ps_name,
376			    ipsec_strerror());
377			reg_fail++;
378		}
379	}
380
381	if (reg_fail == pfkey_nsatypes) {
382		plog(LLV_ERROR, LOCATION, NULL,
383			"failed to regist any protocol.");
384		pfkey_close(lcconf->sock_pfkey);
385		return -1;
386	}
387
388	initsp();
389
390	if (pfkey_send_spddump(lcconf->sock_pfkey) < 0) {
391		plog(LLV_ERROR, LOCATION, NULL,
392			"libipsec sending spddump failed: %s",
393			ipsec_strerror());
394		pfkey_close(lcconf->sock_pfkey);
395		return -1;
396	}
397	return 0;
398}
399
400/* %%% for conversion */
401/* IPSECDOI_ATTR_AUTH -> SADB_AALG */
402static u_int
403ipsecdoi2pfkey_aalg(hashtype)
404	u_int hashtype;
405{
406	switch (hashtype) {
407	case IPSECDOI_ATTR_AUTH_HMAC_MD5:
408		return SADB_AALG_MD5HMAC;
409	case IPSECDOI_ATTR_AUTH_HMAC_SHA1:
410		return SADB_AALG_SHA1HMAC;
411	case IPSECDOI_ATTR_AUTH_KPDK:		/* need special care */
412		return SADB_AALG_NONE;
413
414	/* not supported */
415	case IPSECDOI_ATTR_AUTH_DES_MAC:
416		plog(LLV_ERROR, LOCATION, NULL,
417			"Not supported hash type: %u\n", hashtype);
418		return ~0;
419
420	case 0: /* reserved */
421	default:
422		return SADB_AALG_NONE;
423
424		plog(LLV_ERROR, LOCATION, NULL,
425			"Invalid hash type: %u\n", hashtype);
426		return ~0;
427	}
428	/*NOTREACHED*/
429}
430
431/* IPSECDOI_ESP -> SADB_EALG */
432static u_int
433ipsecdoi2pfkey_ealg(t_id)
434	u_int t_id;
435{
436	switch (t_id) {
437	case IPSECDOI_ESP_DES_IV64:		/* sa_flags |= SADB_X_EXT_OLD */
438		return SADB_EALG_DESCBC;
439	case IPSECDOI_ESP_DES:
440		return SADB_EALG_DESCBC;
441	case IPSECDOI_ESP_3DES:
442		return SADB_EALG_3DESCBC;
443#ifdef SADB_X_EALG_RC5CBC
444	case IPSECDOI_ESP_RC5:
445		return SADB_X_EALG_RC5CBC;
446#endif
447	case IPSECDOI_ESP_CAST:
448		return SADB_X_EALG_CAST128CBC;
449	case IPSECDOI_ESP_BLOWFISH:
450		return SADB_X_EALG_BLOWFISHCBC;
451	case IPSECDOI_ESP_DES_IV32:	/* flags |= (SADB_X_EXT_OLD|
452							SADB_X_EXT_IV4B)*/
453		return SADB_EALG_DESCBC;
454	case IPSECDOI_ESP_NULL:
455		return SADB_EALG_NULL;
456#ifdef SADB_X_EALG_RIJNDAELCBC
457	case IPSECDOI_ESP_RIJNDAEL:
458		return SADB_X_EALG_RIJNDAELCBC;
459#endif
460#ifdef SADB_X_EALG_TWOFISHCBC
461	case IPSECDOI_ESP_TWOFISH:
462		return SADB_X_EALG_TWOFISHCBC;
463#endif
464
465	/* not supported */
466	case IPSECDOI_ESP_3IDEA:
467	case IPSECDOI_ESP_IDEA:
468	case IPSECDOI_ESP_RC4:
469		plog(LLV_ERROR, LOCATION, NULL,
470			"Not supported transform: %u\n", t_id);
471		return ~0;
472
473	case 0: /* reserved */
474	default:
475		plog(LLV_ERROR, LOCATION, NULL,
476			"Invalid transform id: %u\n", t_id);
477		return ~0;
478	}
479	/*NOTREACHED*/
480}
481
482/* IPCOMP -> SADB_CALG */
483static u_int
484ipsecdoi2pfkey_calg(t_id)
485	u_int t_id;
486{
487	switch (t_id) {
488	case IPSECDOI_IPCOMP_OUI:
489		return SADB_X_CALG_OUI;
490	case IPSECDOI_IPCOMP_DEFLATE:
491		return SADB_X_CALG_DEFLATE;
492	case IPSECDOI_IPCOMP_LZS:
493		return SADB_X_CALG_LZS;
494
495	case 0: /* reserved */
496	default:
497		plog(LLV_ERROR, LOCATION, NULL,
498			"Invalid transform id: %u\n", t_id);
499		return ~0;
500	}
501	/*NOTREACHED*/
502}
503
504/* IPSECDOI_PROTO -> SADB_SATYPE */
505u_int
506ipsecdoi2pfkey_proto(proto)
507	u_int proto;
508{
509	switch (proto) {
510	case IPSECDOI_PROTO_IPSEC_AH:
511		return SADB_SATYPE_AH;
512	case IPSECDOI_PROTO_IPSEC_ESP:
513		return SADB_SATYPE_ESP;
514	case IPSECDOI_PROTO_IPCOMP:
515		return SADB_X_SATYPE_IPCOMP;
516
517	default:
518		plog(LLV_ERROR, LOCATION, NULL,
519			"Invalid ipsec_doi proto: %u\n", proto);
520		return ~0;
521	}
522	/*NOTREACHED*/
523}
524
525static u_int
526ipsecdoi2pfkey_alg(algclass, type)
527	u_int algclass, type;
528{
529	switch (algclass) {
530	case IPSECDOI_ATTR_AUTH:
531		return ipsecdoi2pfkey_aalg(type);
532	case IPSECDOI_PROTO_IPSEC_ESP:
533		return ipsecdoi2pfkey_ealg(type);
534	case IPSECDOI_PROTO_IPCOMP:
535		return ipsecdoi2pfkey_calg(type);
536	default:
537		plog(LLV_ERROR, LOCATION, NULL,
538			"Invalid ipsec_doi algclass: %u\n", algclass);
539		return ~0;
540	}
541	/*NOTREACHED*/
542}
543
544/* SADB_SATYPE -> IPSECDOI_PROTO */
545u_int
546pfkey2ipsecdoi_proto(satype)
547	u_int satype;
548{
549	switch (satype) {
550	case SADB_SATYPE_AH:
551		return IPSECDOI_PROTO_IPSEC_AH;
552	case SADB_SATYPE_ESP:
553		return IPSECDOI_PROTO_IPSEC_ESP;
554	case SADB_X_SATYPE_IPCOMP:
555		return IPSECDOI_PROTO_IPCOMP;
556
557	default:
558		plog(LLV_ERROR, LOCATION, NULL,
559			"Invalid pfkey proto: %u\n", satype);
560		return ~0;
561	}
562	/*NOTREACHED*/
563}
564
565/* IPSECDOI_ATTR_ENC_MODE -> IPSEC_MODE */
566u_int
567ipsecdoi2pfkey_mode(mode)
568	u_int mode;
569{
570	switch (mode) {
571	case IPSECDOI_ATTR_ENC_MODE_TUNNEL:
572		return IPSEC_MODE_TUNNEL;
573	case IPSECDOI_ATTR_ENC_MODE_TRNS:
574		return IPSEC_MODE_TRANSPORT;
575	default:
576		plog(LLV_ERROR, LOCATION, NULL, "Invalid mode type: %u\n", mode);
577		return ~0;
578	}
579	/*NOTREACHED*/
580}
581
582/* IPSECDOI_ATTR_ENC_MODE -> IPSEC_MODE */
583u_int
584pfkey2ipsecdoi_mode(mode)
585	u_int mode;
586{
587	switch (mode) {
588	case IPSEC_MODE_TUNNEL:
589		return IPSECDOI_ATTR_ENC_MODE_TUNNEL;
590	case IPSEC_MODE_TRANSPORT:
591		return IPSECDOI_ATTR_ENC_MODE_TRNS;
592	case IPSEC_MODE_ANY:
593		return IPSECDOI_ATTR_ENC_MODE_ANY;
594	default:
595		plog(LLV_ERROR, LOCATION, NULL, "Invalid mode type: %u\n", mode);
596		return ~0;
597	}
598	/*NOTREACHED*/
599}
600
601/* default key length for encryption algorithm */
602static u_int
603keylen_aalg(hashtype)
604	u_int hashtype;
605{
606	int res;
607
608	if (hashtype == 0)
609		return SADB_AALG_NONE;
610
611	res = alg_ipsec_hmacdef_hashlen(hashtype);
612	if (res == -1) {
613		plog(LLV_ERROR, LOCATION, NULL,
614			"invalid hmac algorithm %u.\n", hashtype);
615		return ~0;
616	}
617	return res;
618}
619
620/* default key length for encryption algorithm */
621static u_int
622keylen_ealg(enctype, encklen)
623	u_int enctype;
624	int encklen;
625{
626	int res;
627
628	res = alg_ipsec_encdef_keylen(enctype, encklen);
629	if (res == -1) {
630		plog(LLV_ERROR, LOCATION, NULL,
631			"invalid encryption algorithm %u.\n", enctype);
632		return ~0;
633	}
634	return res;
635}
636
637int
638pfkey_convertfromipsecdoi(proto_id, t_id, hashtype,
639		e_type, e_keylen, a_type, a_keylen, flags)
640	u_int proto_id;
641	u_int t_id;
642	u_int hashtype;
643	u_int *e_type;
644	u_int *e_keylen;
645	u_int *a_type;
646	u_int *a_keylen;
647	u_int *flags;
648{
649	*flags = 0;
650	switch (proto_id) {
651	case IPSECDOI_PROTO_IPSEC_ESP:
652		if ((*e_type = ipsecdoi2pfkey_ealg(t_id)) == ~0)
653			goto bad;
654		if ((*e_keylen = keylen_ealg(t_id, *e_keylen)) == ~0)
655			goto bad;
656		*e_keylen >>= 3;
657
658		if ((*a_type = ipsecdoi2pfkey_aalg(hashtype)) == ~0)
659			goto bad;
660		if ((*a_keylen = keylen_aalg(hashtype)) == ~0)
661			goto bad;
662		*a_keylen >>= 3;
663
664		if (*e_type == SADB_EALG_NONE) {
665			plog(LLV_ERROR, LOCATION, NULL, "no ESP algorithm.\n");
666			goto bad;
667		}
668		break;
669
670	case IPSECDOI_PROTO_IPSEC_AH:
671		if ((*a_type = ipsecdoi2pfkey_aalg(hashtype)) == ~0)
672			goto bad;
673		if ((*a_keylen = keylen_aalg(hashtype)) == ~0)
674			goto bad;
675		*a_keylen >>= 3;
676
677		if (t_id == IPSECDOI_ATTR_AUTH_HMAC_MD5
678		 && hashtype == IPSECDOI_ATTR_AUTH_KPDK) {
679			/* AH_MD5 + Auth(KPDK) = RFC1826 keyed-MD5 */
680			*a_type = SADB_X_AALG_MD5;
681			*flags |= SADB_X_EXT_OLD;
682		}
683		*e_type = SADB_EALG_NONE;
684		*e_keylen = 0;
685		if (*a_type == SADB_AALG_NONE) {
686			plog(LLV_ERROR, LOCATION, NULL, "no AH algorithm.\n");
687			goto bad;
688		}
689		break;
690
691	case IPSECDOI_PROTO_IPCOMP:
692		if ((*e_type = ipsecdoi2pfkey_calg(t_id)) == ~0)
693			goto bad;
694		*e_keylen = 0;
695
696		*flags = SADB_X_EXT_RAWCPI;
697
698		*a_type = SADB_AALG_NONE;
699		*a_keylen = 0;
700		if (*e_type == SADB_X_CALG_NONE) {
701			plog(LLV_ERROR, LOCATION, NULL, "no IPCOMP algorithm.\n");
702			goto bad;
703		}
704		break;
705
706	default:
707		plog(LLV_ERROR, LOCATION, NULL, "unknown IPsec protocol.\n");
708		goto bad;
709	}
710
711	return 0;
712
713    bad:
714	errno = EINVAL;
715	return -1;
716}
717
718/* called from scheduler */
719void
720pfkey_timeover_stub(p)
721	void *p;
722{
723
724	pfkey_timeover((struct ph2handle *)p);
725}
726
727void
728pfkey_timeover(iph2)
729	struct ph2handle *iph2;
730{
731	plog(LLV_ERROR, LOCATION, NULL,
732		"%s give up to get IPsec-SA due to time up to wait.\n",
733		saddrwop2str(iph2->dst));
734	SCHED_KILL(iph2->sce);
735
736	/* If initiator side, send error to kernel by SADB_ACQUIRE. */
737	if (iph2->side == INITIATOR)
738		pk_sendeacquire(iph2);
739
740	unbindph12(iph2);
741	remph2(iph2);
742	delph2(iph2);
743
744	return;
745}
746
747/*%%%*/
748/* send getspi message per ipsec protocol per remote address */
749/*
750 * the local address and remote address in ph1handle are dealed
751 * with destination address and source address respectively.
752 * Because SPI is decided by responder.
753 */
754int
755pk_sendgetspi(iph2)
756	struct ph2handle *iph2;
757{
758	u_int satype, mode;
759	struct saprop *pp;
760	struct saproto *pr;
761
762	pp = iph2->side == INITIATOR
763			? iph2->proposal
764			: iph2->approval;
765
766	for (pr = pp->head; pr != NULL; pr = pr->next) {
767
768		/* validity check */
769		satype = ipsecdoi2pfkey_proto(pr->proto_id);
770		if (satype == ~0) {
771			plog(LLV_ERROR, LOCATION, NULL,
772				"invalid proto_id %d\n", pr->proto_id);
773			return -1;
774		}
775		mode = ipsecdoi2pfkey_mode(pr->encmode);
776		if (mode == ~0) {
777			plog(LLV_ERROR, LOCATION, NULL,
778				"invalid encmode %d\n", pr->encmode);
779			return -1;
780		}
781
782		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_getspi\n");
783		if (pfkey_send_getspi(
784				lcconf->sock_pfkey,
785				satype,
786				mode,
787				iph2->dst,		/* src of SA */
788				iph2->src,		/* dst of SA */
789				0, 0, pr->reqid_in, iph2->seq) < 0) {
790			plog(LLV_ERROR, LOCATION, NULL,
791				"ipseclib failed send getspi (%s)\n",
792				ipsec_strerror());
793			return -1;
794		}
795		plog(LLV_DEBUG, LOCATION, NULL,
796			"pfkey GETSPI sent: %s\n",
797			sadbsecas2str(iph2->dst, iph2->src, satype, 0, mode));
798	}
799
800	return 0;
801}
802
803/*
804 * receive GETSPI from kernel.
805 */
806static int
807pk_recvgetspi(mhp)
808	caddr_t *mhp;
809{
810	struct sadb_msg *msg;
811	struct sadb_sa *sa;
812	struct ph2handle *iph2;
813	struct sockaddr *dst;
814	int proto_id;
815	int allspiok, notfound;
816	struct saprop *pp;
817	struct saproto *pr;
818
819	/* validity check */
820	if (mhp[SADB_EXT_SA] == NULL
821	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
822		plog(LLV_ERROR, LOCATION, NULL,
823			"inappropriate sadb getspi message passed.\n");
824		return -1;
825	}
826	msg = (struct sadb_msg *)mhp[0];
827	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
828	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]); /* note SA dir */
829
830	/* the message has to be processed or not ? */
831	if (msg->sadb_msg_pid != getpid()) {
832		plog(LLV_DEBUG, LOCATION, NULL,
833			"%s message is not interesting "
834			"because pid %d is not mine.\n",
835			s_pfkey_type(msg->sadb_msg_type),
836			msg->sadb_msg_pid);
837		return -1;
838	}
839
840	iph2 = getph2byseq(msg->sadb_msg_seq);
841	if (iph2 == NULL) {
842		plog(LLV_DEBUG, LOCATION, NULL,
843			"seq %d of %s message not interesting.\n",
844			msg->sadb_msg_seq,
845			s_pfkey_type(msg->sadb_msg_type));
846		return -1;
847	}
848
849	if (iph2->status != PHASE2ST_GETSPISENT) {
850		plog(LLV_ERROR, LOCATION, NULL,
851			"status mismatch (db:%d msg:%d)\n",
852			iph2->status, PHASE2ST_GETSPISENT);
853		return -1;
854	}
855
856	/* set SPI, and check to get all spi whether or not */
857	allspiok = 1;
858	notfound = 1;
859	proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
860	pp = iph2->side == INITIATOR ? iph2->proposal : iph2->approval;
861
862	for (pr = pp->head; pr != NULL; pr = pr->next) {
863		if (pr->proto_id == proto_id && pr->spi == 0) {
864			pr->spi = sa->sadb_sa_spi;
865			notfound = 0;
866			plog(LLV_DEBUG, LOCATION, NULL,
867				"pfkey GETSPI succeeded: %s\n",
868				sadbsecas2str(iph2->dst, iph2->src,
869				    msg->sadb_msg_satype,
870				    sa->sadb_sa_spi,
871				    ipsecdoi2pfkey_mode(pr->encmode)));
872		}
873		if (pr->spi == 0)
874			allspiok = 0;	/* not get all spi */
875	}
876
877	if (notfound) {
878		plog(LLV_ERROR, LOCATION, NULL,
879			"get spi for unknown address %s\n",
880			saddrwop2str(iph2->dst));
881		return -1;
882	}
883
884	if (allspiok) {
885		/* update status */
886		iph2->status = PHASE2ST_GETSPIDONE;
887		if (isakmp_post_getspi(iph2) < 0) {
888			plog(LLV_ERROR, LOCATION, NULL,
889				"failed to start post getspi.\n");
890			unbindph12(iph2);
891			remph2(iph2);
892			delph2(iph2);
893			iph2 = NULL;
894			return -1;
895		}
896	}
897
898	return 0;
899}
900
901/*
902 * set inbound SA
903 */
904int
905pk_sendupdate(iph2)
906	struct ph2handle *iph2;
907{
908	struct saproto *pr;
909	struct sockaddr *src = NULL, *dst = NULL;
910	int e_type, e_keylen, a_type, a_keylen, flags;
911	u_int satype, mode;
912	u_int64_t lifebyte = 0;
913
914	/* sanity check */
915	if (iph2->approval == NULL) {
916		plog(LLV_ERROR, LOCATION, NULL,
917			"no approvaled SAs found.\n");
918	}
919
920	/* for mobile IPv6 */
921	if (iph2->ph1->rmconf->support_mip6 && iph2->src_id && iph2->dst_id) {
922		src = iph2->src_id;
923		dst = iph2->dst_id;
924	} else {
925		src = iph2->src;
926		dst = iph2->dst;
927	}
928
929	for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
930		/* validity check */
931		satype = ipsecdoi2pfkey_proto(pr->proto_id);
932		if (satype == ~0) {
933			plog(LLV_ERROR, LOCATION, NULL,
934				"invalid proto_id %d\n", pr->proto_id);
935			return -1;
936		}
937#ifdef ENABLE_SAMODE_UNSPECIFIED
938		mode = IPSEC_MODE_ANY;
939#else
940		mode = ipsecdoi2pfkey_mode(pr->encmode);
941		if (mode == ~0) {
942			plog(LLV_ERROR, LOCATION, NULL,
943				"invalid encmode %d\n", pr->encmode);
944			return -1;
945		}
946#endif
947
948		/* set algorithm type and key length */
949		e_keylen = pr->head->encklen;
950		if (pfkey_convertfromipsecdoi(
951				pr->proto_id,
952				pr->head->trns_id,
953				pr->head->authtype,
954				&e_type, &e_keylen,
955				&a_type, &a_keylen, &flags) < 0)
956			return -1;
957
958		lifebyte = 0;
959
960		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_update\n");
961
962		if (pfkey_send_update(
963				lcconf->sock_pfkey,
964				satype,
965				mode,
966				iph2->dst,
967				iph2->src,
968				pr->spi,
969				pr->reqid_in,
970				4,
971				pr->keymat->v,
972				e_type, e_keylen, a_type, a_keylen, flags,
973				0, lifebyte, iph2->approval->lifetime, 0,
974				iph2->seq) < 0) {
975			plog(LLV_ERROR, LOCATION, NULL,
976				"libipsec failed send update (%s)\n",
977				ipsec_strerror());
978			return -1;
979		}
980
981		if (!lcconf->pathinfo[LC_PATHTYPE_BACKUPSA])
982			continue;
983
984		/*
985		 * It maybe good idea to call backupsa_to_file() after
986		 * racoon will receive the sadb_update messages.
987		 * But it is impossible because there is not key in the
988		 * information from the kernel.
989		 */
990		if (backupsa_to_file(satype, mode, iph2->dst, iph2->src,
991				pr->spi, pr->reqid_in, 4,
992				pr->keymat->v,
993				e_type, e_keylen, a_type, a_keylen, flags,
994				0, iph2->approval->lifebyte * 1024,
995				iph2->approval->lifetime, 0,
996				iph2->seq) < 0) {
997			plog(LLV_ERROR, LOCATION, NULL,
998				"backuped SA failed: %s\n",
999				sadbsecas2str(iph2->dst, iph2->src,
1000				satype, pr->spi, mode));
1001		}
1002		plog(LLV_DEBUG, LOCATION, NULL,
1003			"backuped SA: %s\n",
1004			sadbsecas2str(iph2->dst, iph2->src,
1005			satype, pr->spi, mode));
1006	}
1007
1008	return 0;
1009}
1010
1011static int
1012pk_recvupdate(mhp)
1013	caddr_t *mhp;
1014{
1015	struct sadb_msg *msg;
1016	struct sadb_sa *sa;
1017	struct sockaddr *src, *dst;
1018	struct ph2handle *iph2;
1019	u_int proto_id, encmode, sa_mode;
1020	int incomplete = 0;
1021	struct saproto *pr;
1022
1023	/* ignore this message because of local test mode. */
1024	if (f_local)
1025		return 0;
1026
1027	/* sanity check */
1028	if (mhp[0] == NULL
1029	 || mhp[SADB_EXT_SA] == NULL
1030	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1031	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1032		plog(LLV_ERROR, LOCATION, NULL,
1033			"inappropriate sadb update message passed.\n");
1034		return -1;
1035	}
1036	msg = (struct sadb_msg *)mhp[0];
1037	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1038	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1039	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1040
1041	sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1042		? IPSEC_MODE_ANY
1043		: ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1044
1045	/* the message has to be processed or not ? */
1046	if (msg->sadb_msg_pid != getpid()) {
1047		plog(LLV_DEBUG, LOCATION, NULL,
1048			"%s message is not interesting "
1049			"because pid %d is not mine.\n",
1050			s_pfkey_type(msg->sadb_msg_type),
1051			msg->sadb_msg_pid);
1052		return -1;
1053	}
1054
1055	iph2 = getph2byseq(msg->sadb_msg_seq);
1056	if (iph2 == NULL) {
1057		plog(LLV_DEBUG, LOCATION, NULL,
1058			"seq %d of %s message not interesting.\n",
1059			msg->sadb_msg_seq,
1060			s_pfkey_type(msg->sadb_msg_type));
1061		return -1;
1062	}
1063
1064	if (iph2->status != PHASE2ST_ADDSA) {
1065		plog(LLV_ERROR, LOCATION, NULL,
1066			"status mismatch (db:%d msg:%d)\n",
1067			iph2->status, PHASE2ST_ADDSA);
1068		return -1;
1069	}
1070
1071	/* check to complete all keys ? */
1072	for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1073		proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1074		if (proto_id == ~0) {
1075			plog(LLV_ERROR, LOCATION, NULL,
1076				"invalid proto_id %d\n", msg->sadb_msg_satype);
1077			return -1;
1078		}
1079		encmode = pfkey2ipsecdoi_mode(sa_mode);
1080		if (encmode == ~0) {
1081			plog(LLV_ERROR, LOCATION, NULL,
1082				"invalid encmode %d\n", sa_mode);
1083			return -1;
1084		}
1085
1086		if (pr->proto_id == proto_id
1087		 && pr->spi == sa->sadb_sa_spi) {
1088			pr->ok = 1;
1089			plog(LLV_DEBUG, LOCATION, NULL,
1090				"pfkey UPDATE succeeded: %s\n",
1091				sadbsecas2str(iph2->dst, iph2->src,
1092				    msg->sadb_msg_satype,
1093				    sa->sadb_sa_spi,
1094				    sa_mode));
1095
1096			plog(LLV_INFO, LOCATION, NULL,
1097				"IPsec-SA established: %s\n",
1098				sadbsecas2str(iph2->dst, iph2->src,
1099					msg->sadb_msg_satype, sa->sadb_sa_spi,
1100					sa_mode));
1101		}
1102
1103		if (pr->ok == 0)
1104			incomplete = 1;
1105	}
1106
1107	if (incomplete)
1108		return 0;
1109
1110	/* turn off the timer for calling pfkey_timeover() */
1111	SCHED_KILL(iph2->sce);
1112
1113	/* update status */
1114	iph2->status = PHASE2ST_ESTABLISHED;
1115
1116#ifdef ENABLE_STATS
1117	gettimeofday(&iph2->end, NULL);
1118	syslog(LOG_NOTICE, "%s(%s): %8.6f",
1119		"phase2", "quick", timedelta(&iph2->start, &iph2->end));
1120#endif
1121
1122	/* count up */
1123	iph2->ph1->ph2cnt++;
1124
1125	/*
1126	 * since we are going to reuse the phase2 handler, we need to
1127	 * remain it and refresh all the references between ph1 and ph2 to use.
1128	 */
1129	unbindph12(iph2);
1130
1131	iph2->sce = sched_new(iph2->approval->lifetime,
1132	    isakmp_ph2expire_stub, iph2);
1133
1134	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1135	return 0;
1136}
1137
1138/*
1139 * set outbound SA
1140 */
1141int
1142pk_sendadd(iph2)
1143	struct ph2handle *iph2;
1144{
1145	struct saproto *pr;
1146	struct sockaddr *src = NULL, *dst = NULL;
1147	int e_type, e_keylen, a_type, a_keylen, flags;
1148	u_int satype, mode;
1149	u_int64_t lifebyte = 0;
1150
1151	/* sanity check */
1152	if (iph2->approval == NULL) {
1153		plog(LLV_ERROR, LOCATION, NULL,
1154			"no approvaled SAs found.\n");
1155	}
1156
1157	/* for mobile IPv6 */
1158	if (iph2->ph1->rmconf->support_mip6 && iph2->src_id && iph2->dst_id) {
1159		src = iph2->src_id;
1160		dst = iph2->dst_id;
1161	} else {
1162		src = iph2->src;
1163		dst = iph2->dst;
1164	}
1165
1166	for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
1167		/* validity check */
1168		satype = ipsecdoi2pfkey_proto(pr->proto_id);
1169		if (satype == ~0) {
1170			plog(LLV_ERROR, LOCATION, NULL,
1171				"invalid proto_id %d\n", pr->proto_id);
1172			return -1;
1173		}
1174#ifdef ENABLE_SAMODE_UNSPECIFIED
1175		mode = IPSEC_MODE_ANY;
1176#else
1177		mode = ipsecdoi2pfkey_mode(pr->encmode);
1178		if (mode == ~0) {
1179			plog(LLV_ERROR, LOCATION, NULL,
1180				"invalid encmode %d\n", pr->encmode);
1181			return -1;
1182		}
1183#endif
1184
1185		/* set algorithm type and key length */
1186		e_keylen = pr->head->encklen;
1187		if (pfkey_convertfromipsecdoi(
1188				pr->proto_id,
1189				pr->head->trns_id,
1190				pr->head->authtype,
1191				&e_type, &e_keylen,
1192				&a_type, &a_keylen, &flags) < 0)
1193			return -1;
1194
1195		lifebyte = 0;
1196
1197		plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_add\n");
1198
1199		if (pfkey_send_add(
1200				lcconf->sock_pfkey,
1201				satype,
1202				mode,
1203				iph2->src,
1204				iph2->dst,
1205				pr->spi_p,
1206				pr->reqid_out,
1207				4,
1208				pr->keymat_p->v,
1209				e_type, e_keylen, a_type, a_keylen, flags,
1210				0, lifebyte, iph2->approval->lifetime, 0,
1211				iph2->seq) < 0) {
1212			plog(LLV_ERROR, LOCATION, NULL,
1213				"libipsec failed send add (%s)\n",
1214				ipsec_strerror());
1215			return -1;
1216		}
1217
1218		if (!lcconf->pathinfo[LC_PATHTYPE_BACKUPSA])
1219			continue;
1220
1221		/*
1222		 * It maybe good idea to call backupsa_to_file() after
1223		 * racoon will receive the sadb_update messages.
1224		 * But it is impossible because there is not key in the
1225		 * information from the kernel.
1226		 */
1227		if (backupsa_to_file(satype, mode, iph2->src, iph2->dst,
1228				pr->spi_p, pr->reqid_out, 4,
1229				pr->keymat_p->v,
1230				e_type, e_keylen, a_type, a_keylen, flags,
1231				0, iph2->approval->lifebyte * 1024,
1232				iph2->approval->lifetime, 0,
1233				iph2->seq) < 0) {
1234			plog(LLV_ERROR, LOCATION, NULL,
1235				"backuped SA failed: %s\n",
1236				sadbsecas2str(iph2->src, iph2->dst,
1237				satype, pr->spi_p, mode));
1238		}
1239		plog(LLV_DEBUG, LOCATION, NULL,
1240			"backuped SA: %s\n",
1241			sadbsecas2str(iph2->src, iph2->dst,
1242			satype, pr->spi_p, mode));
1243	}
1244
1245	return 0;
1246}
1247
1248static int
1249pk_recvadd(mhp)
1250	caddr_t *mhp;
1251{
1252	struct sadb_msg *msg;
1253	struct sadb_sa *sa;
1254	struct sockaddr *src, *dst;
1255	struct ph2handle *iph2;
1256	u_int sa_mode;
1257
1258	/* ignore this message because of local test mode. */
1259	if (f_local)
1260		return 0;
1261
1262	/* sanity check */
1263	if (mhp[0] == NULL
1264	 || mhp[SADB_EXT_SA] == NULL
1265	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1266	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1267		plog(LLV_ERROR, LOCATION, NULL,
1268			"inappropriate sadb add message passed.\n");
1269		return -1;
1270	}
1271	msg = (struct sadb_msg *)mhp[0];
1272	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1273	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1274	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1275
1276	sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1277		? IPSEC_MODE_ANY
1278		: ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1279
1280	/* the message has to be processed or not ? */
1281	if (msg->sadb_msg_pid != getpid()) {
1282		plog(LLV_DEBUG, LOCATION, NULL,
1283			"%s message is not interesting "
1284			"because pid %d is not mine.\n",
1285			s_pfkey_type(msg->sadb_msg_type),
1286			msg->sadb_msg_pid);
1287		return -1;
1288	}
1289
1290	iph2 = getph2byseq(msg->sadb_msg_seq);
1291	if (iph2 == NULL) {
1292		plog(LLV_DEBUG, LOCATION, NULL,
1293			"seq %d of %s message not interesting.\n",
1294			msg->sadb_msg_seq,
1295			s_pfkey_type(msg->sadb_msg_type));
1296		return -1;
1297	}
1298
1299	/*
1300	 * NOTE don't update any status of phase2 handle
1301	 * because they must be updated by SADB_UPDATE message
1302	 */
1303
1304	plog(LLV_INFO, LOCATION, NULL,
1305		"IPsec-SA established: %s\n",
1306		sadbsecas2str(iph2->src, iph2->dst,
1307			msg->sadb_msg_satype, sa->sadb_sa_spi, sa_mode));
1308
1309	plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1310	return 0;
1311}
1312
1313static int
1314pk_recvexpire(mhp)
1315	caddr_t *mhp;
1316{
1317	struct sadb_msg *msg;
1318	struct sadb_sa *sa;
1319	struct sockaddr *src, *dst;
1320	struct ph2handle *iph2;
1321	u_int proto_id, sa_mode;
1322
1323	/* sanity check */
1324	if (mhp[0] == NULL
1325	 || mhp[SADB_EXT_SA] == NULL
1326	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1327	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
1328	 || (mhp[SADB_EXT_LIFETIME_HARD] != NULL
1329	  && mhp[SADB_EXT_LIFETIME_SOFT] != NULL)) {
1330		plog(LLV_ERROR, LOCATION, NULL,
1331			"inappropriate sadb expire message passed.\n");
1332		return -1;
1333	}
1334	msg = (struct sadb_msg *)mhp[0];
1335	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1336	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1337	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1338
1339	sa_mode = mhp[SADB_X_EXT_SA2] == NULL
1340		? IPSEC_MODE_ANY
1341		: ((struct sadb_x_sa2 *)mhp[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
1342
1343	proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1344	if (proto_id == ~0) {
1345		plog(LLV_ERROR, LOCATION, NULL,
1346			"invalid proto_id %d\n", msg->sadb_msg_satype);
1347		return -1;
1348	}
1349
1350	plog(LLV_INFO, LOCATION, NULL,
1351		"IPsec-SA expired: %s\n",
1352		sadbsecas2str(src, dst,
1353			msg->sadb_msg_satype, sa->sadb_sa_spi, sa_mode));
1354
1355	iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
1356	if (iph2 == NULL) {
1357		/*
1358		 * Ignore it because two expire messages are come up.
1359		 * phase2 handler has been deleted already when 2nd message
1360		 * is received.
1361		 */
1362		plog(LLV_DEBUG, LOCATION, NULL,
1363			"no such a SA found: %s\n",
1364			sadbsecas2str(src, dst,
1365			    msg->sadb_msg_satype, sa->sadb_sa_spi,
1366			    sa_mode));
1367		return 0;
1368	}
1369	if (iph2->status != PHASE2ST_ESTABLISHED) {
1370		/*
1371		 * If the status is not equal to PHASE2ST_ESTABLISHED,
1372		 * racoon ignores this expire message.  There are two reason.
1373		 * One is that the phase 2 probably starts becuase there is
1374		 * a potential that racoon receives the acquire message
1375		 * without receiving a expire message.  Another is that racoon
1376		 * may receive the multiple expire messages from the kernel.
1377		 */
1378		plog(LLV_WARNING, LOCATION, NULL,
1379			"the expire message is received "
1380			"but the handler has not been established.\n");
1381		return 0;
1382	}
1383
1384	/* turn off the timer for calling isakmp_ph2expire() */
1385	SCHED_KILL(iph2->sce);
1386
1387	iph2->status = PHASE2ST_EXPIRED;
1388
1389	/* INITIATOR, begin phase 2 exchange. */
1390	/* allocate buffer for status management of pfkey message */
1391	if (iph2->side == INITIATOR) {
1392
1393		initph2(iph2);
1394
1395		/* update status for re-use */
1396		iph2->status = PHASE2ST_STATUS2;
1397
1398		/* start isakmp initiation by using ident exchange */
1399		if (isakmp_post_acquire(iph2) < 0) {
1400			plog(LLV_ERROR, LOCATION, iph2->dst,
1401				"failed to begin ipsec sa "
1402				"re-negotication.\n");
1403			unbindph12(iph2);
1404			remph2(iph2);
1405			delph2(iph2);
1406			return -1;
1407		}
1408
1409		return 0;
1410		/*NOTREACHED*/
1411	}
1412
1413	/* If not received SADB_EXPIRE, INITIATOR delete ph2handle. */
1414	/* RESPONDER always delete ph2handle, keep silent.  RESPONDER doesn't
1415	 * manage IPsec SA, so delete the list */
1416	unbindph12(iph2);
1417	remph2(iph2);
1418	delph2(iph2);
1419
1420	return 0;
1421}
1422
1423static int
1424pk_recvacquire(mhp)
1425	caddr_t *mhp;
1426{
1427	struct sadb_msg *msg;
1428	struct sadb_x_policy *xpl;
1429	struct secpolicy *sp_out = NULL, *sp_in = NULL;
1430#define MAXNESTEDSA	5
1431	struct ph2handle *iph2[MAXNESTEDSA];
1432	int n;	/* # of phase 2 handler */
1433
1434	/* ignore this message because of local test mode. */
1435	if (f_local)
1436		return 0;
1437
1438	/* sanity check */
1439	if (mhp[0] == NULL
1440	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1441	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
1442	 || mhp[SADB_X_EXT_POLICY] == NULL) {
1443		plog(LLV_ERROR, LOCATION, NULL,
1444			"inappropriate sadb acquire message passed.\n");
1445		return -1;
1446	}
1447	msg = (struct sadb_msg *)mhp[0];
1448	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
1449
1450	/* ignore if type is not IPSEC_POLICY_IPSEC */
1451	if (xpl->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
1452		plog(LLV_DEBUG, LOCATION, NULL,
1453			"ignore SPDGET message. type is not IPsec.\n");
1454		return 0;
1455	}
1456
1457	/* ignore it if src is multicast address */
1458    {
1459	struct sockaddr *sa = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1460
1461	if ((sa->sa_family == AF_INET
1462	  && IN_MULTICAST(ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr)))
1463#ifdef INET6
1464	 || (sa->sa_family == AF_INET6
1465	  && IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)sa)->sin6_addr))
1466#endif
1467	) {
1468		plog(LLV_DEBUG, LOCATION, NULL,
1469			"ignore due to multicast address: %s.\n",
1470			saddrwop2str(sa));
1471		return 0;
1472	}
1473    }
1474
1475	/*
1476	 * If there is a phase 2 handler against the policy identifier in
1477	 * the acquire message, and if
1478	 *    1. its state is less than PHASE2ST_ESTABLISHED, then racoon
1479	 *       should ignore such a acquire message becuase the phase 2
1480	 *       is just negotiating.
1481	 *    2. its state is equal to PHASE2ST_ESTABLISHED, then racoon
1482	 *       has to prcesss such a acquire message becuase racoon may
1483	 *       lost the expire message.
1484	 */
1485	iph2[0] = getph2byspid(xpl->sadb_x_policy_id);
1486	if (iph2[0] != NULL) {
1487		if (iph2[0]->status < PHASE2ST_ESTABLISHED) {
1488			plog(LLV_DEBUG, LOCATION, NULL,
1489				"ignore the acquire becuase ph2 found\n");
1490			return -1;
1491		}
1492		if (iph2[0]->status == PHASE2ST_EXPIRED)
1493			iph2[0] = NULL;
1494		/*FALLTHROUGH*/
1495	}
1496
1497	/* search for proper policyindex */
1498	sp_out = getspbyspid(xpl->sadb_x_policy_id);
1499	if (sp_out == NULL) {
1500		plog(LLV_ERROR, LOCATION, NULL, "no policy found: id:%d.\n",
1501			xpl->sadb_x_policy_id);
1502		return -1;
1503	}
1504	plog(LLV_DEBUG, LOCATION, NULL,
1505		"suitable outbound SP found: %s.\n", spidx2str(&sp_out->spidx));
1506
1507	/* get inbound policy */
1508    {
1509	struct policyindex spidx;
1510
1511	spidx.dir = IPSEC_DIR_INBOUND;
1512	memcpy(&spidx.src, &sp_out->spidx.dst, sizeof(spidx.src));
1513	memcpy(&spidx.dst, &sp_out->spidx.src, sizeof(spidx.dst));
1514	spidx.prefs = sp_out->spidx.prefd;
1515	spidx.prefd = sp_out->spidx.prefs;
1516	spidx.ul_proto = sp_out->spidx.ul_proto;
1517
1518	sp_in = getsp(&spidx);
1519	if (sp_in) {
1520		plog(LLV_DEBUG, LOCATION, NULL,
1521			"suitable inbound SP found: %s.\n",
1522			spidx2str(&sp_in->spidx));
1523	} else {
1524		plog(LLV_NOTIFY, LOCATION, NULL,
1525			"no in-bound policy found: %s\n",
1526			spidx2str(&spidx));
1527	}
1528    }
1529
1530	memset(iph2, 0, MAXNESTEDSA);
1531
1532	n = 0;
1533
1534	/* allocate a phase 2 */
1535	iph2[n] = newph2();
1536	if (iph2[n] == NULL) {
1537		plog(LLV_ERROR, LOCATION, NULL,
1538			"failed to allocate phase2 entry.\n");
1539		return -1;
1540	}
1541	iph2[n]->side = INITIATOR;
1542	iph2[n]->spid = xpl->sadb_x_policy_id;
1543	iph2[n]->satype = msg->sadb_msg_satype;
1544	iph2[n]->seq = msg->sadb_msg_seq;
1545	iph2[n]->status = PHASE2ST_STATUS2;
1546
1547	/* set end addresses of SA */
1548	iph2[n]->dst = dupsaddr(PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]));
1549	if (iph2[n]->dst == NULL) {
1550		delph2(iph2[n]);
1551		return -1;
1552	}
1553	iph2[n]->src = dupsaddr(PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]));
1554	if (iph2[n]->src == NULL) {
1555		delph2(iph2[n]);
1556		return -1;
1557	}
1558
1559	plog(LLV_DEBUG, LOCATION, NULL,
1560		"new acquire %s\n", spidx2str(&sp_out->spidx));
1561
1562	/* get sainfo */
1563    {
1564	vchar_t *idsrc, *iddst;
1565
1566	idsrc = ipsecdoi_sockaddr2id((struct sockaddr *)&sp_out->spidx.src,
1567				sp_out->spidx.prefs, sp_out->spidx.ul_proto);
1568	if (idsrc == NULL) {
1569		plog(LLV_ERROR, LOCATION, NULL,
1570			"failed to get ID for %s\n",
1571			spidx2str(&sp_out->spidx));
1572		delph2(iph2[n]);
1573		return -1;
1574	}
1575	iddst = ipsecdoi_sockaddr2id((struct sockaddr *)&sp_out->spidx.dst,
1576				sp_out->spidx.prefd, sp_out->spidx.ul_proto);
1577	if (iddst == NULL) {
1578		plog(LLV_ERROR, LOCATION, NULL,
1579			"failed to get ID for %s\n",
1580			spidx2str(&sp_out->spidx));
1581		vfree(idsrc);
1582		delph2(iph2[n]);
1583		return -1;
1584	}
1585	iph2[n]->sainfo = getsainfo(idsrc, iddst);
1586	vfree(idsrc);
1587	vfree(iddst);
1588	if (iph2[n]->sainfo == NULL) {
1589		plog(LLV_ERROR, LOCATION, NULL,
1590			"failed to get sainfo.\n");
1591		delph2(iph2[n]);
1592		return -1;
1593	}
1594    }
1595
1596	if (set_proposal_from_policy(iph2[n], sp_out, sp_in) < 0) {
1597		plog(LLV_ERROR, LOCATION, NULL,
1598			"failed to create saprop.\n");
1599		delph2(iph2[n]);
1600		return -1;
1601	}
1602	insph2(iph2[n]);
1603
1604	/* start isakmp initiation by using ident exchange */
1605	if (isakmp_post_acquire(iph2[n]) < 0) {
1606		plog(LLV_ERROR, LOCATION, NULL,
1607			"failed to begin ipsec sa negotication.\n");
1608		goto err;
1609	}
1610
1611	return 0;
1612
1613err:
1614	while (n >= 0) {
1615		unbindph12(iph2[n]);
1616		remph2(iph2[n]);
1617		delph2(iph2[n]);
1618		iph2[n] = NULL;
1619		n--;
1620	}
1621	return -1;
1622}
1623
1624static int
1625pk_recvdelete(mhp)
1626	caddr_t *mhp;
1627{
1628	struct sadb_msg *msg;
1629	struct sadb_sa *sa;
1630	struct sockaddr *src, *dst;
1631	struct ph2handle *iph2 = NULL;
1632	u_int proto_id;
1633
1634	/* ignore this message because of local test mode. */
1635	if (f_local)
1636		return 0;
1637
1638	/* sanity check */
1639	if (mhp[0] == NULL
1640	 || mhp[SADB_EXT_SA] == NULL
1641	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1642	 || mhp[SADB_EXT_ADDRESS_DST] == NULL) {
1643		plog(LLV_ERROR, LOCATION, NULL,
1644			"inappropriate sadb acquire message passed.\n");
1645		return -1;
1646	}
1647	msg = (struct sadb_msg *)mhp[0];
1648	sa = (struct sadb_sa *)mhp[SADB_EXT_SA];
1649	src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
1650	dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
1651
1652	/* the message has to be processed or not ? */
1653	if (msg->sadb_msg_pid == getpid()) {
1654		plog(LLV_DEBUG, LOCATION, NULL,
1655			"%s message is not interesting "
1656			"because the message was originated by me.\n",
1657			s_pfkey_type(msg->sadb_msg_type),
1658			msg->sadb_msg_pid);
1659		return -1;
1660	}
1661
1662	proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
1663	if (proto_id == ~0) {
1664		plog(LLV_ERROR, LOCATION, NULL,
1665			"invalid proto_id %d\n", msg->sadb_msg_satype);
1666		return -1;
1667	}
1668
1669	iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
1670	if (iph2 == NULL) {
1671		/* ignore */
1672		plog(LLV_ERROR, LOCATION, NULL,
1673			"no iph2 found: %s\n",
1674			sadbsecas2str(src, dst, msg->sadb_msg_satype,
1675				sa->sadb_sa_spi, IPSEC_MODE_ANY));
1676		return 0;
1677	}
1678
1679	plog(LLV_ERROR, LOCATION, NULL,
1680		"pfkey DELETE received: %s\n",
1681		sadbsecas2str(iph2->src, iph2->dst,
1682			msg->sadb_msg_satype, sa->sadb_sa_spi, IPSEC_MODE_ANY));
1683
1684	/* send delete information */
1685	if (iph2->status == PHASE2ST_ESTABLISHED)
1686		isakmp_info_send_d2(iph2);
1687
1688	unbindph12(iph2);
1689	remph2(iph2);
1690	delph2(iph2);
1691
1692	return 0;
1693}
1694
1695static int
1696pk_recvflush(mhp)
1697	caddr_t *mhp;
1698{
1699	/* ignore this message because of local test mode. */
1700	if (f_local)
1701		return 0;
1702
1703	/* sanity check */
1704	if (mhp[0] == NULL) {
1705		plog(LLV_ERROR, LOCATION, NULL,
1706			"inappropriate sadb acquire message passed.\n");
1707		return -1;
1708	}
1709
1710	flushph2();
1711
1712	return 0;
1713}
1714
1715static int
1716getsadbpolicy(policy0, policylen0, type, iph2)
1717	caddr_t *policy0;
1718	int *policylen0, type;
1719	struct ph2handle *iph2;
1720{
1721	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
1722	struct sadb_x_policy *xpl;
1723	struct sadb_x_ipsecrequest *xisr;
1724	struct saproto *pr;
1725	caddr_t policy, p;
1726	int policylen;
1727	int xisrlen;
1728	u_int satype, mode;
1729
1730	/* get policy buffer size */
1731	policylen = sizeof(struct sadb_x_policy);
1732	if (type != SADB_X_SPDDELETE) {
1733		for (pr = iph2->approval->head; pr; pr = pr->next) {
1734			xisrlen = sizeof(*xisr);
1735			if (pr->encmode == IPSECDOI_ATTR_ENC_MODE_TUNNEL) {
1736				xisrlen += (sysdep_sa_len(iph2->src)
1737				          + sysdep_sa_len(iph2->dst));
1738			}
1739
1740			policylen += PFKEY_ALIGN8(xisrlen);
1741		}
1742	}
1743
1744	/* make policy structure */
1745	policy = racoon_malloc(policylen);
1746	if (!policy) {
1747		plog(LLV_ERROR, LOCATION, NULL,
1748			"buffer allocation failed.\n");
1749		return -1;
1750	}
1751
1752	xpl = (struct sadb_x_policy *)policy;
1753	xpl->sadb_x_policy_len = PFKEY_UNIT64(policylen);
1754	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1755	xpl->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
1756	xpl->sadb_x_policy_dir = spidx->dir;
1757	xpl->sadb_x_policy_id = 0;
1758
1759	/* no need to append policy information any more if type is SPDDELETE */
1760	if (type == SADB_X_SPDDELETE)
1761		goto end;
1762
1763	xisr = (struct sadb_x_ipsecrequest *)(xpl + 1);
1764
1765	for (pr = iph2->approval->head; pr; pr = pr->next) {
1766
1767		satype = doi2ipproto(pr->proto_id);
1768		if (satype == ~0) {
1769			plog(LLV_ERROR, LOCATION, NULL,
1770				"invalid proto_id %d\n", pr->proto_id);
1771			goto err;
1772		}
1773		mode = ipsecdoi2pfkey_mode(pr->encmode);
1774		if (mode == ~0) {
1775			plog(LLV_ERROR, LOCATION, NULL,
1776				"invalid encmode %d\n", pr->encmode);
1777			goto err;
1778		}
1779
1780		/*
1781		 * the policy level cannot be unique because the policy
1782		 * is defined later than SA, so req_id cannot be bound to SA.
1783		 */
1784		xisr->sadb_x_ipsecrequest_proto = satype;
1785		xisr->sadb_x_ipsecrequest_mode = mode;
1786		xisr->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE;
1787		xisr->sadb_x_ipsecrequest_reqid = 0;
1788		p = (caddr_t)(xisr + 1);
1789
1790		xisrlen = sizeof(*xisr);
1791
1792		if (pr->encmode == IPSECDOI_ATTR_ENC_MODE_TUNNEL) {
1793			int src_len, dst_len;
1794
1795			src_len = sysdep_sa_len(iph2->src);
1796			dst_len = sysdep_sa_len(iph2->dst);
1797			xisrlen += src_len + dst_len;
1798
1799			memcpy(p, iph2->src, src_len);
1800			p += src_len;
1801
1802			memcpy(p, iph2->dst, dst_len);
1803			p += dst_len;
1804		}
1805
1806		xisr->sadb_x_ipsecrequest_len = PFKEY_ALIGN8(xisrlen);
1807	}
1808
1809end:
1810	*policy0 = policy;
1811	*policylen0 = policylen;
1812
1813	return 0;
1814
1815err:
1816	if (policy)
1817		racoon_free(policy);
1818
1819	return -1;
1820}
1821
1822int
1823pk_sendspdupdate2(iph2)
1824	struct ph2handle *iph2;
1825{
1826	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
1827	caddr_t policy = NULL;
1828	int policylen = 0;
1829	u_int64_t ltime, vtime;
1830
1831	ltime = iph2->approval->lifetime;
1832	vtime = 0;
1833
1834	if (getsadbpolicy(&policy, &policylen, SADB_X_SPDUPDATE, iph2)) {
1835		plog(LLV_ERROR, LOCATION, NULL,
1836			"getting sadb policy failed.\n");
1837		return -1;
1838	}
1839
1840	if (pfkey_send_spdupdate2(
1841			lcconf->sock_pfkey,
1842			(struct sockaddr *)&spidx->src,
1843			spidx->prefs,
1844			(struct sockaddr *)&spidx->dst,
1845			spidx->prefd,
1846			spidx->ul_proto,
1847			ltime, vtime,
1848			policy, policylen, 0) < 0) {
1849		plog(LLV_ERROR, LOCATION, NULL,
1850			"libipsec failed send spdupdate2 (%s)\n",
1851			ipsec_strerror());
1852		goto end;
1853	}
1854	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spdupdate2\n");
1855
1856end:
1857	if (policy)
1858		racoon_free(policy);
1859
1860	return 0;
1861}
1862
1863static int
1864pk_recvspdupdate(mhp)
1865	caddr_t *mhp;
1866{
1867	/* sanity check */
1868	if (mhp[0] == NULL) {
1869		plog(LLV_ERROR, LOCATION, NULL,
1870			"inappropriate sadb spdupdate message passed.\n");
1871		return -1;
1872	}
1873
1874	return 0;
1875}
1876
1877/*
1878 * this function has to be used by responder side.
1879 */
1880int
1881pk_sendspdadd2(iph2)
1882	struct ph2handle *iph2;
1883{
1884	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
1885	caddr_t policy = NULL;
1886	int policylen = 0;
1887	u_int64_t ltime, vtime;
1888
1889	ltime = iph2->approval->lifetime;
1890	vtime = 0;
1891
1892	if (getsadbpolicy(&policy, &policylen, SADB_X_SPDADD, iph2)) {
1893		plog(LLV_ERROR, LOCATION, NULL,
1894			"getting sadb policy failed.\n");
1895		return -1;
1896	}
1897
1898	if (pfkey_send_spdadd2(
1899			lcconf->sock_pfkey,
1900			(struct sockaddr *)&spidx->src,
1901			spidx->prefs,
1902			(struct sockaddr *)&spidx->dst,
1903			spidx->prefd,
1904			spidx->ul_proto,
1905			ltime, vtime,
1906			policy, policylen, 0) < 0) {
1907		plog(LLV_ERROR, LOCATION, NULL,
1908			"libipsec failed send spdadd2 (%s)\n",
1909			ipsec_strerror());
1910		goto end;
1911	}
1912	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spdadd2\n");
1913
1914end:
1915	if (policy)
1916		racoon_free(policy);
1917
1918	return 0;
1919}
1920
1921static int
1922pk_recvspdadd(mhp)
1923	caddr_t *mhp;
1924{
1925	struct sadb_address *saddr, *daddr;
1926	struct sadb_x_policy *xpl;
1927	struct policyindex spidx;
1928	struct secpolicy *sp;
1929
1930	/* sanity check */
1931	if (mhp[0] == NULL
1932	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
1933	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
1934	 || mhp[SADB_X_EXT_POLICY] == NULL) {
1935		plog(LLV_ERROR, LOCATION, NULL,
1936			"inappropriate sadb spdadd message passed.\n");
1937		return -1;
1938	}
1939	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
1940	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
1941	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
1942
1943	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
1944			saddr + 1,
1945			daddr + 1,
1946			saddr->sadb_address_prefixlen,
1947			daddr->sadb_address_prefixlen,
1948			saddr->sadb_address_proto,
1949			&spidx);
1950
1951	sp = getsp(&spidx);
1952	if (sp != NULL) {
1953		plog(LLV_ERROR, LOCATION, NULL,
1954			"such policy already exists. "
1955			"anyway replace it: %s\n",
1956			spidx2str(&spidx));
1957		remsp(sp);
1958		delsp(sp);
1959	}
1960
1961	if (addnewsp(mhp) < 0)
1962		return -1;
1963
1964	return 0;
1965}
1966
1967/*
1968 * this function has to be used by responder side.
1969 */
1970int
1971pk_sendspddelete(iph2)
1972	struct ph2handle *iph2;
1973{
1974	struct policyindex *spidx = (struct policyindex *)iph2->spidx_gen;
1975	caddr_t policy = NULL;
1976	int policylen;
1977
1978	if (getsadbpolicy(&policy, &policylen, SADB_X_SPDDELETE, iph2)) {
1979		plog(LLV_ERROR, LOCATION, NULL,
1980			"getting sadb policy failed.\n");
1981		return -1;
1982	}
1983
1984	if (pfkey_send_spddelete(
1985			lcconf->sock_pfkey,
1986			(struct sockaddr *)&spidx->src,
1987			spidx->prefs,
1988			(struct sockaddr *)&spidx->dst,
1989			spidx->prefd,
1990			spidx->ul_proto,
1991			policy, policylen, 0) < 0) {
1992		plog(LLV_ERROR, LOCATION, NULL,
1993			"libipsec failed send spddelete (%s)\n",
1994			ipsec_strerror());
1995		goto end;
1996	}
1997	plog(LLV_DEBUG, LOCATION, NULL, "call pfkey_send_spddelete\n");
1998
1999end:
2000	if (policy)
2001		racoon_free(policy);
2002
2003	return 0;
2004}
2005
2006static int
2007pk_recvspddelete(mhp)
2008	caddr_t *mhp;
2009{
2010	struct sadb_address *saddr, *daddr;
2011	struct sadb_x_policy *xpl;
2012	struct policyindex spidx;
2013	struct secpolicy *sp;
2014
2015	/* sanity check */
2016	if (mhp[0] == NULL
2017	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2018	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2019	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2020		plog(LLV_ERROR, LOCATION, NULL,
2021			"inappropriate sadb spddelete message passed.\n");
2022		return -1;
2023	}
2024	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2025	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2026	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2027
2028	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2029			saddr + 1,
2030			daddr + 1,
2031			saddr->sadb_address_prefixlen,
2032			daddr->sadb_address_prefixlen,
2033			saddr->sadb_address_proto,
2034			&spidx);
2035
2036	sp = getsp(&spidx);
2037	if (sp == NULL) {
2038		plog(LLV_ERROR, LOCATION, NULL,
2039			"no policy found: %s\n",
2040			spidx2str(&spidx));
2041		return -1;
2042	}
2043
2044	remsp(sp);
2045	delsp(sp);
2046
2047	return 0;
2048}
2049
2050static int
2051pk_recvspdexpire(mhp)
2052	caddr_t *mhp;
2053{
2054	struct sadb_address *saddr, *daddr;
2055	struct sadb_x_policy *xpl;
2056	struct policyindex spidx;
2057	struct secpolicy *sp;
2058
2059	/* sanity check */
2060	if (mhp[0] == NULL
2061	 || mhp[SADB_EXT_ADDRESS_SRC] == NULL
2062	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2063	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2064		plog(LLV_ERROR, LOCATION, NULL,
2065			"inappropriate sadb spdexpire message passed.\n");
2066		return -1;
2067	}
2068	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2069	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2070	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2071
2072	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2073			saddr + 1,
2074			daddr + 1,
2075			saddr->sadb_address_prefixlen,
2076			daddr->sadb_address_prefixlen,
2077			saddr->sadb_address_proto,
2078			&spidx);
2079
2080	sp = getsp(&spidx);
2081	if (sp == NULL) {
2082		plog(LLV_ERROR, LOCATION, NULL,
2083			"no policy found: %s\n",
2084			spidx2str(&spidx));
2085		return -1;
2086	}
2087
2088	remsp(sp);
2089	delsp(sp);
2090
2091	return 0;
2092}
2093
2094static int
2095pk_recvspdget(mhp)
2096	caddr_t *mhp;
2097{
2098	/* sanity check */
2099	if (mhp[0] == NULL) {
2100		plog(LLV_ERROR, LOCATION, NULL,
2101			"inappropriate sadb spdget message passed.\n");
2102		return -1;
2103	}
2104
2105	return 0;
2106}
2107
2108static int
2109pk_recvspddump(mhp)
2110	caddr_t *mhp;
2111{
2112	struct sadb_msg *msg;
2113	struct sadb_address *saddr, *daddr;
2114	struct sadb_x_policy *xpl;
2115	struct policyindex spidx;
2116	struct secpolicy *sp;
2117
2118	/* sanity check */
2119	if (mhp[0] == NULL) {
2120		plog(LLV_ERROR, LOCATION, NULL,
2121			"inappropriate sadb spddump message passed.\n");
2122		return -1;
2123	}
2124	msg = (struct sadb_msg *)mhp[0];
2125
2126	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2127	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2128	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2129
2130	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2131			saddr + 1,
2132			daddr + 1,
2133			saddr->sadb_address_prefixlen,
2134			daddr->sadb_address_prefixlen,
2135			saddr->sadb_address_proto,
2136			&spidx);
2137
2138	sp = getsp(&spidx);
2139	if (sp != NULL) {
2140		plog(LLV_ERROR, LOCATION, NULL,
2141			"such policy already exists. "
2142			"anyway replace it: %s\n",
2143			spidx2str(&spidx));
2144		remsp(sp);
2145		delsp(sp);
2146	}
2147
2148	if (addnewsp(mhp) < 0)
2149		return -1;
2150
2151	return 0;
2152}
2153
2154static int
2155pk_recvspdflush(mhp)
2156	caddr_t *mhp;
2157{
2158	/* sanity check */
2159	if (mhp[0] == NULL) {
2160		plog(LLV_ERROR, LOCATION, NULL,
2161			"inappropriate sadb spdflush message passed.\n");
2162		return -1;
2163	}
2164
2165	flushsp();
2166
2167	return 0;
2168}
2169
2170/*
2171 * send error against acquire message to kenrel.
2172 */
2173int
2174pk_sendeacquire(iph2)
2175	struct ph2handle *iph2;
2176{
2177	struct sadb_msg *newmsg;
2178	int len;
2179
2180	len = sizeof(struct sadb_msg);
2181	newmsg = racoon_calloc(1, len);
2182	if (newmsg == NULL) {
2183		plog(LLV_ERROR, LOCATION, NULL,
2184			"failed to get buffer to send acquire.\n");
2185		return -1;
2186	}
2187
2188	memset(newmsg, 0, len);
2189	newmsg->sadb_msg_version = PF_KEY_V2;
2190	newmsg->sadb_msg_type = SADB_ACQUIRE;
2191	newmsg->sadb_msg_errno = ENOENT;
2192	newmsg->sadb_msg_satype = iph2->satype;
2193	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
2194	newmsg->sadb_msg_reserved = 0;
2195	newmsg->sadb_msg_seq = iph2->seq;
2196	newmsg->sadb_msg_pid = (u_int32_t)getpid();
2197
2198	/* send message */
2199	len = pfkey_send(lcconf->sock_pfkey, newmsg, len);
2200
2201	racoon_free(newmsg);
2202
2203	return 0;
2204}
2205
2206/*
2207 * check if the algorithm is supported or not.
2208 * OUT	 0: ok
2209 *	-1: ng
2210 */
2211int
2212pk_checkalg(class, calg, keylen)
2213	int class, calg, keylen;
2214{
2215	int sup, error;
2216	u_int alg;
2217	struct sadb_alg alg0;
2218
2219	switch (algclass2doi(class)) {
2220	case IPSECDOI_PROTO_IPSEC_ESP:
2221		sup = SADB_EXT_SUPPORTED_ENCRYPT;
2222		break;
2223	case IPSECDOI_ATTR_AUTH:
2224		sup = SADB_EXT_SUPPORTED_AUTH;
2225		break;
2226	case IPSECDOI_PROTO_IPCOMP:
2227		plog(LLV_DEBUG, LOCATION, NULL,
2228			"compression algorithm can not be checked "
2229			"because sadb message doesn't support it.\n");
2230		return 0;
2231	default:
2232		plog(LLV_ERROR, LOCATION, NULL,
2233			"invalid algorithm class.\n");
2234		return -1;
2235	}
2236	alg = ipsecdoi2pfkey_alg(algclass2doi(class), algtype2doi(class, calg));
2237	if (alg == ~0)
2238		return -1;
2239
2240	if (keylen == 0) {
2241		if (ipsec_get_keylen(sup, alg, &alg0)) {
2242			plog(LLV_ERROR, LOCATION, NULL,
2243				"%s.\n", ipsec_strerror());
2244			return -1;
2245		}
2246		keylen = alg0.sadb_alg_minbits;
2247	}
2248
2249	error = ipsec_check_keylen(sup, alg, keylen);
2250	if (error)
2251		plog(LLV_ERROR, LOCATION, NULL,
2252			"%s.\n", ipsec_strerror());
2253
2254	return error;
2255}
2256
2257/*
2258 * differences with pfkey_recv() in libipsec/pfkey.c:
2259 * - never performs busy wait loop.
2260 * - returns NULL and set *lenp to negative on fatal failures
2261 * - returns NULL and set *lenp to non-negative on non-fatal failures
2262 * - returns non-NULL on success
2263 */
2264static struct sadb_msg *
2265pk_recv(so, lenp)
2266	int so;
2267	int *lenp;
2268{
2269	struct sadb_msg buf, *newmsg;
2270	int reallen;
2271
2272	*lenp = recv(so, (caddr_t)&buf, sizeof(buf), MSG_PEEK);
2273	if (*lenp < 0)
2274		return NULL;	/*fatal*/
2275	else if (*lenp < sizeof(buf))
2276		return NULL;
2277
2278	reallen = PFKEY_UNUNIT64(buf.sadb_msg_len);
2279	if ((newmsg = racoon_calloc(1, reallen)) == NULL)
2280		return NULL;
2281
2282	*lenp = recv(so, (caddr_t)newmsg, reallen, MSG_PEEK);
2283	if (*lenp < 0) {
2284		racoon_free(newmsg);
2285		return NULL;	/*fatal*/
2286	} else if (*lenp != reallen) {
2287		racoon_free(newmsg);
2288		return NULL;
2289	}
2290
2291	*lenp = recv(so, (caddr_t)newmsg, reallen, 0);
2292	if (*lenp < 0) {
2293		racoon_free(newmsg);
2294		return NULL;	/*fatal*/
2295	} else if (*lenp != reallen) {
2296		racoon_free(newmsg);
2297		return NULL;
2298	}
2299
2300	return newmsg;
2301}
2302
2303/* see handler.h */
2304u_int32_t
2305pk_getseq()
2306{
2307	return (u_int32_t)random();
2308}
2309
2310static int
2311addnewsp(mhp)
2312	caddr_t *mhp;
2313{
2314	struct secpolicy *new;
2315	struct sadb_address *saddr, *daddr;
2316	struct sadb_x_policy *xpl;
2317
2318	/* sanity check */
2319	if (mhp[SADB_EXT_ADDRESS_SRC] == NULL
2320	 || mhp[SADB_EXT_ADDRESS_DST] == NULL
2321	 || mhp[SADB_X_EXT_POLICY] == NULL) {
2322		plog(LLV_ERROR, LOCATION, NULL,
2323			"inappropriate sadb spd management message passed.\n");
2324		return -1;
2325	}
2326
2327	saddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_SRC];
2328	daddr = (struct sadb_address *)mhp[SADB_EXT_ADDRESS_DST];
2329	xpl = (struct sadb_x_policy *)mhp[SADB_X_EXT_POLICY];
2330
2331	new = newsp();
2332	if (new == NULL) {
2333		plog(LLV_ERROR, LOCATION, NULL,
2334			"failed to allocate buffer\n");
2335		return -1;
2336	}
2337
2338	new->spidx.dir = xpl->sadb_x_policy_dir;
2339	new->id = xpl->sadb_x_policy_id;
2340	new->policy = xpl->sadb_x_policy_type;
2341	new->req = NULL;
2342
2343	/* check policy */
2344	switch (xpl->sadb_x_policy_type) {
2345	case IPSEC_POLICY_DISCARD:
2346	case IPSEC_POLICY_NONE:
2347	case IPSEC_POLICY_ENTRUST:
2348	case IPSEC_POLICY_BYPASS:
2349		break;
2350
2351	case IPSEC_POLICY_IPSEC:
2352	    {
2353		int tlen;
2354		struct sadb_x_ipsecrequest *xisr;
2355		struct ipsecrequest **p_isr = &new->req;
2356
2357		/* validity check */
2358		if (PFKEY_EXTLEN(xpl) < sizeof(*xpl)) {
2359			plog(LLV_ERROR, LOCATION, NULL,
2360				"invalid msg length.\n");
2361			return -1;
2362		}
2363
2364		tlen = PFKEY_EXTLEN(xpl) - sizeof(*xpl);
2365		xisr = (struct sadb_x_ipsecrequest *)(xpl + 1);
2366
2367		while (tlen > 0) {
2368
2369			/* length check */
2370			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
2371				plog(LLV_ERROR, LOCATION, NULL,
2372					"invalid msg length.\n");
2373				return -1;
2374			}
2375
2376			/* allocate request buffer */
2377			*p_isr = newipsecreq();
2378			if (*p_isr == NULL) {
2379				plog(LLV_ERROR, LOCATION, NULL,
2380					"failed to get new ipsecreq.\n");
2381				return -1;
2382			}
2383
2384			/* set values */
2385			(*p_isr)->next = NULL;
2386
2387			switch (xisr->sadb_x_ipsecrequest_proto) {
2388			case IPPROTO_ESP:
2389			case IPPROTO_AH:
2390			case IPPROTO_COMP:
2391				break;
2392			default:
2393				plog(LLV_ERROR, LOCATION, NULL,
2394					"invalid proto type: %u\n",
2395					xisr->sadb_x_ipsecrequest_proto);
2396				return -1;
2397			}
2398			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
2399
2400			switch (xisr->sadb_x_ipsecrequest_mode) {
2401			case IPSEC_MODE_TRANSPORT:
2402			case IPSEC_MODE_TUNNEL:
2403				break;
2404			case IPSEC_MODE_ANY:
2405			default:
2406				plog(LLV_ERROR, LOCATION, NULL,
2407					"invalid mode: %u\n",
2408					xisr->sadb_x_ipsecrequest_mode);
2409				return -1;
2410			}
2411			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
2412
2413			switch (xisr->sadb_x_ipsecrequest_level) {
2414			case IPSEC_LEVEL_DEFAULT:
2415			case IPSEC_LEVEL_USE:
2416			case IPSEC_LEVEL_REQUIRE:
2417				break;
2418			case IPSEC_LEVEL_UNIQUE:
2419				(*p_isr)->saidx.reqid =
2420					xisr->sadb_x_ipsecrequest_reqid;
2421				break;
2422
2423			default:
2424				plog(LLV_ERROR, LOCATION, NULL,
2425					"invalid level: %u\n",
2426					xisr->sadb_x_ipsecrequest_level);
2427				return -1;
2428			}
2429			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
2430
2431			/* set IP addresses if there */
2432			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
2433				struct sockaddr *paddr;
2434
2435				paddr = (struct sockaddr *)(xisr + 1);
2436				bcopy(paddr, &(*p_isr)->saidx.src,
2437					sysdep_sa_len(paddr));
2438
2439				paddr = (struct sockaddr *)((caddr_t)paddr
2440							+ sysdep_sa_len(paddr));
2441				bcopy(paddr, &(*p_isr)->saidx.dst,
2442					sysdep_sa_len(paddr));
2443			}
2444
2445			(*p_isr)->sp = new;
2446
2447			/* initialization for the next. */
2448			p_isr = &(*p_isr)->next;
2449			tlen -= xisr->sadb_x_ipsecrequest_len;
2450
2451			/* validity check */
2452			if (tlen < 0) {
2453				plog(LLV_ERROR, LOCATION, NULL,
2454					"becoming tlen < 0\n");
2455			}
2456
2457			xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
2458			                 + xisr->sadb_x_ipsecrequest_len);
2459		}
2460	    }
2461		break;
2462	default:
2463		plog(LLV_ERROR, LOCATION, NULL,
2464			"invalid policy type.\n");
2465		return -1;
2466	}
2467
2468	KEY_SETSECSPIDX(xpl->sadb_x_policy_dir,
2469			saddr + 1,
2470			daddr + 1,
2471			saddr->sadb_address_prefixlen,
2472			daddr->sadb_address_prefixlen,
2473			saddr->sadb_address_proto,
2474			&new->spidx);
2475
2476	inssp(new);
2477
2478	return 0;
2479}
2480
2481/* proto/mode/src->dst spi */
2482const char *
2483sadbsecas2str(src, dst, proto, spi, mode)
2484	struct sockaddr *src, *dst;
2485	int proto;
2486	u_int32_t spi;
2487	int mode;
2488{
2489	static char buf[256];
2490	u_int doi_proto, doi_mode = 0;
2491	char *p;
2492	int blen, i;
2493
2494	doi_proto = pfkey2ipsecdoi_proto(proto);
2495	if (doi_proto == ~0)
2496		return NULL;
2497	if (mode) {
2498		doi_mode = pfkey2ipsecdoi_mode(mode);
2499		if (doi_mode == ~0)
2500			return NULL;
2501	}
2502
2503	blen = sizeof(buf) - 1;
2504	p = buf;
2505
2506	i = snprintf(p, blen, "%s%s%s ",
2507		s_ipsecdoi_proto(doi_proto),
2508		mode ? "/" : "",
2509		mode ? s_ipsecdoi_encmode(doi_mode) : "");
2510	if (i < 0 || i >= blen)
2511		return NULL;
2512	p += i;
2513	blen -= i;
2514
2515	i = snprintf(p, blen, "%s->", saddrwop2str(src));
2516	if (i < 0 || i >= blen)
2517		return NULL;
2518	p += i;
2519	blen -= i;
2520
2521	i = snprintf(p, blen, "%s ", saddrwop2str(dst));
2522	if (i < 0 || i >= blen)
2523		return NULL;
2524	p += i;
2525	blen -= i;
2526
2527	if (spi) {
2528		snprintf(p, blen, "spi=%lu(0x%lx)", (unsigned long)ntohl(spi),
2529		    (unsigned long)ntohl(spi));
2530	}
2531
2532	return buf;
2533}
2534