1/* $NetBSD: key.c,v 1.101 2016/07/20 07:37:51 ozaki-r Exp $ */
2/* $FreeBSD: src/sys/netipsec/key.c,v 1.3.2.3 2004/02/14 22:23:23 bms Exp $ */
3/* $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane 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 <sys/cdefs.h>
35__KERNEL_RCSID(0, "$NetBSD: key.c,v 1.101 2016/07/20 07:37:51 ozaki-r Exp $");
36
37/*
38 * This code is referd to RFC 2367
39 */
40
41#include "opt_inet.h"
42#ifdef __FreeBSD__
43#include "opt_inet6.h"
44#endif
45#include "opt_ipsec.h"
46#ifdef __NetBSD__
47#include "opt_gateway.h"
48#endif
49
50#include <sys/types.h>
51#include <sys/param.h>
52#include <sys/systm.h>
53#include <sys/callout.h>
54#include <sys/kernel.h>
55#include <sys/mbuf.h>
56#include <sys/domain.h>
57#include <sys/protosw.h>
58#include <sys/malloc.h>
59#include <sys/socket.h>
60#include <sys/socketvar.h>
61#include <sys/sysctl.h>
62#include <sys/errno.h>
63#include <sys/proc.h>
64#include <sys/queue.h>
65#include <sys/syslog.h>
66#include <sys/once.h>
67#include <sys/cprng.h>
68
69#include <net/if.h>
70#include <net/route.h>
71#include <net/raw_cb.h>
72
73#include <netinet/in.h>
74#include <netinet/in_systm.h>
75#include <netinet/ip.h>
76#include <netinet/in_var.h>
77#ifdef INET
78#include <netinet/ip_var.h>
79#endif
80
81#ifdef INET6
82#include <netinet/ip6.h>
83#include <netinet6/in6_var.h>
84#include <netinet6/ip6_var.h>
85#endif /* INET6 */
86
87#ifdef INET
88#include <netinet/in_pcb.h>
89#endif
90#ifdef INET6
91#include <netinet6/in6_pcb.h>
92#endif /* INET6 */
93
94#include <net/pfkeyv2.h>
95#include <netipsec/keydb.h>
96#include <netipsec/key.h>
97#include <netipsec/keysock.h>
98#include <netipsec/key_debug.h>
99
100#include <netipsec/ipsec.h>
101#ifdef INET6
102#include <netipsec/ipsec6.h>
103#endif
104#include <netipsec/ipsec_private.h>
105
106#include <netipsec/xform.h>
107#include <netipsec/ipsec_osdep.h>
108#include <netipsec/ipcomp.h>
109
110
111#include <net/net_osdep.h>
112
113#define FULLMASK 0xff
114#define _BITS(bytes) ((bytes) << 3)
115
116#define PORT_NONE 0
117#define PORT_LOOSE 1
118#define PORT_STRICT 2
119
120percpu_t *pfkeystat_percpu;
121
122/*
123 * Note on SA reference counting:
124 * - SAs that are not in DEAD state will have (total external reference + 1)
125 * following value in reference count field. they cannot be freed and are
126 * referenced from SA header.
127 * - SAs that are in DEAD state will have (total external reference)
128 * in reference count field. they are ready to be freed. reference from
129 * SA header will be removed in key_delsav(), when the reference count
130 * field hits 0 (= no external reference other than from SA header.
131 */
132
133u_int32_t key_debug_level = 0;
134static u_int key_spi_trycnt = 1000;
135static u_int32_t key_spi_minval = 0x100;
136static u_int32_t key_spi_maxval = 0x0fffffff; /* XXX */
137static u_int32_t policy_id = 0;
138static u_int key_int_random = 60; /*interval to initialize randseed,1(m)*/
139static u_int key_larval_lifetime = 30; /* interval to expire acquiring, 30(s)*/
140static int key_blockacq_count = 10; /* counter for blocking SADB_ACQUIRE.*/
141static int key_blockacq_lifetime = 20; /* lifetime for blocking SADB_ACQUIRE.*/
142static int key_prefered_oldsa = 0; /* prefered old sa rather than new sa.*/
143
144static u_int32_t acq_seq = 0;
145
146static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX]; /* SPD */
147static LIST_HEAD(_sahtree, secashead) sahtree; /* SAD */
148static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
149 /* registed list */
150#ifndef IPSEC_NONBLOCK_ACQUIRE
151static LIST_HEAD(_acqtree, secacq) acqtree; /* acquiring list */
152#endif
153static LIST_HEAD(_spacqtree, secspacq) spacqtree; /* SP acquiring list */
154
155/* search order for SAs */
156 /*
157 * This order is important because we must select the oldest SA
158 * for outbound processing. For inbound, This is not important.
159 */
160static const u_int saorder_state_valid_prefer_old[] = {
161 SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
162};
163static const u_int saorder_state_valid_prefer_new[] = {
164 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
165};
166
167static const u_int saorder_state_alive[] = {
168 /* except DEAD */
169 SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
170};
171static const u_int saorder_state_any[] = {
172 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
173 SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
174};
175
176static const int minsize[] = {
177 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
178 sizeof(struct sadb_sa), /* SADB_EXT_SA */
179 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
180 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
181 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
182 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_SRC */
183 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_DST */
184 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_PROXY */
185 sizeof(struct sadb_key), /* SADB_EXT_KEY_AUTH */
186 sizeof(struct sadb_key), /* SADB_EXT_KEY_ENCRYPT */
187 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_SRC */
188 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_DST */
189 sizeof(struct sadb_sens), /* SADB_EXT_SENSITIVITY */
190 sizeof(struct sadb_prop), /* SADB_EXT_PROPOSAL */
191 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_AUTH */
192 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_ENCRYPT */
193 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
194 0, /* SADB_X_EXT_KMPRIVATE */
195 sizeof(struct sadb_x_policy), /* SADB_X_EXT_POLICY */
196 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
197 sizeof(struct sadb_x_nat_t_type), /* SADB_X_EXT_NAT_T_TYPE */
198 sizeof(struct sadb_x_nat_t_port), /* SADB_X_EXT_NAT_T_SPORT */
199 sizeof(struct sadb_x_nat_t_port), /* SADB_X_EXT_NAT_T_DPORT */
200 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAI */
201 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAR */
202 sizeof(struct sadb_x_nat_t_frag), /* SADB_X_EXT_NAT_T_FRAG */
203};
204static const int maxsize[] = {
205 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
206 sizeof(struct sadb_sa), /* SADB_EXT_SA */
207 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
208 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
209 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
210 0, /* SADB_EXT_ADDRESS_SRC */
211 0, /* SADB_EXT_ADDRESS_DST */
212 0, /* SADB_EXT_ADDRESS_PROXY */
213 0, /* SADB_EXT_KEY_AUTH */
214 0, /* SADB_EXT_KEY_ENCRYPT */
215 0, /* SADB_EXT_IDENTITY_SRC */
216 0, /* SADB_EXT_IDENTITY_DST */
217 0, /* SADB_EXT_SENSITIVITY */
218 0, /* SADB_EXT_PROPOSAL */
219 0, /* SADB_EXT_SUPPORTED_AUTH */
220 0, /* SADB_EXT_SUPPORTED_ENCRYPT */
221 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
222 0, /* SADB_X_EXT_KMPRIVATE */
223 0, /* SADB_X_EXT_POLICY */
224 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
225 sizeof(struct sadb_x_nat_t_type), /* SADB_X_EXT_NAT_T_TYPE */
226 sizeof(struct sadb_x_nat_t_port), /* SADB_X_EXT_NAT_T_SPORT */
227 sizeof(struct sadb_x_nat_t_port), /* SADB_X_EXT_NAT_T_DPORT */
228 0, /* SADB_X_EXT_NAT_T_OAI */
229 0, /* SADB_X_EXT_NAT_T_OAR */
230 sizeof(struct sadb_x_nat_t_frag), /* SADB_X_EXT_NAT_T_FRAG */
231};
232
233static int ipsec_esp_keymin = 256;
234static int ipsec_esp_auth = 0;
235static int ipsec_ah_keymin = 128;
236
237#ifdef SYSCTL_DECL
238SYSCTL_DECL(_net_key);
239#endif
240
241#ifdef SYSCTL_INT
242SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug, CTLFLAG_RW, \
243 &key_debug_level, 0, "");
244
245/* max count of trial for the decision of spi value */
246SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt, CTLFLAG_RW, \
247 &key_spi_trycnt, 0, "");
248
249/* minimum spi value to allocate automatically. */
250SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval, CTLFLAG_RW, \
251 &key_spi_minval, 0, "");
252
253/* maximun spi value to allocate automatically. */
254SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval, CTLFLAG_RW, \
255 &key_spi_maxval, 0, "");
256
257/* interval to initialize randseed */
258SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random, CTLFLAG_RW, \
259 &key_int_random, 0, "");
260
261/* lifetime for larval SA */
262SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime, CTLFLAG_RW, \
263 &key_larval_lifetime, 0, "");
264
265/* counter for blocking to send SADB_ACQUIRE to IKEd */
266SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count, CTLFLAG_RW, \
267 &key_blockacq_count, 0, "");
268
269/* lifetime for blocking to send SADB_ACQUIRE to IKEd */
270SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime, CTLFLAG_RW, \
271 &key_blockacq_lifetime, 0, "");
272
273/* ESP auth */
274SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth, CTLFLAG_RW, \
275 &ipsec_esp_auth, 0, "");
276
277/* minimum ESP key length */
278SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin, CTLFLAG_RW, \
279 &ipsec_esp_keymin, 0, "");
280
281/* minimum AH key length */
282SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin, CTLFLAG_RW, \
283 &ipsec_ah_keymin, 0, "");
284
285/* perfered old SA rather than new SA */
286SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, prefered_oldsa, CTLFLAG_RW,\
287 &key_prefered_oldsa, 0, "");
288#endif /* SYSCTL_INT */
289
290#ifndef LIST_FOREACH
291#define LIST_FOREACH(elm, head, field) \
292 for (elm = LIST_FIRST(head); elm; elm = LIST_NEXT(elm, field))
293#endif
294#define __LIST_CHAINED(elm) \
295 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
296#define LIST_INSERT_TAIL(head, elm, type, field) \
297do {\
298 struct type *curelm = LIST_FIRST(head); \
299 if (curelm == NULL) {\
300 LIST_INSERT_HEAD(head, elm, field); \
301 } else { \
302 while (LIST_NEXT(curelm, field)) \
303 curelm = LIST_NEXT(curelm, field);\
304 LIST_INSERT_AFTER(curelm, elm, field);\
305 }\
306} while (0)
307
308#define KEY_CHKSASTATE(head, sav, name) \
309/* do */ { \
310 if ((head) != (sav)) { \
311 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
312 (name), (head), (sav))); \
313 continue; \
314 } \
315} /* while (0) */
316
317#define KEY_CHKSPDIR(head, sp, name) \
318do { \
319 if ((head) != (sp)) { \
320 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
321 "anyway continue.\n", \
322 (name), (head), (sp))); \
323 } \
324} while (0)
325
326MALLOC_DEFINE(M_SECA, "key mgmt", "security associations, key management");
327
328#if 1
329#define KMALLOC(p, t, n) \
330 ((p) = (t) malloc((unsigned long)(n), M_SECA, M_NOWAIT))
331#define KFREE(p) \
332 free((p), M_SECA)
333#else
334#define KMALLOC(p, t, n) \
335do { \
336 ((p) = malloc((unsigned long)(n), M_SECA, M_NOWAIT)); \
337 printf("%s %d: %p <- KMALLOC(%s, %d)\n", \
338 __FILE__, __LINE__, (p), #t, n); \
339} while (0)
340
341#define KFREE(p) \
342 do { \
343 printf("%s %d: %p -> KFREE()\n", __FILE__, __LINE__, (p)); \
344 free((p), M_SECA); \
345 } while (0)
346#endif
347
348/*
349 * set parameters into secpolicyindex buffer.
350 * Must allocate secpolicyindex buffer passed to this function.
351 */
352#define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
353do { \
354 memset((idx), 0, sizeof(struct secpolicyindex)); \
355 (idx)->dir = (_dir); \
356 (idx)->prefs = (ps); \
357 (idx)->prefd = (pd); \
358 (idx)->ul_proto = (ulp); \
359 memcpy(&(idx)->src, (s), ((const struct sockaddr *)(s))->sa_len); \
360 memcpy(&(idx)->dst, (d), ((const struct sockaddr *)(d))->sa_len); \
361} while (0)
362
363/*
364 * set parameters into secasindex buffer.
365 * Must allocate secasindex buffer before calling this function.
366 */
367static int
368key_setsecasidx (int, int, int, const struct sadb_address *,
369 const struct sadb_address *, struct secasindex *);
370
371/* key statistics */
372struct _keystat {
373 u_long getspi_count; /* the avarage of count to try to get new SPI */
374} keystat;
375
376struct sadb_msghdr {
377 struct sadb_msg *msg;
378 struct sadb_ext *ext[SADB_EXT_MAX + 1];
379 int extoff[SADB_EXT_MAX + 1];
380 int extlen[SADB_EXT_MAX + 1];
381};
382
383static struct secasvar *key_allocsa_policy (const struct secasindex *);
384static void key_freesp_so (struct secpolicy **);
385static struct secasvar *key_do_allocsa_policy (struct secashead *, u_int);
386static void key_delsp (struct secpolicy *);
387static struct secpolicy *key_getsp (const struct secpolicyindex *);
388static struct secpolicy *key_getspbyid (u_int32_t);
389static u_int16_t key_newreqid (void);
390static struct mbuf *key_gather_mbuf (struct mbuf *,
391 const struct sadb_msghdr *, int, int, ...);
392static int key_spdadd (struct socket *, struct mbuf *,
393 const struct sadb_msghdr *);
394static u_int32_t key_getnewspid (void);
395static int key_spddelete (struct socket *, struct mbuf *,
396 const struct sadb_msghdr *);
397static int key_spddelete2 (struct socket *, struct mbuf *,
398 const struct sadb_msghdr *);
399static int key_spdget (struct socket *, struct mbuf *,
400 const struct sadb_msghdr *);
401static int key_spdflush (struct socket *, struct mbuf *,
402 const struct sadb_msghdr *);
403static int key_spddump (struct socket *, struct mbuf *,
404 const struct sadb_msghdr *);
405static struct mbuf * key_setspddump (int *errorp, pid_t);
406static struct mbuf * key_setspddump_chain (int *errorp, int *lenp, pid_t pid);
407static int key_nat_map (struct socket *, struct mbuf *,
408 const struct sadb_msghdr *);
409static struct mbuf *key_setdumpsp (struct secpolicy *,
410 u_int8_t, u_int32_t, pid_t);
411static u_int key_getspreqmsglen (const struct secpolicy *);
412static int key_spdexpire (struct secpolicy *);
413static struct secashead *key_newsah (const struct secasindex *);
414static void key_delsah (struct secashead *);
415static struct secasvar *key_newsav (struct mbuf *,
416 const struct sadb_msghdr *, struct secashead *, int *,
417 const char*, int);
418#define KEY_NEWSAV(m, sadb, sah, e) \
419 key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
420static void key_delsav (struct secasvar *);
421static struct secashead *key_getsah (const struct secasindex *);
422static struct secasvar *key_checkspidup (const struct secasindex *, u_int32_t);
423static struct secasvar *key_getsavbyspi (struct secashead *, u_int32_t);
424static int key_setsaval (struct secasvar *, struct mbuf *,
425 const struct sadb_msghdr *);
426static int key_mature (struct secasvar *);
427static struct mbuf *key_setdumpsa (struct secasvar *, u_int8_t,
428 u_int8_t, u_int32_t, u_int32_t);
429static struct mbuf *key_setsadbxport (u_int16_t, u_int16_t);
430static struct mbuf *key_setsadbxtype (u_int16_t);
431static struct mbuf *key_setsadbxfrag (u_int16_t);
432static void key_porttosaddr (union sockaddr_union *, u_int16_t);
433static int key_checksalen (const union sockaddr_union *);
434static struct mbuf *key_setsadbmsg (u_int8_t, u_int16_t, u_int8_t,
435 u_int32_t, pid_t, u_int16_t);
436static struct mbuf *key_setsadbsa (struct secasvar *);
437static struct mbuf *key_setsadbaddr (u_int16_t,
438 const struct sockaddr *, u_int8_t, u_int16_t);
439#if 0
440static struct mbuf *key_setsadbident (u_int16_t, u_int16_t, void *,
441 int, u_int64_t);
442#endif
443static struct mbuf *key_setsadbxsa2 (u_int8_t, u_int32_t, u_int16_t);
444static struct mbuf *key_setsadbxpolicy (u_int16_t, u_int8_t,
445 u_int32_t);
446static void *key_newbuf (const void *, u_int);
447#ifdef INET6
448static int key_ismyaddr6 (const struct sockaddr_in6 *);
449#endif
450
451/* flags for key_cmpsaidx() */
452#define CMP_HEAD 1 /* protocol, addresses. */
453#define CMP_MODE_REQID 2 /* additionally HEAD, reqid, mode. */
454#define CMP_REQID 3 /* additionally HEAD, reaid. */
455#define CMP_EXACTLY 4 /* all elements. */
456static int key_cmpsaidx
457 (const struct secasindex *, const struct secasindex *, int);
458
459static int key_sockaddrcmp (const struct sockaddr *, const struct sockaddr *, int);
460static int key_bbcmp (const void *, const void *, u_int);
461static u_int16_t key_satype2proto (u_int8_t);
462static u_int8_t key_proto2satype (u_int16_t);
463
464static int key_getspi (struct socket *, struct mbuf *,
465 const struct sadb_msghdr *);
466static u_int32_t key_do_getnewspi (const struct sadb_spirange *,
467 const struct secasindex *);
468static int key_handle_natt_info (struct secasvar *,
469 const struct sadb_msghdr *);
470static int key_set_natt_ports (union sockaddr_union *,
471 union sockaddr_union *,
472 const struct sadb_msghdr *);
473static int key_update (struct socket *, struct mbuf *,
474 const struct sadb_msghdr *);
475#ifdef IPSEC_DOSEQCHECK
476static struct secasvar *key_getsavbyseq (struct secashead *, u_int32_t);
477#endif
478static int key_add (struct socket *, struct mbuf *,
479 const struct sadb_msghdr *);
480static int key_setident (struct secashead *, struct mbuf *,
481 const struct sadb_msghdr *);
482static struct mbuf *key_getmsgbuf_x1 (struct mbuf *,
483 const struct sadb_msghdr *);
484static int key_delete (struct socket *, struct mbuf *,
485 const struct sadb_msghdr *);
486static int key_get (struct socket *, struct mbuf *,
487 const struct sadb_msghdr *);
488
489static void key_getcomb_setlifetime (struct sadb_comb *);
490static struct mbuf *key_getcomb_esp (void);
491static struct mbuf *key_getcomb_ah (void);
492static struct mbuf *key_getcomb_ipcomp (void);
493static struct mbuf *key_getprop (const struct secasindex *);
494
495static int key_acquire (const struct secasindex *, struct secpolicy *);
496#ifndef IPSEC_NONBLOCK_ACQUIRE
497static struct secacq *key_newacq (const struct secasindex *);
498static struct secacq *key_getacq (const struct secasindex *);
499static struct secacq *key_getacqbyseq (u_int32_t);
500#endif
501static struct secspacq *key_newspacq (const struct secpolicyindex *);
502static struct secspacq *key_getspacq (const struct secpolicyindex *);
503static int key_acquire2 (struct socket *, struct mbuf *,
504 const struct sadb_msghdr *);
505static int key_register (struct socket *, struct mbuf *,
506 const struct sadb_msghdr *);
507static int key_expire (struct secasvar *);
508static int key_flush (struct socket *, struct mbuf *,
509 const struct sadb_msghdr *);
510static struct mbuf *key_setdump_chain (u_int8_t req_satype, int *errorp,
511 int *lenp, pid_t pid);
512static int key_dump (struct socket *, struct mbuf *,
513 const struct sadb_msghdr *);
514static int key_promisc (struct socket *, struct mbuf *,
515 const struct sadb_msghdr *);
516static int key_senderror (struct socket *, struct mbuf *, int);
517static int key_validate_ext (const struct sadb_ext *, int);
518static int key_align (struct mbuf *, struct sadb_msghdr *);
519#if 0
520static const char *key_getfqdn (void);
521static const char *key_getuserfqdn (void);
522#endif
523static void key_sa_chgstate (struct secasvar *, u_int8_t);
524static inline void key_sp_dead (struct secpolicy *);
525static void key_sp_unlink (struct secpolicy *sp);
526
527static struct mbuf *key_alloc_mbuf (int);
528struct callout key_timehandler_ch;
529
530#define SA_ADDREF(p) do { \
531 (p)->refcnt++; \
532 IPSEC_ASSERT((p)->refcnt != 0, \
533 ("SA refcnt overflow at %s:%u", __FILE__, __LINE__)); \
534} while (0)
535#define SA_DELREF(p) do { \
536 IPSEC_ASSERT((p)->refcnt > 0, \
537 ("SA refcnt underflow at %s:%u", __FILE__, __LINE__)); \
538 (p)->refcnt--; \
539} while (0)
540
541#define SP_ADDREF(p) do { \
542 (p)->refcnt++; \
543 IPSEC_ASSERT((p)->refcnt != 0, \
544 ("SP refcnt overflow at %s:%u", __FILE__, __LINE__)); \
545} while (0)
546#define SP_DELREF(p) do { \
547 IPSEC_ASSERT((p)->refcnt > 0, \
548 ("SP refcnt underflow at %s:%u", __FILE__, __LINE__)); \
549 (p)->refcnt--; \
550} while (0)
551
552
553static inline void
554key_sp_dead(struct secpolicy *sp)
555{
556
557 /* mark the SP dead */
558 sp->state = IPSEC_SPSTATE_DEAD;
559}
560
561static void
562key_sp_unlink(struct secpolicy *sp)
563{
564
565 /* remove from SP index */
566 if (__LIST_CHAINED(sp)) {
567 LIST_REMOVE(sp, chain);
568 /* Release refcount held just for being on chain */
569 KEY_FREESP(&sp);
570 }
571}
572
573
574/*
575 * Return 0 when there are known to be no SP's for the specified
576 * direction. Otherwise return 1. This is used by IPsec code
577 * to optimize performance.
578 */
579int
580key_havesp(u_int dir)
581{
582 return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
583 LIST_FIRST(&sptree[dir]) != NULL : 1);
584}
585
586/* %%% IPsec policy management */
587/*
588 * allocating a SP for OUTBOUND or INBOUND packet.
589 * Must call key_freesp() later.
590 * OUT: NULL: not found
591 * others: found and return the pointer.
592 */
593struct secpolicy *
594key_allocsp(const struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
595{
596 struct secpolicy *sp;
597 int s;
598
599 IPSEC_ASSERT(spidx != NULL, ("key_allocsp: null spidx"));
600 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
601 ("key_allocsp: invalid direction %u", dir));
602
603 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
604 printf("DP %s from %s:%u\n", __func__, where, tag));
605
606 /* get a SP entry */
607 s = splsoftnet(); /*called from softclock()*/
608 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
609 printf("*** objects\n");
610 kdebug_secpolicyindex(spidx));
611
612 LIST_FOREACH(sp, &sptree[dir], chain) {
613 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
614 printf("*** in SPD\n");
615 kdebug_secpolicyindex(&sp->spidx));
616
617 if (sp->state == IPSEC_SPSTATE_DEAD)
618 continue;
619 if (key_cmpspidx_withmask(&sp->spidx, spidx))
620 goto found;
621 }
622 sp = NULL;
623found:
624 if (sp) {
625 /* sanity check */
626 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp");
627
628 /* found a SPD entry */
629 sp->lastused = time_uptime;
630 SP_ADDREF(sp);
631 }
632 splx(s);
633
634 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
635 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
636 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
637 return sp;
638}
639
640/*
641 * allocating a SP for OUTBOUND or INBOUND packet.
642 * Must call key_freesp() later.
643 * OUT: NULL: not found
644 * others: found and return the pointer.
645 */
646struct secpolicy *
647key_allocsp2(u_int32_t spi,
648 const union sockaddr_union *dst,
649 u_int8_t proto,
650 u_int dir,
651 const char* where, int tag)
652{
653 struct secpolicy *sp;
654 int s;
655
656 IPSEC_ASSERT(dst != NULL, ("key_allocsp2: null dst"));
657 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
658 ("key_allocsp2: invalid direction %u", dir));
659
660 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
661 printf("DP %s from %s:%u\n", __func__, where, tag));
662
663 /* get a SP entry */
664 s = splsoftnet(); /*called from softclock()*/
665 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
666 printf("*** objects\n");
667 printf("spi %u proto %u dir %u\n", spi, proto, dir);
668 kdebug_sockaddr(&dst->sa));
669
670 LIST_FOREACH(sp, &sptree[dir], chain) {
671 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
672 printf("*** in SPD\n");
673 kdebug_secpolicyindex(&sp->spidx));
674
675 if (sp->state == IPSEC_SPSTATE_DEAD)
676 continue;
677 /* compare simple values, then dst address */
678 if (sp->spidx.ul_proto != proto)
679 continue;
680 /* NB: spi's must exist and match */
681 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
682 continue;
683 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, PORT_STRICT) == 0)
684 goto found;
685 }
686 sp = NULL;
687found:
688 if (sp) {
689 /* sanity check */
690 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp2");
691
692 /* found a SPD entry */
693 sp->lastused = time_uptime;
694 SP_ADDREF(sp);
695 }
696 splx(s);
697
698 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
699 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
700 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
701 return sp;
702}
703
704/*
705 * return a policy that matches this particular inbound packet.
706 * XXX slow
707 */
708struct secpolicy *
709key_gettunnel(const struct sockaddr *osrc,
710 const struct sockaddr *odst,
711 const struct sockaddr *isrc,
712 const struct sockaddr *idst,
713 const char* where, int tag)
714{
715 struct secpolicy *sp;
716 const int dir = IPSEC_DIR_INBOUND;
717 int s;
718 struct ipsecrequest *r1, *r2, *p;
719 struct secpolicyindex spidx;
720
721 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
722 printf("DP %s from %s:%u\n", __func__, where, tag));
723
724 if (isrc->sa_family != idst->sa_family) {
725 ipseclog((LOG_ERR, "protocol family mismatched %d != %d\n.",
726 isrc->sa_family, idst->sa_family));
727 sp = NULL;
728 goto done;
729 }
730
731 s = splsoftnet(); /*called from softclock()*/
732 LIST_FOREACH(sp, &sptree[dir], chain) {
733 if (sp->state == IPSEC_SPSTATE_DEAD)
734 continue;
735
736 r1 = r2 = NULL;
737 for (p = sp->req; p; p = p->next) {
738 if (p->saidx.mode != IPSEC_MODE_TUNNEL)
739 continue;
740
741 r1 = r2;
742 r2 = p;
743
744 if (!r1) {
745 /* here we look at address matches only */
746 spidx = sp->spidx;
747 if (isrc->sa_len > sizeof(spidx.src) ||
748 idst->sa_len > sizeof(spidx.dst))
749 continue;
750 memcpy(&spidx.src, isrc, isrc->sa_len);
751 memcpy(&spidx.dst, idst, idst->sa_len);
752 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
753 continue;
754 } else {
755 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, PORT_NONE) ||
756 key_sockaddrcmp(&r1->saidx.dst.sa, idst, PORT_NONE))
757 continue;
758 }
759
760 if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, PORT_NONE) ||
761 key_sockaddrcmp(&r2->saidx.dst.sa, odst, PORT_NONE))
762 continue;
763
764 goto found;
765 }
766 }
767 sp = NULL;
768found:
769 if (sp) {
770 sp->lastused = time_uptime;
771 SP_ADDREF(sp);
772 }
773 splx(s);
774done:
775 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
776 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
777 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
778 return sp;
779}
780
781/*
782 * allocating an SA entry for an *OUTBOUND* packet.
783 * checking each request entries in SP, and acquire an SA if need.
784 * OUT: 0: there are valid requests.
785 * ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
786 */
787int
788key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
789{
790 u_int level;
791 int error;
792
793 IPSEC_ASSERT(isr != NULL, ("key_checkrequest: null isr"));
794 IPSEC_ASSERT(saidx != NULL, ("key_checkrequest: null saidx"));
795 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
796 saidx->mode == IPSEC_MODE_TUNNEL,
797 ("key_checkrequest: unexpected policy %u", saidx->mode));
798
799 /* get current level */
800 level = ipsec_get_reqlevel(isr);
801
802 /*
803 * XXX guard against protocol callbacks from the crypto
804 * thread as they reference ipsecrequest.sav which we
805 * temporarily null out below. Need to rethink how we
806 * handle bundled SA's in the callback thread.
807 */
808 IPSEC_SPLASSERT_SOFTNET("key_checkrequest");
809#if 0
810 /*
811 * We do allocate new SA only if the state of SA in the holder is
812 * SADB_SASTATE_DEAD. The SA for outbound must be the oldest.
813 */
814 if (isr->sav != NULL) {
815 if (isr->sav->sah == NULL)
816 panic("key_checkrequest: sah is null");
817 if (isr->sav == (struct secasvar *)LIST_FIRST(
818 &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
819 KEY_FREESAV(&isr->sav);
820 isr->sav = NULL;
821 }
822 }
823#else
824 /*
825 * we free any SA stashed in the IPsec request because a different
826 * SA may be involved each time this request is checked, either
827 * because new SAs are being configured, or this request is
828 * associated with an unconnected datagram socket, or this request
829 * is associated with a system default policy.
830 *
831 * The operation may have negative impact to performance. We may
832 * want to check cached SA carefully, rather than picking new SA
833 * every time.
834 */
835 if (isr->sav != NULL) {
836 KEY_FREESAV(&isr->sav);
837 isr->sav = NULL;
838 }
839#endif
840
841 /*
842 * new SA allocation if no SA found.
843 * key_allocsa_policy should allocate the oldest SA available.
844 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
845 */
846 if (isr->sav == NULL)
847 isr->sav = key_allocsa_policy(saidx);
848
849 /* When there is SA. */
850 if (isr->sav != NULL) {
851 if (isr->sav->state != SADB_SASTATE_MATURE &&
852 isr->sav->state != SADB_SASTATE_DYING)
853 return EINVAL;
854 return 0;
855 }
856
857 /* there is no SA */
858 error = key_acquire(saidx, isr->sp);
859 if (error != 0) {
860 /* XXX What should I do ? */
861 ipseclog((LOG_DEBUG, "key_checkrequest: error %d returned "
862 "from key_acquire.\n", error));
863 return error;
864 }
865
866 if (level != IPSEC_LEVEL_REQUIRE) {
867 /* XXX sigh, the interface to this routine is botched */
868 IPSEC_ASSERT(isr->sav == NULL, ("key_checkrequest: unexpected SA"));
869 return 0;
870 } else {
871 return ENOENT;
872 }
873}
874
875/*
876 * allocating a SA for policy entry from SAD.
877 * NOTE: searching SAD of aliving state.
878 * OUT: NULL: not found.
879 * others: found and return the pointer.
880 */
881static struct secasvar *
882key_allocsa_policy(const struct secasindex *saidx)
883{
884 struct secashead *sah;
885 struct secasvar *sav;
886 u_int stateidx, state;
887 const u_int *saorder_state_valid;
888 int arraysize;
889
890 LIST_FOREACH(sah, &sahtree, chain) {
891 if (sah->state == SADB_SASTATE_DEAD)
892 continue;
893 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
894 goto found;
895 }
896
897 return NULL;
898
899 found:
900
901 /*
902 * search a valid state list for outbound packet.
903 * This search order is important.
904 */
905 if (key_prefered_oldsa) {
906 saorder_state_valid = saorder_state_valid_prefer_old;
907 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
908 } else {
909 saorder_state_valid = saorder_state_valid_prefer_new;
910 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
911 }
912
913 /* search valid state */
914 for (stateidx = 0;
915 stateidx < arraysize;
916 stateidx++) {
917
918 state = saorder_state_valid[stateidx];
919
920 sav = key_do_allocsa_policy(sah, state);
921 if (sav != NULL)
922 return sav;
923 }
924
925 return NULL;
926}
927
928/*
929 * searching SAD with direction, protocol, mode and state.
930 * called by key_allocsa_policy().
931 * OUT:
932 * NULL : not found
933 * others : found, pointer to a SA.
934 */
935static struct secasvar *
936key_do_allocsa_policy(struct secashead *sah, u_int state)
937{
938 struct secasvar *sav, *nextsav, *candidate, *d;
939
940 /* initilize */
941 candidate = NULL;
942
943 for (sav = LIST_FIRST(&sah->savtree[state]);
944 sav != NULL;
945 sav = nextsav) {
946
947 nextsav = LIST_NEXT(sav, chain);
948
949 /* sanity check */
950 KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy");
951
952 /* initialize */
953 if (candidate == NULL) {
954 candidate = sav;
955 continue;
956 }
957
958 /* Which SA is the better ? */
959
960 /* sanity check 2 */
961 if (candidate->lft_c == NULL || sav->lft_c == NULL)
962 panic("key_do_allocsa_policy: "
963 "lifetime_current is NULL");
964
965 /* What the best method is to compare ? */
966 if (key_prefered_oldsa) {
967 if (candidate->lft_c->sadb_lifetime_addtime >
968 sav->lft_c->sadb_lifetime_addtime) {
969 candidate = sav;
970 }
971 continue;
972 /*NOTREACHED*/
973 }
974
975 /* prefered new sa rather than old sa */
976 if (candidate->lft_c->sadb_lifetime_addtime <
977 sav->lft_c->sadb_lifetime_addtime) {
978 d = candidate;
979 candidate = sav;
980 } else
981 d = sav;
982
983 /*
984 * prepared to delete the SA when there is more
985 * suitable candidate and the lifetime of the SA is not
986 * permanent.
987 */
988 if (d->lft_c->sadb_lifetime_addtime != 0) {
989 struct mbuf *m, *result = 0;
990 uint8_t satype;
991
992 key_sa_chgstate(d, SADB_SASTATE_DEAD);
993
994 IPSEC_ASSERT(d->refcnt > 0,
995 ("key_do_allocsa_policy: bogus ref count"));
996
997 satype = key_proto2satype(d->sah->saidx.proto);
998 if (satype == 0)
999 goto msgfail;
1000
1001 m = key_setsadbmsg(SADB_DELETE, 0,
1002 satype, 0, 0, d->refcnt - 1);
1003 if (!m)
1004 goto msgfail;
1005 result = m;
1006
1007 /* set sadb_address for saidx's. */
1008 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
1009 &d->sah->saidx.src.sa,
1010 d->sah->saidx.src.sa.sa_len << 3,
1011 IPSEC_ULPROTO_ANY);
1012 if (!m)
1013 goto msgfail;
1014 m_cat(result, m);
1015
1016 /* set sadb_address for saidx's. */
1017 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1018 &d->sah->saidx.src.sa,
1019 d->sah->saidx.src.sa.sa_len << 3,
1020 IPSEC_ULPROTO_ANY);
1021 if (!m)
1022 goto msgfail;
1023 m_cat(result, m);
1024
1025 /* create SA extension */
1026 m = key_setsadbsa(d);
1027 if (!m)
1028 goto msgfail;
1029 m_cat(result, m);
1030
1031 if (result->m_len < sizeof(struct sadb_msg)) {
1032 result = m_pullup(result,
1033 sizeof(struct sadb_msg));
1034 if (result == NULL)
1035 goto msgfail;
1036 }
1037
1038 result->m_pkthdr.len = 0;
1039 for (m = result; m; m = m->m_next)
1040 result->m_pkthdr.len += m->m_len;
1041 mtod(result, struct sadb_msg *)->sadb_msg_len =
1042 PFKEY_UNIT64(result->m_pkthdr.len);
1043
1044 key_sendup_mbuf(NULL, result,
1045 KEY_SENDUP_REGISTERED);
1046 result = 0;
1047 msgfail:
1048 if (result)
1049 m_freem(result);
1050 KEY_FREESAV(&d);
1051 }
1052 }
1053
1054 if (candidate) {
1055 SA_ADDREF(candidate);
1056 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1057 printf("DP %s cause refcnt++:%d SA:%p\n", __func__,
1058 candidate->refcnt, candidate));
1059 }
1060 return candidate;
1061}
1062
1063/*
1064 * allocating a usable SA entry for a *INBOUND* packet.
1065 * Must call key_freesav() later.
1066 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
1067 * NULL: not found, or error occurred.
1068 *
1069 * In the comparison, no source address is used--for RFC2401 conformance.
1070 * To quote, from section 4.1:
1071 * A security association is uniquely identified by a triple consisting
1072 * of a Security Parameter Index (SPI), an IP Destination Address, and a
1073 * security protocol (AH or ESP) identifier.
1074 * Note that, however, we do need to keep source address in IPsec SA.
1075 * IKE specification and PF_KEY specification do assume that we
1076 * keep source address in IPsec SA. We see a tricky situation here.
1077 *
1078 * sport and dport are used for NAT-T. network order is always used.
1079 */
1080struct secasvar *
1081key_allocsa(
1082 const union sockaddr_union *dst,
1083 u_int proto,
1084 u_int32_t spi,
1085 u_int16_t sport,
1086 u_int16_t dport,
1087 const char* where, int tag)
1088{
1089 struct secashead *sah;
1090 struct secasvar *sav;
1091 u_int stateidx, state;
1092 const u_int *saorder_state_valid;
1093 int arraysize, chkport;
1094 int s;
1095
1096 int must_check_spi = 1;
1097 int must_check_alg = 0;
1098 u_int16_t cpi = 0;
1099 u_int8_t algo = 0;
1100
1101 if ((sport != 0) && (dport != 0))
1102 chkport = PORT_STRICT;
1103 else
1104 chkport = PORT_NONE;
1105
1106 IPSEC_ASSERT(dst != NULL, ("key_allocsa: null dst address"));
1107
1108 /*
1109 * XXX IPCOMP case
1110 * We use cpi to define spi here. In the case where cpi <=
1111 * IPCOMP_CPI_NEGOTIATE_MIN, cpi just define the algorithm used, not
1112 * the real spi. In this case, don't check the spi but check the
1113 * algorithm
1114 */
1115
1116 if (proto == IPPROTO_IPCOMP) {
1117 u_int32_t tmp;
1118 tmp = ntohl(spi);
1119 cpi = (u_int16_t) tmp;
1120 if (cpi < IPCOMP_CPI_NEGOTIATE_MIN) {
1121 algo = (u_int8_t) cpi;
1122 must_check_spi = 0;
1123 must_check_alg = 1;
1124 }
1125 }
1126 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1127 printf("DP %s from %s:%u check_spi=%d, check_alg=%d\n",
1128 __func__, where, tag, must_check_spi, must_check_alg));
1129
1130
1131 /*
1132 * searching SAD.
1133 * XXX: to be checked internal IP header somewhere. Also when
1134 * IPsec tunnel packet is received. But ESP tunnel mode is
1135 * encrypted so we can't check internal IP header.
1136 */
1137 s = splsoftnet(); /*called from softclock()*/
1138 if (key_prefered_oldsa) {
1139 saorder_state_valid = saorder_state_valid_prefer_old;
1140 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1141 } else {
1142 saorder_state_valid = saorder_state_valid_prefer_new;
1143 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1144 }
1145 LIST_FOREACH(sah, &sahtree, chain) {
1146 /* search valid state */
1147 for (stateidx = 0; stateidx < arraysize; stateidx++) {
1148 state = saorder_state_valid[stateidx];
1149 LIST_FOREACH(sav, &sah->savtree[state], chain) {
1150 KEYDEBUG(KEYDEBUG_MATCH,
1151 printf("try match spi %#x, %#x\n",
1152 ntohl(spi), ntohl(sav->spi)));
1153 /* sanity check */
1154 KEY_CHKSASTATE(sav->state, state, "key_allocsav");
1155 /* do not return entries w/ unusable state */
1156 if (sav->state != SADB_SASTATE_MATURE &&
1157 sav->state != SADB_SASTATE_DYING) {
1158 KEYDEBUG(KEYDEBUG_MATCH,
1159 printf("bad state %d\n",
1160 sav->state));
1161 continue;
1162 }
1163 if (proto != sav->sah->saidx.proto) {
1164 KEYDEBUG(KEYDEBUG_MATCH,
1165 printf("proto fail %d != %d\n",
1166 proto, sav->sah->saidx.proto));
1167 continue;
1168 }
1169 if (must_check_spi && spi != sav->spi) {
1170 KEYDEBUG(KEYDEBUG_MATCH,
1171 printf("spi fail %#x != %#x\n",
1172 ntohl(spi), ntohl(sav->spi)));
1173 continue;
1174 }
1175 /* XXX only on the ipcomp case */
1176 if (must_check_alg && algo != sav->alg_comp) {
1177 KEYDEBUG(KEYDEBUG_MATCH,
1178 printf("algo fail %d != %d\n",
1179 algo, sav->alg_comp));
1180 continue;
1181 }
1182
1183#if 0 /* don't check src */
1184 /* Fix port in src->sa */
1185
1186 /* check src address */
1187 if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, PORT_NONE) != 0)
1188 continue;
1189#endif
1190 /* fix port of dst address XXX*/
1191 key_porttosaddr(__UNCONST(dst), dport);
1192 /* check dst address */
1193 if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, chkport) != 0)
1194 continue;
1195 SA_ADDREF(sav);
1196 goto done;
1197 }
1198 }
1199 }
1200 sav = NULL;
1201done:
1202 splx(s);
1203
1204 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1205 printf("DP %s return SA:%p; refcnt %u\n", __func__,
1206 sav, sav ? sav->refcnt : 0));
1207 return sav;
1208}
1209
1210/*
1211 * Must be called after calling key_allocsp().
1212 * For both the packet without socket and key_freeso().
1213 */
1214void
1215_key_freesp(struct secpolicy **spp, const char* where, int tag)
1216{
1217 struct secpolicy *sp = *spp;
1218
1219 IPSEC_ASSERT(sp != NULL, ("key_freesp: null sp"));
1220
1221 SP_DELREF(sp);
1222
1223 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1224 printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1225 __func__, sp, sp->id, where, tag, sp->refcnt));
1226
1227 if (sp->refcnt == 0) {
1228 *spp = NULL;
1229 key_delsp(sp);
1230 }
1231}
1232
1233/*
1234 * Must be called after calling key_allocsp().
1235 * For the packet with socket.
1236 */
1237void
1238key_freeso(struct socket *so)
1239{
1240 /* sanity check */
1241 IPSEC_ASSERT(so != NULL, ("key_freeso: null so"));
1242
1243 switch (so->so_proto->pr_domain->dom_family) {
1244#ifdef INET
1245 case PF_INET:
1246 {
1247 struct inpcb *pcb = sotoinpcb(so);
1248
1249 /* Does it have a PCB ? */
1250 if (pcb == NULL)
1251 return;
1252
1253 struct inpcbpolicy *sp = pcb->inp_sp;
1254 key_freesp_so(&sp->sp_in);
1255 key_freesp_so(&sp->sp_out);
1256 }
1257 break;
1258#endif
1259#ifdef INET6
1260 case PF_INET6:
1261 {
1262#ifdef HAVE_NRL_INPCB
1263 struct inpcb *pcb = sotoinpcb(so);
1264 struct inpcbpolicy *sp = pcb->inp_sp;
1265
1266 /* Does it have a PCB ? */
1267 if (pcb == NULL)
1268 return;
1269 key_freesp_so(&sp->sp_in);
1270 key_freesp_so(&sp->sp_out);
1271#else
1272 struct in6pcb *pcb = sotoin6pcb(so);
1273
1274 /* Does it have a PCB ? */
1275 if (pcb == NULL)
1276 return;
1277 key_freesp_so(&pcb->in6p_sp->sp_in);
1278 key_freesp_so(&pcb->in6p_sp->sp_out);
1279#endif
1280 }
1281 break;
1282#endif /* INET6 */
1283 default:
1284 ipseclog((LOG_DEBUG, "key_freeso: unknown address family=%d.\n",
1285 so->so_proto->pr_domain->dom_family));
1286 return;
1287 }
1288}
1289
1290static void
1291key_freesp_so(struct secpolicy **sp)
1292{
1293 IPSEC_ASSERT(sp != NULL && *sp != NULL, ("key_freesp_so: null sp"));
1294
1295 if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1296 (*sp)->policy == IPSEC_POLICY_BYPASS)
1297 return;
1298
1299 IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1300 ("key_freesp_so: invalid policy %u", (*sp)->policy));
1301 KEY_FREESP(sp);
1302}
1303
1304/*
1305 * Must be called after calling key_allocsa().
1306 * This function is called by key_freesp() to free some SA allocated
1307 * for a policy.
1308 */
1309void
1310key_freesav(struct secasvar **psav, const char* where, int tag)
1311{
1312 struct secasvar *sav = *psav;
1313
1314 IPSEC_ASSERT(sav != NULL, ("key_freesav: null sav"));
1315
1316 SA_DELREF(sav);
1317
1318 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1319 printf("DP %s SA:%p (SPI %lu) from %s:%u; refcnt now %u\n",
1320 __func__, sav, (u_long)ntohl(sav->spi), where, tag,
1321 sav->refcnt));
1322
1323 if (sav->refcnt == 0) {
1324 *psav = NULL;
1325 key_delsav(sav);
1326 }
1327}
1328
1329/* %%% SPD management */
1330/*
1331 * free security policy entry.
1332 */
1333static void
1334key_delsp(struct secpolicy *sp)
1335{
1336 int s;
1337
1338 IPSEC_ASSERT(sp != NULL, ("key_delsp: null sp"));
1339
1340 key_sp_dead(sp);
1341
1342 IPSEC_ASSERT(sp->refcnt == 0,
1343 ("key_delsp: SP with references deleted (refcnt %u)",
1344 sp->refcnt));
1345
1346 s = splsoftnet(); /*called from softclock()*/
1347
1348 {
1349 struct ipsecrequest *isr = sp->req, *nextisr;
1350
1351 while (isr != NULL) {
1352 if (isr->sav != NULL) {
1353 KEY_FREESAV(&isr->sav);
1354 isr->sav = NULL;
1355 }
1356
1357 nextisr = isr->next;
1358 KFREE(isr);
1359 isr = nextisr;
1360 }
1361 }
1362
1363 KFREE(sp);
1364
1365 splx(s);
1366}
1367
1368/*
1369 * search SPD
1370 * OUT: NULL : not found
1371 * others : found, pointer to a SP.
1372 */
1373static struct secpolicy *
1374key_getsp(const struct secpolicyindex *spidx)
1375{
1376 struct secpolicy *sp;
1377
1378 IPSEC_ASSERT(spidx != NULL, ("key_getsp: null spidx"));
1379
1380 LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
1381 if (sp->state == IPSEC_SPSTATE_DEAD)
1382 continue;
1383 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1384 SP_ADDREF(sp);
1385 return sp;
1386 }
1387 }
1388
1389 return NULL;
1390}
1391
1392/*
1393 * get SP by index.
1394 * OUT: NULL : not found
1395 * others : found, pointer to a SP.
1396 */
1397static struct secpolicy *
1398key_getspbyid(u_int32_t id)
1399{
1400 struct secpolicy *sp;
1401
1402 LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
1403 if (sp->state == IPSEC_SPSTATE_DEAD)
1404 continue;
1405 if (sp->id == id) {
1406 SP_ADDREF(sp);
1407 return sp;
1408 }
1409 }
1410
1411 LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
1412 if (sp->state == IPSEC_SPSTATE_DEAD)
1413 continue;
1414 if (sp->id == id) {
1415 SP_ADDREF(sp);
1416 return sp;
1417 }
1418 }
1419
1420 return NULL;
1421}
1422
1423struct secpolicy *
1424key_newsp(const char* where, int tag)
1425{
1426 struct secpolicy *newsp = NULL;
1427
1428 newsp = (struct secpolicy *)
1429 malloc(sizeof(struct secpolicy), M_SECA, M_NOWAIT|M_ZERO);
1430 if (newsp) {
1431 newsp->refcnt = 1;
1432 newsp->req = NULL;
1433 }
1434
1435 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1436 printf("DP %s from %s:%u return SP:%p\n", __func__,
1437 where, tag, newsp));
1438 return newsp;
1439}
1440
1441/*
1442 * create secpolicy structure from sadb_x_policy structure.
1443 * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1444 * so must be set properly later.
1445 */
1446struct secpolicy *
1447key_msg2sp(const struct sadb_x_policy *xpl0, size_t len, int *error)
1448{
1449 struct secpolicy *newsp;
1450
1451 /* sanity check */
1452 if (xpl0 == NULL)
1453 panic("key_msg2sp: NULL pointer was passed");
1454 if (len < sizeof(*xpl0))
1455 panic("key_msg2sp: invalid length");
1456 if (len != PFKEY_EXTLEN(xpl0)) {
1457 ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n"));
1458 *error = EINVAL;
1459 return NULL;
1460 }
1461
1462 if ((newsp = KEY_NEWSP()) == NULL) {
1463 *error = ENOBUFS;
1464 return NULL;
1465 }
1466
1467 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1468 newsp->policy = xpl0->sadb_x_policy_type;
1469
1470 /* check policy */
1471 switch (xpl0->sadb_x_policy_type) {
1472 case IPSEC_POLICY_DISCARD:
1473 case IPSEC_POLICY_NONE:
1474 case IPSEC_POLICY_ENTRUST:
1475 case IPSEC_POLICY_BYPASS:
1476 newsp->req = NULL;
1477 break;
1478
1479 case IPSEC_POLICY_IPSEC:
1480 {
1481 int tlen;
1482 const struct sadb_x_ipsecrequest *xisr;
1483 uint16_t xisr_reqid;
1484 struct ipsecrequest **p_isr = &newsp->req;
1485
1486 /* validity check */
1487 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1488 ipseclog((LOG_DEBUG,
1489 "key_msg2sp: Invalid msg length.\n"));
1490 KEY_FREESP(&newsp);
1491 *error = EINVAL;
1492 return NULL;
1493 }
1494
1495 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1496 xisr = (const struct sadb_x_ipsecrequest *)(xpl0 + 1);
1497
1498 while (tlen > 0) {
1499 /* length check */
1500 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1501 ipseclog((LOG_DEBUG, "key_msg2sp: "
1502 "invalid ipsecrequest length.\n"));
1503 KEY_FREESP(&newsp);
1504 *error = EINVAL;
1505 return NULL;
1506 }
1507
1508 /* allocate request buffer */
1509 KMALLOC(*p_isr, struct ipsecrequest *, sizeof(**p_isr));
1510 if ((*p_isr) == NULL) {
1511 ipseclog((LOG_DEBUG,
1512 "key_msg2sp: No more memory.\n"));
1513 KEY_FREESP(&newsp);
1514 *error = ENOBUFS;
1515 return NULL;
1516 }
1517 memset(*p_isr, 0, sizeof(**p_isr));
1518
1519 /* set values */
1520 (*p_isr)->next = NULL;
1521
1522 switch (xisr->sadb_x_ipsecrequest_proto) {
1523 case IPPROTO_ESP:
1524 case IPPROTO_AH:
1525 case IPPROTO_IPCOMP:
1526 break;
1527 default:
1528 ipseclog((LOG_DEBUG,
1529 "key_msg2sp: invalid proto type=%u\n",
1530 xisr->sadb_x_ipsecrequest_proto));
1531 KEY_FREESP(&newsp);
1532 *error = EPROTONOSUPPORT;
1533 return NULL;
1534 }
1535 (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1536
1537 switch (xisr->sadb_x_ipsecrequest_mode) {
1538 case IPSEC_MODE_TRANSPORT:
1539 case IPSEC_MODE_TUNNEL:
1540 break;
1541 case IPSEC_MODE_ANY:
1542 default:
1543 ipseclog((LOG_DEBUG,
1544 "key_msg2sp: invalid mode=%u\n",
1545 xisr->sadb_x_ipsecrequest_mode));
1546 KEY_FREESP(&newsp);
1547 *error = EINVAL;
1548 return NULL;
1549 }
1550 (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1551
1552 switch (xisr->sadb_x_ipsecrequest_level) {
1553 case IPSEC_LEVEL_DEFAULT:
1554 case IPSEC_LEVEL_USE:
1555 case IPSEC_LEVEL_REQUIRE:
1556 break;
1557 case IPSEC_LEVEL_UNIQUE:
1558 xisr_reqid = xisr->sadb_x_ipsecrequest_reqid;
1559 /* validity check */
1560 /*
1561 * If range violation of reqid, kernel will
1562 * update it, don't refuse it.
1563 */
1564 if (xisr_reqid > IPSEC_MANUAL_REQID_MAX) {
1565 ipseclog((LOG_DEBUG,
1566 "key_msg2sp: reqid=%d range "
1567 "violation, updated by kernel.\n",
1568 xisr_reqid));
1569 xisr_reqid = 0;
1570 }
1571
1572 /* allocate new reqid id if reqid is zero. */
1573 if (xisr_reqid == 0) {
1574 u_int16_t reqid;
1575 if ((reqid = key_newreqid()) == 0) {
1576 KEY_FREESP(&newsp);
1577 *error = ENOBUFS;
1578 return NULL;
1579 }
1580 (*p_isr)->saidx.reqid = reqid;
1581 } else {
1582 /* set it for manual keying. */
1583 (*p_isr)->saidx.reqid = xisr_reqid;
1584 }
1585 break;
1586
1587 default:
1588 ipseclog((LOG_DEBUG, "key_msg2sp: invalid level=%u\n",
1589 xisr->sadb_x_ipsecrequest_level));
1590 KEY_FREESP(&newsp);
1591 *error = EINVAL;
1592 return NULL;
1593 }
1594 (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1595
1596 /* set IP addresses if there */
1597 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1598 const struct sockaddr *paddr;
1599
1600 paddr = (const struct sockaddr *)(xisr + 1);
1601
1602 /* validity check */
1603 if (paddr->sa_len
1604 > sizeof((*p_isr)->saidx.src)) {
1605 ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
1606 "address length.\n"));
1607 KEY_FREESP(&newsp);
1608 *error = EINVAL;
1609 return NULL;
1610 }
1611 memcpy(&(*p_isr)->saidx.src, paddr, paddr->sa_len);
1612
1613 paddr = (const struct sockaddr *)((const char *)paddr
1614 + paddr->sa_len);
1615
1616 /* validity check */
1617 if (paddr->sa_len
1618 > sizeof((*p_isr)->saidx.dst)) {
1619 ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
1620 "address length.\n"));
1621 KEY_FREESP(&newsp);
1622 *error = EINVAL;
1623 return NULL;
1624 }
1625 memcpy(&(*p_isr)->saidx.dst, paddr, paddr->sa_len);
1626 }
1627
1628 (*p_isr)->sav = NULL;
1629 (*p_isr)->sp = newsp;
1630
1631 /* initialization for the next. */
1632 p_isr = &(*p_isr)->next;
1633 tlen -= xisr->sadb_x_ipsecrequest_len;
1634
1635 /* validity check */
1636 if (tlen < 0) {
1637 ipseclog((LOG_DEBUG, "key_msg2sp: becoming tlen < 0.\n"));
1638 KEY_FREESP(&newsp);
1639 *error = EINVAL;
1640 return NULL;
1641 }
1642
1643 xisr = (const struct sadb_x_ipsecrequest *)((const char *)xisr
1644 + xisr->sadb_x_ipsecrequest_len);
1645 }
1646 }
1647 break;
1648 default:
1649 ipseclog((LOG_DEBUG, "key_msg2sp: invalid policy type.\n"));
1650 KEY_FREESP(&newsp);
1651 *error = EINVAL;
1652 return NULL;
1653 }
1654
1655 *error = 0;
1656 return newsp;
1657}
1658
1659static u_int16_t
1660key_newreqid(void)
1661{
1662 static u_int16_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1663
1664 auto_reqid = (auto_reqid == 0xffff
1665 ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1666
1667 /* XXX should be unique check */
1668
1669 return auto_reqid;
1670}
1671
1672/*
1673 * copy secpolicy struct to sadb_x_policy structure indicated.
1674 */
1675struct mbuf *
1676key_sp2msg(const struct secpolicy *sp)
1677{
1678 struct sadb_x_policy *xpl;
1679 int tlen;
1680 char *p;
1681 struct mbuf *m;
1682
1683 /* sanity check. */
1684 if (sp == NULL)
1685 panic("key_sp2msg: NULL pointer was passed");
1686
1687 tlen = key_getspreqmsglen(sp);
1688
1689 m = key_alloc_mbuf(tlen);
1690 if (!m || m->m_next) { /*XXX*/
1691 if (m)
1692 m_freem(m);
1693 return NULL;
1694 }
1695
1696 m->m_len = tlen;
1697 m->m_next = NULL;
1698 xpl = mtod(m, struct sadb_x_policy *);
1699 memset(xpl, 0, tlen);
1700
1701 xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1702 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1703 xpl->sadb_x_policy_type = sp->policy;
1704 xpl->sadb_x_policy_dir = sp->spidx.dir;
1705 xpl->sadb_x_policy_id = sp->id;
1706 p = (char *)xpl + sizeof(*xpl);
1707
1708 /* if is the policy for ipsec ? */
1709 if (sp->policy == IPSEC_POLICY_IPSEC) {
1710 struct sadb_x_ipsecrequest *xisr;
1711 struct ipsecrequest *isr;
1712
1713 for (isr = sp->req; isr != NULL; isr = isr->next) {
1714
1715 xisr = (struct sadb_x_ipsecrequest *)p;
1716
1717 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1718 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1719 xisr->sadb_x_ipsecrequest_level = isr->level;
1720 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1721
1722 p += sizeof(*xisr);
1723 memcpy(p, &isr->saidx.src, isr->saidx.src.sa.sa_len);
1724 p += isr->saidx.src.sa.sa_len;
1725 memcpy(p, &isr->saidx.dst, isr->saidx.dst.sa.sa_len);
1726 p += isr->saidx.src.sa.sa_len;
1727
1728 xisr->sadb_x_ipsecrequest_len =
1729 PFKEY_ALIGN8(sizeof(*xisr)
1730 + isr->saidx.src.sa.sa_len
1731 + isr->saidx.dst.sa.sa_len);
1732 }
1733 }
1734
1735 return m;
1736}
1737
1738/* m will not be freed nor modified */
1739static struct mbuf *
1740key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1741 int ndeep, int nitem, ...)
1742{
1743 va_list ap;
1744 int idx;
1745 int i;
1746 struct mbuf *result = NULL, *n;
1747 int len;
1748
1749 if (m == NULL || mhp == NULL)
1750 panic("null pointer passed to key_gather");
1751
1752 va_start(ap, nitem);
1753 for (i = 0; i < nitem; i++) {
1754 idx = va_arg(ap, int);
1755 if (idx < 0 || idx > SADB_EXT_MAX)
1756 goto fail;
1757 /* don't attempt to pull empty extension */
1758 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1759 continue;
1760 if (idx != SADB_EXT_RESERVED &&
1761 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1762 continue;
1763
1764 if (idx == SADB_EXT_RESERVED) {
1765 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1766#ifdef DIAGNOSTIC
1767 if (len > MHLEN)
1768 panic("assumption failed");
1769#endif
1770 MGETHDR(n, M_DONTWAIT, MT_DATA);
1771 if (!n)
1772 goto fail;
1773 n->m_len = len;
1774 n->m_next = NULL;
1775 m_copydata(m, 0, sizeof(struct sadb_msg),
1776 mtod(n, void *));
1777 } else if (i < ndeep) {
1778 len = mhp->extlen[idx];
1779 n = key_alloc_mbuf(len);
1780 if (!n || n->m_next) { /*XXX*/
1781 if (n)
1782 m_freem(n);
1783 goto fail;
1784 }
1785 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1786 mtod(n, void *));
1787 } else {
1788 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1789 M_DONTWAIT);
1790 }
1791 if (n == NULL)
1792 goto fail;
1793
1794 if (result)
1795 m_cat(result, n);
1796 else
1797 result = n;
1798 }
1799 va_end(ap);
1800
1801 if (result && (result->m_flags & M_PKTHDR) != 0) {
1802 result->m_pkthdr.len = 0;
1803 for (n = result; n; n = n->m_next)
1804 result->m_pkthdr.len += n->m_len;
1805 }
1806
1807 return result;
1808
1809fail:
1810 va_end(ap);
1811 m_freem(result);
1812 return NULL;
1813}
1814
1815/*
1816 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1817 * add an entry to SP database, when received
1818 * <base, address(SD), (lifetime(H),) policy>
1819 * from the user(?).
1820 * Adding to SP database,
1821 * and send
1822 * <base, address(SD), (lifetime(H),) policy>
1823 * to the socket which was send.
1824 *
1825 * SPDADD set a unique policy entry.
1826 * SPDSETIDX like SPDADD without a part of policy requests.
1827 * SPDUPDATE replace a unique policy entry.
1828 *
1829 * m will always be freed.
1830 */
1831static int
1832key_spdadd(struct socket *so, struct mbuf *m,
1833 const struct sadb_msghdr *mhp)
1834{
1835 const struct sadb_address *src0, *dst0;
1836 const struct sadb_x_policy *xpl0;
1837 struct sadb_x_policy *xpl;
1838 const struct sadb_lifetime *lft = NULL;
1839 struct secpolicyindex spidx;
1840 struct secpolicy *newsp;
1841 int error;
1842
1843 /* sanity check */
1844 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
1845 panic("key_spdadd: NULL pointer is passed");
1846
1847 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1848 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1849 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1850 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1851 return key_senderror(so, m, EINVAL);
1852 }
1853 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1854 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1855 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1856 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1857 return key_senderror(so, m, EINVAL);
1858 }
1859 if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1860 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1861 < sizeof(struct sadb_lifetime)) {
1862 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1863 return key_senderror(so, m, EINVAL);
1864 }
1865 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1866 }
1867
1868 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1869 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1870 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1871
1872 /* make secindex */
1873 /* XXX boundary check against sa_len */
1874 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1875 src0 + 1,
1876 dst0 + 1,
1877 src0->sadb_address_prefixlen,
1878 dst0->sadb_address_prefixlen,
1879 src0->sadb_address_proto,
1880 &spidx);
1881
1882 /* checking the direciton. */
1883 switch (xpl0->sadb_x_policy_dir) {
1884 case IPSEC_DIR_INBOUND:
1885 case IPSEC_DIR_OUTBOUND:
1886 break;
1887 default:
1888 ipseclog((LOG_DEBUG, "key_spdadd: Invalid SP direction.\n"));
1889 mhp->msg->sadb_msg_errno = EINVAL;
1890 return 0;
1891 }
1892
1893 /* check policy */
1894 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1895 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1896 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1897 ipseclog((LOG_DEBUG, "key_spdadd: Invalid policy type.\n"));
1898 return key_senderror(so, m, EINVAL);
1899 }
1900
1901 /* policy requests are mandatory when action is ipsec. */
1902 if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1903 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1904 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1905 ipseclog((LOG_DEBUG, "key_spdadd: some policy requests part required.\n"));
1906 return key_senderror(so, m, EINVAL);
1907 }
1908
1909 /*
1910 * checking there is SP already or not.
1911 * SPDUPDATE doesn't depend on whether there is a SP or not.
1912 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1913 * then error.
1914 */
1915 newsp = key_getsp(&spidx);
1916 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1917 if (newsp) {
1918 key_sp_dead(newsp);
1919 key_sp_unlink(newsp); /* XXX jrs ordering */
1920 KEY_FREESP(&newsp);
1921 newsp = NULL;
1922 }
1923 } else {
1924 if (newsp != NULL) {
1925 KEY_FREESP(&newsp);
1926 ipseclog((LOG_DEBUG, "key_spdadd: a SP entry exists already.\n"));
1927 return key_senderror(so, m, EEXIST);
1928 }
1929 }
1930
1931 /* allocation new SP entry */
1932 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1933 return key_senderror(so, m, error);
1934 }
1935
1936 if ((newsp->id = key_getnewspid()) == 0) {
1937 KFREE(newsp);
1938 return key_senderror(so, m, ENOBUFS);
1939 }
1940
1941 /* XXX boundary check against sa_len */
1942 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1943 src0 + 1,
1944 dst0 + 1,
1945 src0->sadb_address_prefixlen,
1946 dst0->sadb_address_prefixlen,
1947 src0->sadb_address_proto,
1948 &newsp->spidx);
1949
1950 /* sanity check on addr pair */
1951 if (((const struct sockaddr *)(src0 + 1))->sa_family !=
1952 ((const struct sockaddr *)(dst0+ 1))->sa_family) {
1953 KFREE(newsp);
1954 return key_senderror(so, m, EINVAL);
1955 }
1956 if (((const struct sockaddr *)(src0 + 1))->sa_len !=
1957 ((const struct sockaddr *)(dst0+ 1))->sa_len) {
1958 KFREE(newsp);
1959 return key_senderror(so, m, EINVAL);
1960 }
1961
1962 newsp->created = time_uptime;
1963 newsp->lastused = newsp->created;
1964 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1965 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1966
1967 newsp->refcnt = 1; /* do not reclaim until I say I do */
1968 newsp->state = IPSEC_SPSTATE_ALIVE;
1969 LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1970
1971 /* delete the entry in spacqtree */
1972 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1973 struct secspacq *spacq;
1974 if ((spacq = key_getspacq(&spidx)) != NULL) {
1975 /* reset counter in order to deletion by timehandler. */
1976 spacq->created = time_uptime;
1977 spacq->count = 0;
1978 }
1979 }
1980
1981#if defined(__NetBSD__)
1982 /* Invalidate all cached SPD pointers in the PCBs. */
1983 ipsec_invalpcbcacheall();
1984
1985#if defined(GATEWAY)
1986 /* Invalidate the ipflow cache, as well. */
1987 ipflow_invalidate_all(0);
1988#ifdef INET6
1989 ip6flow_invalidate_all(0);
1990#endif /* INET6 */
1991#endif /* GATEWAY */
1992#endif /* __NetBSD__ */
1993
1994 {
1995 struct mbuf *n, *mpolicy;
1996 struct sadb_msg *newmsg;
1997 int off;
1998
1999 /* create new sadb_msg to reply. */
2000 if (lft) {
2001 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
2002 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
2003 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2004 } else {
2005 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
2006 SADB_X_EXT_POLICY,
2007 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2008 }
2009 if (!n)
2010 return key_senderror(so, m, ENOBUFS);
2011
2012 if (n->m_len < sizeof(*newmsg)) {
2013 n = m_pullup(n, sizeof(*newmsg));
2014 if (!n)
2015 return key_senderror(so, m, ENOBUFS);
2016 }
2017 newmsg = mtod(n, struct sadb_msg *);
2018 newmsg->sadb_msg_errno = 0;
2019 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2020
2021 off = 0;
2022 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
2023 sizeof(*xpl), &off);
2024 if (mpolicy == NULL) {
2025 /* n is already freed */
2026 return key_senderror(so, m, ENOBUFS);
2027 }
2028 xpl = (struct sadb_x_policy *)(mtod(mpolicy, char *) + off);
2029 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2030 m_freem(n);
2031 return key_senderror(so, m, EINVAL);
2032 }
2033 xpl->sadb_x_policy_id = newsp->id;
2034
2035 m_freem(m);
2036 key_update_used();
2037 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2038 }
2039}
2040
2041/*
2042 * get new policy id.
2043 * OUT:
2044 * 0: failure.
2045 * others: success.
2046 */
2047static u_int32_t
2048key_getnewspid(void)
2049{
2050 u_int32_t newid = 0;
2051 int count = key_spi_trycnt; /* XXX */
2052 struct secpolicy *sp;
2053
2054 /* when requesting to allocate spi ranged */
2055 while (count--) {
2056 newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
2057
2058 if ((sp = key_getspbyid(newid)) == NULL)
2059 break;
2060
2061 KEY_FREESP(&sp);
2062 }
2063
2064 if (count == 0 || newid == 0) {
2065 ipseclog((LOG_DEBUG, "key_getnewspid: to allocate policy id is failed.\n"));
2066 return 0;
2067 }
2068
2069 return newid;
2070}
2071
2072/*
2073 * SADB_SPDDELETE processing
2074 * receive
2075 * <base, address(SD), policy(*)>
2076 * from the user(?), and set SADB_SASTATE_DEAD,
2077 * and send,
2078 * <base, address(SD), policy(*)>
2079 * to the ikmpd.
2080 * policy(*) including direction of policy.
2081 *
2082 * m will always be freed.
2083 */
2084static int
2085key_spddelete(struct socket *so, struct mbuf *m,
2086 const struct sadb_msghdr *mhp)
2087{
2088 struct sadb_address *src0, *dst0;
2089 struct sadb_x_policy *xpl0;
2090 struct secpolicyindex spidx;
2091 struct secpolicy *sp;
2092
2093 /* sanity check */
2094 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2095 panic("key_spddelete: NULL pointer is passed");
2096
2097 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2098 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2099 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2100 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
2101 return key_senderror(so, m, EINVAL);
2102 }
2103 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2104 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2105 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2106 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
2107 return key_senderror(so, m, EINVAL);
2108 }
2109
2110 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2111 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2112 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2113
2114 /* make secindex */
2115 /* XXX boundary check against sa_len */
2116 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2117 src0 + 1,
2118 dst0 + 1,
2119 src0->sadb_address_prefixlen,
2120 dst0->sadb_address_prefixlen,
2121 src0->sadb_address_proto,
2122 &spidx);
2123
2124 /* checking the direciton. */
2125 switch (xpl0->sadb_x_policy_dir) {
2126 case IPSEC_DIR_INBOUND:
2127 case IPSEC_DIR_OUTBOUND:
2128 break;
2129 default:
2130 ipseclog((LOG_DEBUG, "key_spddelete: Invalid SP direction.\n"));
2131 return key_senderror(so, m, EINVAL);
2132 }
2133
2134 /* Is there SP in SPD ? */
2135 if ((sp = key_getsp(&spidx)) == NULL) {
2136 ipseclog((LOG_DEBUG, "key_spddelete: no SP found.\n"));
2137 return key_senderror(so, m, EINVAL);
2138 }
2139
2140 /* save policy id to buffer to be returned. */
2141 xpl0->sadb_x_policy_id = sp->id;
2142
2143 key_sp_dead(sp);
2144 key_sp_unlink(sp); /* XXX jrs ordering */
2145 KEY_FREESP(&sp); /* ref gained by key_getspbyid */
2146
2147#if defined(__NetBSD__)
2148 /* Invalidate all cached SPD pointers in the PCBs. */
2149 ipsec_invalpcbcacheall();
2150
2151 /* We're deleting policy; no need to invalidate the ipflow cache. */
2152#endif /* __NetBSD__ */
2153
2154 {
2155 struct mbuf *n;
2156 struct sadb_msg *newmsg;
2157
2158 /* create new sadb_msg to reply. */
2159 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2160 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2161 if (!n)
2162 return key_senderror(so, m, ENOBUFS);
2163
2164 newmsg = mtod(n, struct sadb_msg *);
2165 newmsg->sadb_msg_errno = 0;
2166 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2167
2168 m_freem(m);
2169 key_update_used();
2170 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2171 }
2172}
2173
2174/*
2175 * SADB_SPDDELETE2 processing
2176 * receive
2177 * <base, policy(*)>
2178 * from the user(?), and set SADB_SASTATE_DEAD,
2179 * and send,
2180 * <base, policy(*)>
2181 * to the ikmpd.
2182 * policy(*) including direction of policy.
2183 *
2184 * m will always be freed.
2185 */
2186static int
2187key_spddelete2(struct socket *so, struct mbuf *m,
2188 const struct sadb_msghdr *mhp)
2189{
2190 u_int32_t id;
2191 struct secpolicy *sp;
2192
2193 /* sanity check */
2194 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2195 panic("key_spddelete2: NULL pointer is passed");
2196
2197 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2198 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2199 ipseclog((LOG_DEBUG, "key_spddelete2: invalid message is passed.\n"));
2200 key_senderror(so, m, EINVAL);
2201 return 0;
2202 }
2203
2204 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2205
2206 /* Is there SP in SPD ? */
2207 if ((sp = key_getspbyid(id)) == NULL) {
2208 ipseclog((LOG_DEBUG, "key_spddelete2: no SP found id:%u.\n", id));
2209 return key_senderror(so, m, EINVAL);
2210 }
2211
2212 key_sp_dead(sp);
2213 key_sp_unlink(sp); /* XXX jrs ordering */
2214 KEY_FREESP(&sp); /* ref gained by key_getsp */
2215 sp = NULL;
2216
2217#if defined(__NetBSD__)
2218 /* Invalidate all cached SPD pointers in the PCBs. */
2219 ipsec_invalpcbcacheall();
2220
2221 /* We're deleting policy; no need to invalidate the ipflow cache. */
2222#endif /* __NetBSD__ */
2223
2224 {
2225 struct mbuf *n, *nn;
2226 struct sadb_msg *newmsg;
2227 int off, len;
2228
2229 /* create new sadb_msg to reply. */
2230 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2231
2232 if (len > MCLBYTES)
2233 return key_senderror(so, m, ENOBUFS);
2234 MGETHDR(n, M_DONTWAIT, MT_DATA);
2235 if (n && len > MHLEN) {
2236 MCLGET(n, M_DONTWAIT);
2237 if ((n->m_flags & M_EXT) == 0) {
2238 m_freem(n);
2239 n = NULL;
2240 }
2241 }
2242 if (!n)
2243 return key_senderror(so, m, ENOBUFS);
2244
2245 n->m_len = len;
2246 n->m_next = NULL;
2247 off = 0;
2248
2249 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
2250 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2251
2252#ifdef DIAGNOSTIC
2253 if (off != len)
2254 panic("length inconsistency in key_spddelete2");
2255#endif
2256
2257 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2258 mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2259 if (!n->m_next) {
2260 m_freem(n);
2261 return key_senderror(so, m, ENOBUFS);
2262 }
2263
2264 n->m_pkthdr.len = 0;
2265 for (nn = n; nn; nn = nn->m_next)
2266 n->m_pkthdr.len += nn->m_len;
2267
2268 newmsg = mtod(n, struct sadb_msg *);
2269 newmsg->sadb_msg_errno = 0;
2270 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2271
2272 m_freem(m);
2273 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2274 }
2275}
2276
2277/*
2278 * SADB_X_GET processing
2279 * receive
2280 * <base, policy(*)>
2281 * from the user(?),
2282 * and send,
2283 * <base, address(SD), policy>
2284 * to the ikmpd.
2285 * policy(*) including direction of policy.
2286 *
2287 * m will always be freed.
2288 */
2289static int
2290key_spdget(struct socket *so, struct mbuf *m,
2291 const struct sadb_msghdr *mhp)
2292{
2293 u_int32_t id;
2294 struct secpolicy *sp;
2295 struct mbuf *n;
2296
2297 /* sanity check */
2298 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2299 panic("key_spdget: NULL pointer is passed");
2300
2301 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2302 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2303 ipseclog((LOG_DEBUG, "key_spdget: invalid message is passed.\n"));
2304 return key_senderror(so, m, EINVAL);
2305 }
2306
2307 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2308
2309 /* Is there SP in SPD ? */
2310 if ((sp = key_getspbyid(id)) == NULL) {
2311 ipseclog((LOG_DEBUG, "key_spdget: no SP found id:%u.\n", id));
2312 return key_senderror(so, m, ENOENT);
2313 }
2314
2315 n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
2316 mhp->msg->sadb_msg_pid);
2317 KEY_FREESP(&sp); /* ref gained by key_getspbyid */
2318 if (n != NULL) {
2319 m_freem(m);
2320 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2321 } else
2322 return key_senderror(so, m, ENOBUFS);
2323}
2324
2325/*
2326 * SADB_X_SPDACQUIRE processing.
2327 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2328 * send
2329 * <base, policy(*)>
2330 * to KMD, and expect to receive
2331 * <base> with SADB_X_SPDACQUIRE if error occurred,
2332 * or
2333 * <base, policy>
2334 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2335 * policy(*) is without policy requests.
2336 *
2337 * 0 : succeed
2338 * others: error number
2339 */
2340int
2341key_spdacquire(const struct secpolicy *sp)
2342{
2343 struct mbuf *result = NULL, *m;
2344 struct secspacq *newspacq;
2345 int error;
2346
2347 /* sanity check */
2348 if (sp == NULL)
2349 panic("key_spdacquire: NULL pointer is passed");
2350 if (sp->req != NULL)
2351 panic("key_spdacquire: called but there is request");
2352 if (sp->policy != IPSEC_POLICY_IPSEC)
2353 panic("key_spdacquire: policy mismathed. IPsec is expected");
2354
2355 /* Get an entry to check whether sent message or not. */
2356 if ((newspacq = key_getspacq(&sp->spidx)) != NULL) {
2357 if (key_blockacq_count < newspacq->count) {
2358 /* reset counter and do send message. */
2359 newspacq->count = 0;
2360 } else {
2361 /* increment counter and do nothing. */
2362 newspacq->count++;
2363 return 0;
2364 }
2365 } else {
2366 /* make new entry for blocking to send SADB_ACQUIRE. */
2367 if ((newspacq = key_newspacq(&sp->spidx)) == NULL)
2368 return ENOBUFS;
2369
2370 /* add to acqtree */
2371 LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
2372 }
2373
2374 /* create new sadb_msg to reply. */
2375 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2376 if (!m) {
2377 error = ENOBUFS;
2378 goto fail;
2379 }
2380 result = m;
2381
2382 result->m_pkthdr.len = 0;
2383 for (m = result; m; m = m->m_next)
2384 result->m_pkthdr.len += m->m_len;
2385
2386 mtod(result, struct sadb_msg *)->sadb_msg_len =
2387 PFKEY_UNIT64(result->m_pkthdr.len);
2388
2389 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2390
2391fail:
2392 if (result)
2393 m_freem(result);
2394 return error;
2395}
2396
2397/*
2398 * SADB_SPDFLUSH processing
2399 * receive
2400 * <base>
2401 * from the user, and free all entries in secpctree.
2402 * and send,
2403 * <base>
2404 * to the user.
2405 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2406 *
2407 * m will always be freed.
2408 */
2409static int
2410key_spdflush(struct socket *so, struct mbuf *m,
2411 const struct sadb_msghdr *mhp)
2412{
2413 struct sadb_msg *newmsg;
2414 struct secpolicy *sp;
2415 u_int dir;
2416
2417 /* sanity check */
2418 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2419 panic("key_spdflush: NULL pointer is passed");
2420
2421 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2422 return key_senderror(so, m, EINVAL);
2423
2424 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2425 struct secpolicy * nextsp;
2426 for (sp = LIST_FIRST(&sptree[dir]);
2427 sp != NULL;
2428 sp = nextsp) {
2429
2430 nextsp = LIST_NEXT(sp, chain);
2431 if (sp->state == IPSEC_SPSTATE_DEAD)
2432 continue;
2433 key_sp_dead(sp);
2434 key_sp_unlink(sp);
2435 /* 'sp' dead; continue transfers to 'sp = nextsp' */
2436 continue;
2437 }
2438 }
2439
2440#if defined(__NetBSD__)
2441 /* Invalidate all cached SPD pointers in the PCBs. */
2442 ipsec_invalpcbcacheall();
2443
2444 /* We're deleting policy; no need to invalidate the ipflow cache. */
2445#endif /* __NetBSD__ */
2446
2447 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2448 ipseclog((LOG_DEBUG, "key_spdflush: No more memory.\n"));
2449 return key_senderror(so, m, ENOBUFS);
2450 }
2451
2452 if (m->m_next)
2453 m_freem(m->m_next);
2454 m->m_next = NULL;
2455 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2456 newmsg = mtod(m, struct sadb_msg *);
2457 newmsg->sadb_msg_errno = 0;
2458 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2459
2460 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2461}
2462
2463static struct sockaddr key_src = {
2464 .sa_len = 2,
2465 .sa_family = PF_KEY,
2466};
2467
2468static struct mbuf *
2469key_setspddump_chain(int *errorp, int *lenp, pid_t pid)
2470{
2471 struct secpolicy *sp;
2472 int cnt;
2473 u_int dir;
2474 struct mbuf *m, *n, *prev;
2475 int totlen;
2476
2477 *lenp = 0;
2478
2479 /* search SPD entry and get buffer size. */
2480 cnt = 0;
2481 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2482 LIST_FOREACH(sp, &sptree[dir], chain) {
2483 cnt++;
2484 }
2485 }
2486
2487 if (cnt == 0) {
2488 *errorp = ENOENT;
2489 return (NULL);
2490 }
2491
2492 m = NULL;
2493 prev = m;
2494 totlen = 0;
2495 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2496 LIST_FOREACH(sp, &sptree[dir], chain) {
2497 --cnt;
2498 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
2499
2500 if (!n) {
2501 *errorp = ENOBUFS;
2502 if (m) m_freem(m);
2503 return (NULL);
2504 }
2505
2506 totlen += n->m_pkthdr.len;
2507 if (!m) {
2508 m = n;
2509 } else {
2510 prev->m_nextpkt = n;
2511 }
2512 prev = n;
2513 }
2514 }
2515
2516 *lenp = totlen;
2517 *errorp = 0;
2518 return (m);
2519}
2520
2521/*
2522 * SADB_SPDDUMP processing
2523 * receive
2524 * <base>
2525 * from the user, and dump all SP leaves
2526 * and send,
2527 * <base> .....
2528 * to the ikmpd.
2529 *
2530 * m will always be freed.
2531 */
2532static int
2533key_spddump(struct socket *so, struct mbuf *m0,
2534 const struct sadb_msghdr *mhp)
2535{
2536 struct mbuf *n;
2537 int error, len;
2538 int ok, s;
2539 pid_t pid;
2540
2541 /* sanity check */
2542 if (so == NULL || m0 == NULL || mhp == NULL || mhp->msg == NULL)
2543 panic("key_spddump: NULL pointer is passed");
2544
2545
2546 pid = mhp->msg->sadb_msg_pid;
2547 /*
2548 * If the requestor has insufficient socket-buffer space
2549 * for the entire chain, nobody gets any response to the DUMP.
2550 * XXX For now, only the requestor ever gets anything.
2551 * Moreover, if the requestor has any space at all, they receive
2552 * the entire chain, otherwise the request is refused with ENOBUFS.
2553 */
2554 if (sbspace(&so->so_rcv) <= 0) {
2555 return key_senderror(so, m0, ENOBUFS);
2556 }
2557
2558 s = splsoftnet();
2559 n = key_setspddump_chain(&error, &len, pid);
2560 splx(s);
2561
2562 if (n == NULL) {
2563 return key_senderror(so, m0, ENOENT);
2564 }
2565 {
2566 uint64_t *ps = PFKEY_STAT_GETREF();
2567 ps[PFKEY_STAT_IN_TOTAL]++;
2568 ps[PFKEY_STAT_IN_BYTES] += len;
2569 PFKEY_STAT_PUTREF();
2570 }
2571
2572 /*
2573 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
2574 * The requestor receives either the entire chain, or an
2575 * error message with ENOBUFS.
2576 */
2577
2578 /*
2579 * sbappendchainwith record takes the chain of entries, one
2580 * packet-record per SPD entry, prepends the key_src sockaddr
2581 * to each packet-record, links the sockaddr mbufs into a new
2582 * list of records, then appends the entire resulting
2583 * list to the requesting socket.
2584 */
2585 ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src,
2586 n, SB_PRIO_ONESHOT_OVERFLOW);
2587
2588 if (!ok) {
2589 PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
2590 m_freem(n);
2591 return key_senderror(so, m0, ENOBUFS);
2592 }
2593
2594 m_freem(m0);
2595 return error;
2596}
2597
2598/*
2599 * SADB_X_NAT_T_NEW_MAPPING. Unused by racoon as of 2005/04/23
2600 */
2601static int
2602key_nat_map(struct socket *so, struct mbuf *m,
2603 const struct sadb_msghdr *mhp)
2604{
2605 struct sadb_x_nat_t_type *type;
2606 struct sadb_x_nat_t_port *sport;
2607 struct sadb_x_nat_t_port *dport;
2608 struct sadb_address *iaddr, *raddr;
2609 struct sadb_x_nat_t_frag *frag;
2610
2611 /* sanity check */
2612 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2613 panic("key_nat_map: NULL pointer is passed.");
2614
2615 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
2616 mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
2617 mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL) {
2618 ipseclog((LOG_DEBUG, "key_nat_map: invalid message.\n"));
2619 return key_senderror(so, m, EINVAL);
2620 }
2621 if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
2622 (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
2623 (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
2624 ipseclog((LOG_DEBUG, "key_nat_map: invalid message.\n"));
2625 return key_senderror(so, m, EINVAL);
2626 }
2627
2628 if ((mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) &&
2629 (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr))) {
2630 ipseclog((LOG_DEBUG, "key_nat_map: invalid message\n"));
2631 return key_senderror(so, m, EINVAL);
2632 }
2633
2634 if ((mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) &&
2635 (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr))) {
2636 ipseclog((LOG_DEBUG, "key_nat_map: invalid message\n"));
2637 return key_senderror(so, m, EINVAL);
2638 }
2639
2640 if ((mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) &&
2641 (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag))) {
2642 ipseclog((LOG_DEBUG, "key_nat_map: invalid message\n"));
2643 return key_senderror(so, m, EINVAL);
2644 }
2645
2646 type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
2647 sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
2648 dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
2649 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
2650 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
2651 frag = (struct sadb_x_nat_t_frag *) mhp->ext[SADB_X_EXT_NAT_T_FRAG];
2652
2653 /*
2654 * XXX handle that, it should also contain a SA, or anything
2655 * that enable to update the SA information.
2656 */
2657
2658 return 0;
2659}
2660
2661static struct mbuf *
2662key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, pid_t pid)
2663{
2664 struct mbuf *result = NULL, *m;
2665
2666 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2667 if (!m)
2668 goto fail;
2669 result = m;
2670
2671 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2672 &sp->spidx.src.sa, sp->spidx.prefs,
2673 sp->spidx.ul_proto);
2674 if (!m)
2675 goto fail;
2676 m_cat(result, m);
2677
2678 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2679 &sp->spidx.dst.sa, sp->spidx.prefd,
2680 sp->spidx.ul_proto);
2681 if (!m)
2682 goto fail;
2683 m_cat(result, m);
2684
2685 m = key_sp2msg(sp);
2686 if (!m)
2687 goto fail;
2688 m_cat(result, m);
2689
2690 if ((result->m_flags & M_PKTHDR) == 0)
2691 goto fail;
2692
2693 if (result->m_len < sizeof(struct sadb_msg)) {
2694 result = m_pullup(result, sizeof(struct sadb_msg));
2695 if (result == NULL)
2696 goto fail;
2697 }
2698
2699 result->m_pkthdr.len = 0;
2700 for (m = result; m; m = m->m_next)
2701 result->m_pkthdr.len += m->m_len;
2702
2703 mtod(result, struct sadb_msg *)->sadb_msg_len =
2704 PFKEY_UNIT64(result->m_pkthdr.len);
2705
2706 return result;
2707
2708fail:
2709 m_freem(result);
2710 return NULL;
2711}
2712
2713/*
2714 * get PFKEY message length for security policy and request.
2715 */
2716static u_int
2717key_getspreqmsglen(const struct secpolicy *sp)
2718{
2719 u_int tlen;
2720
2721 tlen = sizeof(struct sadb_x_policy);
2722
2723 /* if is the policy for ipsec ? */
2724 if (sp->policy != IPSEC_POLICY_IPSEC)
2725 return tlen;
2726
2727 /* get length of ipsec requests */
2728 {
2729 const struct ipsecrequest *isr;
2730 int len;
2731
2732 for (isr = sp->req; isr != NULL; isr = isr->next) {
2733 len = sizeof(struct sadb_x_ipsecrequest)
2734 + isr->saidx.src.sa.sa_len
2735 + isr->saidx.dst.sa.sa_len;
2736
2737 tlen += PFKEY_ALIGN8(len);
2738 }
2739 }
2740
2741 return tlen;
2742}
2743
2744/*
2745 * SADB_SPDEXPIRE processing
2746 * send
2747 * <base, address(SD), lifetime(CH), policy>
2748 * to KMD by PF_KEY.
2749 *
2750 * OUT: 0 : succeed
2751 * others : error number
2752 */
2753static int
2754key_spdexpire(struct secpolicy *sp)
2755{
2756 int s;
2757 struct mbuf *result = NULL, *m;
2758 int len;
2759 int error = -1;
2760 struct sadb_lifetime *lt;
2761
2762 /* XXX: Why do we lock ? */
2763 s = splsoftnet(); /*called from softclock()*/
2764
2765 /* sanity check */
2766 if (sp == NULL)
2767 panic("key_spdexpire: NULL pointer is passed");
2768
2769 /* set msg header */
2770 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2771 if (!m) {
2772 error = ENOBUFS;
2773 goto fail;
2774 }
2775 result = m;
2776
2777 /* create lifetime extension (current and hard) */
2778 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2779 m = key_alloc_mbuf(len);
2780 if (!m || m->m_next) { /*XXX*/
2781 if (m)
2782 m_freem(m);
2783 error = ENOBUFS;
2784 goto fail;
2785 }
2786 memset(mtod(m, void *), 0, len);
2787 lt = mtod(m, struct sadb_lifetime *);
2788 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2789 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2790 lt->sadb_lifetime_allocations = 0;
2791 lt->sadb_lifetime_bytes = 0;
2792 lt->sadb_lifetime_addtime = sp->created + time_second - time_uptime;
2793 lt->sadb_lifetime_usetime = sp->lastused + time_second - time_uptime;
2794 lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
2795 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2796 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2797 lt->sadb_lifetime_allocations = 0;
2798 lt->sadb_lifetime_bytes = 0;
2799 lt->sadb_lifetime_addtime = sp->lifetime;
2800 lt->sadb_lifetime_usetime = sp->validtime;
2801 m_cat(result, m);
2802
2803 /* set sadb_address for source */
2804 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2805 &sp->spidx.src.sa,
2806 sp->spidx.prefs, sp->spidx.ul_proto);
2807 if (!m) {
2808 error = ENOBUFS;
2809 goto fail;
2810 }
2811 m_cat(result, m);
2812
2813 /* set sadb_address for destination */
2814 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2815 &sp->spidx.dst.sa,
2816 sp->spidx.prefd, sp->spidx.ul_proto);
2817 if (!m) {
2818 error = ENOBUFS;
2819 goto fail;
2820 }
2821 m_cat(result, m);
2822
2823 /* set secpolicy */
2824 m = key_sp2msg(sp);
2825 if (!m) {
2826 error = ENOBUFS;
2827 goto fail;
2828 }
2829 m_cat(result, m);
2830
2831 if ((result->m_flags & M_PKTHDR) == 0) {
2832 error = EINVAL;
2833 goto fail;
2834 }
2835
2836 if (result->m_len < sizeof(struct sadb_msg)) {
2837 result = m_pullup(result, sizeof(struct sadb_msg));
2838 if (result == NULL) {
2839 error = ENOBUFS;
2840 goto fail;
2841 }
2842 }
2843
2844 result->m_pkthdr.len = 0;
2845 for (m = result; m; m = m->m_next)
2846 result->m_pkthdr.len += m->m_len;
2847
2848 mtod(result, struct sadb_msg *)->sadb_msg_len =
2849 PFKEY_UNIT64(result->m_pkthdr.len);
2850
2851 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2852
2853 fail:
2854 if (result)
2855 m_freem(result);
2856 splx(s);
2857 return error;
2858}
2859
2860/* %%% SAD management */
2861/*
2862 * allocating a memory for new SA head, and copy from the values of mhp.
2863 * OUT: NULL : failure due to the lack of memory.
2864 * others : pointer to new SA head.
2865 */
2866static struct secashead *
2867key_newsah(const struct secasindex *saidx)
2868{
2869 struct secashead *newsah;
2870
2871 IPSEC_ASSERT(saidx != NULL, ("key_newsaidx: null saidx"));
2872
2873 newsah = (struct secashead *)
2874 malloc(sizeof(struct secashead), M_SECA, M_NOWAIT|M_ZERO);
2875 if (newsah != NULL) {
2876 int i;
2877 for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2878 LIST_INIT(&newsah->savtree[i]);
2879 newsah->saidx = *saidx;
2880
2881 /* add to saidxtree */
2882 newsah->state = SADB_SASTATE_MATURE;
2883 LIST_INSERT_HEAD(&sahtree, newsah, chain);
2884 }
2885 return(newsah);
2886}
2887
2888/*
2889 * delete SA index and all SA registerd.
2890 */
2891static void
2892key_delsah(struct secashead *sah)
2893{
2894 struct secasvar *sav, *nextsav;
2895 u_int stateidx, state;
2896 int s;
2897 int zombie = 0;
2898
2899 /* sanity check */
2900 if (sah == NULL)
2901 panic("key_delsah: NULL pointer is passed");
2902
2903 s = splsoftnet(); /*called from softclock()*/
2904
2905 /* searching all SA registerd in the secindex. */
2906 for (stateidx = 0;
2907 stateidx < _ARRAYLEN(saorder_state_any);
2908 stateidx++) {
2909
2910 state = saorder_state_any[stateidx];
2911 for (sav = (struct secasvar *)LIST_FIRST(&sah->savtree[state]);
2912 sav != NULL;
2913 sav = nextsav) {
2914
2915 nextsav = LIST_NEXT(sav, chain);
2916
2917 if (sav->refcnt == 0) {
2918 /* sanity check */
2919 KEY_CHKSASTATE(state, sav->state, "key_delsah");
2920 KEY_FREESAV(&sav);
2921 } else {
2922 /* give up to delete this sa */
2923 zombie++;
2924 }
2925 }
2926 }
2927
2928 /* don't delete sah only if there are savs. */
2929 if (zombie) {
2930 splx(s);
2931 return;
2932 }
2933
2934 rtcache_free(&sah->sa_route);
2935
2936 /* remove from tree of SA index */
2937 if (__LIST_CHAINED(sah))
2938 LIST_REMOVE(sah, chain);
2939
2940 KFREE(sah);
2941
2942 splx(s);
2943 return;
2944}
2945
2946/*
2947 * allocating a new SA with LARVAL state. key_add() and key_getspi() call,
2948 * and copy the values of mhp into new buffer.
2949 * When SAD message type is GETSPI:
2950 * to set sequence number from acq_seq++,
2951 * to set zero to SPI.
2952 * not to call key_setsava().
2953 * OUT: NULL : fail
2954 * others : pointer to new secasvar.
2955 *
2956 * does not modify mbuf. does not free mbuf on error.
2957 */
2958static struct secasvar *
2959key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp,
2960 struct secashead *sah, int *errp,
2961 const char* where, int tag)
2962{
2963 struct secasvar *newsav;
2964 const struct sadb_sa *xsa;
2965
2966 /* sanity check */
2967 if (m == NULL || mhp == NULL || mhp->msg == NULL || sah == NULL)
2968 panic("key_newsa: NULL pointer is passed");
2969
2970 KMALLOC(newsav, struct secasvar *, sizeof(struct secasvar));
2971 if (newsav == NULL) {
2972 ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n"));
2973 *errp = ENOBUFS;
2974 goto done;
2975 }
2976 memset(newsav, 0, sizeof(struct secasvar));
2977
2978 switch (mhp->msg->sadb_msg_type) {
2979 case SADB_GETSPI:
2980 newsav->spi = 0;
2981
2982#ifdef IPSEC_DOSEQCHECK
2983 /* sync sequence number */
2984 if (mhp->msg->sadb_msg_seq == 0)
2985 newsav->seq =
2986 (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
2987 else
2988#endif
2989 newsav->seq = mhp->msg->sadb_msg_seq;
2990 break;
2991
2992 case SADB_ADD:
2993 /* sanity check */
2994 if (mhp->ext[SADB_EXT_SA] == NULL) {
2995 KFREE(newsav), newsav = NULL;
2996 ipseclog((LOG_DEBUG, "key_newsa: invalid message is passed.\n"));
2997 *errp = EINVAL;
2998 goto done;
2999 }
3000 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3001 newsav->spi = xsa->sadb_sa_spi;
3002 newsav->seq = mhp->msg->sadb_msg_seq;
3003 break;
3004 default:
3005 KFREE(newsav), newsav = NULL;
3006 *errp = EINVAL;
3007 goto done;
3008 }
3009
3010 /* copy sav values */
3011 if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
3012 *errp = key_setsaval(newsav, m, mhp);
3013 if (*errp) {
3014 KFREE(newsav), newsav = NULL;
3015 goto done;
3016 }
3017 }
3018
3019 /* reset created */
3020 newsav->created = time_uptime;
3021 newsav->pid = mhp->msg->sadb_msg_pid;
3022
3023 /* add to satree */
3024 newsav->sah = sah;
3025 newsav->refcnt = 1;
3026 newsav->state = SADB_SASTATE_LARVAL;
3027 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
3028 secasvar, chain);
3029done:
3030 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3031 printf("DP %s from %s:%u return SP:%p\n", __func__,
3032 where, tag, newsav));
3033
3034 return newsav;
3035}
3036
3037/*
3038 * free() SA variable entry.
3039 */
3040static void
3041key_delsav(struct secasvar *sav)
3042{
3043 IPSEC_ASSERT(sav != NULL, ("key_delsav: null sav"));
3044 IPSEC_ASSERT(sav->refcnt == 0,
3045 ("key_delsav: reference count %u > 0", sav->refcnt));
3046
3047 /* remove from SA header */
3048 if (__LIST_CHAINED(sav))
3049 LIST_REMOVE(sav, chain);
3050
3051 /*
3052 * Cleanup xform state. Note that zeroize'ing causes the
3053 * keys to be cleared; otherwise we must do it ourself.
3054 */
3055 if (sav->tdb_xform != NULL) {
3056 sav->tdb_xform->xf_zeroize(sav);
3057 sav->tdb_xform = NULL;
3058 } else {
3059 if (sav->key_auth != NULL)
3060 explicit_memset(_KEYBUF(sav->key_auth), 0,
3061 _KEYLEN(sav->key_auth));
3062 if (sav->key_enc != NULL)
3063 explicit_memset(_KEYBUF(sav->key_enc), 0,
3064 _KEYLEN(sav->key_enc));
3065 }
3066 if (sav->key_auth != NULL) {
3067 KFREE(sav->key_auth);
3068 sav->key_auth = NULL;
3069 }
3070 if (sav->key_enc != NULL) {
3071 KFREE(sav->key_enc);
3072 sav->key_enc = NULL;
3073 }
3074 if (sav->replay != NULL) {
3075 KFREE(sav->replay);
3076 sav->replay = NULL;
3077 }
3078 if (sav->lft_c != NULL) {
3079 KFREE(sav->lft_c);
3080 sav->lft_c = NULL;
3081 }
3082 if (sav->lft_h != NULL) {
3083 KFREE(sav->lft_h);
3084 sav->lft_h = NULL;
3085 }
3086 if (sav->lft_s != NULL) {
3087 KFREE(sav->lft_s);
3088 sav->lft_s = NULL;
3089 }
3090
3091 KFREE(sav);
3092
3093 return;
3094}
3095
3096/*
3097 * search SAD.
3098 * OUT:
3099 * NULL : not found
3100 * others : found, pointer to a SA.
3101 */
3102static struct secashead *
3103key_getsah(const struct secasindex *saidx)
3104{
3105 struct secashead *sah;
3106
3107 LIST_FOREACH(sah, &sahtree, chain) {
3108 if (sah->state == SADB_SASTATE_DEAD)
3109 continue;
3110 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
3111 return sah;
3112 }
3113
3114 return NULL;
3115}
3116
3117/*
3118 * check not to be duplicated SPI.
3119 * NOTE: this function is too slow due to searching all SAD.
3120 * OUT:
3121 * NULL : not found
3122 * others : found, pointer to a SA.
3123 */
3124static struct secasvar *
3125key_checkspidup(const struct secasindex *saidx, u_int32_t spi)
3126{
3127 struct secashead *sah;
3128 struct secasvar *sav;
3129
3130 /* check address family */
3131 if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
3132 ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
3133 return NULL;
3134 }
3135
3136 /* check all SAD */
3137 LIST_FOREACH(sah, &sahtree, chain) {
3138 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
3139 continue;
3140 sav = key_getsavbyspi(sah, spi);
3141 if (sav != NULL)
3142 return sav;
3143 }
3144
3145 return NULL;
3146}
3147
3148/*
3149 * search SAD litmited alive SA, protocol, SPI.
3150 * OUT:
3151 * NULL : not found
3152 * others : found, pointer to a SA.
3153 */
3154static struct secasvar *
3155key_getsavbyspi(struct secashead *sah, u_int32_t spi)
3156{
3157 struct secasvar *sav;
3158 u_int stateidx, state;
3159
3160 /* search all status */
3161 for (stateidx = 0;
3162 stateidx < _ARRAYLEN(saorder_state_alive);
3163 stateidx++) {
3164
3165 state = saorder_state_alive[stateidx];
3166 LIST_FOREACH(sav, &sah->savtree[state], chain) {
3167
3168 /* sanity check */
3169 if (sav->state != state) {
3170 ipseclog((LOG_DEBUG, "key_getsavbyspi: "
3171 "invalid sav->state (queue: %d SA: %d)\n",
3172 state, sav->state));
3173 continue;
3174 }
3175
3176 if (sav->spi == spi)
3177 return sav;
3178 }
3179 }
3180
3181 return NULL;
3182}
3183
3184/*
3185 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3186 * You must update these if need.
3187 * OUT: 0: success.
3188 * !0: failure.
3189 *
3190 * does not modify mbuf. does not free mbuf on error.
3191 */
3192static int
3193key_setsaval(struct secasvar *sav, struct mbuf *m,
3194 const struct sadb_msghdr *mhp)
3195{
3196 int error = 0;
3197
3198 /* sanity check */
3199 if (m == NULL || mhp == NULL || mhp->msg == NULL)
3200 panic("key_setsaval: NULL pointer is passed");
3201
3202 /* initialization */
3203 sav->replay = NULL;
3204 sav->key_auth = NULL;
3205 sav->key_enc = NULL;
3206 sav->lft_c = NULL;
3207 sav->lft_h = NULL;
3208 sav->lft_s = NULL;
3209 sav->tdb_xform = NULL; /* transform */
3210 sav->tdb_encalgxform = NULL; /* encoding algorithm */
3211 sav->tdb_authalgxform = NULL; /* authentication algorithm */
3212 sav->tdb_compalgxform = NULL; /* compression algorithm */
3213 sav->natt_type = 0;
3214 sav->esp_frag = 0;
3215
3216 /* SA */
3217 if (mhp->ext[SADB_EXT_SA] != NULL) {
3218 const struct sadb_sa *sa0;
3219
3220 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3221 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3222 error = EINVAL;
3223 goto fail;
3224 }
3225
3226 sav->alg_auth = sa0->sadb_sa_auth;
3227 sav->alg_enc = sa0->sadb_sa_encrypt;
3228 sav->flags = sa0->sadb_sa_flags;
3229
3230 /* replay window */
3231 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3232 sav->replay = (struct secreplay *)
3233 malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_SECA, M_NOWAIT|M_ZERO);
3234 if (sav->replay == NULL) {
3235 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3236 error = ENOBUFS;
3237 goto fail;
3238 }
3239 if (sa0->sadb_sa_replay != 0)
3240 sav->replay->bitmap = (char*)(sav->replay+1);
3241 sav->replay->wsize = sa0->sadb_sa_replay;
3242 }
3243 }
3244
3245 /* Authentication keys */
3246 if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3247 const struct sadb_key *key0;
3248 int len;
3249
3250 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3251 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3252
3253 error = 0;
3254 if (len < sizeof(*key0)) {
3255 error = EINVAL;
3256 goto fail;
3257 }
3258 switch (mhp->msg->sadb_msg_satype) {
3259 case SADB_SATYPE_AH:
3260 case SADB_SATYPE_ESP:
3261 case SADB_X_SATYPE_TCPSIGNATURE:
3262 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3263 sav->alg_auth != SADB_X_AALG_NULL)
3264 error = EINVAL;
3265 break;
3266 case SADB_X_SATYPE_IPCOMP:
3267 default:
3268 error = EINVAL;
3269 break;
3270 }
3271 if (error) {
3272 ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
3273 goto fail;
3274 }
3275
3276 sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
3277 if (sav->key_auth == NULL) {
3278 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3279 error = ENOBUFS;
3280 goto fail;
3281 }
3282 }
3283
3284 /* Encryption key */
3285 if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3286 const struct sadb_key *key0;
3287 int len;
3288
3289 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3290 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3291
3292 error = 0;
3293 if (len < sizeof(*key0)) {
3294 error = EINVAL;
3295 goto fail;
3296 }
3297 switch (mhp->msg->sadb_msg_satype) {
3298 case SADB_SATYPE_ESP:
3299 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3300 sav->alg_enc != SADB_EALG_NULL) {
3301 error = EINVAL;
3302 break;
3303 }
3304 sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
3305 if (sav->key_enc == NULL) {
3306 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3307 error = ENOBUFS;
3308 goto fail;
3309 }
3310 break;
3311 case SADB_X_SATYPE_IPCOMP:
3312 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3313 error = EINVAL;
3314 sav->key_enc = NULL; /*just in case*/
3315 break;
3316 case SADB_SATYPE_AH:
3317 case SADB_X_SATYPE_TCPSIGNATURE:
3318 default:
3319 error = EINVAL;
3320 break;
3321 }
3322 if (error) {
3323 ipseclog((LOG_DEBUG, "key_setsatval: invalid key_enc value.\n"));
3324 goto fail;
3325 }
3326 }
3327
3328 /* set iv */
3329 sav->ivlen = 0;
3330
3331 switch (mhp->msg->sadb_msg_satype) {
3332 case SADB_SATYPE_AH:
3333 error = xform_init(sav, XF_AH);
3334 break;
3335 case SADB_SATYPE_ESP:
3336 error = xform_init(sav, XF_ESP);
3337 break;
3338 case SADB_X_SATYPE_IPCOMP:
3339 error = xform_init(sav, XF_IPCOMP);
3340 break;
3341 case SADB_X_SATYPE_TCPSIGNATURE:
3342 error = xform_init(sav, XF_TCPSIGNATURE);
3343 break;
3344 }
3345 if (error) {
3346 ipseclog((LOG_DEBUG,
3347 "key_setsaval: unable to initialize SA type %u.\n",
3348 mhp->msg->sadb_msg_satype));
3349 goto fail;
3350 }
3351
3352 /* reset created */
3353 sav->created = time_uptime;
3354
3355 /* make lifetime for CURRENT */
3356 KMALLOC(sav->lft_c, struct sadb_lifetime *,
3357 sizeof(struct sadb_lifetime));
3358 if (sav->lft_c == NULL) {
3359 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3360 error = ENOBUFS;
3361 goto fail;
3362 }
3363
3364 sav->lft_c->sadb_lifetime_len =
3365 PFKEY_UNIT64(sizeof(struct sadb_lifetime));
3366 sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
3367 sav->lft_c->sadb_lifetime_allocations = 0;
3368 sav->lft_c->sadb_lifetime_bytes = 0;
3369 sav->lft_c->sadb_lifetime_addtime = time_uptime;
3370 sav->lft_c->sadb_lifetime_usetime = 0;
3371
3372 /* lifetimes for HARD and SOFT */
3373 {
3374 const struct sadb_lifetime *lft0;
3375
3376 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3377 if (lft0 != NULL) {
3378 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3379 error = EINVAL;
3380 goto fail;
3381 }
3382 sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
3383 sizeof(*lft0));
3384 if (sav->lft_h == NULL) {
3385 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3386 error = ENOBUFS;
3387 goto fail;
3388 }
3389 /* to be initialize ? */
3390 }
3391
3392 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3393 if (lft0 != NULL) {
3394 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3395 error = EINVAL;
3396 goto fail;
3397 }
3398 sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
3399 sizeof(*lft0));
3400 if (sav->lft_s == NULL) {
3401 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3402 error = ENOBUFS;
3403 goto fail;
3404 }
3405 /* to be initialize ? */
3406 }
3407 }
3408
3409 return 0;
3410
3411 fail:
3412 /* initialization */
3413 if (sav->replay != NULL) {
3414 KFREE(sav->replay);
3415 sav->replay = NULL;
3416 }
3417 if (sav->key_auth != NULL) {
3418 KFREE(sav->key_auth);
3419 sav->key_auth = NULL;
3420 }
3421 if (sav->key_enc != NULL) {
3422 KFREE(sav->key_enc);
3423 sav->key_enc = NULL;
3424 }
3425 if (sav->lft_c != NULL) {
3426 KFREE(sav->lft_c);
3427 sav->lft_c = NULL;
3428 }
3429 if (sav->lft_h != NULL) {
3430 KFREE(sav->lft_h);
3431 sav->lft_h = NULL;
3432 }
3433 if (sav->lft_s != NULL) {
3434 KFREE(sav->lft_s);
3435 sav->lft_s = NULL;
3436 }
3437
3438 return error;
3439}
3440
3441/*
3442 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3443 * OUT: 0: valid
3444 * other: errno
3445 */
3446static int
3447key_mature(struct secasvar *sav)
3448{
3449 int error;
3450
3451 /* check SPI value */
3452 switch (sav->sah->saidx.proto) {
3453 case IPPROTO_ESP:
3454 case IPPROTO_AH:
3455 if (ntohl(sav->spi) <= 255) {
3456 ipseclog((LOG_DEBUG,
3457 "key_mature: illegal range of SPI %u.\n",
3458 (u_int32_t)ntohl(sav->spi)));
3459 return EINVAL;
3460 }
3461 break;
3462 }
3463
3464 /* check satype */
3465 switch (sav->sah->saidx.proto) {
3466 case IPPROTO_ESP:
3467 /* check flags */
3468 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3469 (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3470 ipseclog((LOG_DEBUG, "key_mature: "
3471 "invalid flag (derived) given to old-esp.\n"));
3472 return EINVAL;
3473 }
3474 error = xform_init(sav, XF_ESP);
3475 break;
3476 case IPPROTO_AH:
3477 /* check flags */
3478 if (sav->flags & SADB_X_EXT_DERIV) {
3479 ipseclog((LOG_DEBUG, "key_mature: "
3480 "invalid flag (derived) given to AH SA.\n"));
3481 return EINVAL;
3482 }
3483 if (sav->alg_enc != SADB_EALG_NONE) {
3484 ipseclog((LOG_DEBUG, "key_mature: "
3485 "protocol and algorithm mismated.\n"));
3486 return(EINVAL);
3487 }
3488 error = xform_init(sav, XF_AH);
3489 break;
3490 case IPPROTO_IPCOMP:
3491 if (sav->alg_auth != SADB_AALG_NONE) {
3492 ipseclog((LOG_DEBUG, "key_mature: "
3493 "protocol and algorithm mismated.\n"));
3494 return(EINVAL);
3495 }
3496 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3497 && ntohl(sav->spi) >= 0x10000) {
3498 ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
3499 return(EINVAL);
3500 }
3501 error = xform_init(sav, XF_IPCOMP);
3502 break;
3503 case IPPROTO_TCP:
3504 if (sav->alg_enc != SADB_EALG_NONE) {
3505 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3506 "mismated.\n", __func__));
3507 return(EINVAL);
3508 }
3509 error = xform_init(sav, XF_TCPSIGNATURE);
3510 break;
3511 default:
3512 ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
3513 error = EPROTONOSUPPORT;
3514 break;
3515 }
3516 if (error == 0)
3517 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3518 return (error);
3519}
3520
3521/*
3522 * subroutine for SADB_GET and SADB_DUMP.
3523 */
3524static struct mbuf *
3525key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3526 u_int32_t seq, u_int32_t pid)
3527{
3528 struct mbuf *result = NULL, *tres = NULL, *m;
3529 int l = 0;
3530 int i;
3531 void *p;
3532 struct sadb_lifetime lt;
3533 int dumporder[] = {
3534 SADB_EXT_SA, SADB_X_EXT_SA2,
3535 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3536 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3537 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3538 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3539 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3540 SADB_X_EXT_NAT_T_TYPE,
3541 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3542 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3543 SADB_X_EXT_NAT_T_FRAG,
3544
3545 };
3546
3547 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3548 if (m == NULL)
3549 goto fail;
3550 result = m;
3551
3552 for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3553 m = NULL;
3554 p = NULL;
3555 switch (dumporder[i]) {
3556 case SADB_EXT_SA:
3557 m = key_setsadbsa(sav);
3558 break;
3559
3560 case SADB_X_EXT_SA2:
3561 m = key_setsadbxsa2(sav->sah->saidx.mode,
3562 sav->replay ? sav->replay->count : 0,
3563 sav->sah->saidx.reqid);
3564 break;
3565
3566 case SADB_EXT_ADDRESS_SRC:
3567 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3568 &sav->sah->saidx.src.sa,
3569 FULLMASK, IPSEC_ULPROTO_ANY);
3570 break;
3571
3572 case SADB_EXT_ADDRESS_DST:
3573 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3574 &sav->sah->saidx.dst.sa,
3575 FULLMASK, IPSEC_ULPROTO_ANY);
3576 break;
3577
3578 case SADB_EXT_KEY_AUTH:
3579 if (!sav->key_auth)
3580 continue;
3581 l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
3582 p = sav->key_auth;
3583 break;
3584
3585 case SADB_EXT_KEY_ENCRYPT:
3586 if (!sav->key_enc)
3587 continue;
3588 l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
3589 p = sav->key_enc;
3590 break;
3591
3592 case SADB_EXT_LIFETIME_CURRENT:
3593 if (!sav->lft_c)
3594 continue;
3595 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
3596 memcpy(&lt, sav->lft_c, sizeof(struct sadb_lifetime));
3597 lt.sadb_lifetime_addtime += time_second - time_uptime;
3598 lt.sadb_lifetime_usetime += time_second - time_uptime;
3599 p = &lt;
3600 break;
3601
3602 case SADB_EXT_LIFETIME_HARD:
3603 if (!sav->lft_h)
3604 continue;
3605 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
3606 p = sav->lft_h;
3607 break;
3608
3609 case SADB_EXT_LIFETIME_SOFT:
3610 if (!sav->lft_s)
3611 continue;
3612 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
3613 p = sav->lft_s;
3614 break;
3615
3616 case SADB_X_EXT_NAT_T_TYPE:
3617 m = key_setsadbxtype(sav->natt_type);
3618 break;
3619
3620 case SADB_X_EXT_NAT_T_DPORT:
3621 if (sav->natt_type == 0)
3622 continue;
3623 m = key_setsadbxport(
3624 key_portfromsaddr(&sav->sah->saidx.dst),
3625 SADB_X_EXT_NAT_T_DPORT);
3626 break;
3627
3628 case SADB_X_EXT_NAT_T_SPORT:
3629 if (sav->natt_type == 0)
3630 continue;
3631 m = key_setsadbxport(
3632 key_portfromsaddr(&sav->sah->saidx.src),
3633 SADB_X_EXT_NAT_T_SPORT);
3634 break;
3635
3636 case SADB_X_EXT_NAT_T_FRAG:
3637 /* don't send frag info if not set */
3638 if (sav->natt_type == 0 || sav->esp_frag == IP_MAXPACKET)
3639 continue;
3640 m = key_setsadbxfrag(sav->esp_frag);
3641 break;
3642
3643 case SADB_X_EXT_NAT_T_OAI:
3644 case SADB_X_EXT_NAT_T_OAR:
3645 continue;
3646
3647 case SADB_EXT_ADDRESS_PROXY:
3648 case SADB_EXT_IDENTITY_SRC:
3649 case SADB_EXT_IDENTITY_DST:
3650 /* XXX: should we brought from SPD ? */
3651 case SADB_EXT_SENSITIVITY:
3652 default:
3653 continue;
3654 }
3655
3656 KASSERT(!(m && p));
3657 if (!m && !p)
3658 goto fail;
3659 if (p && tres) {
3660 M_PREPEND(tres, l, M_DONTWAIT);
3661 if (!tres)
3662 goto fail;
3663 memcpy(mtod(tres, void *), p, l);
3664 continue;
3665 }
3666 if (p) {
3667 m = key_alloc_mbuf(l);
3668 if (!m)
3669 goto fail;
3670 m_copyback(m, 0, l, p);
3671 }
3672
3673 if (tres)
3674 m_cat(m, tres);
3675 tres = m;
3676 }
3677
3678 m_cat(result, tres);
3679 tres = NULL; /* avoid free on error below */
3680
3681 if (result->m_len < sizeof(struct sadb_msg)) {
3682 result = m_pullup(result, sizeof(struct sadb_msg));
3683 if (result == NULL)
3684 goto fail;
3685 }
3686
3687 result->m_pkthdr.len = 0;
3688 for (m = result; m; m = m->m_next)
3689 result->m_pkthdr.len += m->m_len;
3690
3691 mtod(result, struct sadb_msg *)->sadb_msg_len =
3692 PFKEY_UNIT64(result->m_pkthdr.len);
3693
3694 return result;
3695
3696fail:
3697 m_freem(result);
3698 m_freem(tres);
3699 return NULL;
3700}
3701
3702
3703/*
3704 * set a type in sadb_x_nat_t_type
3705 */
3706static struct mbuf *
3707key_setsadbxtype(u_int16_t type)
3708{
3709 struct mbuf *m;
3710 size_t len;
3711 struct sadb_x_nat_t_type *p;
3712
3713 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3714
3715 m = key_alloc_mbuf(len);
3716 if (!m || m->m_next) { /*XXX*/
3717 if (m)
3718 m_freem(m);
3719 return NULL;
3720 }
3721
3722 p = mtod(m, struct sadb_x_nat_t_type *);
3723
3724 memset(p, 0, len);
3725 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3726 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3727 p->sadb_x_nat_t_type_type = type;
3728
3729 return m;
3730}
3731/*
3732 * set a port in sadb_x_nat_t_port. port is in network order
3733 */
3734static struct mbuf *
3735key_setsadbxport(u_int16_t port, u_int16_t type)
3736{
3737 struct mbuf *m;
3738 size_t len;
3739 struct sadb_x_nat_t_port *p;
3740
3741 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3742
3743 m = key_alloc_mbuf(len);
3744 if (!m || m->m_next) { /*XXX*/
3745 if (m)
3746 m_freem(m);
3747 return NULL;
3748 }
3749
3750 p = mtod(m, struct sadb_x_nat_t_port *);
3751
3752 memset(p, 0, len);
3753 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3754 p->sadb_x_nat_t_port_exttype = type;
3755 p->sadb_x_nat_t_port_port = port;
3756
3757 return m;
3758}
3759
3760/*
3761 * set fragmentation info in sadb_x_nat_t_frag
3762 */
3763static struct mbuf *
3764key_setsadbxfrag(u_int16_t flen)
3765{
3766 struct mbuf *m;
3767 size_t len;
3768 struct sadb_x_nat_t_frag *p;
3769
3770 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_frag));
3771
3772 m = key_alloc_mbuf(len);
3773 if (!m || m->m_next) { /*XXX*/
3774 if (m)
3775 m_freem(m);
3776 return NULL;
3777 }
3778
3779 p = mtod(m, struct sadb_x_nat_t_frag *);
3780
3781 memset(p, 0, len);
3782 p->sadb_x_nat_t_frag_len = PFKEY_UNIT64(len);
3783 p->sadb_x_nat_t_frag_exttype = SADB_X_EXT_NAT_T_FRAG;
3784 p->sadb_x_nat_t_frag_fraglen = flen;
3785
3786 return m;
3787}
3788
3789/*
3790 * Get port from sockaddr, port is in network order
3791 */
3792u_int16_t
3793key_portfromsaddr(const union sockaddr_union *saddr)
3794{
3795 u_int16_t port;
3796
3797 switch (saddr->sa.sa_family) {
3798 case AF_INET: {
3799 port = saddr->sin.sin_port;
3800 break;
3801 }
3802#ifdef INET6
3803 case AF_INET6: {
3804 port = saddr->sin6.sin6_port;
3805 break;
3806 }
3807#endif
3808 default:
3809 printf("%s: unexpected address family\n", __func__);
3810 port = 0;
3811 break;
3812 }
3813
3814 return port;
3815}
3816
3817
3818/*
3819 * Set port is struct sockaddr. port is in network order
3820 */
3821static void
3822key_porttosaddr(union sockaddr_union *saddr, u_int16_t port)
3823{
3824 switch (saddr->sa.sa_family) {
3825 case AF_INET: {
3826 saddr->sin.sin_port = port;
3827 break;
3828 }
3829#ifdef INET6
3830 case AF_INET6: {
3831 saddr->sin6.sin6_port = port;
3832 break;
3833 }
3834#endif
3835 default:
3836 printf("%s: unexpected address family %d\n", __func__,
3837 saddr->sa.sa_family);
3838 break;
3839 }
3840
3841 return;
3842}
3843
3844/*
3845 * Safety check sa_len
3846 */
3847static int
3848key_checksalen(const union sockaddr_union *saddr)
3849{
3850 switch (saddr->sa.sa_family) {
3851 case AF_INET:
3852 if (saddr->sa.sa_len != sizeof(struct sockaddr_in))
3853 return -1;
3854 break;
3855#ifdef INET6
3856 case AF_INET6:
3857 if (saddr->sa.sa_len != sizeof(struct sockaddr_in6))
3858 return -1;
3859 break;
3860#endif
3861 default:
3862 printf("%s: unexpected sa_family %d\n", __func__,
3863 saddr->sa.sa_family);
3864 return -1;
3865 break;
3866 }
3867 return 0;
3868}
3869
3870
3871/*
3872 * set data into sadb_msg.
3873 */
3874static struct mbuf *
3875key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype,
3876 u_int32_t seq, pid_t pid, u_int16_t reserved)
3877{
3878 struct mbuf *m;
3879 struct sadb_msg *p;
3880 int len;
3881
3882 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3883 if (len > MCLBYTES)
3884 return NULL;
3885 MGETHDR(m, M_DONTWAIT, MT_DATA);
3886 if (m && len > MHLEN) {
3887 MCLGET(m, M_DONTWAIT);
3888 if ((m->m_flags & M_EXT) == 0) {
3889 m_freem(m);
3890 m = NULL;
3891 }
3892 }
3893 if (!m)
3894 return NULL;
3895 m->m_pkthdr.len = m->m_len = len;
3896 m->m_next = NULL;
3897
3898 p = mtod(m, struct sadb_msg *);
3899
3900 memset(p, 0, len);
3901 p->sadb_msg_version = PF_KEY_V2;
3902 p->sadb_msg_type = type;
3903 p->sadb_msg_errno = 0;
3904 p->sadb_msg_satype = satype;
3905 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3906 p->sadb_msg_reserved = reserved;
3907 p->sadb_msg_seq = seq;
3908 p->sadb_msg_pid = (u_int32_t)pid;
3909
3910 return m;
3911}
3912
3913/*
3914 * copy secasvar data into sadb_address.
3915 */
3916static struct mbuf *
3917key_setsadbsa(struct secasvar *sav)
3918{
3919 struct mbuf *m;
3920 struct sadb_sa *p;
3921 int len;
3922
3923 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3924 m = key_alloc_mbuf(len);
3925 if (!m || m->m_next) { /*XXX*/
3926 if (m)
3927 m_freem(m);
3928 return NULL;
3929 }
3930
3931 p = mtod(m, struct sadb_sa *);
3932
3933 memset(p, 0, len);
3934 p->sadb_sa_len = PFKEY_UNIT64(len);
3935 p->sadb_sa_exttype = SADB_EXT_SA;
3936 p->sadb_sa_spi = sav->spi;
3937 p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3938 p->sadb_sa_state = sav->state;
3939 p->sadb_sa_auth = sav->alg_auth;
3940 p->sadb_sa_encrypt = sav->alg_enc;
3941 p->sadb_sa_flags = sav->flags;
3942
3943 return m;
3944}
3945
3946/*
3947 * set data into sadb_address.
3948 */
3949static struct mbuf *
3950key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3951 u_int8_t prefixlen, u_int16_t ul_proto)
3952{
3953 struct mbuf *m;
3954 struct sadb_address *p;
3955 size_t len;
3956
3957 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3958 PFKEY_ALIGN8(saddr->sa_len);
3959 m = key_alloc_mbuf(len);
3960 if (!m || m->m_next) { /*XXX*/
3961 if (m)
3962 m_freem(m);
3963 return NULL;
3964 }
3965
3966 p = mtod(m, struct sadb_address *);
3967
3968 memset(p, 0, len);
3969 p->sadb_address_len = PFKEY_UNIT64(len);
3970 p->sadb_address_exttype = exttype;
3971 p->sadb_address_proto = ul_proto;
3972 if (prefixlen == FULLMASK) {
3973 switch (saddr->sa_family) {
3974 case AF_INET:
3975 prefixlen = sizeof(struct in_addr) << 3;
3976 break;
3977 case AF_INET6:
3978 prefixlen = sizeof(struct in6_addr) << 3;
3979 break;
3980 default:
3981 ; /*XXX*/
3982 }
3983 }
3984 p->sadb_address_prefixlen = prefixlen;
3985 p->sadb_address_reserved = 0;
3986
3987 memcpy(mtod(m, char *) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3988 saddr, saddr->sa_len);
3989
3990 return m;
3991}
3992
3993#if 0
3994/*
3995 * set data into sadb_ident.
3996 */
3997static struct mbuf *
3998key_setsadbident(u_int16_t exttype, u_int16_t idtype,
3999 void *string, int stringlen, u_int64_t id)
4000{
4001 struct mbuf *m;
4002 struct sadb_ident *p;
4003 size_t len;
4004
4005 len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
4006 m = key_alloc_mbuf(len);
4007 if (!m || m->m_next) { /*XXX*/
4008 if (m)
4009 m_freem(m);
4010 return NULL;
4011 }
4012
4013 p = mtod(m, struct sadb_ident *);
4014
4015 memset(p, 0, len);
4016 p->sadb_ident_len = PFKEY_UNIT64(len);
4017 p->sadb_ident_exttype = exttype;
4018 p->sadb_ident_type = idtype;
4019 p->sadb_ident_reserved = 0;
4020 p->sadb_ident_id = id;
4021
4022 memcpy(mtod(m, void *) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
4023 string, stringlen);
4024
4025 return m;
4026}
4027#endif
4028
4029/*
4030 * set data into sadb_x_sa2.
4031 */
4032static struct mbuf *
4033key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int16_t reqid)
4034{
4035 struct mbuf *m;
4036 struct sadb_x_sa2 *p;
4037 size_t len;
4038
4039 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
4040 m = key_alloc_mbuf(len);
4041 if (!m || m->m_next) { /*XXX*/
4042 if (m)
4043 m_freem(m);
4044 return NULL;
4045 }
4046
4047 p = mtod(m, struct sadb_x_sa2 *);
4048
4049 memset(p, 0, len);
4050 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
4051 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
4052 p->sadb_x_sa2_mode = mode;
4053 p->sadb_x_sa2_reserved1 = 0;
4054 p->sadb_x_sa2_reserved2 = 0;
4055 p->sadb_x_sa2_sequence = seq;
4056 p->sadb_x_sa2_reqid = reqid;
4057
4058 return m;
4059}
4060
4061/*
4062 * set data into sadb_x_policy
4063 */
4064static struct mbuf *
4065key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
4066{
4067 struct mbuf *m;
4068 struct sadb_x_policy *p;
4069 size_t len;
4070
4071 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
4072 m = key_alloc_mbuf(len);
4073 if (!m || m->m_next) { /*XXX*/
4074 if (m)
4075 m_freem(m);
4076 return NULL;
4077 }
4078
4079 p = mtod(m, struct sadb_x_policy *);
4080
4081 memset(p, 0, len);
4082 p->sadb_x_policy_len = PFKEY_UNIT64(len);
4083 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
4084 p->sadb_x_policy_type = type;
4085 p->sadb_x_policy_dir = dir;
4086 p->sadb_x_policy_id = id;
4087
4088 return m;
4089}
4090
4091/* %%% utilities */
4092/*
4093 * copy a buffer into the new buffer allocated.
4094 */
4095static void *
4096key_newbuf(const void *src, u_int len)
4097{
4098 void *new;
4099
4100 KMALLOC(new, void *, len);
4101 if (new == NULL) {
4102 ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
4103 return NULL;
4104 }
4105 memcpy(new, src, len);
4106
4107 return new;
4108}
4109
4110/* compare my own address
4111 * OUT: 1: true, i.e. my address.
4112 * 0: false
4113 */
4114int
4115key_ismyaddr(const struct sockaddr *sa)
4116{
4117#ifdef INET
4118 const struct sockaddr_in *sin;
4119 const struct in_ifaddr *ia;
4120 int s;
4121#endif
4122
4123 /* sanity check */
4124 if (sa == NULL)
4125 panic("key_ismyaddr: NULL pointer is passed");
4126
4127 switch (sa->sa_family) {
4128#ifdef INET
4129 case AF_INET:
4130 sin = (const struct sockaddr_in *)sa;
4131 s = pserialize_read_enter();
4132 IN_ADDRLIST_READER_FOREACH(ia) {
4133 if (sin->sin_family == ia->ia_addr.sin_family &&
4134 sin->sin_len == ia->ia_addr.sin_len &&
4135 sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
4136 {
4137 pserialize_read_exit(s);
4138 return 1;
4139 }
4140 }
4141 pserialize_read_exit(s);
4142 break;
4143#endif
4144#ifdef INET6
4145 case AF_INET6:
4146 return key_ismyaddr6((const struct sockaddr_in6 *)sa);
4147#endif
4148 }
4149
4150 return 0;
4151}
4152
4153#ifdef INET6
4154/*
4155 * compare my own address for IPv6.
4156 * 1: ours
4157 * 0: other
4158 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
4159 */
4160#include <netinet6/in6_var.h>
4161
4162static int
4163key_ismyaddr6(const struct sockaddr_in6 *sin6)
4164{
4165 struct in6_ifaddr *ia;
4166 const struct in6_multi *in6m;
4167 int s;
4168
4169 s = pserialize_read_enter();
4170 IN6_ADDRLIST_READER_FOREACH(ia) {
4171 if (key_sockaddrcmp((const struct sockaddr *)&sin6,
4172 (const struct sockaddr *)&ia->ia_addr, 0) == 0) {
4173 pserialize_read_exit(s);
4174 return 1;
4175 }
4176
4177 /*
4178 * XXX Multicast
4179 * XXX why do we care about multlicast here while we don't care
4180 * about IPv4 multicast??
4181 * XXX scope
4182 */
4183 in6m = NULL;
4184#ifdef __FreeBSD__
4185 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
4186#else
4187 for ((in6m) = ia->ia6_multiaddrs.lh_first;
4188 (in6m) != NULL &&
4189 !IN6_ARE_ADDR_EQUAL(&(in6m)->in6m_addr, &sin6->sin6_addr);
4190 (in6m) = in6m->in6m_entry.le_next)
4191 continue;
4192#endif
4193 if (in6m) {
4194 pserialize_read_exit(s);
4195 return 1;
4196 }
4197 }
4198 pserialize_read_exit(s);
4199
4200 /* loopback, just for safety */
4201 if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
4202 return 1;
4203
4204 return 0;
4205}
4206#endif /*INET6*/
4207
4208/*
4209 * compare two secasindex structure.
4210 * flag can specify to compare 2 saidxes.
4211 * compare two secasindex structure without both mode and reqid.
4212 * don't compare port.
4213 * IN:
4214 * saidx0: source, it can be in SAD.
4215 * saidx1: object.
4216 * OUT:
4217 * 1 : equal
4218 * 0 : not equal
4219 */
4220static int
4221key_cmpsaidx(
4222 const struct secasindex *saidx0,
4223 const struct secasindex *saidx1,
4224 int flag)
4225{
4226 int chkport;
4227 const struct sockaddr *sa0src, *sa0dst, *sa1src, *sa1dst;
4228
4229 /* sanity */
4230 if (saidx0 == NULL && saidx1 == NULL)
4231 return 1;
4232
4233 if (saidx0 == NULL || saidx1 == NULL)
4234 return 0;
4235
4236 if (saidx0->proto != saidx1->proto)
4237 return 0;
4238
4239 if (flag == CMP_EXACTLY) {
4240 if (saidx0->mode != saidx1->mode)
4241 return 0;
4242 if (saidx0->reqid != saidx1->reqid)
4243 return 0;
4244 if (memcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4245 memcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4246 return 0;
4247 } else {
4248
4249 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4250 if (flag == CMP_MODE_REQID
4251 ||flag == CMP_REQID) {
4252 /*
4253 * If reqid of SPD is non-zero, unique SA is required.
4254 * The result must be of same reqid in this case.
4255 */
4256 if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4257 return 0;
4258 }
4259
4260 if (flag == CMP_MODE_REQID) {
4261 if (saidx0->mode != IPSEC_MODE_ANY
4262 && saidx0->mode != saidx1->mode)
4263 return 0;
4264 }
4265
4266
4267 sa0src = &saidx0->src.sa;
4268 sa0dst = &saidx0->dst.sa;
4269 sa1src = &saidx1->src.sa;
4270 sa1dst = &saidx1->dst.sa;
4271 /*
4272 * If NAT-T is enabled, check ports for tunnel mode.
4273 * Don't do it for transport mode, as there is no
4274 * port information available in the SP.
4275 * Also don't check ports if they are set to zero
4276 * in the SPD: This means we have a non-generated
4277 * SPD which can't know UDP ports.
4278 */
4279 if (saidx1->mode == IPSEC_MODE_TUNNEL)
4280 chkport = PORT_LOOSE;
4281 else
4282 chkport = PORT_NONE;
4283
4284 if (key_sockaddrcmp(sa0src, sa1src, chkport) != 0) {
4285 return 0;
4286 }
4287 if (key_sockaddrcmp(sa0dst, sa1dst, chkport) != 0) {
4288 return 0;
4289 }
4290 }
4291
4292 return 1;
4293}
4294
4295/*
4296 * compare two secindex structure exactly.
4297 * IN:
4298 * spidx0: source, it is often in SPD.
4299 * spidx1: object, it is often from PFKEY message.
4300 * OUT:
4301 * 1 : equal
4302 * 0 : not equal
4303 */
4304int
4305key_cmpspidx_exactly(
4306 const struct secpolicyindex *spidx0,
4307 const struct secpolicyindex *spidx1)
4308{
4309 /* sanity */
4310 if (spidx0 == NULL && spidx1 == NULL)
4311 return 1;
4312
4313 if (spidx0 == NULL || spidx1 == NULL)
4314 return 0;
4315
4316 if (spidx0->prefs != spidx1->prefs
4317 || spidx0->prefd != spidx1->prefd
4318 || spidx0->ul_proto != spidx1->ul_proto)
4319 return 0;
4320
4321 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, PORT_STRICT) == 0 &&
4322 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, PORT_STRICT) == 0;
4323}
4324
4325/*
4326 * compare two secindex structure with mask.
4327 * IN:
4328 * spidx0: source, it is often in SPD.
4329 * spidx1: object, it is often from IP header.
4330 * OUT:
4331 * 1 : equal
4332 * 0 : not equal
4333 */
4334int
4335key_cmpspidx_withmask(
4336 const struct secpolicyindex *spidx0,
4337 const struct secpolicyindex *spidx1)
4338{
4339 /* sanity */
4340 if (spidx0 == NULL && spidx1 == NULL)
4341 return 1;
4342
4343 if (spidx0 == NULL || spidx1 == NULL)
4344 return 0;
4345
4346 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4347 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4348 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4349 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4350 return 0;
4351
4352 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4353 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4354 && spidx0->ul_proto != spidx1->ul_proto)
4355 return 0;
4356
4357 switch (spidx0->src.sa.sa_family) {
4358 case AF_INET:
4359 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4360 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4361 return 0;
4362 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4363 &spidx1->src.sin.sin_addr, spidx0->prefs))
4364 return 0;
4365 break;
4366 case AF_INET6:
4367 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4368 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4369 return 0;
4370 /*
4371 * scope_id check. if sin6_scope_id is 0, we regard it
4372 * as a wildcard scope, which matches any scope zone ID.
4373 */
4374 if (spidx0->src.sin6.sin6_scope_id &&
4375 spidx1->src.sin6.sin6_scope_id &&
4376 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4377 return 0;
4378 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4379 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4380 return 0;
4381 break;
4382 default:
4383 /* XXX */
4384 if (memcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4385 return 0;
4386 break;
4387 }
4388
4389 switch (spidx0->dst.sa.sa_family) {
4390 case AF_INET:
4391 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4392 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4393 return 0;
4394 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4395 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4396 return 0;
4397 break;
4398 case AF_INET6:
4399 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4400 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4401 return 0;
4402 /*
4403 * scope_id check. if sin6_scope_id is 0, we regard it
4404 * as a wildcard scope, which matches any scope zone ID.
4405 */
4406 if (spidx0->src.sin6.sin6_scope_id &&
4407 spidx1->src.sin6.sin6_scope_id &&
4408 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4409 return 0;
4410 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4411 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4412 return 0;
4413 break;
4414 default:
4415 /* XXX */
4416 if (memcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4417 return 0;
4418 break;
4419 }
4420
4421 /* XXX Do we check other field ? e.g. flowinfo */
4422
4423 return 1;
4424}
4425
4426/* returns 0 on match */
4427static int
4428key_portcomp(in_port_t port1, in_port_t port2, int howport)
4429{
4430 switch (howport) {
4431 case PORT_NONE:
4432 return 0;
4433 case PORT_LOOSE:
4434 if (port1 == 0 || port2 == 0)
4435 return 0;
4436 /*FALLTHROUGH*/
4437 case PORT_STRICT:
4438 if (port1 != port2) {
4439 KEYDEBUG(KEYDEBUG_MATCH,
4440 printf("port fail %d != %d\n", port1, port2));
4441 return 1;
4442 }
4443 return 0;
4444 default:
4445 KASSERT(0);
4446 return 1;
4447 }
4448}
4449
4450/* returns 0 on match */
4451static int
4452key_sockaddrcmp(
4453 const struct sockaddr *sa1,
4454 const struct sockaddr *sa2,
4455 int howport)
4456{
4457 const struct sockaddr_in *sin1, *sin2;
4458 const struct sockaddr_in6 *sin61, *sin62;
4459
4460 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) {
4461 KEYDEBUG(KEYDEBUG_MATCH,
4462 printf("fam/len fail %d != %d || %d != %d\n",
4463 sa1->sa_family, sa2->sa_family, sa1->sa_len,
4464 sa2->sa_len));
4465 return 1;
4466 }
4467
4468 switch (sa1->sa_family) {
4469 case AF_INET:
4470 if (sa1->sa_len != sizeof(struct sockaddr_in)) {
4471 KEYDEBUG(KEYDEBUG_MATCH,
4472 printf("len fail %d != %zu\n",
4473 sa1->sa_len, sizeof(struct sockaddr_in)));
4474 return 1;
4475 }
4476 sin1 = (const struct sockaddr_in *)sa1;
4477 sin2 = (const struct sockaddr_in *)sa2;
4478 if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) {
4479 KEYDEBUG(KEYDEBUG_MATCH,
4480 printf("addr fail %#x != %#x\n",
4481 sin1->sin_addr.s_addr,
4482 sin2->sin_addr.s_addr));
4483 return 1;
4484 }
4485 if (key_portcomp(sin1->sin_port, sin2->sin_port, howport)) {
4486 return 1;
4487 }
4488 KEYDEBUG(KEYDEBUG_MATCH,
4489 printf("addr success %#x[%d] == %#x[%d]\n",
4490 sin1->sin_addr.s_addr,
4491 sin1->sin_port,
4492 sin2->sin_addr.s_addr,
4493 sin2->sin_port));
4494 break;
4495 case AF_INET6:
4496 sin61 = (const struct sockaddr_in6 *)sa1;
4497 sin62 = (const struct sockaddr_in6 *)sa2;
4498 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4499 return 1; /*EINVAL*/
4500
4501 if (sin61->sin6_scope_id != sin62->sin6_scope_id) {
4502 return 1;
4503 }
4504 if (!IN6_ARE_ADDR_EQUAL(&sin61->sin6_addr, &sin62->sin6_addr)) {
4505 return 1;
4506 }
4507 if (key_portcomp(sin61->sin6_port, sin62->sin6_port, howport)) {
4508 return 1;
4509 }
4510 break;
4511 default:
4512 if (memcmp(sa1, sa2, sa1->sa_len) != 0)
4513 return 1;
4514 break;
4515 }
4516
4517 return 0;
4518}
4519
4520/*
4521 * compare two buffers with mask.
4522 * IN:
4523 * addr1: source
4524 * addr2: object
4525 * bits: Number of bits to compare
4526 * OUT:
4527 * 1 : equal
4528 * 0 : not equal
4529 */
4530static int
4531key_bbcmp(const void *a1, const void *a2, u_int bits)
4532{
4533 const unsigned char *p1 = a1;
4534 const unsigned char *p2 = a2;
4535
4536 /* XXX: This could be considerably faster if we compare a word
4537 * at a time, but it is complicated on LSB Endian machines */
4538
4539 /* Handle null pointers */
4540 if (p1 == NULL || p2 == NULL)
4541 return (p1 == p2);
4542
4543 while (bits >= 8) {
4544 if (*p1++ != *p2++)
4545 return 0;
4546 bits -= 8;
4547 }
4548
4549 if (bits > 0) {
4550 u_int8_t mask = ~((1<<(8-bits))-1);
4551 if ((*p1 & mask) != (*p2 & mask))
4552 return 0;
4553 }
4554 return 1; /* Match! */
4555}
4556
4557/*
4558 * time handler.
4559 * scanning SPD and SAD to check status for each entries,
4560 * and do to remove or to expire.
4561 */
4562void
4563key_timehandler(void* arg)
4564{
4565 u_int dir;
4566 int s;
4567 time_t now = time_uptime;
4568
4569 s = splsoftnet(); /*called from softclock()*/
4570 mutex_enter(softnet_lock);
4571
4572 /* SPD */
4573 {
4574 struct secpolicy *sp, *nextsp;
4575
4576 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4577 for (sp = LIST_FIRST(&sptree[dir]);
4578 sp != NULL;
4579 sp = nextsp) {
4580
4581 nextsp = LIST_NEXT(sp, chain);
4582
4583 if (sp->state == IPSEC_SPSTATE_DEAD) {
4584 key_sp_unlink(sp); /*XXX*/
4585
4586 /* 'sp' dead; continue transfers to
4587 * 'sp = nextsp'
4588 */
4589 continue;
4590 }
4591
4592 if (sp->lifetime == 0 && sp->validtime == 0)
4593 continue;
4594
4595 /* the deletion will occur next time */
4596 if ((sp->lifetime && now - sp->created > sp->lifetime)
4597 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4598 key_sp_dead(sp);
4599 key_spdexpire(sp);
4600 continue;
4601 }
4602 }
4603 }
4604 }
4605
4606 /* SAD */
4607 {
4608 struct secashead *sah, *nextsah;
4609 struct secasvar *sav, *nextsav;
4610
4611 for (sah = LIST_FIRST(&sahtree);
4612 sah != NULL;
4613 sah = nextsah) {
4614
4615 nextsah = LIST_NEXT(sah, chain);
4616
4617 /* if sah has been dead, then delete it and process next sah. */
4618 if (sah->state == SADB_SASTATE_DEAD) {
4619 key_delsah(sah);
4620 continue;
4621 }
4622
4623 /* if LARVAL entry doesn't become MATURE, delete it. */
4624 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
4625 sav != NULL;
4626 sav = nextsav) {
4627
4628 nextsav = LIST_NEXT(sav, chain);
4629
4630 if (now - sav->created > key_larval_lifetime) {
4631 KEY_FREESAV(&sav);
4632 }
4633 }
4634
4635 /*
4636 * check MATURE entry to start to send expire message
4637 * whether or not.
4638 */
4639 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
4640 sav != NULL;
4641 sav = nextsav) {
4642
4643 nextsav = LIST_NEXT(sav, chain);
4644
4645 /* we don't need to check. */
4646 if (sav->lft_s == NULL)
4647 continue;
4648
4649 /* sanity check */
4650 if (sav->lft_c == NULL) {
4651 ipseclog((LOG_DEBUG,"key_timehandler: "
4652 "There is no CURRENT time, why?\n"));
4653 continue;
4654 }
4655
4656 /* check SOFT lifetime */
4657 if (sav->lft_s->sadb_lifetime_addtime != 0
4658 && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4659 /*
4660 * check SA to be used whether or not.
4661 * when SA hasn't been used, delete it.
4662 */
4663 if (sav->lft_c->sadb_lifetime_usetime == 0) {
4664 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4665 KEY_FREESAV(&sav);
4666 } else {
4667 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4668 /*
4669 * XXX If we keep to send expire
4670 * message in the status of
4671 * DYING. Do remove below code.
4672 */
4673 key_expire(sav);
4674 }
4675 }
4676 /* check SOFT lifetime by bytes */
4677 /*
4678 * XXX I don't know the way to delete this SA
4679 * when new SA is installed. Caution when it's
4680 * installed too big lifetime by time.
4681 */
4682 else if (sav->lft_s->sadb_lifetime_bytes != 0
4683 && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4684
4685 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4686 /*
4687 * XXX If we keep to send expire
4688 * message in the status of
4689 * DYING. Do remove below code.
4690 */
4691 key_expire(sav);
4692 }
4693 }
4694
4695 /* check DYING entry to change status to DEAD. */
4696 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
4697 sav != NULL;
4698 sav = nextsav) {
4699
4700 nextsav = LIST_NEXT(sav, chain);
4701
4702 /* we don't need to check. */
4703 if (sav->lft_h == NULL)
4704 continue;
4705
4706 /* sanity check */
4707 if (sav->lft_c == NULL) {
4708 ipseclog((LOG_DEBUG, "key_timehandler: "
4709 "There is no CURRENT time, why?\n"));
4710 continue;
4711 }
4712
4713 if (sav->lft_h->sadb_lifetime_addtime != 0
4714 && now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4715 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4716 KEY_FREESAV(&sav);
4717 }
4718#if 0 /* XXX Should we keep to send expire message until HARD lifetime ? */
4719 else if (sav->lft_s != NULL
4720 && sav->lft_s->sadb_lifetime_addtime != 0
4721 && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4722 /*
4723 * XXX: should be checked to be
4724 * installed the valid SA.
4725 */
4726
4727 /*
4728 * If there is no SA then sending
4729 * expire message.
4730 */
4731 key_expire(sav);
4732 }
4733#endif
4734 /* check HARD lifetime by bytes */
4735 else if (sav->lft_h->sadb_lifetime_bytes != 0
4736 && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4737 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4738 KEY_FREESAV(&sav);
4739 }
4740 }
4741
4742 /* delete entry in DEAD */
4743 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
4744 sav != NULL;
4745 sav = nextsav) {
4746
4747 nextsav = LIST_NEXT(sav, chain);
4748
4749 /* sanity check */
4750 if (sav->state != SADB_SASTATE_DEAD) {
4751 ipseclog((LOG_DEBUG, "key_timehandler: "
4752 "invalid sav->state "
4753 "(queue: %d SA: %d): "
4754 "kill it anyway\n",
4755 SADB_SASTATE_DEAD, sav->state));
4756 }
4757
4758 /*
4759 * do not call key_freesav() here.
4760 * sav should already be freed, and sav->refcnt
4761 * shows other references to sav
4762 * (such as from SPD).
4763 */
4764 }
4765 }
4766 }
4767
4768#ifndef IPSEC_NONBLOCK_ACQUIRE
4769 /* ACQ tree */
4770 {
4771 struct secacq *acq, *nextacq;
4772
4773 for (acq = LIST_FIRST(&acqtree);
4774 acq != NULL;
4775 acq = nextacq) {
4776
4777 nextacq = LIST_NEXT(acq, chain);
4778
4779 if (now - acq->created > key_blockacq_lifetime
4780 && __LIST_CHAINED(acq)) {
4781 LIST_REMOVE(acq, chain);
4782 KFREE(acq);
4783 }
4784 }
4785 }
4786#endif
4787
4788 /* SP ACQ tree */
4789 {
4790 struct secspacq *acq, *nextacq;
4791
4792 for (acq = LIST_FIRST(&spacqtree);
4793 acq != NULL;
4794 acq = nextacq) {
4795
4796 nextacq = LIST_NEXT(acq, chain);
4797
4798 if (now - acq->created > key_blockacq_lifetime
4799 && __LIST_CHAINED(acq)) {
4800 LIST_REMOVE(acq, chain);
4801 KFREE(acq);
4802 }
4803 }
4804 }
4805
4806#ifndef IPSEC_DEBUG2
4807 /* do exchange to tick time !! */
4808 callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
4809#endif /* IPSEC_DEBUG2 */
4810
4811 mutex_exit(softnet_lock);
4812 splx(s);
4813 return;
4814}
4815
4816u_long
4817key_random(void)
4818{
4819 u_long value;
4820
4821 key_randomfill(&value, sizeof(value));
4822 return value;
4823}
4824
4825void
4826key_randomfill(void *p, size_t l)
4827{
4828
4829 cprng_fast(p, l);
4830}
4831
4832/*
4833 * map SADB_SATYPE_* to IPPROTO_*.
4834 * if satype == SADB_SATYPE then satype is mapped to ~0.
4835 * OUT:
4836 * 0: invalid satype.
4837 */
4838static u_int16_t
4839key_satype2proto(u_int8_t satype)
4840{
4841 switch (satype) {
4842 case SADB_SATYPE_UNSPEC:
4843 return IPSEC_PROTO_ANY;
4844 case SADB_SATYPE_AH:
4845 return IPPROTO_AH;
4846 case SADB_SATYPE_ESP:
4847 return IPPROTO_ESP;
4848 case SADB_X_SATYPE_IPCOMP:
4849 return IPPROTO_IPCOMP;
4850 case SADB_X_SATYPE_TCPSIGNATURE:
4851 return IPPROTO_TCP;
4852 default:
4853 return 0;
4854 }
4855 /* NOTREACHED */
4856}
4857
4858/*
4859 * map IPPROTO_* to SADB_SATYPE_*
4860 * OUT:
4861 * 0: invalid protocol type.
4862 */
4863static u_int8_t
4864key_proto2satype(u_int16_t proto)
4865{
4866 switch (proto) {
4867 case IPPROTO_AH:
4868 return SADB_SATYPE_AH;
4869 case IPPROTO_ESP:
4870 return SADB_SATYPE_ESP;
4871 case IPPROTO_IPCOMP:
4872 return SADB_X_SATYPE_IPCOMP;
4873 case IPPROTO_TCP:
4874 return SADB_X_SATYPE_TCPSIGNATURE;
4875 default:
4876 return 0;
4877 }
4878 /* NOTREACHED */
4879}
4880
4881static int
4882key_setsecasidx(int proto, int mode, int reqid,
4883 const struct sadb_address * src,
4884 const struct sadb_address * dst,
4885 struct secasindex * saidx)
4886{
4887 const union sockaddr_union * src_u =
4888 (const union sockaddr_union *) src;
4889 const union sockaddr_union * dst_u =
4890 (const union sockaddr_union *) dst;
4891
4892 /* sa len safety check */
4893 if (key_checksalen(src_u) != 0)
4894 return -1;
4895 if (key_checksalen(dst_u) != 0)
4896 return -1;
4897
4898 memset(saidx, 0, sizeof(*saidx));
4899 saidx->proto = proto;
4900 saidx->mode = mode;
4901 saidx->reqid = reqid;
4902 memcpy(&saidx->src, src_u, src_u->sa.sa_len);
4903 memcpy(&saidx->dst, dst_u, dst_u->sa.sa_len);
4904
4905 key_porttosaddr(&((saidx)->src),0);
4906 key_porttosaddr(&((saidx)->dst),0);
4907 return 0;
4908}
4909
4910/* %%% PF_KEY */
4911/*
4912 * SADB_GETSPI processing is to receive
4913 * <base, (SA2), src address, dst address, (SPI range)>
4914 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4915 * tree with the status of LARVAL, and send
4916 * <base, SA(*), address(SD)>
4917 * to the IKMPd.
4918 *
4919 * IN: mhp: pointer to the pointer to each header.
4920 * OUT: NULL if fail.
4921 * other if success, return pointer to the message to send.
4922 */
4923static int
4924key_getspi(struc