key.c revision 1.194 1 /* $NetBSD: key.c,v 1.194 2017/07/26 09:18:15 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.194 2017/07/26 09:18:15 ozaki-r Exp $");
36
37 /*
38 * This code is referd to RFC 2367
39 */
40
41 #if defined(_KERNEL_OPT)
42 #include "opt_inet.h"
43 #include "opt_ipsec.h"
44 #include "opt_gateway.h"
45 #endif
46
47 #include <sys/types.h>
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/callout.h>
51 #include <sys/kernel.h>
52 #include <sys/mbuf.h>
53 #include <sys/domain.h>
54 #include <sys/socket.h>
55 #include <sys/socketvar.h>
56 #include <sys/sysctl.h>
57 #include <sys/errno.h>
58 #include <sys/proc.h>
59 #include <sys/queue.h>
60 #include <sys/syslog.h>
61 #include <sys/once.h>
62 #include <sys/cprng.h>
63 #include <sys/psref.h>
64 #include <sys/lwp.h>
65 #include <sys/workqueue.h>
66 #include <sys/kmem.h>
67 #include <sys/cpu.h>
68 #include <sys/atomic.h>
69 #include <sys/pslist.h>
70
71 #include <net/if.h>
72 #include <net/route.h>
73
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/ip.h>
77 #include <netinet/in_var.h>
78 #ifdef INET
79 #include <netinet/ip_var.h>
80 #endif
81
82 #ifdef INET6
83 #include <netinet/ip6.h>
84 #include <netinet6/in6_var.h>
85 #include <netinet6/ip6_var.h>
86 #endif /* INET6 */
87
88 #ifdef INET
89 #include <netinet/in_pcb.h>
90 #endif
91 #ifdef INET6
92 #include <netinet6/in6_pcb.h>
93 #endif /* INET6 */
94
95 #include <net/pfkeyv2.h>
96 #include <netipsec/keydb.h>
97 #include <netipsec/key.h>
98 #include <netipsec/keysock.h>
99 #include <netipsec/key_debug.h>
100
101 #include <netipsec/ipsec.h>
102 #ifdef INET6
103 #include <netipsec/ipsec6.h>
104 #endif
105 #include <netipsec/ipsec_private.h>
106
107 #include <netipsec/xform.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
120 percpu_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
133 u_int32_t key_debug_level = 0;
134 static u_int key_spi_trycnt = 1000;
135 static u_int32_t key_spi_minval = 0x100;
136 static u_int32_t key_spi_maxval = 0x0fffffff; /* XXX */
137 static u_int32_t policy_id = 0;
138 static u_int key_int_random = 60; /*interval to initialize randseed,1(m)*/
139 static u_int key_larval_lifetime = 30; /* interval to expire acquiring, 30(s)*/
140 static int key_blockacq_count = 10; /* counter for blocking SADB_ACQUIRE.*/
141 static int key_blockacq_lifetime = 20; /* lifetime for blocking SADB_ACQUIRE.*/
142 static int key_prefered_oldsa = 0; /* prefered old sa rather than new sa.*/
143
144 static u_int32_t acq_seq = 0;
145
146 static struct pslist_head sptree[IPSEC_DIR_MAX]; /* SPD */
147 static LIST_HEAD(_sahtree, secashead) sahtree; /* SAD */
148 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
149 /* registed list */
150 #ifndef IPSEC_NONBLOCK_ACQUIRE
151 static LIST_HEAD(_acqtree, secacq) acqtree; /* acquiring list */
152 #endif
153 #ifdef notyet
154 static LIST_HEAD(_spacqtree, secspacq) spacqtree; /* SP acquiring list */
155 #endif
156
157 #define SPLIST_ENTRY_INIT(sp) \
158 PSLIST_ENTRY_INIT((sp), pslist_entry)
159 #define SPLIST_ENTRY_DESTROY(sp) \
160 PSLIST_ENTRY_DESTROY((sp), pslist_entry)
161 #define SPLIST_WRITER_REMOVE(sp) \
162 PSLIST_WRITER_REMOVE((sp), pslist_entry)
163 #define SPLIST_READER_EMPTY(dir) \
164 (PSLIST_READER_FIRST(&sptree[(dir)], struct secpolicy, \
165 pslist_entry) == NULL)
166 #define SPLIST_READER_FOREACH(sp, dir) \
167 PSLIST_READER_FOREACH((sp), &sptree[(dir)], struct secpolicy, \
168 pslist_entry)
169 #define SPLIST_WRITER_FOREACH(sp, dir) \
170 PSLIST_WRITER_FOREACH((sp), &sptree[(dir)], struct secpolicy, \
171 pslist_entry)
172 #define SPLIST_WRITER_INSERT_AFTER(sp, new) \
173 PSLIST_WRITER_INSERT_AFTER((sp), (new), pslist_entry)
174 #define SPLIST_WRITER_EMPTY(dir) \
175 (PSLIST_WRITER_FIRST(&sptree[(dir)], struct secpolicy, \
176 pslist_entry) == NULL)
177 #define SPLIST_WRITER_INSERT_HEAD(dir, sp) \
178 PSLIST_WRITER_INSERT_HEAD(&sptree[(dir)], (sp), pslist_entry)
179 #define SPLIST_WRITER_NEXT(sp) \
180 PSLIST_WRITER_NEXT((sp), struct secpolicy, pslist_entry)
181 #define SPLIST_WRITER_INSERT_TAIL(dir, new) \
182 do { \
183 if (SPLIST_WRITER_EMPTY((dir))) { \
184 SPLIST_WRITER_INSERT_HEAD((dir), (new)); \
185 } else { \
186 struct secpolicy *__sp; \
187 SPLIST_WRITER_FOREACH(__sp, (dir)) { \
188 if (SPLIST_WRITER_NEXT(__sp) == NULL) { \
189 SPLIST_WRITER_INSERT_AFTER(__sp,\
190 (new)); \
191 break; \
192 } \
193 } \
194 } \
195 } while (0)
196
197 /*
198 * Protect regtree, acqtree and items stored in the lists.
199 */
200 static kmutex_t key_mtx __cacheline_aligned;
201
202 /* search order for SAs */
203 /*
204 * This order is important because we must select the oldest SA
205 * for outbound processing. For inbound, This is not important.
206 */
207 static const u_int saorder_state_valid_prefer_old[] = {
208 SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
209 };
210 static const u_int saorder_state_valid_prefer_new[] = {
211 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
212 };
213
214 static const u_int saorder_state_alive[] = {
215 /* except DEAD */
216 SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
217 };
218 static const u_int saorder_state_any[] = {
219 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
220 SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
221 };
222
223 #define SASTATE_ALIVE_FOREACH(s) \
224 for (int _i = 0; \
225 _i < __arraycount(saorder_state_alive) ? \
226 (s) = saorder_state_alive[_i], true : false; \
227 _i++)
228 #define SASTATE_ANY_FOREACH(s) \
229 for (int _i = 0; \
230 _i < __arraycount(saorder_state_any) ? \
231 (s) = saorder_state_any[_i], true : false; \
232 _i++)
233
234 static const int minsize[] = {
235 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
236 sizeof(struct sadb_sa), /* SADB_EXT_SA */
237 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
238 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
239 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
240 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_SRC */
241 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_DST */
242 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_PROXY */
243 sizeof(struct sadb_key), /* SADB_EXT_KEY_AUTH */
244 sizeof(struct sadb_key), /* SADB_EXT_KEY_ENCRYPT */
245 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_SRC */
246 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_DST */
247 sizeof(struct sadb_sens), /* SADB_EXT_SENSITIVITY */
248 sizeof(struct sadb_prop), /* SADB_EXT_PROPOSAL */
249 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_AUTH */
250 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_ENCRYPT */
251 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
252 0, /* SADB_X_EXT_KMPRIVATE */
253 sizeof(struct sadb_x_policy), /* SADB_X_EXT_POLICY */
254 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
255 sizeof(struct sadb_x_nat_t_type), /* SADB_X_EXT_NAT_T_TYPE */
256 sizeof(struct sadb_x_nat_t_port), /* SADB_X_EXT_NAT_T_SPORT */
257 sizeof(struct sadb_x_nat_t_port), /* SADB_X_EXT_NAT_T_DPORT */
258 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAI */
259 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAR */
260 sizeof(struct sadb_x_nat_t_frag), /* SADB_X_EXT_NAT_T_FRAG */
261 };
262 static const int maxsize[] = {
263 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
264 sizeof(struct sadb_sa), /* SADB_EXT_SA */
265 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
266 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
267 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
268 0, /* SADB_EXT_ADDRESS_SRC */
269 0, /* SADB_EXT_ADDRESS_DST */
270 0, /* SADB_EXT_ADDRESS_PROXY */
271 0, /* SADB_EXT_KEY_AUTH */
272 0, /* SADB_EXT_KEY_ENCRYPT */
273 0, /* SADB_EXT_IDENTITY_SRC */
274 0, /* SADB_EXT_IDENTITY_DST */
275 0, /* SADB_EXT_SENSITIVITY */
276 0, /* SADB_EXT_PROPOSAL */
277 0, /* SADB_EXT_SUPPORTED_AUTH */
278 0, /* SADB_EXT_SUPPORTED_ENCRYPT */
279 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
280 0, /* SADB_X_EXT_KMPRIVATE */
281 0, /* SADB_X_EXT_POLICY */
282 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
283 sizeof(struct sadb_x_nat_t_type), /* SADB_X_EXT_NAT_T_TYPE */
284 sizeof(struct sadb_x_nat_t_port), /* SADB_X_EXT_NAT_T_SPORT */
285 sizeof(struct sadb_x_nat_t_port), /* SADB_X_EXT_NAT_T_DPORT */
286 0, /* SADB_X_EXT_NAT_T_OAI */
287 0, /* SADB_X_EXT_NAT_T_OAR */
288 sizeof(struct sadb_x_nat_t_frag), /* SADB_X_EXT_NAT_T_FRAG */
289 };
290
291 static int ipsec_esp_keymin = 256;
292 static int ipsec_esp_auth = 0;
293 static int ipsec_ah_keymin = 128;
294
295 #ifdef SYSCTL_DECL
296 SYSCTL_DECL(_net_key);
297 #endif
298
299 #ifdef SYSCTL_INT
300 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug, CTLFLAG_RW, \
301 &key_debug_level, 0, "");
302
303 /* max count of trial for the decision of spi value */
304 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt, CTLFLAG_RW, \
305 &key_spi_trycnt, 0, "");
306
307 /* minimum spi value to allocate automatically. */
308 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval, CTLFLAG_RW, \
309 &key_spi_minval, 0, "");
310
311 /* maximun spi value to allocate automatically. */
312 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval, CTLFLAG_RW, \
313 &key_spi_maxval, 0, "");
314
315 /* interval to initialize randseed */
316 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random, CTLFLAG_RW, \
317 &key_int_random, 0, "");
318
319 /* lifetime for larval SA */
320 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime, CTLFLAG_RW, \
321 &key_larval_lifetime, 0, "");
322
323 /* counter for blocking to send SADB_ACQUIRE to IKEd */
324 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count, CTLFLAG_RW, \
325 &key_blockacq_count, 0, "");
326
327 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
328 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime, CTLFLAG_RW, \
329 &key_blockacq_lifetime, 0, "");
330
331 /* ESP auth */
332 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth, CTLFLAG_RW, \
333 &ipsec_esp_auth, 0, "");
334
335 /* minimum ESP key length */
336 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin, CTLFLAG_RW, \
337 &ipsec_esp_keymin, 0, "");
338
339 /* minimum AH key length */
340 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin, CTLFLAG_RW, \
341 &ipsec_ah_keymin, 0, "");
342
343 /* perfered old SA rather than new SA */
344 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, prefered_oldsa, CTLFLAG_RW,\
345 &key_prefered_oldsa, 0, "");
346 #endif /* SYSCTL_INT */
347
348 #define __LIST_CHAINED(elm) \
349 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
350 #define LIST_INSERT_TAIL(head, elm, type, field) \
351 do {\
352 struct type *curelm = LIST_FIRST(head); \
353 if (curelm == NULL) {\
354 LIST_INSERT_HEAD(head, elm, field); \
355 } else { \
356 while (LIST_NEXT(curelm, field)) \
357 curelm = LIST_NEXT(curelm, field);\
358 LIST_INSERT_AFTER(curelm, elm, field);\
359 }\
360 } while (0)
361
362 #define KEY_CHKSASTATE(head, sav) \
363 /* do */ { \
364 if ((head) != (sav)) { \
365 IPSECLOG(LOG_DEBUG, \
366 "state mismatched (TREE=%d SA=%d)\n", \
367 (head), (sav)); \
368 continue; \
369 } \
370 } /* while (0) */
371
372 #define KEY_CHKSPDIR(head, sp) \
373 do { \
374 if ((head) != (sp)) { \
375 IPSECLOG(LOG_DEBUG, \
376 "direction mismatched (TREE=%d SP=%d), anyway continue.\n",\
377 (head), (sp)); \
378 } \
379 } while (0)
380
381 /*
382 * set parameters into secasindex buffer.
383 * Must allocate secasindex buffer before calling this function.
384 */
385 static int
386 key_setsecasidx(int, int, int, const struct sockaddr *,
387 const struct sockaddr *, struct secasindex *);
388
389 /* key statistics */
390 struct _keystat {
391 u_long getspi_count; /* the avarage of count to try to get new SPI */
392 } keystat;
393
394 struct sadb_msghdr {
395 struct sadb_msg *msg;
396 struct sadb_ext *ext[SADB_EXT_MAX + 1];
397 int extoff[SADB_EXT_MAX + 1];
398 int extlen[SADB_EXT_MAX + 1];
399 };
400
401 static void
402 key_init_spidx_bymsghdr(struct secpolicyindex *, const struct sadb_msghdr *);
403
404 static const struct sockaddr *
405 key_msghdr_get_sockaddr(const struct sadb_msghdr *mhp, int idx)
406 {
407
408 return PFKEY_ADDR_SADDR((struct sadb_address *)mhp->ext[idx]);
409 }
410
411 static struct mbuf *
412 key_fill_replymsg(struct mbuf *m, int seq)
413 {
414 struct sadb_msg *msg;
415
416 if (m->m_len < sizeof(*msg)) {
417 m = m_pullup(m, sizeof(*msg));
418 if (m == NULL)
419 return NULL;
420 }
421 msg = mtod(m, struct sadb_msg *);
422 msg->sadb_msg_errno = 0;
423 msg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
424 if (seq != 0)
425 msg->sadb_msg_seq = seq;
426
427 return m;
428 }
429
430 static struct secasvar *key_lookup_sa_bysaidx(const struct secasindex *);
431 #if 0
432 static void key_freeso(struct socket *);
433 static void key_freesp_so(struct secpolicy **);
434 #endif
435 static void key_delsp (struct secpolicy *);
436 static struct secpolicy *key_getsp (const struct secpolicyindex *);
437 static struct secpolicy *key_getspbyid (u_int32_t);
438 static u_int16_t key_newreqid (void);
439 static struct mbuf *key_gather_mbuf (struct mbuf *,
440 const struct sadb_msghdr *, int, int, ...);
441 static int key_api_spdadd(struct socket *, struct mbuf *,
442 const struct sadb_msghdr *);
443 static u_int32_t key_getnewspid (void);
444 static int key_api_spddelete(struct socket *, struct mbuf *,
445 const struct sadb_msghdr *);
446 static int key_api_spddelete2(struct socket *, struct mbuf *,
447 const struct sadb_msghdr *);
448 static int key_api_spdget(struct socket *, struct mbuf *,
449 const struct sadb_msghdr *);
450 static int key_api_spdflush(struct socket *, struct mbuf *,
451 const struct sadb_msghdr *);
452 static int key_api_spddump(struct socket *, struct mbuf *,
453 const struct sadb_msghdr *);
454 static struct mbuf * key_setspddump (int *errorp, pid_t);
455 static struct mbuf * key_setspddump_chain (int *errorp, int *lenp, pid_t pid);
456 static int key_api_nat_map(struct socket *, struct mbuf *,
457 const struct sadb_msghdr *);
458 static struct mbuf *key_setdumpsp (struct secpolicy *,
459 u_int8_t, u_int32_t, pid_t);
460 static u_int key_getspreqmsglen (const struct secpolicy *);
461 static int key_spdexpire (struct secpolicy *);
462 static struct secashead *key_newsah (const struct secasindex *);
463 static void key_delsah (struct secashead *);
464 static struct secasvar *key_newsav(struct mbuf *,
465 const struct sadb_msghdr *, int *, const char*, int);
466 #define KEY_NEWSAV(m, sadb, e) \
467 key_newsav(m, sadb, e, __func__, __LINE__)
468 static void key_delsav (struct secasvar *);
469 static struct secashead *key_getsah(const struct secasindex *, int);
470 static bool key_checkspidup(const struct secasindex *, u_int32_t);
471 static struct secasvar *key_getsavbyspi (struct secashead *, u_int32_t);
472 static int key_setsaval (struct secasvar *, struct mbuf *,
473 const struct sadb_msghdr *);
474 static void key_freesaval(struct secasvar *);
475 static int key_init_xform(struct secasvar *);
476 static void key_clear_xform(struct secasvar *);
477 static struct mbuf *key_setdumpsa (struct secasvar *, u_int8_t,
478 u_int8_t, u_int32_t, u_int32_t);
479 static struct mbuf *key_setsadbxport (u_int16_t, u_int16_t);
480 static struct mbuf *key_setsadbxtype (u_int16_t);
481 static struct mbuf *key_setsadbxfrag (u_int16_t);
482 static void key_porttosaddr (union sockaddr_union *, u_int16_t);
483 static int key_checksalen (const union sockaddr_union *);
484 static struct mbuf *key_setsadbmsg (u_int8_t, u_int16_t, u_int8_t,
485 u_int32_t, pid_t, u_int16_t);
486 static struct mbuf *key_setsadbsa (struct secasvar *);
487 static struct mbuf *key_setsadbaddr (u_int16_t,
488 const struct sockaddr *, u_int8_t, u_int16_t);
489 #if 0
490 static struct mbuf *key_setsadbident (u_int16_t, u_int16_t, void *,
491 int, u_int64_t);
492 #endif
493 static struct mbuf *key_setsadbxsa2 (u_int8_t, u_int32_t, u_int16_t);
494 static struct mbuf *key_setsadbxpolicy (u_int16_t, u_int8_t,
495 u_int32_t);
496 static void *key_newbuf (const void *, u_int);
497 #ifdef INET6
498 static int key_ismyaddr6 (const struct sockaddr_in6 *);
499 #endif
500
501 static void sysctl_net_keyv2_setup(struct sysctllog **);
502 static void sysctl_net_key_compat_setup(struct sysctllog **);
503
504 /* flags for key_saidx_match() */
505 #define CMP_HEAD 1 /* protocol, addresses. */
506 #define CMP_MODE_REQID 2 /* additionally HEAD, reqid, mode. */
507 #define CMP_REQID 3 /* additionally HEAD, reaid. */
508 #define CMP_EXACTLY 4 /* all elements. */
509 static int key_saidx_match(const struct secasindex *,
510 const struct secasindex *, int);
511
512 static int key_sockaddr_match(const struct sockaddr *,
513 const struct sockaddr *, int);
514 static int key_bb_match_withmask(const void *, const void *, u_int);
515 static u_int16_t key_satype2proto (u_int8_t);
516 static u_int8_t key_proto2satype (u_int16_t);
517
518 static int key_spidx_match_exactly(const struct secpolicyindex *,
519 const struct secpolicyindex *);
520 static int key_spidx_match_withmask(const struct secpolicyindex *,
521 const struct secpolicyindex *);
522
523 static int key_api_getspi(struct socket *, struct mbuf *,
524 const struct sadb_msghdr *);
525 static u_int32_t key_do_getnewspi (const struct sadb_spirange *,
526 const struct secasindex *);
527 static int key_handle_natt_info (struct secasvar *,
528 const struct sadb_msghdr *);
529 static int key_set_natt_ports (union sockaddr_union *,
530 union sockaddr_union *,
531 const struct sadb_msghdr *);
532 static int key_api_update(struct socket *, struct mbuf *,
533 const struct sadb_msghdr *);
534 #ifdef IPSEC_DOSEQCHECK
535 static struct secasvar *key_getsavbyseq (struct secashead *, u_int32_t);
536 #endif
537 static int key_api_add(struct socket *, struct mbuf *,
538 const struct sadb_msghdr *);
539 static int key_setident (struct secashead *, struct mbuf *,
540 const struct sadb_msghdr *);
541 static struct mbuf *key_getmsgbuf_x1 (struct mbuf *,
542 const struct sadb_msghdr *);
543 static int key_api_delete(struct socket *, struct mbuf *,
544 const struct sadb_msghdr *);
545 static int key_api_get(struct socket *, struct mbuf *,
546 const struct sadb_msghdr *);
547
548 static void key_getcomb_setlifetime (struct sadb_comb *);
549 static struct mbuf *key_getcomb_esp (void);
550 static struct mbuf *key_getcomb_ah (void);
551 static struct mbuf *key_getcomb_ipcomp (void);
552 static struct mbuf *key_getprop (const struct secasindex *);
553
554 static int key_acquire (const struct secasindex *, struct secpolicy *);
555 #ifndef IPSEC_NONBLOCK_ACQUIRE
556 static struct secacq *key_newacq (const struct secasindex *);
557 static struct secacq *key_getacq (const struct secasindex *);
558 static struct secacq *key_getacqbyseq (u_int32_t);
559 #endif
560 #ifdef notyet
561 static struct secspacq *key_newspacq (const struct secpolicyindex *);
562 static struct secspacq *key_getspacq (const struct secpolicyindex *);
563 #endif
564 static int key_api_acquire(struct socket *, struct mbuf *,
565 const struct sadb_msghdr *);
566 static int key_api_register(struct socket *, struct mbuf *,
567 const struct sadb_msghdr *);
568 static int key_expire (struct secasvar *);
569 static int key_api_flush(struct socket *, struct mbuf *,
570 const struct sadb_msghdr *);
571 static struct mbuf *key_setdump_chain (u_int8_t req_satype, int *errorp,
572 int *lenp, pid_t pid);
573 static int key_api_dump(struct socket *, struct mbuf *,
574 const struct sadb_msghdr *);
575 static int key_api_promisc(struct socket *, struct mbuf *,
576 const struct sadb_msghdr *);
577 static int key_senderror (struct socket *, struct mbuf *, int);
578 static int key_validate_ext (const struct sadb_ext *, int);
579 static int key_align (struct mbuf *, struct sadb_msghdr *);
580 #if 0
581 static const char *key_getfqdn (void);
582 static const char *key_getuserfqdn (void);
583 #endif
584 static void key_sa_chgstate (struct secasvar *, u_int8_t);
585 static inline void key_sp_dead (struct secpolicy *);
586 static void key_sp_unlink (struct secpolicy *sp);
587
588 static struct mbuf *key_alloc_mbuf (int);
589
590 static void key_timehandler(void *);
591 static void key_timehandler_work(struct work *, void *);
592 static struct callout key_timehandler_ch;
593 static struct workqueue *key_timehandler_wq;
594 static struct work key_timehandler_wk;
595
596 #ifdef IPSEC_REF_DEBUG
597 #define REFLOG(label, p, where, tag) \
598 log(LOG_DEBUG, "%s:%d: " label " : refcnt=%d (%p)\n.", \
599 (where), (tag), (p)->refcnt, (p))
600 #else
601 #define REFLOG(label, p, where, tag) do {} while (0)
602 #endif
603
604 #define SA_ADDREF(p) do { \
605 atomic_inc_uint(&(p)->refcnt); \
606 REFLOG("SA_ADDREF", (p), __func__, __LINE__); \
607 KASSERTMSG((p)->refcnt != 0, "SA refcnt overflow"); \
608 } while (0)
609 #define SA_ADDREF2(p, where, tag) do { \
610 atomic_inc_uint(&(p)->refcnt); \
611 REFLOG("SA_ADDREF", (p), (where), (tag)); \
612 KASSERTMSG((p)->refcnt != 0, "SA refcnt overflow"); \
613 } while (0)
614 #define SA_DELREF(p) do { \
615 KASSERTMSG((p)->refcnt > 0, "SA refcnt underflow"); \
616 atomic_dec_uint(&(p)->refcnt); \
617 REFLOG("SA_DELREF", (p), __func__, __LINE__); \
618 } while (0)
619 #define SA_DELREF2(p, nv, where, tag) do { \
620 KASSERTMSG((p)->refcnt > 0, "SA refcnt underflow"); \
621 nv = atomic_dec_uint_nv(&(p)->refcnt); \
622 REFLOG("SA_DELREF", (p), (where), (tag)); \
623 } while (0)
624
625 #define SP_ADDREF(p) do { \
626 atomic_inc_uint(&(p)->refcnt); \
627 REFLOG("SP_ADDREF", (p), __func__, __LINE__); \
628 KASSERTMSG((p)->refcnt != 0, "SP refcnt overflow"); \
629 } while (0)
630 #define SP_ADDREF2(p, where, tag) do { \
631 atomic_inc_uint(&(p)->refcnt); \
632 REFLOG("SP_ADDREF", (p), (where), (tag)); \
633 KASSERTMSG((p)->refcnt != 0, "SP refcnt overflow"); \
634 } while (0)
635 #define SP_DELREF(p) do { \
636 KASSERTMSG((p)->refcnt > 0, "SP refcnt underflow"); \
637 atomic_dec_uint(&(p)->refcnt); \
638 REFLOG("SP_DELREF", (p), __func__, __LINE__); \
639 } while (0)
640 #define SP_DELREF2(p, nv, where, tag) do { \
641 KASSERTMSG((p)->refcnt > 0, "SP refcnt underflow"); \
642 nv = atomic_dec_uint_nv(&(p)->refcnt); \
643 REFLOG("SP_DELREF", (p), (where), (tag)); \
644 } while (0)
645
646 u_int
647 key_sp_refcnt(const struct secpolicy *sp)
648 {
649
650 if (sp == NULL)
651 return 0;
652
653 return sp->refcnt;
654 }
655
656 static inline void
657 key_sp_dead(struct secpolicy *sp)
658 {
659
660 /* mark the SP dead */
661 sp->state = IPSEC_SPSTATE_DEAD;
662 }
663
664 static void
665 key_sp_unlink(struct secpolicy *sp)
666 {
667
668 /* remove from SP index */
669 SPLIST_WRITER_REMOVE(sp);
670 /* Release refcount held just for being on chain */
671 KEY_FREESP(&sp);
672 }
673
674
675 /*
676 * Return 0 when there are known to be no SP's for the specified
677 * direction. Otherwise return 1. This is used by IPsec code
678 * to optimize performance.
679 */
680 int
681 key_havesp(u_int dir)
682 {
683 return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
684 !SPLIST_READER_EMPTY(dir) : 1);
685 }
686
687 /* %%% IPsec policy management */
688 /*
689 * allocating a SP for OUTBOUND or INBOUND packet.
690 * Must call key_freesp() later.
691 * OUT: NULL: not found
692 * others: found and return the pointer.
693 */
694 struct secpolicy *
695 key_lookup_sp_byspidx(const struct secpolicyindex *spidx,
696 u_int dir, const char* where, int tag)
697 {
698 struct secpolicy *sp;
699 int s;
700
701 KASSERT(spidx != NULL);
702 KASSERTMSG(IPSEC_DIR_IS_INOROUT(dir), "invalid direction %u", dir);
703
704 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
705
706 /* get a SP entry */
707 s = splsoftnet(); /*called from softclock()*/
708 if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
709 printf("*** objects\n");
710 kdebug_secpolicyindex(spidx);
711 }
712
713 SPLIST_READER_FOREACH(sp, dir) {
714 if (KEYDEBUG_ON(KEYDEBUG_IPSEC_DATA)) {
715 printf("*** in SPD\n");
716 kdebug_secpolicyindex(&sp->spidx);
717 }
718
719 if (sp->state == IPSEC_SPSTATE_DEAD)
720 continue;
721 if (key_spidx_match_withmask(&sp->spidx, spidx))
722 goto found;
723 }
724 sp = NULL;
725 found:
726 if (sp) {
727 /* sanity check */
728 KEY_CHKSPDIR(sp->spidx.dir, dir);
729
730 /* found a SPD entry */
731 sp->lastused = time_uptime;
732 SP_ADDREF2(sp, where, tag);
733 }
734 splx(s);
735
736 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
737 "DP return SP:%p (ID=%u) refcnt %u\n",
738 sp, sp ? sp->id : 0, key_sp_refcnt(sp));
739 return sp;
740 }
741
742 /*
743 * return a policy that matches this particular inbound packet.
744 * XXX slow
745 */
746 struct secpolicy *
747 key_gettunnel(const struct sockaddr *osrc,
748 const struct sockaddr *odst,
749 const struct sockaddr *isrc,
750 const struct sockaddr *idst,
751 const char* where, int tag)
752 {
753 struct secpolicy *sp;
754 const int dir = IPSEC_DIR_INBOUND;
755 int s;
756 struct ipsecrequest *r1, *r2, *p;
757 struct secpolicyindex spidx;
758
759 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP, "DP from %s:%u\n", where, tag);
760
761 if (isrc->sa_family != idst->sa_family) {
762 IPSECLOG(LOG_ERR, "protocol family mismatched %d != %d\n.",
763 isrc->sa_family, idst->sa_family);
764 sp = NULL;
765 goto done;
766 }
767
768 s = splsoftnet(); /*called from softclock()*/
769 SPLIST_READER_FOREACH(sp, dir) {
770 if (sp->state == IPSEC_SPSTATE_DEAD)
771 continue;
772
773 r1 = r2 = NULL;
774 for (p = sp->req; p; p = p->next) {
775 if (p->saidx.mode != IPSEC_MODE_TUNNEL)
776 continue;
777
778 r1 = r2;
779 r2 = p;
780
781 if (!r1) {
782 /* here we look at address matches only */
783 spidx = sp->spidx;
784 if (isrc->sa_len > sizeof(spidx.src) ||
785 idst->sa_len > sizeof(spidx.dst))
786 continue;
787 memcpy(&spidx.src, isrc, isrc->sa_len);
788 memcpy(&spidx.dst, idst, idst->sa_len);
789 if (!key_spidx_match_withmask(&sp->spidx, &spidx))
790 continue;
791 } else {
792 if (!key_sockaddr_match(&r1->saidx.src.sa, isrc, PORT_NONE) ||
793 !key_sockaddr_match(&r1->saidx.dst.sa, idst, PORT_NONE))
794 continue;
795 }
796
797 if (!key_sockaddr_match(&r2->saidx.src.sa, osrc, PORT_NONE) ||
798 !key_sockaddr_match(&r2->saidx.dst.sa, odst, PORT_NONE))
799 continue;
800
801 goto found;
802 }
803 }
804 sp = NULL;
805 found:
806 if (sp) {
807 sp->lastused = time_uptime;
808 SP_ADDREF2(sp, where, tag);
809 }
810 splx(s);
811 done:
812 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
813 "DP return SP:%p (ID=%u) refcnt %u\n",
814 sp, sp ? sp->id : 0, key_sp_refcnt(sp));
815 return sp;
816 }
817
818 /*
819 * allocating an SA entry for an *OUTBOUND* packet.
820 * checking each request entries in SP, and acquire an SA if need.
821 * OUT: 0: there are valid requests.
822 * ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
823 */
824 int
825 key_checkrequest(struct ipsecrequest *isr, struct secasvar **ret)
826 {
827 u_int level;
828 int error;
829 const struct secasindex *saidx = &isr->saidx;
830 struct secasvar *sav;
831
832 KASSERT(isr != NULL);
833 KASSERTMSG(saidx->mode == IPSEC_MODE_TRANSPORT ||
834 saidx->mode == IPSEC_MODE_TUNNEL,
835 "unexpected policy %u", saidx->mode);
836
837 /* get current level */
838 level = ipsec_get_reqlevel(isr);
839
840 /*
841 * XXX guard against protocol callbacks from the crypto
842 * thread as they reference ipsecrequest.sav which we
843 * temporarily null out below. Need to rethink how we
844 * handle bundled SA's in the callback thread.
845 */
846 IPSEC_SPLASSERT_SOFTNET("key_checkrequest");
847
848 sav = key_lookup_sa_bysaidx(saidx);
849 if (sav != NULL) {
850 *ret = sav;
851 return 0;
852 }
853
854 /* there is no SA */
855 error = key_acquire(saidx, isr->sp);
856 if (error != 0) {
857 /* XXX What should I do ? */
858 IPSECLOG(LOG_DEBUG, "error %d returned from key_acquire.\n",
859 error);
860 return error;
861 }
862
863 if (level != IPSEC_LEVEL_REQUIRE) {
864 /* XXX sigh, the interface to this routine is botched */
865 *ret = NULL;
866 return 0;
867 } else {
868 return ENOENT;
869 }
870 }
871
872 /*
873 * looking up a SA for policy entry from SAD.
874 * NOTE: searching SAD of aliving state.
875 * OUT: NULL: not found.
876 * others: found and return the pointer.
877 */
878 static struct secasvar *
879 key_lookup_sa_bysaidx(const struct secasindex *saidx)
880 {
881 struct secashead *sah;
882 struct secasvar *sav;
883 u_int stateidx, state;
884 const u_int *saorder_state_valid;
885 int arraysize;
886
887 sah = key_getsah(saidx, CMP_MODE_REQID);
888 if (sah == NULL)
889 return NULL;
890
891 /*
892 * search a valid state list for outbound packet.
893 * This search order is important.
894 */
895 if (key_prefered_oldsa) {
896 saorder_state_valid = saorder_state_valid_prefer_old;
897 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
898 } else {
899 saorder_state_valid = saorder_state_valid_prefer_new;
900 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
901 }
902
903 /* search valid state */
904 for (stateidx = 0;
905 stateidx < arraysize;
906 stateidx++) {
907
908 state = saorder_state_valid[stateidx];
909
910 if (key_prefered_oldsa)
911 sav = LIST_FIRST(&sah->savtree[state]);
912 else {
913 /* XXX need O(1) lookup */
914 struct secasvar *last = NULL;
915
916 LIST_FOREACH(sav, &sah->savtree[state], chain)
917 last = sav;
918 sav = last;
919 }
920 if (sav != NULL) {
921 SA_ADDREF(sav);
922 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
923 "DP cause refcnt++:%d SA:%p\n",
924 sav->refcnt, sav);
925 return sav;
926 }
927 }
928
929 return NULL;
930 }
931
932 #if 0
933 static void
934 key_sendup_message_delete(struct secasvar *sav)
935 {
936 struct mbuf *m, *result = 0;
937 uint8_t satype;
938
939 satype = key_proto2satype(sav->sah->saidx.proto);
940 if (satype == 0)
941 goto msgfail;
942
943 m = key_setsadbmsg(SADB_DELETE, 0, satype, 0, 0, sav->refcnt - 1);
944 if (m == NULL)
945 goto msgfail;
946 result = m;
947
948 /* set sadb_address for saidx's. */
949 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &sav->sah->saidx.src.sa,
950 sav->sah->saidx.src.sa.sa_len << 3, IPSEC_ULPROTO_ANY);
951 if (m == NULL)
952 goto msgfail;
953 m_cat(result, m);
954
955 /* set sadb_address for saidx's. */
956 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &sav->sah->saidx.src.sa,
957 sav->sah->saidx.src.sa.sa_len << 3, IPSEC_ULPROTO_ANY);
958 if (m == NULL)
959 goto msgfail;
960 m_cat(result, m);
961
962 /* create SA extension */
963 m = key_setsadbsa(sav);
964 if (m == NULL)
965 goto msgfail;
966 m_cat(result, m);
967
968 if (result->m_len < sizeof(struct sadb_msg)) {
969 result = m_pullup(result, sizeof(struct sadb_msg));
970 if (result == NULL)
971 goto msgfail;
972 }
973
974 result->m_pkthdr.len = 0;
975 for (m = result; m; m = m->m_next)
976 result->m_pkthdr.len += m->m_len;
977 mtod(result, struct sadb_msg *)->sadb_msg_len =
978 PFKEY_UNIT64(result->m_pkthdr.len);
979
980 key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
981 result = NULL;
982 msgfail:
983 if (result)
984 m_freem(result);
985 }
986 #endif
987
988 /*
989 * allocating a usable SA entry for a *INBOUND* packet.
990 * Must call key_freesav() later.
991 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
992 * NULL: not found, or error occurred.
993 *
994 * In the comparison, no source address is used--for RFC2401 conformance.
995 * To quote, from section 4.1:
996 * A security association is uniquely identified by a triple consisting
997 * of a Security Parameter Index (SPI), an IP Destination Address, and a
998 * security protocol (AH or ESP) identifier.
999 * Note that, however, we do need to keep source address in IPsec SA.
1000 * IKE specification and PF_KEY specification do assume that we
1001 * keep source address in IPsec SA. We see a tricky situation here.
1002 *
1003 * sport and dport are used for NAT-T. network order is always used.
1004 */
1005 struct secasvar *
1006 key_lookup_sa(
1007 const union sockaddr_union *dst,
1008 u_int proto,
1009 u_int32_t spi,
1010 u_int16_t sport,
1011 u_int16_t dport,
1012 const char* where, int tag)
1013 {
1014 struct secashead *sah;
1015 struct secasvar *sav;
1016 u_int stateidx, state;
1017 const u_int *saorder_state_valid;
1018 int arraysize, chkport;
1019 int s;
1020
1021 int must_check_spi = 1;
1022 int must_check_alg = 0;
1023 u_int16_t cpi = 0;
1024 u_int8_t algo = 0;
1025
1026 if ((sport != 0) && (dport != 0))
1027 chkport = PORT_STRICT;
1028 else
1029 chkport = PORT_NONE;
1030
1031 KASSERT(dst != NULL);
1032
1033 /*
1034 * XXX IPCOMP case
1035 * We use cpi to define spi here. In the case where cpi <=
1036 * IPCOMP_CPI_NEGOTIATE_MIN, cpi just define the algorithm used, not
1037 * the real spi. In this case, don't check the spi but check the
1038 * algorithm
1039 */
1040
1041 if (proto == IPPROTO_IPCOMP) {
1042 u_int32_t tmp;
1043 tmp = ntohl(spi);
1044 cpi = (u_int16_t) tmp;
1045 if (cpi < IPCOMP_CPI_NEGOTIATE_MIN) {
1046 algo = (u_int8_t) cpi;
1047 must_check_spi = 0;
1048 must_check_alg = 1;
1049 }
1050 }
1051 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
1052 "DP from %s:%u check_spi=%d, check_alg=%d\n",
1053 where, tag, must_check_spi, must_check_alg);
1054
1055
1056 /*
1057 * searching SAD.
1058 * XXX: to be checked internal IP header somewhere. Also when
1059 * IPsec tunnel packet is received. But ESP tunnel mode is
1060 * encrypted so we can't check internal IP header.
1061 */
1062 s = splsoftnet(); /*called from softclock()*/
1063 if (key_prefered_oldsa) {
1064 saorder_state_valid = saorder_state_valid_prefer_old;
1065 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1066 } else {
1067 saorder_state_valid = saorder_state_valid_prefer_new;
1068 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1069 }
1070 LIST_FOREACH(sah, &sahtree, chain) {
1071 /* search valid state */
1072 for (stateidx = 0; stateidx < arraysize; stateidx++) {
1073 state = saorder_state_valid[stateidx];
1074 LIST_FOREACH(sav, &sah->savtree[state], chain) {
1075 KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
1076 "try match spi %#x, %#x\n",
1077 ntohl(spi), ntohl(sav->spi));
1078 /* sanity check */
1079 KEY_CHKSASTATE(sav->state, state);
1080 /* do not return entries w/ unusable state */
1081 if (!SADB_SASTATE_USABLE_P(sav)) {
1082 KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
1083 "bad state %d\n", sav->state);
1084 continue;
1085 }
1086 if (proto != sav->sah->saidx.proto) {
1087 KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
1088 "proto fail %d != %d\n",
1089 proto, sav->sah->saidx.proto);
1090 continue;
1091 }
1092 if (must_check_spi && spi != sav->spi) {
1093 KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
1094 "spi fail %#x != %#x\n",
1095 ntohl(spi), ntohl(sav->spi));
1096 continue;
1097 }
1098 /* XXX only on the ipcomp case */
1099 if (must_check_alg && algo != sav->alg_comp) {
1100 KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
1101 "algo fail %d != %d\n",
1102 algo, sav->alg_comp);
1103 continue;
1104 }
1105
1106 #if 0 /* don't check src */
1107 /* Fix port in src->sa */
1108
1109 /* check src address */
1110 if (!key_sockaddr_match(&src->sa, &sav->sah->saidx.src.sa, PORT_NONE))
1111 continue;
1112 #endif
1113 /* fix port of dst address XXX*/
1114 key_porttosaddr(__UNCONST(dst), dport);
1115 /* check dst address */
1116 if (!key_sockaddr_match(&dst->sa, &sav->sah->saidx.dst.sa, chkport))
1117 continue;
1118 SA_ADDREF2(sav, where, tag);
1119 goto done;
1120 }
1121 }
1122 }
1123 sav = NULL;
1124 done:
1125 splx(s);
1126
1127 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
1128 "DP return SA:%p; refcnt %u\n", sav, sav ? sav->refcnt : 0);
1129 return sav;
1130 }
1131
1132 static void
1133 key_validate_savlist(const struct secashead *sah, const u_int state)
1134 {
1135 #ifdef DEBUG
1136 struct secasvar *sav, *next;
1137
1138 /*
1139 * The list should be sorted by lft_c->sadb_lifetime_addtime
1140 * in ascending order.
1141 */
1142 LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, next) {
1143 if (next != NULL &&
1144 sav->lft_c != NULL && next->lft_c != NULL) {
1145 KDASSERTMSG(sav->lft_c->sadb_lifetime_addtime <=
1146 next->lft_c->sadb_lifetime_addtime,
1147 "savlist is not sorted: sah=%p, state=%d, "
1148 "sav=%" PRIu64 ", next=%" PRIu64, sah, state,
1149 sav->lft_c->sadb_lifetime_addtime,
1150 next->lft_c->sadb_lifetime_addtime);
1151 }
1152 }
1153 #endif
1154 }
1155
1156 void
1157 key_sp_ref(struct secpolicy *sp, const char* where, int tag)
1158 {
1159
1160 SP_ADDREF2(sp, where, tag);
1161
1162 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
1163 "DP SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1164 sp, sp->id, where, tag, key_sp_refcnt(sp));
1165 }
1166
1167 void
1168 key_sa_ref(struct secasvar *sav, const char* where, int tag)
1169 {
1170
1171 SA_ADDREF2(sav, where, tag);
1172
1173 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
1174 "DP cause refcnt++:%d SA:%p from %s:%u\n",
1175 sav->refcnt, sav, where, tag);
1176 }
1177
1178 /*
1179 * Must be called after calling key_lookup_sp*().
1180 * For both the packet without socket and key_freeso().
1181 */
1182 void
1183 _key_freesp(struct secpolicy **spp, const char* where, int tag)
1184 {
1185 struct secpolicy *sp = *spp;
1186 unsigned int nv;
1187
1188 KASSERT(sp != NULL);
1189
1190 SP_DELREF2(sp, nv, where, tag);
1191
1192 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
1193 "DP SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1194 sp, sp->id, where, tag, nv);
1195
1196 if (nv == 0) {
1197 *spp = NULL;
1198 key_delsp(sp);
1199 }
1200 }
1201
1202 #if 0
1203 /*
1204 * Must be called after calling key_lookup_sp*().
1205 * For the packet with socket.
1206 */
1207 static void
1208 key_freeso(struct socket *so)
1209 {
1210 /* sanity check */
1211 KASSERT(so != NULL);
1212
1213 switch (so->so_proto->pr_domain->dom_family) {
1214 #ifdef INET
1215 case PF_INET:
1216 {
1217 struct inpcb *pcb = sotoinpcb(so);
1218
1219 /* Does it have a PCB ? */
1220 if (pcb == NULL)
1221 return;
1222
1223 struct inpcbpolicy *sp = pcb->inp_sp;
1224 key_freesp_so(&sp->sp_in);
1225 key_freesp_so(&sp->sp_out);
1226 }
1227 break;
1228 #endif
1229 #ifdef INET6
1230 case PF_INET6:
1231 {
1232 #ifdef HAVE_NRL_INPCB
1233 struct inpcb *pcb = sotoinpcb(so);
1234 struct inpcbpolicy *sp = pcb->inp_sp;
1235
1236 /* Does it have a PCB ? */
1237 if (pcb == NULL)
1238 return;
1239 key_freesp_so(&sp->sp_in);
1240 key_freesp_so(&sp->sp_out);
1241 #else
1242 struct in6pcb *pcb = sotoin6pcb(so);
1243
1244 /* Does it have a PCB ? */
1245 if (pcb == NULL)
1246 return;
1247 key_freesp_so(&pcb->in6p_sp->sp_in);
1248 key_freesp_so(&pcb->in6p_sp->sp_out);
1249 #endif
1250 }
1251 break;
1252 #endif /* INET6 */
1253 default:
1254 IPSECLOG(LOG_DEBUG, "unknown address family=%d.\n",
1255 so->so_proto->pr_domain->dom_family);
1256 return;
1257 }
1258 }
1259
1260 static void
1261 key_freesp_so(struct secpolicy **sp)
1262 {
1263
1264 KASSERT(sp != NULL);
1265 KASSERT(*sp != NULL);
1266
1267 if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1268 (*sp)->policy == IPSEC_POLICY_BYPASS)
1269 return;
1270
1271 KASSERTMSG((*sp)->policy == IPSEC_POLICY_IPSEC,
1272 "invalid policy %u", (*sp)->policy);
1273 KEY_FREESP(sp);
1274 }
1275 #endif
1276
1277 /*
1278 * Must be called after calling key_lookup_sa().
1279 * This function is called by key_freesp() to free some SA allocated
1280 * for a policy.
1281 */
1282 void
1283 key_freesav(struct secasvar **psav, const char* where, int tag)
1284 {
1285 struct secasvar *sav = *psav;
1286 unsigned int nv;
1287
1288 KASSERT(sav != NULL);
1289
1290 SA_DELREF2(sav, nv, where, tag);
1291
1292 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
1293 "DP SA:%p (SPI %lu) from %s:%u; refcnt now %u\n",
1294 sav, (u_long)ntohl(sav->spi), where, tag, nv);
1295
1296 if (nv == 0) {
1297 *psav = NULL;
1298
1299 /* remove from SA header */
1300 KASSERT(__LIST_CHAINED(sav));
1301 LIST_REMOVE(sav, chain);
1302
1303 key_delsav(sav);
1304 }
1305 }
1306
1307 /* %%% SPD management */
1308 /*
1309 * free security policy entry.
1310 */
1311 static void
1312 key_delsp(struct secpolicy *sp)
1313 {
1314 int s;
1315
1316 KASSERT(sp != NULL);
1317
1318 key_sp_dead(sp);
1319
1320 KASSERTMSG(sp->refcnt == 0,
1321 "SP with references deleted (refcnt %u)", sp->refcnt);
1322
1323 s = splsoftnet(); /*called from softclock()*/
1324
1325 {
1326 struct ipsecrequest *isr = sp->req, *nextisr;
1327
1328 while (isr != NULL) {
1329 nextisr = isr->next;
1330 kmem_intr_free(isr, sizeof(*isr));
1331 isr = nextisr;
1332 }
1333 }
1334
1335 SPLIST_ENTRY_DESTROY(sp);
1336 kmem_intr_free(sp, sizeof(*sp));
1337
1338 splx(s);
1339 }
1340
1341 /*
1342 * search SPD
1343 * OUT: NULL : not found
1344 * others : found, pointer to a SP.
1345 */
1346 static struct secpolicy *
1347 key_getsp(const struct secpolicyindex *spidx)
1348 {
1349 struct secpolicy *sp;
1350
1351 KASSERT(spidx != NULL);
1352
1353 SPLIST_READER_FOREACH(sp, spidx->dir) {
1354 if (sp->state == IPSEC_SPSTATE_DEAD)
1355 continue;
1356 if (key_spidx_match_exactly(spidx, &sp->spidx)) {
1357 SP_ADDREF(sp);
1358 return sp;
1359 }
1360 }
1361
1362 return NULL;
1363 }
1364
1365 /*
1366 * get SP by index.
1367 * OUT: NULL : not found
1368 * others : found, pointer to a SP.
1369 */
1370 static struct secpolicy *
1371 key_getspbyid(u_int32_t id)
1372 {
1373 struct secpolicy *sp;
1374
1375 SPLIST_READER_FOREACH(sp, IPSEC_DIR_INBOUND) {
1376 if (sp->state == IPSEC_SPSTATE_DEAD)
1377 continue;
1378 if (sp->id == id) {
1379 SP_ADDREF(sp);
1380 return sp;
1381 }
1382 }
1383
1384 SPLIST_READER_FOREACH(sp, IPSEC_DIR_OUTBOUND) {
1385 if (sp->state == IPSEC_SPSTATE_DEAD)
1386 continue;
1387 if (sp->id == id) {
1388 SP_ADDREF(sp);
1389 return sp;
1390 }
1391 }
1392
1393 return NULL;
1394 }
1395
1396 struct secpolicy *
1397 key_newsp(const char* where, int tag)
1398 {
1399 struct secpolicy *newsp = NULL;
1400
1401 newsp = kmem_intr_zalloc(sizeof(struct secpolicy), KM_NOSLEEP);
1402 if (newsp != NULL)
1403 newsp->refcnt = 1;
1404
1405 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
1406 "DP from %s:%u return SP:%p\n", where, tag, newsp);
1407 return newsp;
1408 }
1409
1410 /*
1411 * create secpolicy structure from sadb_x_policy structure.
1412 * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1413 * so must be set properly later.
1414 */
1415 struct secpolicy *
1416 key_msg2sp(const struct sadb_x_policy *xpl0, size_t len, int *error)
1417 {
1418 struct secpolicy *newsp;
1419
1420 KASSERT(!cpu_softintr_p());
1421 KASSERT(xpl0 != NULL);
1422 KASSERT(len >= sizeof(*xpl0));
1423
1424 if (len != PFKEY_EXTLEN(xpl0)) {
1425 IPSECLOG(LOG_DEBUG, "Invalid msg length.\n");
1426 *error = EINVAL;
1427 return NULL;
1428 }
1429
1430 newsp = KEY_NEWSP();
1431 if (newsp == NULL) {
1432 *error = ENOBUFS;
1433 return NULL;
1434 }
1435
1436 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1437 newsp->policy = xpl0->sadb_x_policy_type;
1438
1439 /* check policy */
1440 switch (xpl0->sadb_x_policy_type) {
1441 case IPSEC_POLICY_DISCARD:
1442 case IPSEC_POLICY_NONE:
1443 case IPSEC_POLICY_ENTRUST:
1444 case IPSEC_POLICY_BYPASS:
1445 newsp->req = NULL;
1446 *error = 0;
1447 return newsp;
1448
1449 case IPSEC_POLICY_IPSEC:
1450 /* Continued */
1451 break;
1452 default:
1453 IPSECLOG(LOG_DEBUG, "invalid policy type.\n");
1454 KEY_FREESP(&newsp);
1455 *error = EINVAL;
1456 return NULL;
1457 }
1458
1459 /* IPSEC_POLICY_IPSEC */
1460 {
1461 int tlen;
1462 const struct sadb_x_ipsecrequest *xisr;
1463 uint16_t xisr_reqid;
1464 struct ipsecrequest **p_isr = &newsp->req;
1465
1466 /* validity check */
1467 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1468 IPSECLOG(LOG_DEBUG, "Invalid msg length.\n");
1469 *error = EINVAL;
1470 goto free_exit;
1471 }
1472
1473 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1474 xisr = (const struct sadb_x_ipsecrequest *)(xpl0 + 1);
1475
1476 while (tlen > 0) {
1477 /* length check */
1478 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1479 IPSECLOG(LOG_DEBUG, "invalid ipsecrequest length.\n");
1480 *error = EINVAL;
1481 goto free_exit;
1482 }
1483
1484 /* allocate request buffer */
1485 *p_isr = kmem_zalloc(sizeof(**p_isr), KM_SLEEP);
1486
1487 /* set values */
1488 (*p_isr)->next = NULL;
1489
1490 switch (xisr->sadb_x_ipsecrequest_proto) {
1491 case IPPROTO_ESP:
1492 case IPPROTO_AH:
1493 case IPPROTO_IPCOMP:
1494 break;
1495 default:
1496 IPSECLOG(LOG_DEBUG, "invalid proto type=%u\n",
1497 xisr->sadb_x_ipsecrequest_proto);
1498 *error = EPROTONOSUPPORT;
1499 goto free_exit;
1500 }
1501 (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1502
1503 switch (xisr->sadb_x_ipsecrequest_mode) {
1504 case IPSEC_MODE_TRANSPORT:
1505 case IPSEC_MODE_TUNNEL:
1506 break;
1507 case IPSEC_MODE_ANY:
1508 default:
1509 IPSECLOG(LOG_DEBUG, "invalid mode=%u\n",
1510 xisr->sadb_x_ipsecrequest_mode);
1511 *error = EINVAL;
1512 goto free_exit;
1513 }
1514 (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1515
1516 switch (xisr->sadb_x_ipsecrequest_level) {
1517 case IPSEC_LEVEL_DEFAULT:
1518 case IPSEC_LEVEL_USE:
1519 case IPSEC_LEVEL_REQUIRE:
1520 break;
1521 case IPSEC_LEVEL_UNIQUE:
1522 xisr_reqid = xisr->sadb_x_ipsecrequest_reqid;
1523 /* validity check */
1524 /*
1525 * If range violation of reqid, kernel will
1526 * update it, don't refuse it.
1527 */
1528 if (xisr_reqid > IPSEC_MANUAL_REQID_MAX) {
1529 IPSECLOG(LOG_DEBUG,
1530 "reqid=%d range "
1531 "violation, updated by kernel.\n",
1532 xisr_reqid);
1533 xisr_reqid = 0;
1534 }
1535
1536 /* allocate new reqid id if reqid is zero. */
1537 if (xisr_reqid == 0) {
1538 u_int16_t reqid = key_newreqid();
1539 if (reqid == 0) {
1540 *error = ENOBUFS;
1541 goto free_exit;
1542 }
1543 (*p_isr)->saidx.reqid = reqid;
1544 } else {
1545 /* set it for manual keying. */
1546 (*p_isr)->saidx.reqid = xisr_reqid;
1547 }
1548 break;
1549
1550 default:
1551 IPSECLOG(LOG_DEBUG, "invalid level=%u\n",
1552 xisr->sadb_x_ipsecrequest_level);
1553 *error = EINVAL;
1554 goto free_exit;
1555 }
1556 (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1557
1558 /* set IP addresses if there */
1559 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1560 const struct sockaddr *paddr;
1561
1562 paddr = (const struct sockaddr *)(xisr + 1);
1563
1564 /* validity check */
1565 if (paddr->sa_len > sizeof((*p_isr)->saidx.src)) {
1566 IPSECLOG(LOG_DEBUG, "invalid request "
1567 "address length.\n");
1568 *error = EINVAL;
1569 goto free_exit;
1570 }
1571 memcpy(&(*p_isr)->saidx.src, paddr, paddr->sa_len);
1572
1573 paddr = (const struct sockaddr *)((const char *)paddr
1574 + paddr->sa_len);
1575
1576 /* validity check */
1577 if (paddr->sa_len > sizeof((*p_isr)->saidx.dst)) {
1578 IPSECLOG(LOG_DEBUG, "invalid request "
1579 "address length.\n");
1580 *error = EINVAL;
1581 goto free_exit;
1582 }
1583 memcpy(&(*p_isr)->saidx.dst, paddr, paddr->sa_len);
1584 }
1585
1586 (*p_isr)->sp = newsp;
1587
1588 /* initialization for the next. */
1589 p_isr = &(*p_isr)->next;
1590 tlen -= xisr->sadb_x_ipsecrequest_len;
1591
1592 /* validity check */
1593 if (tlen < 0) {
1594 IPSECLOG(LOG_DEBUG, "becoming tlen < 0.\n");
1595 *error = EINVAL;
1596 goto free_exit;
1597 }
1598
1599 xisr = (const struct sadb_x_ipsecrequest *)((const char *)xisr +
1600 xisr->sadb_x_ipsecrequest_len);
1601 }
1602 }
1603
1604 *error = 0;
1605 return newsp;
1606
1607 free_exit:
1608 KEY_FREESP(&newsp);
1609 return NULL;
1610 }
1611
1612 static u_int16_t
1613 key_newreqid(void)
1614 {
1615 static u_int16_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1616
1617 auto_reqid = (auto_reqid == 0xffff ?
1618 IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1619
1620 /* XXX should be unique check */
1621
1622 return auto_reqid;
1623 }
1624
1625 /*
1626 * copy secpolicy struct to sadb_x_policy structure indicated.
1627 */
1628 struct mbuf *
1629 key_sp2msg(const struct secpolicy *sp)
1630 {
1631 struct sadb_x_policy *xpl;
1632 int tlen;
1633 char *p;
1634 struct mbuf *m;
1635
1636 KASSERT(sp != NULL);
1637
1638 tlen = key_getspreqmsglen(sp);
1639
1640 m = key_alloc_mbuf(tlen);
1641 if (!m || m->m_next) { /*XXX*/
1642 if (m)
1643 m_freem(m);
1644 return NULL;
1645 }
1646
1647 m->m_len = tlen;
1648 m->m_next = NULL;
1649 xpl = mtod(m, struct sadb_x_policy *);
1650 memset(xpl, 0, tlen);
1651
1652 xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1653 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1654 xpl->sadb_x_policy_type = sp->policy;
1655 xpl->sadb_x_policy_dir = sp->spidx.dir;
1656 xpl->sadb_x_policy_id = sp->id;
1657 p = (char *)xpl + sizeof(*xpl);
1658
1659 /* if is the policy for ipsec ? */
1660 if (sp->policy == IPSEC_POLICY_IPSEC) {
1661 struct sadb_x_ipsecrequest *xisr;
1662 struct ipsecrequest *isr;
1663
1664 for (isr = sp->req; isr != NULL; isr = isr->next) {
1665
1666 xisr = (struct sadb_x_ipsecrequest *)p;
1667
1668 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1669 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1670 xisr->sadb_x_ipsecrequest_level = isr->level;
1671 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1672
1673 p += sizeof(*xisr);
1674 memcpy(p, &isr->saidx.src, isr->saidx.src.sa.sa_len);
1675 p += isr->saidx.src.sa.sa_len;
1676 memcpy(p, &isr->saidx.dst, isr->saidx.dst.sa.sa_len);
1677 p += isr->saidx.src.sa.sa_len;
1678
1679 xisr->sadb_x_ipsecrequest_len =
1680 PFKEY_ALIGN8(sizeof(*xisr)
1681 + isr->saidx.src.sa.sa_len
1682 + isr->saidx.dst.sa.sa_len);
1683 }
1684 }
1685
1686 return m;
1687 }
1688
1689 /* m will not be freed nor modified */
1690 static struct mbuf *
1691 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1692 int ndeep, int nitem, ...)
1693 {
1694 va_list ap;
1695 int idx;
1696 int i;
1697 struct mbuf *result = NULL, *n;
1698 int len;
1699
1700 KASSERT(m != NULL);
1701 KASSERT(mhp != NULL);
1702
1703 va_start(ap, nitem);
1704 for (i = 0; i < nitem; i++) {
1705 idx = va_arg(ap, int);
1706 if (idx < 0 || idx > SADB_EXT_MAX)
1707 goto fail;
1708 /* don't attempt to pull empty extension */
1709 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1710 continue;
1711 if (idx != SADB_EXT_RESERVED &&
1712 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1713 continue;
1714
1715 if (idx == SADB_EXT_RESERVED) {
1716 CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= MHLEN);
1717 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1718 MGETHDR(n, M_DONTWAIT, MT_DATA);
1719 if (!n)
1720 goto fail;
1721 n->m_len = len;
1722 n->m_next = NULL;
1723 m_copydata(m, 0, sizeof(struct sadb_msg),
1724 mtod(n, void *));
1725 } else if (i < ndeep) {
1726 len = mhp->extlen[idx];
1727 n = key_alloc_mbuf(len);
1728 if (!n || n->m_next) { /*XXX*/
1729 if (n)
1730 m_freem(n);
1731 goto fail;
1732 }
1733 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1734 mtod(n, void *));
1735 } else {
1736 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1737 M_DONTWAIT);
1738 }
1739 if (n == NULL)
1740 goto fail;
1741
1742 if (result)
1743 m_cat(result, n);
1744 else
1745 result = n;
1746 }
1747 va_end(ap);
1748
1749 if (result && (result->m_flags & M_PKTHDR) != 0) {
1750 result->m_pkthdr.len = 0;
1751 for (n = result; n; n = n->m_next)
1752 result->m_pkthdr.len += n->m_len;
1753 }
1754
1755 return result;
1756
1757 fail:
1758 va_end(ap);
1759 m_freem(result);
1760 return NULL;
1761 }
1762
1763 /*
1764 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1765 * add an entry to SP database, when received
1766 * <base, address(SD), (lifetime(H),) policy>
1767 * from the user(?).
1768 * Adding to SP database,
1769 * and send
1770 * <base, address(SD), (lifetime(H),) policy>
1771 * to the socket which was send.
1772 *
1773 * SPDADD set a unique policy entry.
1774 * SPDSETIDX like SPDADD without a part of policy requests.
1775 * SPDUPDATE replace a unique policy entry.
1776 *
1777 * m will always be freed.
1778 */
1779 static int
1780 key_api_spdadd(struct socket *so, struct mbuf *m,
1781 const struct sadb_msghdr *mhp)
1782 {
1783 const struct sockaddr *src, *dst;
1784 const struct sadb_x_policy *xpl0;
1785 struct sadb_x_policy *xpl;
1786 const struct sadb_lifetime *lft = NULL;
1787 struct secpolicyindex spidx;
1788 struct secpolicy *newsp;
1789 int error;
1790
1791 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1792 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1793 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1794 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
1795 return key_senderror(so, m, EINVAL);
1796 }
1797 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1798 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1799 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1800 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
1801 return key_senderror(so, m, EINVAL);
1802 }
1803 if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1804 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] <
1805 sizeof(struct sadb_lifetime)) {
1806 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
1807 return key_senderror(so, m, EINVAL);
1808 }
1809 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1810 }
1811
1812 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1813
1814 /* checking the direciton. */
1815 switch (xpl0->sadb_x_policy_dir) {
1816 case IPSEC_DIR_INBOUND:
1817 case IPSEC_DIR_OUTBOUND:
1818 break;
1819 default:
1820 IPSECLOG(LOG_DEBUG, "Invalid SP direction.\n");
1821 return key_senderror(so, m, EINVAL);
1822 }
1823
1824 /* check policy */
1825 /* key_api_spdadd() accepts DISCARD, NONE and IPSEC. */
1826 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST ||
1827 xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1828 IPSECLOG(LOG_DEBUG, "Invalid policy type.\n");
1829 return key_senderror(so, m, EINVAL);
1830 }
1831
1832 /* policy requests are mandatory when action is ipsec. */
1833 if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX &&
1834 xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
1835 mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1836 IPSECLOG(LOG_DEBUG, "some policy requests part required.\n");
1837 return key_senderror(so, m, EINVAL);
1838 }
1839
1840 src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
1841 dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
1842
1843 /* sanity check on addr pair */
1844 if (src->sa_family != dst->sa_family)
1845 return key_senderror(so, m, EINVAL);
1846 if (src->sa_len != dst->sa_len)
1847 return key_senderror(so, m, EINVAL);
1848
1849 key_init_spidx_bymsghdr(&spidx, mhp);
1850
1851 /*
1852 * checking there is SP already or not.
1853 * SPDUPDATE doesn't depend on whether there is a SP or not.
1854 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1855 * then error.
1856 */
1857 {
1858 struct secpolicy *sp;
1859
1860 sp = key_getsp(&spidx);
1861 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1862 if (sp) {
1863 key_sp_dead(sp);
1864 key_sp_unlink(sp); /* XXX jrs ordering */
1865 KEY_FREESP(&sp);
1866 }
1867 } else {
1868 if (sp != NULL) {
1869 KEY_FREESP(&sp);
1870 IPSECLOG(LOG_DEBUG, "a SP entry exists already.\n");
1871 return key_senderror(so, m, EEXIST);
1872 }
1873 }
1874 }
1875
1876 /* allocation new SP entry */
1877 newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error);
1878 if (newsp == NULL) {
1879 return key_senderror(so, m, error);
1880 }
1881
1882 newsp->id = key_getnewspid();
1883 if (newsp->id == 0) {
1884 kmem_free(newsp, sizeof(*newsp));
1885 return key_senderror(so, m, ENOBUFS);
1886 }
1887
1888 newsp->spidx = spidx;
1889 newsp->created = time_uptime;
1890 newsp->lastused = newsp->created;
1891 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1892 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1893
1894 newsp->refcnt = 1; /* do not reclaim until I say I do */
1895 newsp->state = IPSEC_SPSTATE_ALIVE;
1896 if (newsp->policy == IPSEC_POLICY_IPSEC)
1897 KASSERT(newsp->req != NULL);
1898 SPLIST_ENTRY_INIT(newsp);
1899 SPLIST_WRITER_INSERT_TAIL(newsp->spidx.dir, newsp);
1900
1901 #ifdef notyet
1902 /* delete the entry in spacqtree */
1903 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1904 struct secspacq *spacq = key_getspacq(&spidx);
1905 if (spacq != NULL) {
1906 /* reset counter in order to deletion by timehandler. */
1907 spacq->created = time_uptime;
1908 spacq->count = 0;
1909 }
1910 }
1911 #endif
1912
1913 /* Invalidate all cached SPD pointers in the PCBs. */
1914 ipsec_invalpcbcacheall();
1915
1916 #if defined(GATEWAY)
1917 /* Invalidate the ipflow cache, as well. */
1918 ipflow_invalidate_all(0);
1919 #ifdef INET6
1920 if (in6_present)
1921 ip6flow_invalidate_all(0);
1922 #endif /* INET6 */
1923 #endif /* GATEWAY */
1924
1925 {
1926 struct mbuf *n, *mpolicy;
1927 int off;
1928
1929 /* create new sadb_msg to reply. */
1930 if (lft) {
1931 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1932 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1933 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1934 } else {
1935 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1936 SADB_X_EXT_POLICY,
1937 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1938 }
1939 if (!n)
1940 return key_senderror(so, m, ENOBUFS);
1941
1942 n = key_fill_replymsg(n, 0);
1943 if (n == NULL)
1944 return key_senderror(so, m, ENOBUFS);
1945
1946 off = 0;
1947 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1948 sizeof(*xpl), &off);
1949 if (mpolicy == NULL) {
1950 /* n is already freed */
1951 return key_senderror(so, m, ENOBUFS);
1952 }
1953 xpl = (struct sadb_x_policy *)(mtod(mpolicy, char *) + off);
1954 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1955 m_freem(n);
1956 return key_senderror(so, m, EINVAL);
1957 }
1958 xpl->sadb_x_policy_id = newsp->id;
1959
1960 m_freem(m);
1961 key_update_used();
1962 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1963 }
1964 }
1965
1966 /*
1967 * get new policy id.
1968 * OUT:
1969 * 0: failure.
1970 * others: success.
1971 */
1972 static u_int32_t
1973 key_getnewspid(void)
1974 {
1975 u_int32_t newid = 0;
1976 int count = key_spi_trycnt; /* XXX */
1977 struct secpolicy *sp;
1978
1979 /* when requesting to allocate spi ranged */
1980 while (count--) {
1981 newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
1982
1983 sp = key_getspbyid(newid);
1984 if (sp == NULL)
1985 break;
1986
1987 KEY_FREESP(&sp);
1988 }
1989
1990 if (count == 0 || newid == 0) {
1991 IPSECLOG(LOG_DEBUG, "to allocate policy id is failed.\n");
1992 return 0;
1993 }
1994
1995 return newid;
1996 }
1997
1998 /*
1999 * SADB_SPDDELETE processing
2000 * receive
2001 * <base, address(SD), policy(*)>
2002 * from the user(?), and set SADB_SASTATE_DEAD,
2003 * and send,
2004 * <base, address(SD), policy(*)>
2005 * to the ikmpd.
2006 * policy(*) including direction of policy.
2007 *
2008 * m will always be freed.
2009 */
2010 static int
2011 key_api_spddelete(struct socket *so, struct mbuf *m,
2012 const struct sadb_msghdr *mhp)
2013 {
2014 struct sadb_x_policy *xpl0;
2015 struct secpolicyindex spidx;
2016 struct secpolicy *sp;
2017
2018 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2019 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2020 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2021 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
2022 return key_senderror(so, m, EINVAL);
2023 }
2024 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2025 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2026 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2027 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
2028 return key_senderror(so, m, EINVAL);
2029 }
2030
2031 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2032
2033 /* checking the direciton. */
2034 switch (xpl0->sadb_x_policy_dir) {
2035 case IPSEC_DIR_INBOUND:
2036 case IPSEC_DIR_OUTBOUND:
2037 break;
2038 default:
2039 IPSECLOG(LOG_DEBUG, "Invalid SP direction.\n");
2040 return key_senderror(so, m, EINVAL);
2041 }
2042
2043 /* make secindex */
2044 key_init_spidx_bymsghdr(&spidx, mhp);
2045
2046 /* Is there SP in SPD ? */
2047 sp = key_getsp(&spidx);
2048 if (sp == NULL) {
2049 IPSECLOG(LOG_DEBUG, "no SP found.\n");
2050 return key_senderror(so, m, EINVAL);
2051 }
2052
2053 /* save policy id to buffer to be returned. */
2054 xpl0->sadb_x_policy_id = sp->id;
2055
2056 key_sp_dead(sp);
2057 key_sp_unlink(sp); /* XXX jrs ordering */
2058 KEY_FREESP(&sp); /* ref gained by key_getspbyid */
2059
2060 /* Invalidate all cached SPD pointers in the PCBs. */
2061 ipsec_invalpcbcacheall();
2062
2063 /* We're deleting policy; no need to invalidate the ipflow cache. */
2064
2065 {
2066 struct mbuf *n;
2067
2068 /* create new sadb_msg to reply. */
2069 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2070 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2071 if (!n)
2072 return key_senderror(so, m, ENOBUFS);
2073
2074 n = key_fill_replymsg(n, 0);
2075 if (n == NULL)
2076 return key_senderror(so, m, ENOBUFS);
2077
2078 m_freem(m);
2079 key_update_used();
2080 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2081 }
2082 }
2083
2084 /*
2085 * SADB_SPDDELETE2 processing
2086 * receive
2087 * <base, policy(*)>
2088 * from the user(?), and set SADB_SASTATE_DEAD,
2089 * and send,
2090 * <base, policy(*)>
2091 * to the ikmpd.
2092 * policy(*) including direction of policy.
2093 *
2094 * m will always be freed.
2095 */
2096 static int
2097 key_api_spddelete2(struct socket *so, struct mbuf *m,
2098 const struct sadb_msghdr *mhp)
2099 {
2100 u_int32_t id;
2101 struct secpolicy *sp;
2102
2103 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2104 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2105 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
2106 return key_senderror(so, m, EINVAL);
2107 }
2108
2109 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2110
2111 /* Is there SP in SPD ? */
2112 sp = key_getspbyid(id);
2113 if (sp == NULL) {
2114 IPSECLOG(LOG_DEBUG, "no SP found id:%u.\n", id);
2115 return key_senderror(so, m, EINVAL);
2116 }
2117
2118 key_sp_dead(sp);
2119 key_sp_unlink(sp); /* XXX jrs ordering */
2120 KEY_FREESP(&sp); /* ref gained by key_getsp */
2121 sp = NULL;
2122
2123 /* Invalidate all cached SPD pointers in the PCBs. */
2124 ipsec_invalpcbcacheall();
2125
2126 /* We're deleting policy; no need to invalidate the ipflow cache. */
2127
2128 {
2129 struct mbuf *n, *nn;
2130 int off, len;
2131
2132 CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= MCLBYTES);
2133
2134 /* create new sadb_msg to reply. */
2135 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2136
2137 MGETHDR(n, M_DONTWAIT, MT_DATA);
2138 if (n && len > MHLEN) {
2139 MCLGET(n, M_DONTWAIT);
2140 if ((n->m_flags & M_EXT) == 0) {
2141 m_freem(n);
2142 n = NULL;
2143 }
2144 }
2145 if (!n)
2146 return key_senderror(so, m, ENOBUFS);
2147
2148 n->m_len = len;
2149 n->m_next = NULL;
2150 off = 0;
2151
2152 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
2153 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2154
2155 KASSERTMSG(off == len, "length inconsistency");
2156
2157 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2158 mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2159 if (!n->m_next) {
2160 m_freem(n);
2161 return key_senderror(so, m, ENOBUFS);
2162 }
2163
2164 n->m_pkthdr.len = 0;
2165 for (nn = n; nn; nn = nn->m_next)
2166 n->m_pkthdr.len += nn->m_len;
2167
2168 n = key_fill_replymsg(n, 0);
2169 if (n == NULL)
2170 return key_senderror(so, m, ENOBUFS);
2171
2172 m_freem(m);
2173 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2174 }
2175 }
2176
2177 /*
2178 * SADB_X_GET processing
2179 * receive
2180 * <base, policy(*)>
2181 * from the user(?),
2182 * and send,
2183 * <base, address(SD), policy>
2184 * to the ikmpd.
2185 * policy(*) including direction of policy.
2186 *
2187 * m will always be freed.
2188 */
2189 static int
2190 key_api_spdget(struct socket *so, struct mbuf *m,
2191 const struct sadb_msghdr *mhp)
2192 {
2193 u_int32_t id;
2194 struct secpolicy *sp;
2195 struct mbuf *n;
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, "invalid message is passed.\n");
2200 return key_senderror(so, m, EINVAL);
2201 }
2202
2203 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2204
2205 /* Is there SP in SPD ? */
2206 sp = key_getspbyid(id);
2207 if (sp == NULL) {
2208 IPSECLOG(LOG_DEBUG, "no SP found id:%u.\n", id);
2209 return key_senderror(so, m, ENOENT);
2210 }
2211
2212 n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
2213 mhp->msg->sadb_msg_pid);
2214 KEY_FREESP(&sp); /* ref gained by key_getspbyid */
2215 if (n != NULL) {
2216 m_freem(m);
2217 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2218 } else
2219 return key_senderror(so, m, ENOBUFS);
2220 }
2221
2222 #ifdef notyet
2223 /*
2224 * SADB_X_SPDACQUIRE processing.
2225 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2226 * send
2227 * <base, policy(*)>
2228 * to KMD, and expect to receive
2229 * <base> with SADB_X_SPDACQUIRE if error occurred,
2230 * or
2231 * <base, policy>
2232 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2233 * policy(*) is without policy requests.
2234 *
2235 * 0 : succeed
2236 * others: error number
2237 */
2238 int
2239 key_spdacquire(const struct secpolicy *sp)
2240 {
2241 struct mbuf *result = NULL, *m;
2242 struct secspacq *newspacq;
2243 int error;
2244
2245 KASSERT(sp != NULL);
2246 KASSERTMSG(sp->req == NULL, "called but there is request");
2247 KASSERTMSG(sp->policy == IPSEC_POLICY_IPSEC,
2248 "policy mismathed. IPsec is expected");
2249
2250 /* Get an entry to check whether sent message or not. */
2251 newspacq = key_getspacq(&sp->spidx);
2252 if (newspacq != NULL) {
2253 if (key_blockacq_count < newspacq->count) {
2254 /* reset counter and do send message. */
2255 newspacq->count = 0;
2256 } else {
2257 /* increment counter and do nothing. */
2258 newspacq->count++;
2259 return 0;
2260 }
2261 } else {
2262 /* make new entry for blocking to send SADB_ACQUIRE. */
2263 newspacq = key_newspacq(&sp->spidx);
2264 if (newspacq == NULL)
2265 return ENOBUFS;
2266
2267 /* add to acqtree */
2268 LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
2269 }
2270
2271 /* create new sadb_msg to reply. */
2272 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2273 if (!m) {
2274 error = ENOBUFS;
2275 goto fail;
2276 }
2277 result = m;
2278
2279 result->m_pkthdr.len = 0;
2280 for (m = result; m; m = m->m_next)
2281 result->m_pkthdr.len += m->m_len;
2282
2283 mtod(result, struct sadb_msg *)->sadb_msg_len =
2284 PFKEY_UNIT64(result->m_pkthdr.len);
2285
2286 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2287
2288 fail:
2289 if (result)
2290 m_freem(result);
2291 return error;
2292 }
2293 #endif /* notyet */
2294
2295 /*
2296 * SADB_SPDFLUSH processing
2297 * receive
2298 * <base>
2299 * from the user, and free all entries in secpctree.
2300 * and send,
2301 * <base>
2302 * to the user.
2303 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2304 *
2305 * m will always be freed.
2306 */
2307 static int
2308 key_api_spdflush(struct socket *so, struct mbuf *m,
2309 const struct sadb_msghdr *mhp)
2310 {
2311 struct sadb_msg *newmsg;
2312 struct secpolicy *sp;
2313 u_int dir;
2314
2315 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2316 return key_senderror(so, m, EINVAL);
2317
2318 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2319 retry:
2320 SPLIST_WRITER_FOREACH(sp, dir) {
2321 if (sp->state == IPSEC_SPSTATE_DEAD)
2322 continue;
2323 key_sp_dead(sp);
2324 key_sp_unlink(sp);
2325 goto retry;
2326 }
2327 }
2328
2329 /* Invalidate all cached SPD pointers in the PCBs. */
2330 ipsec_invalpcbcacheall();
2331
2332 /* We're deleting policy; no need to invalidate the ipflow cache. */
2333
2334 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2335 IPSECLOG(LOG_DEBUG, "No more memory.\n");
2336 return key_senderror(so, m, ENOBUFS);
2337 }
2338
2339 if (m->m_next)
2340 m_freem(m->m_next);
2341 m->m_next = NULL;
2342 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2343 newmsg = mtod(m, struct sadb_msg *);
2344 newmsg->sadb_msg_errno = 0;
2345 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2346
2347 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2348 }
2349
2350 static struct sockaddr key_src = {
2351 .sa_len = 2,
2352 .sa_family = PF_KEY,
2353 };
2354
2355 static struct mbuf *
2356 key_setspddump_chain(int *errorp, int *lenp, pid_t pid)
2357 {
2358 struct secpolicy *sp;
2359 int cnt;
2360 u_int dir;
2361 struct mbuf *m, *n, *prev;
2362 int totlen;
2363
2364 *lenp = 0;
2365
2366 /* search SPD entry and get buffer size. */
2367 cnt = 0;
2368 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2369 SPLIST_READER_FOREACH(sp, dir) {
2370 cnt++;
2371 }
2372 }
2373
2374 if (cnt == 0) {
2375 *errorp = ENOENT;
2376 return (NULL);
2377 }
2378
2379 m = NULL;
2380 prev = m;
2381 totlen = 0;
2382 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2383 SPLIST_READER_FOREACH(sp, dir) {
2384 --cnt;
2385 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
2386
2387 if (!n) {
2388 *errorp = ENOBUFS;
2389 if (m)
2390 m_freem(m);
2391 return (NULL);
2392 }
2393
2394 totlen += n->m_pkthdr.len;
2395 if (!m) {
2396 m = n;
2397 } else {
2398 prev->m_nextpkt = n;
2399 }
2400 prev = n;
2401 }
2402 }
2403
2404 *lenp = totlen;
2405 *errorp = 0;
2406 return (m);
2407 }
2408
2409 /*
2410 * SADB_SPDDUMP processing
2411 * receive
2412 * <base>
2413 * from the user, and dump all SP leaves
2414 * and send,
2415 * <base> .....
2416 * to the ikmpd.
2417 *
2418 * m will always be freed.
2419 */
2420 static int
2421 key_api_spddump(struct socket *so, struct mbuf *m0,
2422 const struct sadb_msghdr *mhp)
2423 {
2424 struct mbuf *n;
2425 int error, len;
2426 int ok, s;
2427 pid_t pid;
2428
2429 pid = mhp->msg->sadb_msg_pid;
2430 /*
2431 * If the requestor has insufficient socket-buffer space
2432 * for the entire chain, nobody gets any response to the DUMP.
2433 * XXX For now, only the requestor ever gets anything.
2434 * Moreover, if the requestor has any space at all, they receive
2435 * the entire chain, otherwise the request is refused with ENOBUFS.
2436 */
2437 if (sbspace(&so->so_rcv) <= 0) {
2438 return key_senderror(so, m0, ENOBUFS);
2439 }
2440
2441 s = splsoftnet();
2442 n = key_setspddump_chain(&error, &len, pid);
2443 splx(s);
2444
2445 if (n == NULL) {
2446 return key_senderror(so, m0, ENOENT);
2447 }
2448 {
2449 uint64_t *ps = PFKEY_STAT_GETREF();
2450 ps[PFKEY_STAT_IN_TOTAL]++;
2451 ps[PFKEY_STAT_IN_BYTES] += len;
2452 PFKEY_STAT_PUTREF();
2453 }
2454
2455 /*
2456 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
2457 * The requestor receives either the entire chain, or an
2458 * error message with ENOBUFS.
2459 */
2460
2461 /*
2462 * sbappendchainwith record takes the chain of entries, one
2463 * packet-record per SPD entry, prepends the key_src sockaddr
2464 * to each packet-record, links the sockaddr mbufs into a new
2465 * list of records, then appends the entire resulting
2466 * list to the requesting socket.
2467 */
2468 ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src, n,
2469 SB_PRIO_ONESHOT_OVERFLOW);
2470
2471 if (!ok) {
2472 PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
2473 m_freem(n);
2474 return key_senderror(so, m0, ENOBUFS);
2475 }
2476
2477 m_freem(m0);
2478 return error;
2479 }
2480
2481 /*
2482 * SADB_X_NAT_T_NEW_MAPPING. Unused by racoon as of 2005/04/23
2483 */
2484 static int
2485 key_api_nat_map(struct socket *so, struct mbuf *m,
2486 const struct sadb_msghdr *mhp)
2487 {
2488 struct sadb_x_nat_t_type *type;
2489 struct sadb_x_nat_t_port *sport;
2490 struct sadb_x_nat_t_port *dport;
2491 struct sadb_address *iaddr, *raddr;
2492 struct sadb_x_nat_t_frag *frag;
2493
2494 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
2495 mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
2496 mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL) {
2497 IPSECLOG(LOG_DEBUG, "invalid message.\n");
2498 return key_senderror(so, m, EINVAL);
2499 }
2500 if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
2501 (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
2502 (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
2503 IPSECLOG(LOG_DEBUG, "invalid message.\n");
2504 return key_senderror(so, m, EINVAL);
2505 }
2506
2507 if ((mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) &&
2508 (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr))) {
2509 IPSECLOG(LOG_DEBUG, "invalid message\n");
2510 return key_senderror(so, m, EINVAL);
2511 }
2512
2513 if ((mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) &&
2514 (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr))) {
2515 IPSECLOG(LOG_DEBUG, "invalid message\n");
2516 return key_senderror(so, m, EINVAL);
2517 }
2518
2519 if ((mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) &&
2520 (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag))) {
2521 IPSECLOG(LOG_DEBUG, "invalid message\n");
2522 return key_senderror(so, m, EINVAL);
2523 }
2524
2525 type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
2526 sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
2527 dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
2528 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
2529 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
2530 frag = (struct sadb_x_nat_t_frag *) mhp->ext[SADB_X_EXT_NAT_T_FRAG];
2531
2532 /*
2533 * XXX handle that, it should also contain a SA, or anything
2534 * that enable to update the SA information.
2535 */
2536
2537 return 0;
2538 }
2539
2540 static struct mbuf *
2541 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, pid_t pid)
2542 {
2543 struct mbuf *result = NULL, *m;
2544
2545 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid,
2546 key_sp_refcnt(sp));
2547 if (!m)
2548 goto fail;
2549 result = m;
2550
2551 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2552 &sp->spidx.src.sa, sp->spidx.prefs, sp->spidx.ul_proto);
2553 if (!m)
2554 goto fail;
2555 m_cat(result, m);
2556
2557 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2558 &sp->spidx.dst.sa, sp->spidx.prefd, sp->spidx.ul_proto);
2559 if (!m)
2560 goto fail;
2561 m_cat(result, m);
2562
2563 m = key_sp2msg(sp);
2564 if (!m)
2565 goto fail;
2566 m_cat(result, m);
2567
2568 if ((result->m_flags & M_PKTHDR) == 0)
2569 goto fail;
2570
2571 if (result->m_len < sizeof(struct sadb_msg)) {
2572 result = m_pullup(result, sizeof(struct sadb_msg));
2573 if (result == NULL)
2574 goto fail;
2575 }
2576
2577 result->m_pkthdr.len = 0;
2578 for (m = result; m; m = m->m_next)
2579 result->m_pkthdr.len += m->m_len;
2580
2581 mtod(result, struct sadb_msg *)->sadb_msg_len =
2582 PFKEY_UNIT64(result->m_pkthdr.len);
2583
2584 return result;
2585
2586 fail:
2587 m_freem(result);
2588 return NULL;
2589 }
2590
2591 /*
2592 * get PFKEY message length for security policy and request.
2593 */
2594 static u_int
2595 key_getspreqmsglen(const struct secpolicy *sp)
2596 {
2597 u_int tlen;
2598
2599 tlen = sizeof(struct sadb_x_policy);
2600
2601 /* if is the policy for ipsec ? */
2602 if (sp->policy != IPSEC_POLICY_IPSEC)
2603 return tlen;
2604
2605 /* get length of ipsec requests */
2606 {
2607 const struct ipsecrequest *isr;
2608 int len;
2609
2610 for (isr = sp->req; isr != NULL; isr = isr->next) {
2611 len = sizeof(struct sadb_x_ipsecrequest)
2612 + isr->saidx.src.sa.sa_len + isr->saidx.dst.sa.sa_len;
2613
2614 tlen += PFKEY_ALIGN8(len);
2615 }
2616 }
2617
2618 return tlen;
2619 }
2620
2621 /*
2622 * SADB_SPDEXPIRE processing
2623 * send
2624 * <base, address(SD), lifetime(CH), policy>
2625 * to KMD by PF_KEY.
2626 *
2627 * OUT: 0 : succeed
2628 * others : error number
2629 */
2630 static int
2631 key_spdexpire(struct secpolicy *sp)
2632 {
2633 int s;
2634 struct mbuf *result = NULL, *m;
2635 int len;
2636 int error = -1;
2637 struct sadb_lifetime *lt;
2638
2639 /* XXX: Why do we lock ? */
2640 s = splsoftnet(); /*called from softclock()*/
2641
2642 KASSERT(sp != NULL);
2643
2644 /* set msg header */
2645 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2646 if (!m) {
2647 error = ENOBUFS;
2648 goto fail;
2649 }
2650 result = m;
2651
2652 /* create lifetime extension (current and hard) */
2653 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2654 m = key_alloc_mbuf(len);
2655 if (!m || m->m_next) { /*XXX*/
2656 if (m)
2657 m_freem(m);
2658 error = ENOBUFS;
2659 goto fail;
2660 }
2661 memset(mtod(m, void *), 0, len);
2662 lt = mtod(m, struct sadb_lifetime *);
2663 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2664 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2665 lt->sadb_lifetime_allocations = 0;
2666 lt->sadb_lifetime_bytes = 0;
2667 lt->sadb_lifetime_addtime = time_mono_to_wall(sp->created);
2668 lt->sadb_lifetime_usetime = time_mono_to_wall(sp->lastused);
2669 lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
2670 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2671 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2672 lt->sadb_lifetime_allocations = 0;
2673 lt->sadb_lifetime_bytes = 0;
2674 lt->sadb_lifetime_addtime = sp->lifetime;
2675 lt->sadb_lifetime_usetime = sp->validtime;
2676 m_cat(result, m);
2677
2678 /* set sadb_address for source */
2679 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &sp->spidx.src.sa,
2680 sp->spidx.prefs, sp->spidx.ul_proto);
2681 if (!m) {
2682 error = ENOBUFS;
2683 goto fail;
2684 }
2685 m_cat(result, m);
2686
2687 /* set sadb_address for destination */
2688 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &sp->spidx.dst.sa,
2689 sp->spidx.prefd, sp->spidx.ul_proto);
2690 if (!m) {
2691 error = ENOBUFS;
2692 goto fail;
2693 }
2694 m_cat(result, m);
2695
2696 /* set secpolicy */
2697 m = key_sp2msg(sp);
2698 if (!m) {
2699 error = ENOBUFS;
2700 goto fail;
2701 }
2702 m_cat(result, m);
2703
2704 if ((result->m_flags & M_PKTHDR) == 0) {
2705 error = EINVAL;
2706 goto fail;
2707 }
2708
2709 if (result->m_len < sizeof(struct sadb_msg)) {
2710 result = m_pullup(result, sizeof(struct sadb_msg));
2711 if (result == NULL) {
2712 error = ENOBUFS;
2713 goto fail;
2714 }
2715 }
2716
2717 result->m_pkthdr.len = 0;
2718 for (m = result; m; m = m->m_next)
2719 result->m_pkthdr.len += m->m_len;
2720
2721 mtod(result, struct sadb_msg *)->sadb_msg_len =
2722 PFKEY_UNIT64(result->m_pkthdr.len);
2723
2724 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2725
2726 fail:
2727 if (result)
2728 m_freem(result);
2729 splx(s);
2730 return error;
2731 }
2732
2733 /* %%% SAD management */
2734 /*
2735 * allocating a memory for new SA head, and copy from the values of mhp.
2736 * OUT: NULL : failure due to the lack of memory.
2737 * others : pointer to new SA head.
2738 */
2739 static struct secashead *
2740 key_newsah(const struct secasindex *saidx)
2741 {
2742 struct secashead *newsah;
2743 int i;
2744
2745 KASSERT(saidx != NULL);
2746
2747 newsah = kmem_zalloc(sizeof(struct secashead), KM_SLEEP);
2748 for (i = 0; i < __arraycount(newsah->savtree); i++)
2749 LIST_INIT(&newsah->savtree[i]);
2750 newsah->saidx = *saidx;
2751
2752 /* add to saidxtree */
2753 newsah->state = SADB_SASTATE_MATURE;
2754 LIST_INSERT_HEAD(&sahtree, newsah, chain);
2755
2756 return newsah;
2757 }
2758
2759 /*
2760 * delete SA index and all SA registerd.
2761 */
2762 static void
2763 key_delsah(struct secashead *sah)
2764 {
2765 struct secasvar *sav;
2766 u_int state;
2767 int s;
2768 int zombie = 0;
2769
2770 KASSERT(!cpu_softintr_p());
2771 KASSERT(sah != NULL);
2772
2773 s = splsoftnet();
2774
2775 /* searching all SA registerd in the secindex. */
2776 SASTATE_ANY_FOREACH(state) {
2777 LIST_FOREACH(sav, &sah->savtree[state], chain) {
2778 /* give up to delete this sa */
2779 zombie++;
2780 }
2781 }
2782
2783 /* don't delete sah only if there are savs. */
2784 if (zombie) {
2785 splx(s);
2786 return;
2787 }
2788
2789 rtcache_free(&sah->sa_route);
2790
2791 /* remove from tree of SA index */
2792 KASSERT(__LIST_CHAINED(sah));
2793 LIST_REMOVE(sah, chain);
2794
2795 if (sah->idents != NULL)
2796 kmem_free(sah->idents, sah->idents_len);
2797 if (sah->identd != NULL)
2798 kmem_free(sah->identd, sah->identd_len);
2799
2800 kmem_free(sah, sizeof(*sah));
2801
2802 splx(s);
2803 return;
2804 }
2805
2806 /*
2807 * allocating a new SA with LARVAL state.
2808 * key_api_add() and key_api_getspi() call,
2809 * and copy the values of mhp into new buffer.
2810 * When SAD message type is GETSPI:
2811 * to set sequence number from acq_seq++,
2812 * to set zero to SPI.
2813 * not to call key_setsava().
2814 * OUT: NULL : fail
2815 * others : pointer to new secasvar.
2816 *
2817 * does not modify mbuf. does not free mbuf on error.
2818 */
2819 static struct secasvar *
2820 key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp,
2821 int *errp, const char* where, int tag)
2822 {
2823 struct secasvar *newsav;
2824 const struct sadb_sa *xsa;
2825
2826 KASSERT(!cpu_softintr_p());
2827 KASSERT(m != NULL);
2828 KASSERT(mhp != NULL);
2829 KASSERT(mhp->msg != NULL);
2830
2831 newsav = kmem_zalloc(sizeof(struct secasvar), KM_SLEEP);
2832
2833 switch (mhp->msg->sadb_msg_type) {
2834 case SADB_GETSPI:
2835 newsav->spi = 0;
2836
2837 #ifdef IPSEC_DOSEQCHECK
2838 /* sync sequence number */
2839 if (mhp->msg->sadb_msg_seq == 0)
2840 newsav->seq =
2841 (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
2842 else
2843 #endif
2844 newsav->seq = mhp->msg->sadb_msg_seq;
2845 break;
2846
2847 case SADB_ADD:
2848 /* sanity check */
2849 if (mhp->ext[SADB_EXT_SA] == NULL) {
2850 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
2851 *errp = EINVAL;
2852 goto error;
2853 }
2854 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2855 newsav->spi = xsa->sadb_sa_spi;
2856 newsav->seq = mhp->msg->sadb_msg_seq;
2857 break;
2858 default:
2859 *errp = EINVAL;
2860 goto error;
2861 }
2862
2863 /* copy sav values */
2864 if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2865 *errp = key_setsaval(newsav, m, mhp);
2866 if (*errp)
2867 goto error;
2868 }
2869
2870 /* reset created */
2871 newsav->created = time_uptime;
2872 newsav->pid = mhp->msg->sadb_msg_pid;
2873
2874 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
2875 "DP from %s:%u return SA:%p\n", where, tag, newsav);
2876 return newsav;
2877
2878 error:
2879 KASSERT(*errp != 0);
2880 kmem_free(newsav, sizeof(*newsav));
2881 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
2882 "DP from %s:%u return SA:NULL\n", where, tag);
2883 return NULL;
2884 }
2885
2886
2887 static void
2888 key_clear_xform(struct secasvar *sav)
2889 {
2890
2891 /*
2892 * Cleanup xform state. Note that zeroize'ing causes the
2893 * keys to be cleared; otherwise we must do it ourself.
2894 */
2895 if (sav->tdb_xform != NULL) {
2896 sav->tdb_xform->xf_zeroize(sav);
2897 sav->tdb_xform = NULL;
2898 } else {
2899 if (sav->key_auth != NULL)
2900 explicit_memset(_KEYBUF(sav->key_auth), 0,
2901 _KEYLEN(sav->key_auth));
2902 if (sav->key_enc != NULL)
2903 explicit_memset(_KEYBUF(sav->key_enc), 0,
2904 _KEYLEN(sav->key_enc));
2905 }
2906 }
2907
2908 /*
2909 * free() SA variable entry.
2910 */
2911 static void
2912 key_delsav(struct secasvar *sav)
2913 {
2914
2915 KASSERT(sav != NULL);
2916 KASSERTMSG(sav->refcnt == 0, "reference count %u > 0", sav->refcnt);
2917
2918 key_clear_xform(sav);
2919 key_freesaval(sav);
2920 kmem_intr_free(sav, sizeof(*sav));
2921
2922 return;
2923 }
2924
2925 /*
2926 * search SAD.
2927 * OUT:
2928 * NULL : not found
2929 * others : found, pointer to a SA.
2930 */
2931 static struct secashead *
2932 key_getsah(const struct secasindex *saidx, int flag)
2933 {
2934 struct secashead *sah;
2935
2936 LIST_FOREACH(sah, &sahtree, chain) {
2937 if (sah->state == SADB_SASTATE_DEAD)
2938 continue;
2939 if (key_saidx_match(&sah->saidx, saidx, flag))
2940 return sah;
2941 }
2942
2943 return NULL;
2944 }
2945
2946 /*
2947 * check not to be duplicated SPI.
2948 * NOTE: this function is too slow due to searching all SAD.
2949 * OUT:
2950 * NULL : not found
2951 * others : found, pointer to a SA.
2952 */
2953 static bool
2954 key_checkspidup(const struct secasindex *saidx, u_int32_t spi)
2955 {
2956 struct secashead *sah;
2957 struct secasvar *sav;
2958
2959 /* check address family */
2960 if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2961 IPSECLOG(LOG_DEBUG, "address family mismatched.\n");
2962 return false;
2963 }
2964
2965 /* check all SAD */
2966 LIST_FOREACH(sah, &sahtree, chain) {
2967 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2968 continue;
2969 sav = key_getsavbyspi(sah, spi);
2970 if (sav != NULL) {
2971 KEY_FREESAV(&sav);
2972 return true;
2973 }
2974 }
2975
2976 return false;
2977 }
2978
2979 /*
2980 * search SAD litmited alive SA, protocol, SPI.
2981 * OUT:
2982 * NULL : not found
2983 * others : found, pointer to a SA.
2984 */
2985 static struct secasvar *
2986 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
2987 {
2988 struct secasvar *sav;
2989 u_int state;
2990
2991 /* search all status */
2992 SASTATE_ALIVE_FOREACH(state) {
2993 LIST_FOREACH(sav, &sah->savtree[state], chain) {
2994
2995 /* sanity check */
2996 if (sav->state != state) {
2997 IPSECLOG(LOG_DEBUG,
2998 "invalid sav->state (queue: %d SA: %d)\n",
2999 state, sav->state);
3000 continue;
3001 }
3002
3003 if (sav->spi == spi) {
3004 SA_ADDREF(sav);
3005 return sav;
3006 }
3007 }
3008 }
3009
3010 return NULL;
3011 }
3012
3013 /*
3014 * Free allocated data to member variables of sav:
3015 * sav->replay, sav->key_* and sav->lft_*.
3016 */
3017 static void
3018 key_freesaval(struct secasvar *sav)
3019 {
3020
3021 KASSERT(sav->refcnt == 0);
3022
3023 if (sav->replay != NULL)
3024 kmem_intr_free(sav->replay, sav->replay_len);
3025 if (sav->key_auth != NULL)
3026 kmem_intr_free(sav->key_auth, sav->key_auth_len);
3027 if (sav->key_enc != NULL)
3028 kmem_intr_free(sav->key_enc, sav->key_enc_len);
3029 if (sav->lft_c != NULL)
3030 kmem_intr_free(sav->lft_c, sizeof(*(sav->lft_c)));
3031 if (sav->lft_h != NULL)
3032 kmem_intr_free(sav->lft_h, sizeof(*(sav->lft_h)));
3033 if (sav->lft_s != NULL)
3034 kmem_intr_free(sav->lft_s, sizeof(*(sav->lft_s)));
3035 }
3036
3037 /*
3038 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3039 * You must update these if need.
3040 * OUT: 0: success.
3041 * !0: failure.
3042 *
3043 * does not modify mbuf. does not free mbuf on error.
3044 */
3045 static int
3046 key_setsaval(struct secasvar *sav, struct mbuf *m,
3047 const struct sadb_msghdr *mhp)
3048 {
3049 int error = 0;
3050
3051 KASSERT(!cpu_softintr_p());
3052 KASSERT(m != NULL);
3053 KASSERT(mhp != NULL);
3054 KASSERT(mhp->msg != NULL);
3055
3056 /* We shouldn't initialize sav variables while someone uses it. */
3057 KASSERT(sav->refcnt == 0);
3058
3059 /* SA */
3060 if (mhp->ext[SADB_EXT_SA] != NULL) {
3061 const struct sadb_sa *sa0;
3062
3063 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3064 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3065 error = EINVAL;
3066 goto fail;
3067 }
3068
3069 sav->alg_auth = sa0->sadb_sa_auth;
3070 sav->alg_enc = sa0->sadb_sa_encrypt;
3071 sav->flags = sa0->sadb_sa_flags;
3072
3073 /* replay window */
3074 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3075 size_t len = sizeof(struct secreplay) +
3076 sa0->sadb_sa_replay;
3077 sav->replay = kmem_zalloc(len, KM_SLEEP);
3078 sav->replay_len = len;
3079 if (sa0->sadb_sa_replay != 0)
3080 sav->replay->bitmap = (char*)(sav->replay+1);
3081 sav->replay->wsize = sa0->sadb_sa_replay;
3082 }
3083 }
3084
3085 /* Authentication keys */
3086 if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3087 const struct sadb_key *key0;
3088 int len;
3089
3090 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3091 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3092
3093 error = 0;
3094 if (len < sizeof(*key0)) {
3095 error = EINVAL;
3096 goto fail;
3097 }
3098 switch (mhp->msg->sadb_msg_satype) {
3099 case SADB_SATYPE_AH:
3100 case SADB_SATYPE_ESP:
3101 case SADB_X_SATYPE_TCPSIGNATURE:
3102 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3103 sav->alg_auth != SADB_X_AALG_NULL)
3104 error = EINVAL;
3105 break;
3106 case SADB_X_SATYPE_IPCOMP:
3107 default:
3108 error = EINVAL;
3109 break;
3110 }
3111 if (error) {
3112 IPSECLOG(LOG_DEBUG, "invalid key_auth values.\n");
3113 goto fail;
3114 }
3115
3116 sav->key_auth = key_newbuf(key0, len);
3117 sav->key_auth_len = len;
3118 }
3119
3120 /* Encryption key */
3121 if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3122 const struct sadb_key *key0;
3123 int len;
3124
3125 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3126 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3127
3128 error = 0;
3129 if (len < sizeof(*key0)) {
3130 error = EINVAL;
3131 goto fail;
3132 }
3133 switch (mhp->msg->sadb_msg_satype) {
3134 case SADB_SATYPE_ESP:
3135 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3136 sav->alg_enc != SADB_EALG_NULL) {
3137 error = EINVAL;
3138 break;
3139 }
3140 sav->key_enc = key_newbuf(key0, len);
3141 sav->key_enc_len = len;
3142 break;
3143 case SADB_X_SATYPE_IPCOMP:
3144 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3145 error = EINVAL;
3146 sav->key_enc = NULL; /*just in case*/
3147 break;
3148 case SADB_SATYPE_AH:
3149 case SADB_X_SATYPE_TCPSIGNATURE:
3150 default:
3151 error = EINVAL;
3152 break;
3153 }
3154 if (error) {
3155 IPSECLOG(LOG_DEBUG, "invalid key_enc value.\n");
3156 goto fail;
3157 }
3158 }
3159
3160 /* set iv */
3161 sav->ivlen = 0;
3162
3163 switch (mhp->msg->sadb_msg_satype) {
3164 case SADB_SATYPE_AH:
3165 error = xform_init(sav, XF_AH);
3166 break;
3167 case SADB_SATYPE_ESP:
3168 error = xform_init(sav, XF_ESP);
3169 break;
3170 case SADB_X_SATYPE_IPCOMP:
3171 error = xform_init(sav, XF_IPCOMP);
3172 break;
3173 case SADB_X_SATYPE_TCPSIGNATURE:
3174 error = xform_init(sav, XF_TCPSIGNATURE);
3175 break;
3176 }
3177 if (error) {
3178 IPSECLOG(LOG_DEBUG, "unable to initialize SA type %u.\n",
3179 mhp->msg->sadb_msg_satype);
3180 goto fail;
3181 }
3182
3183 /* reset created */
3184 sav->created = time_uptime;
3185
3186 /* make lifetime for CURRENT */
3187 sav->lft_c = kmem_alloc(sizeof(struct sadb_lifetime), KM_SLEEP);
3188
3189 sav->lft_c->sadb_lifetime_len =
3190 PFKEY_UNIT64(sizeof(struct sadb_lifetime));
3191 sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
3192 sav->lft_c->sadb_lifetime_allocations = 0;
3193 sav->lft_c->sadb_lifetime_bytes = 0;
3194 sav->lft_c->sadb_lifetime_addtime = time_uptime;
3195 sav->lft_c->sadb_lifetime_usetime = 0;
3196
3197 /* lifetimes for HARD and SOFT */
3198 {
3199 const struct sadb_lifetime *lft0;
3200
3201 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3202 if (lft0 != NULL) {
3203 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3204 error = EINVAL;
3205 goto fail;
3206 }
3207 sav->lft_h = key_newbuf(lft0, sizeof(*lft0));
3208 }
3209
3210 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3211 if (lft0 != NULL) {
3212 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3213 error = EINVAL;
3214 goto fail;
3215 }
3216 sav->lft_s = key_newbuf(lft0, sizeof(*lft0));
3217 /* to be initialize ? */
3218 }
3219 }
3220
3221 return 0;
3222
3223 fail:
3224 key_clear_xform(sav);
3225 key_freesaval(sav);
3226
3227 return error;
3228 }
3229
3230 /*
3231 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3232 * OUT: 0: valid
3233 * other: errno
3234 */
3235 static int
3236 key_init_xform(struct secasvar *sav)
3237 {
3238 int error;
3239
3240 /* We shouldn't initialize sav variables while someone uses it. */
3241 KASSERT(sav->refcnt == 0);
3242
3243 /* check SPI value */
3244 switch (sav->sah->saidx.proto) {
3245 case IPPROTO_ESP:
3246 case IPPROTO_AH:
3247 if (ntohl(sav->spi) <= 255) {
3248 IPSECLOG(LOG_DEBUG, "illegal range of SPI %u.\n",
3249 (u_int32_t)ntohl(sav->spi));
3250 return EINVAL;
3251 }
3252 break;
3253 }
3254
3255 /* check satype */
3256 switch (sav->sah->saidx.proto) {
3257 case IPPROTO_ESP:
3258 /* check flags */
3259 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3260 (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3261 IPSECLOG(LOG_DEBUG,
3262 "invalid flag (derived) given to old-esp.\n");
3263 return EINVAL;
3264 }
3265 error = xform_init(sav, XF_ESP);
3266 break;
3267 case IPPROTO_AH:
3268 /* check flags */
3269 if (sav->flags & SADB_X_EXT_DERIV) {
3270 IPSECLOG(LOG_DEBUG,
3271 "invalid flag (derived) given to AH SA.\n");
3272 return EINVAL;
3273 }
3274 if (sav->alg_enc != SADB_EALG_NONE) {
3275 IPSECLOG(LOG_DEBUG,
3276 "protocol and algorithm mismated.\n");
3277 return(EINVAL);
3278 }
3279 error = xform_init(sav, XF_AH);
3280 break;
3281 case IPPROTO_IPCOMP:
3282 if (sav->alg_auth != SADB_AALG_NONE) {
3283 IPSECLOG(LOG_DEBUG,
3284 "protocol and algorithm mismated.\n");
3285 return(EINVAL);
3286 }
3287 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3288 && ntohl(sav->spi) >= 0x10000) {
3289 IPSECLOG(LOG_DEBUG, "invalid cpi for IPComp.\n");
3290 return(EINVAL);
3291 }
3292 error = xform_init(sav, XF_IPCOMP);
3293 break;
3294 case IPPROTO_TCP:
3295 if (sav->alg_enc != SADB_EALG_NONE) {
3296 IPSECLOG(LOG_DEBUG,
3297 "protocol and algorithm mismated.\n");
3298 return(EINVAL);
3299 }
3300 error = xform_init(sav, XF_TCPSIGNATURE);
3301 break;
3302 default:
3303 IPSECLOG(LOG_DEBUG, "Invalid satype.\n");
3304 error = EPROTONOSUPPORT;
3305 break;
3306 }
3307
3308 return error;
3309 }
3310
3311 /*
3312 * subroutine for SADB_GET and SADB_DUMP.
3313 */
3314 static struct mbuf *
3315 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3316 u_int32_t seq, u_int32_t pid)
3317 {
3318 struct mbuf *result = NULL, *tres = NULL, *m;
3319 int l = 0;
3320 int i;
3321 void *p;
3322 struct sadb_lifetime lt;
3323 int dumporder[] = {
3324 SADB_EXT_SA, SADB_X_EXT_SA2,
3325 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3326 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3327 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3328 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3329 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3330 SADB_X_EXT_NAT_T_TYPE,
3331 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3332 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3333 SADB_X_EXT_NAT_T_FRAG,
3334
3335 };
3336
3337 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3338 if (m == NULL)
3339 goto fail;
3340 result = m;
3341
3342 for (i = __arraycount(dumporder) - 1; i >= 0; i--) {
3343 m = NULL;
3344 p = NULL;
3345 switch (dumporder[i]) {
3346 case SADB_EXT_SA:
3347 m = key_setsadbsa(sav);
3348 break;
3349
3350 case SADB_X_EXT_SA2:
3351 m = key_setsadbxsa2(sav->sah->saidx.mode,
3352 sav->replay ? sav->replay->count : 0,
3353 sav->sah->saidx.reqid);
3354 break;
3355
3356 case SADB_EXT_ADDRESS_SRC:
3357 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3358 &sav->sah->saidx.src.sa,
3359 FULLMASK, IPSEC_ULPROTO_ANY);
3360 break;
3361
3362 case SADB_EXT_ADDRESS_DST:
3363 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3364 &sav->sah->saidx.dst.sa,
3365 FULLMASK, IPSEC_ULPROTO_ANY);
3366 break;
3367
3368 case SADB_EXT_KEY_AUTH:
3369 if (!sav->key_auth)
3370 continue;
3371 l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
3372 p = sav->key_auth;
3373 break;
3374
3375 case SADB_EXT_KEY_ENCRYPT:
3376 if (!sav->key_enc)
3377 continue;
3378 l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
3379 p = sav->key_enc;
3380 break;
3381
3382 case SADB_EXT_LIFETIME_CURRENT:
3383 KASSERT(sav->lft_c != NULL);
3384 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
3385 memcpy(<, sav->lft_c, sizeof(struct sadb_lifetime));
3386 lt.sadb_lifetime_addtime =
3387 time_mono_to_wall(lt.sadb_lifetime_addtime);
3388 lt.sadb_lifetime_usetime =
3389 time_mono_to_wall(lt.sadb_lifetime_usetime);
3390 p = <
3391 break;
3392
3393 case SADB_EXT_LIFETIME_HARD:
3394 if (!sav->lft_h)
3395 continue;
3396 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
3397 p = sav->lft_h;
3398 break;
3399
3400 case SADB_EXT_LIFETIME_SOFT:
3401 if (!sav->lft_s)
3402 continue;
3403 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
3404 p = sav->lft_s;
3405 break;
3406
3407 case SADB_X_EXT_NAT_T_TYPE:
3408 m = key_setsadbxtype(sav->natt_type);
3409 break;
3410
3411 case SADB_X_EXT_NAT_T_DPORT:
3412 if (sav->natt_type == 0)
3413 continue;
3414 m = key_setsadbxport(
3415 key_portfromsaddr(&sav->sah->saidx.dst),
3416 SADB_X_EXT_NAT_T_DPORT);
3417 break;
3418
3419 case SADB_X_EXT_NAT_T_SPORT:
3420 if (sav->natt_type == 0)
3421 continue;
3422 m = key_setsadbxport(
3423 key_portfromsaddr(&sav->sah->saidx.src),
3424 SADB_X_EXT_NAT_T_SPORT);
3425 break;
3426
3427 case SADB_X_EXT_NAT_T_FRAG:
3428 /* don't send frag info if not set */
3429 if (sav->natt_type == 0 || sav->esp_frag == IP_MAXPACKET)
3430 continue;
3431 m = key_setsadbxfrag(sav->esp_frag);
3432 break;
3433
3434 case SADB_X_EXT_NAT_T_OAI:
3435 case SADB_X_EXT_NAT_T_OAR:
3436 continue;
3437
3438 case SADB_EXT_ADDRESS_PROXY:
3439 case SADB_EXT_IDENTITY_SRC:
3440 case SADB_EXT_IDENTITY_DST:
3441 /* XXX: should we brought from SPD ? */
3442 case SADB_EXT_SENSITIVITY:
3443 default:
3444 continue;
3445 }
3446
3447 KASSERT(!(m && p));
3448 if (!m && !p)
3449 goto fail;
3450 if (p && tres) {
3451 M_PREPEND(tres, l, M_DONTWAIT);
3452 if (!tres)
3453 goto fail;
3454 memcpy(mtod(tres, void *), p, l);
3455 continue;
3456 }
3457 if (p) {
3458 m = key_alloc_mbuf(l);
3459 if (!m)
3460 goto fail;
3461 m_copyback(m, 0, l, p);
3462 }
3463
3464 if (tres)
3465 m_cat(m, tres);
3466 tres = m;
3467 }
3468
3469 m_cat(result, tres);
3470 tres = NULL; /* avoid free on error below */
3471
3472 if (result->m_len < sizeof(struct sadb_msg)) {
3473 result = m_pullup(result, sizeof(struct sadb_msg));
3474 if (result == NULL)
3475 goto fail;
3476 }
3477
3478 result->m_pkthdr.len = 0;
3479 for (m = result; m; m = m->m_next)
3480 result->m_pkthdr.len += m->m_len;
3481
3482 mtod(result, struct sadb_msg *)->sadb_msg_len =
3483 PFKEY_UNIT64(result->m_pkthdr.len);
3484
3485 return result;
3486
3487 fail:
3488 m_freem(result);
3489 m_freem(tres);
3490 return NULL;
3491 }
3492
3493
3494 /*
3495 * set a type in sadb_x_nat_t_type
3496 */
3497 static struct mbuf *
3498 key_setsadbxtype(u_int16_t type)
3499 {
3500 struct mbuf *m;
3501 size_t len;
3502 struct sadb_x_nat_t_type *p;
3503
3504 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3505
3506 m = key_alloc_mbuf(len);
3507 if (!m || m->m_next) { /*XXX*/
3508 if (m)
3509 m_freem(m);
3510 return NULL;
3511 }
3512
3513 p = mtod(m, struct sadb_x_nat_t_type *);
3514
3515 memset(p, 0, len);
3516 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3517 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3518 p->sadb_x_nat_t_type_type = type;
3519
3520 return m;
3521 }
3522 /*
3523 * set a port in sadb_x_nat_t_port. port is in network order
3524 */
3525 static struct mbuf *
3526 key_setsadbxport(u_int16_t port, u_int16_t type)
3527 {
3528 struct mbuf *m;
3529 size_t len;
3530 struct sadb_x_nat_t_port *p;
3531
3532 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3533
3534 m = key_alloc_mbuf(len);
3535 if (!m || m->m_next) { /*XXX*/
3536 if (m)
3537 m_freem(m);
3538 return NULL;
3539 }
3540
3541 p = mtod(m, struct sadb_x_nat_t_port *);
3542
3543 memset(p, 0, len);
3544 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3545 p->sadb_x_nat_t_port_exttype = type;
3546 p->sadb_x_nat_t_port_port = port;
3547
3548 return m;
3549 }
3550
3551 /*
3552 * set fragmentation info in sadb_x_nat_t_frag
3553 */
3554 static struct mbuf *
3555 key_setsadbxfrag(u_int16_t flen)
3556 {
3557 struct mbuf *m;
3558 size_t len;
3559 struct sadb_x_nat_t_frag *p;
3560
3561 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_frag));
3562
3563 m = key_alloc_mbuf(len);
3564 if (!m || m->m_next) { /*XXX*/
3565 if (m)
3566 m_freem(m);
3567 return NULL;
3568 }
3569
3570 p = mtod(m, struct sadb_x_nat_t_frag *);
3571
3572 memset(p, 0, len);
3573 p->sadb_x_nat_t_frag_len = PFKEY_UNIT64(len);
3574 p->sadb_x_nat_t_frag_exttype = SADB_X_EXT_NAT_T_FRAG;
3575 p->sadb_x_nat_t_frag_fraglen = flen;
3576
3577 return m;
3578 }
3579
3580 /*
3581 * Get port from sockaddr, port is in network order
3582 */
3583 u_int16_t
3584 key_portfromsaddr(const union sockaddr_union *saddr)
3585 {
3586 u_int16_t port;
3587
3588 switch (saddr->sa.sa_family) {
3589 case AF_INET: {
3590 port = saddr->sin.sin_port;
3591 break;
3592 }
3593 #ifdef INET6
3594 case AF_INET6: {
3595 port = saddr->sin6.sin6_port;
3596 break;
3597 }
3598 #endif
3599 default:
3600 printf("%s: unexpected address family\n", __func__);
3601 port = 0;
3602 break;
3603 }
3604
3605 return port;
3606 }
3607
3608
3609 /*
3610 * Set port is struct sockaddr. port is in network order
3611 */
3612 static void
3613 key_porttosaddr(union sockaddr_union *saddr, u_int16_t port)
3614 {
3615 switch (saddr->sa.sa_family) {
3616 case AF_INET: {
3617 saddr->sin.sin_port = port;
3618 break;
3619 }
3620 #ifdef INET6
3621 case AF_INET6: {
3622 saddr->sin6.sin6_port = port;
3623 break;
3624 }
3625 #endif
3626 default:
3627 printf("%s: unexpected address family %d\n", __func__,
3628 saddr->sa.sa_family);
3629 break;
3630 }
3631
3632 return;
3633 }
3634
3635 /*
3636 * Safety check sa_len
3637 */
3638 static int
3639 key_checksalen(const union sockaddr_union *saddr)
3640 {
3641 switch (saddr->sa.sa_family) {
3642 case AF_INET:
3643 if (saddr->sa.sa_len != sizeof(struct sockaddr_in))
3644 return -1;
3645 break;
3646 #ifdef INET6
3647 case AF_INET6:
3648 if (saddr->sa.sa_len != sizeof(struct sockaddr_in6))
3649 return -1;
3650 break;
3651 #endif
3652 default:
3653 printf("%s: unexpected sa_family %d\n", __func__,
3654 saddr->sa.sa_family);
3655 return -1;
3656 break;
3657 }
3658 return 0;
3659 }
3660
3661
3662 /*
3663 * set data into sadb_msg.
3664 */
3665 static struct mbuf *
3666 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype,
3667 u_int32_t seq, pid_t pid, u_int16_t reserved)
3668 {
3669 struct mbuf *m;
3670 struct sadb_msg *p;
3671 int len;
3672
3673 CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) <= MCLBYTES);
3674
3675 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3676
3677 MGETHDR(m, M_DONTWAIT, MT_DATA);
3678 if (m && len > MHLEN) {
3679 MCLGET(m, M_DONTWAIT);
3680 if ((m->m_flags & M_EXT) == 0) {
3681 m_freem(m);
3682 m = NULL;
3683 }
3684 }
3685 if (!m)
3686 return NULL;
3687 m->m_pkthdr.len = m->m_len = len;
3688 m->m_next = NULL;
3689
3690 p = mtod(m, struct sadb_msg *);
3691
3692 memset(p, 0, len);
3693 p->sadb_msg_version = PF_KEY_V2;
3694 p->sadb_msg_type = type;
3695 p->sadb_msg_errno = 0;
3696 p->sadb_msg_satype = satype;
3697 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3698 p->sadb_msg_reserved = reserved;
3699 p->sadb_msg_seq = seq;
3700 p->sadb_msg_pid = (u_int32_t)pid;
3701
3702 return m;
3703 }
3704
3705 /*
3706 * copy secasvar data into sadb_address.
3707 */
3708 static struct mbuf *
3709 key_setsadbsa(struct secasvar *sav)
3710 {
3711 struct mbuf *m;
3712 struct sadb_sa *p;
3713 int len;
3714
3715 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3716 m = key_alloc_mbuf(len);
3717 if (!m || m->m_next) { /*XXX*/
3718 if (m)
3719 m_freem(m);
3720 return NULL;
3721 }
3722
3723 p = mtod(m, struct sadb_sa *);
3724
3725 memset(p, 0, len);
3726 p->sadb_sa_len = PFKEY_UNIT64(len);
3727 p->sadb_sa_exttype = SADB_EXT_SA;
3728 p->sadb_sa_spi = sav->spi;
3729 p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3730 p->sadb_sa_state = sav->state;
3731 p->sadb_sa_auth = sav->alg_auth;
3732 p->sadb_sa_encrypt = sav->alg_enc;
3733 p->sadb_sa_flags = sav->flags;
3734
3735 return m;
3736 }
3737
3738 /*
3739 * set data into sadb_address.
3740 */
3741 static struct mbuf *
3742 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3743 u_int8_t prefixlen, u_int16_t ul_proto)
3744 {
3745 struct mbuf *m;
3746 struct sadb_address *p;
3747 size_t len;
3748
3749 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3750 PFKEY_ALIGN8(saddr->sa_len);
3751 m = key_alloc_mbuf(len);
3752 if (!m || m->m_next) { /*XXX*/
3753 if (m)
3754 m_freem(m);
3755 return NULL;
3756 }
3757
3758 p = mtod(m, struct sadb_address *);
3759
3760 memset(p, 0, len);
3761 p->sadb_address_len = PFKEY_UNIT64(len);
3762 p->sadb_address_exttype = exttype;
3763 p->sadb_address_proto = ul_proto;
3764 if (prefixlen == FULLMASK) {
3765 switch (saddr->sa_family) {
3766 case AF_INET:
3767 prefixlen = sizeof(struct in_addr) << 3;
3768 break;
3769 case AF_INET6:
3770 prefixlen = sizeof(struct in6_addr) << 3;
3771 break;
3772 default:
3773 ; /*XXX*/
3774 }
3775 }
3776 p->sadb_address_prefixlen = prefixlen;
3777 p->sadb_address_reserved = 0;
3778
3779 memcpy(mtod(m, char *) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3780 saddr, saddr->sa_len);
3781
3782 return m;
3783 }
3784
3785 #if 0
3786 /*
3787 * set data into sadb_ident.
3788 */
3789 static struct mbuf *
3790 key_setsadbident(u_int16_t exttype, u_int16_t idtype,
3791 void *string, int stringlen, u_int64_t id)
3792 {
3793 struct mbuf *m;
3794 struct sadb_ident *p;
3795 size_t len;
3796
3797 len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
3798 m = key_alloc_mbuf(len);
3799 if (!m || m->m_next) { /*XXX*/
3800 if (m)
3801 m_freem(m);
3802 return NULL;
3803 }
3804
3805 p = mtod(m, struct sadb_ident *);
3806
3807 memset(p, 0, len);
3808 p->sadb_ident_len = PFKEY_UNIT64(len);
3809 p->sadb_ident_exttype = exttype;
3810 p->sadb_ident_type = idtype;
3811 p->sadb_ident_reserved = 0;
3812 p->sadb_ident_id = id;
3813
3814 memcpy(mtod(m, void *) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
3815 string, stringlen);
3816
3817 return m;
3818 }
3819 #endif
3820
3821 /*
3822 * set data into sadb_x_sa2.
3823 */
3824 static struct mbuf *
3825 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int16_t reqid)
3826 {
3827 struct mbuf *m;
3828 struct sadb_x_sa2 *p;
3829 size_t len;
3830
3831 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3832 m = key_alloc_mbuf(len);
3833 if (!m || m->m_next) { /*XXX*/
3834 if (m)
3835 m_freem(m);
3836 return NULL;
3837 }
3838
3839 p = mtod(m, struct sadb_x_sa2 *);
3840
3841 memset(p, 0, len);
3842 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3843 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3844 p->sadb_x_sa2_mode = mode;
3845 p->sadb_x_sa2_reserved1 = 0;
3846 p->sadb_x_sa2_reserved2 = 0;
3847 p->sadb_x_sa2_sequence = seq;
3848 p->sadb_x_sa2_reqid = reqid;
3849
3850 return m;
3851 }
3852
3853 /*
3854 * set data into sadb_x_policy
3855 */
3856 static struct mbuf *
3857 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3858 {
3859 struct mbuf *m;
3860 struct sadb_x_policy *p;
3861 size_t len;
3862
3863 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3864 m = key_alloc_mbuf(len);
3865 if (!m || m->m_next) { /*XXX*/
3866 if (m)
3867 m_freem(m);
3868 return NULL;
3869 }
3870
3871 p = mtod(m, struct sadb_x_policy *);
3872
3873 memset(p, 0, len);
3874 p->sadb_x_policy_len = PFKEY_UNIT64(len);
3875 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3876 p->sadb_x_policy_type = type;
3877 p->sadb_x_policy_dir = dir;
3878 p->sadb_x_policy_id = id;
3879
3880 return m;
3881 }
3882
3883 /* %%% utilities */
3884 /*
3885 * copy a buffer into the new buffer allocated.
3886 */
3887 static void *
3888 key_newbuf(const void *src, u_int len)
3889 {
3890 void *new;
3891
3892 new = kmem_alloc(len, KM_SLEEP);
3893 memcpy(new, src, len);
3894
3895 return new;
3896 }
3897
3898 /* compare my own address
3899 * OUT: 1: true, i.e. my address.
3900 * 0: false
3901 */
3902 int
3903 key_ismyaddr(const struct sockaddr *sa)
3904 {
3905 #ifdef INET
3906 const struct sockaddr_in *sin;
3907 const struct in_ifaddr *ia;
3908 int s;
3909 #endif
3910
3911 KASSERT(sa != NULL);
3912
3913 switch (sa->sa_family) {
3914 #ifdef INET
3915 case AF_INET:
3916 sin = (const struct sockaddr_in *)sa;
3917 s = pserialize_read_enter();
3918 IN_ADDRLIST_READER_FOREACH(ia) {
3919 if (sin->sin_family == ia->ia_addr.sin_family &&
3920 sin->sin_len == ia->ia_addr.sin_len &&
3921 sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3922 {
3923 pserialize_read_exit(s);
3924 return 1;
3925 }
3926 }
3927 pserialize_read_exit(s);
3928 break;
3929 #endif
3930 #ifdef INET6
3931 case AF_INET6:
3932 return key_ismyaddr6((const struct sockaddr_in6 *)sa);
3933 #endif
3934 }
3935
3936 return 0;
3937 }
3938
3939 #ifdef INET6
3940 /*
3941 * compare my own address for IPv6.
3942 * 1: ours
3943 * 0: other
3944 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3945 */
3946 #include <netinet6/in6_var.h>
3947
3948 static int
3949 key_ismyaddr6(const struct sockaddr_in6 *sin6)
3950 {
3951 struct in6_ifaddr *ia;
3952 int s;
3953 struct psref psref;
3954 int bound;
3955 int ours = 1;
3956
3957 bound = curlwp_bind();
3958 s = pserialize_read_enter();
3959 IN6_ADDRLIST_READER_FOREACH(ia) {
3960 bool ingroup;
3961
3962 if (key_sockaddr_match((const struct sockaddr *)&sin6,
3963 (const struct sockaddr *)&ia->ia_addr, 0)) {
3964 pserialize_read_exit(s);
3965 goto ours;
3966 }
3967 ia6_acquire(ia, &psref);
3968 pserialize_read_exit(s);
3969
3970 /*
3971 * XXX Multicast
3972 * XXX why do we care about multlicast here while we don't care
3973 * about IPv4 multicast??
3974 * XXX scope
3975 */
3976 ingroup = in6_multi_group(&sin6->sin6_addr, ia->ia_ifp);
3977 if (ingroup) {
3978 ia6_release(ia, &psref);
3979 goto ours;
3980 }
3981
3982 s = pserialize_read_enter();
3983 ia6_release(ia, &psref);
3984 }
3985 pserialize_read_exit(s);
3986
3987 /* loopback, just for safety */
3988 if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3989 goto ours;
3990
3991 ours = 0;
3992 ours:
3993 curlwp_bindx(bound);
3994
3995 return ours;
3996 }
3997 #endif /*INET6*/
3998
3999 /*
4000 * compare two secasindex structure.
4001 * flag can specify to compare 2 saidxes.
4002 * compare two secasindex structure without both mode and reqid.
4003 * don't compare port.
4004 * IN:
4005 * saidx0: source, it can be in SAD.
4006 * saidx1: object.
4007 * OUT:
4008 * 1 : equal
4009 * 0 : not equal
4010 */
4011 static int
4012 key_saidx_match(
4013 const struct secasindex *saidx0,
4014 const struct secasindex *saidx1,
4015 int flag)
4016 {
4017 int chkport;
4018 const struct sockaddr *sa0src, *sa0dst, *sa1src, *sa1dst;
4019
4020 KASSERT(saidx0 != NULL);
4021 KASSERT(saidx1 != NULL);
4022
4023 /* sanity */
4024 if (saidx0->proto != saidx1->proto)
4025 return 0;
4026
4027 if (flag == CMP_EXACTLY) {
4028 if (saidx0->mode != saidx1->mode)
4029 return 0;
4030 if (saidx0->reqid != saidx1->reqid)
4031 return 0;
4032 if (memcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4033 memcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4034 return 0;
4035 } else {
4036
4037 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4038 if (flag == CMP_MODE_REQID ||flag == CMP_REQID) {
4039 /*
4040 * If reqid of SPD is non-zero, unique SA is required.
4041 * The result must be of same reqid in this case.
4042 */
4043 if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4044 return 0;
4045 }
4046
4047 if (flag == CMP_MODE_REQID) {
4048 if (saidx0->mode != IPSEC_MODE_ANY &&
4049 saidx0->mode != saidx1->mode)
4050 return 0;
4051 }
4052
4053
4054 sa0src = &saidx0->src.sa;
4055 sa0dst = &saidx0->dst.sa;
4056 sa1src = &saidx1->src.sa;
4057 sa1dst = &saidx1->dst.sa;
4058 /*
4059 * If NAT-T is enabled, check ports for tunnel mode.
4060 * Don't do it for transport mode, as there is no
4061 * port information available in the SP.
4062 * Also don't check ports if they are set to zero
4063 * in the SPD: This means we have a non-generated
4064 * SPD which can't know UDP ports.
4065 */
4066 if (saidx1->mode == IPSEC_MODE_TUNNEL)
4067 chkport = PORT_LOOSE;
4068 else
4069 chkport = PORT_NONE;
4070
4071 if (!key_sockaddr_match(sa0src, sa1src, chkport)) {
4072 return 0;
4073 }
4074 if (!key_sockaddr_match(sa0dst, sa1dst, chkport)) {
4075 return 0;
4076 }
4077 }
4078
4079 return 1;
4080 }
4081
4082 /*
4083 * compare two secindex structure exactly.
4084 * IN:
4085 * spidx0: source, it is often in SPD.
4086 * spidx1: object, it is often from PFKEY message.
4087 * OUT:
4088 * 1 : equal
4089 * 0 : not equal
4090 */
4091 static int
4092 key_spidx_match_exactly(
4093 const struct secpolicyindex *spidx0,
4094 const struct secpolicyindex *spidx1)
4095 {
4096
4097 KASSERT(spidx0 != NULL);
4098 KASSERT(spidx1 != NULL);
4099
4100 /* sanity */
4101 if (spidx0->prefs != spidx1->prefs ||
4102 spidx0->prefd != spidx1->prefd ||
4103 spidx0->ul_proto != spidx1->ul_proto)
4104 return 0;
4105
4106 return key_sockaddr_match(&spidx0->src.sa, &spidx1->src.sa, PORT_STRICT) &&
4107 key_sockaddr_match(&spidx0->dst.sa, &spidx1->dst.sa, PORT_STRICT);
4108 }
4109
4110 /*
4111 * compare two secindex structure with mask.
4112 * IN:
4113 * spidx0: source, it is often in SPD.
4114 * spidx1: object, it is often from IP header.
4115 * OUT:
4116 * 1 : equal
4117 * 0 : not equal
4118 */
4119 static int
4120 key_spidx_match_withmask(
4121 const struct secpolicyindex *spidx0,
4122 const struct secpolicyindex *spidx1)
4123 {
4124
4125 KASSERT(spidx0 != NULL);
4126 KASSERT(spidx1 != NULL);
4127
4128 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4129 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4130 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4131 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4132 return 0;
4133
4134 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4135 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY &&
4136 spidx0->ul_proto != spidx1->ul_proto)
4137 return 0;
4138
4139 switch (spidx0->src.sa.sa_family) {
4140 case AF_INET:
4141 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY &&
4142 spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4143 return 0;
4144 if (!key_bb_match_withmask(&spidx0->src.sin.sin_addr,
4145 &spidx1->src.sin.sin_addr, spidx0->prefs))
4146 return 0;
4147 break;
4148 case AF_INET6:
4149 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY &&
4150 spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4151 return 0;
4152 /*
4153 * scope_id check. if sin6_scope_id is 0, we regard it
4154 * as a wildcard scope, which matches any scope zone ID.
4155 */
4156 if (spidx0->src.sin6.sin6_scope_id &&
4157 spidx1->src.sin6.sin6_scope_id &&
4158 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4159 return 0;
4160 if (!key_bb_match_withmask(&spidx0->src.sin6.sin6_addr,
4161 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4162 return 0;
4163 break;
4164 default:
4165 /* XXX */
4166 if (memcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4167 return 0;
4168 break;
4169 }
4170
4171 switch (spidx0->dst.sa.sa_family) {
4172 case AF_INET:
4173 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY &&
4174 spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4175 return 0;
4176 if (!key_bb_match_withmask(&spidx0->dst.sin.sin_addr,
4177 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4178 return 0;
4179 break;
4180 case AF_INET6:
4181 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY &&
4182 spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4183 return 0;
4184 /*
4185 * scope_id check. if sin6_scope_id is 0, we regard it
4186 * as a wildcard scope, which matches any scope zone ID.
4187 */
4188 if (spidx0->src.sin6.sin6_scope_id &&
4189 spidx1->src.sin6.sin6_scope_id &&
4190 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4191 return 0;
4192 if (!key_bb_match_withmask(&spidx0->dst.sin6.sin6_addr,
4193 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4194 return 0;
4195 break;
4196 default:
4197 /* XXX */
4198 if (memcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4199 return 0;
4200 break;
4201 }
4202
4203 /* XXX Do we check other field ? e.g. flowinfo */
4204
4205 return 1;
4206 }
4207
4208 /* returns 0 on match */
4209 static int
4210 key_portcomp(in_port_t port1, in_port_t port2, int howport)
4211 {
4212 switch (howport) {
4213 case PORT_NONE:
4214 return 0;
4215 case PORT_LOOSE:
4216 if (port1 == 0 || port2 == 0)
4217 return 0;
4218 /*FALLTHROUGH*/
4219 case PORT_STRICT:
4220 if (port1 != port2) {
4221 KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
4222 "port fail %d != %d\n", port1, port2);
4223 return 1;
4224 }
4225 return 0;
4226 default:
4227 KASSERT(0);
4228 return 1;
4229 }
4230 }
4231
4232 /* returns 1 on match */
4233 static int
4234 key_sockaddr_match(
4235 const struct sockaddr *sa1,
4236 const struct sockaddr *sa2,
4237 int howport)
4238 {
4239 const struct sockaddr_in *sin1, *sin2;
4240 const struct sockaddr_in6 *sin61, *sin62;
4241
4242 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) {
4243 KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
4244 "fam/len fail %d != %d || %d != %d\n",
4245 sa1->sa_family, sa2->sa_family, sa1->sa_len,
4246 sa2->sa_len);
4247 return 0;
4248 }
4249
4250 switch (sa1->sa_family) {
4251 case AF_INET:
4252 if (sa1->sa_len != sizeof(struct sockaddr_in)) {
4253 KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
4254 "len fail %d != %zu\n",
4255 sa1->sa_len, sizeof(struct sockaddr_in));
4256 return 0;
4257 }
4258 sin1 = (const struct sockaddr_in *)sa1;
4259 sin2 = (const struct sockaddr_in *)sa2;
4260 if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) {
4261 KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
4262 "addr fail %#x != %#x\n",
4263 sin1->sin_addr.s_addr, sin2->sin_addr.s_addr);
4264 return 0;
4265 }
4266 if (key_portcomp(sin1->sin_port, sin2->sin_port, howport)) {
4267 return 0;
4268 }
4269 KEYDEBUG_PRINTF(KEYDEBUG_MATCH,
4270 "addr success %#x[%d] == %#x[%d]\n",
4271 sin1->sin_addr.s_addr, sin1->sin_port,
4272 sin2->sin_addr.s_addr, sin2->sin_port);
4273 break;
4274 case AF_INET6:
4275 sin61 = (const struct sockaddr_in6 *)sa1;
4276 sin62 = (const struct sockaddr_in6 *)sa2;
4277 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4278 return 0; /*EINVAL*/
4279
4280 if (sin61->sin6_scope_id != sin62->sin6_scope_id) {
4281 return 0;
4282 }
4283 if (!IN6_ARE_ADDR_EQUAL(&sin61->sin6_addr, &sin62->sin6_addr)) {
4284 return 0;
4285 }
4286 if (key_portcomp(sin61->sin6_port, sin62->sin6_port, howport)) {
4287 return 0;
4288 }
4289 break;
4290 default:
4291 if (memcmp(sa1, sa2, sa1->sa_len) != 0)
4292 return 0;
4293 break;
4294 }
4295
4296 return 1;
4297 }
4298
4299 /*
4300 * compare two buffers with mask.
4301 * IN:
4302 * addr1: source
4303 * addr2: object
4304 * bits: Number of bits to compare
4305 * OUT:
4306 * 1 : equal
4307 * 0 : not equal
4308 */
4309 static int
4310 key_bb_match_withmask(const void *a1, const void *a2, u_int bits)
4311 {
4312 const unsigned char *p1 = a1;
4313 const unsigned char *p2 = a2;
4314
4315 /* XXX: This could be considerably faster if we compare a word
4316 * at a time, but it is complicated on LSB Endian machines */
4317
4318 /* Handle null pointers */
4319 if (p1 == NULL || p2 == NULL)
4320 return (p1 == p2);
4321
4322 while (bits >= 8) {
4323 if (*p1++ != *p2++)
4324 return 0;
4325 bits -= 8;
4326 }
4327
4328 if (bits > 0) {
4329 u_int8_t mask = ~((1<<(8-bits))-1);
4330 if ((*p1 & mask) != (*p2 & mask))
4331 return 0;
4332 }
4333 return 1; /* Match! */
4334 }
4335
4336 static void
4337 key_timehandler_spd(time_t now)
4338 {
4339 u_int dir;
4340 struct secpolicy *sp;
4341
4342 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4343 retry:
4344 SPLIST_WRITER_FOREACH(sp, dir) {
4345 if (sp->state == IPSEC_SPSTATE_DEAD) {
4346 key_sp_unlink(sp); /*XXX*/
4347 goto retry;
4348 }
4349
4350 if (sp->lifetime == 0 && sp->validtime == 0)
4351 continue;
4352
4353 /* the deletion will occur next time */
4354 if ((sp->lifetime && now - sp->created > sp->lifetime) ||
4355 (sp->validtime && now - sp->lastused > sp->validtime)) {
4356 key_sp_dead(sp);
4357 key_spdexpire(sp);
4358 goto retry;
4359 }
4360 }
4361 }
4362 }
4363
4364 static void
4365 key_timehandler_sad(time_t now)
4366 {
4367 struct secashead *sah, *nextsah;
4368 struct secasvar *sav, *nextsav;
4369
4370 LIST_FOREACH_SAFE(sah, &sahtree, chain, nextsah) {
4371 /* if sah has been dead, then delete it and process next sah. */
4372 if (sah->state == SADB_SASTATE_DEAD) {
4373 key_delsah(sah);
4374 continue;
4375 }
4376
4377 /* if LARVAL entry doesn't become MATURE, delete it. */
4378 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL],
4379 chain, nextsav) {
4380 if (now - sav->created > key_larval_lifetime) {
4381 KEY_FREESAV(&sav);
4382 }
4383 }
4384
4385 /*
4386 * check MATURE entry to start to send expire message
4387 * whether or not.
4388 */
4389 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE],
4390 chain, nextsav) {
4391 /* we don't need to check. */
4392 if (sav->lft_s == NULL)
4393 continue;
4394
4395 /* sanity check */
4396 KASSERT(sav->lft_c != NULL);
4397
4398 /* check SOFT lifetime */
4399 if (sav->lft_s->sadb_lifetime_addtime != 0 &&
4400 now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4401 /*
4402 * check SA to be used whether or not.
4403 * when SA hasn't been used, delete it.
4404 */
4405 if (sav->lft_c->sadb_lifetime_usetime == 0) {
4406 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4407 KEY_FREESAV(&sav);
4408 } else {
4409 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4410 /*
4411 * XXX If we keep to send expire
4412 * message in the status of
4413 * DYING. Do remove below code.
4414 */
4415 key_expire(sav);
4416 }
4417 }
4418 /* check SOFT lifetime by bytes */
4419 /*
4420 * XXX I don't know the way to delete this SA
4421 * when new SA is installed. Caution when it's
4422 * installed too big lifetime by time.
4423 */
4424 else if (sav->lft_s->sadb_lifetime_bytes != 0 &&
4425 sav->lft_s->sadb_lifetime_bytes <
4426 sav->lft_c->sadb_lifetime_bytes) {
4427
4428 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4429 /*
4430 * XXX If we keep to send expire
4431 * message in the status of
4432 * DYING. Do remove below code.
4433 */
4434 key_expire(sav);
4435 }
4436 }
4437
4438 /* check DYING entry to change status to DEAD. */
4439 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING],
4440 chain, nextsav) {
4441 /* we don't need to check. */
4442 if (sav->lft_h == NULL)
4443 continue;
4444
4445 /* sanity check */
4446 KASSERT(sav->lft_c != NULL);
4447
4448 if (sav->lft_h->sadb_lifetime_addtime != 0 &&
4449 now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4450 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4451 KEY_FREESAV(&sav);
4452 }
4453 #if 0 /* XXX Should we keep to send expire message until HARD lifetime ? */
4454 else if (sav->lft_s != NULL
4455 && sav->lft_s->sadb_lifetime_addtime != 0
4456 && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4457 /*
4458 * XXX: should be checked to be
4459 * installed the valid SA.
4460 */
4461
4462 /*
4463 * If there is no SA then sending
4464 * expire message.
4465 */
4466 key_expire(sav);
4467 }
4468 #endif
4469 /* check HARD lifetime by bytes */
4470 else if (sav->lft_h->sadb_lifetime_bytes != 0 &&
4471 sav->lft_h->sadb_lifetime_bytes <
4472 sav->lft_c->sadb_lifetime_bytes) {
4473 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4474 KEY_FREESAV(&sav);
4475 }
4476 }
4477
4478 /* delete entry in DEAD */
4479 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD],
4480 chain, nextsav) {
4481 /* sanity check */
4482 if (sav->state != SADB_SASTATE_DEAD) {
4483 IPSECLOG(LOG_DEBUG,
4484 "invalid sav->state (queue: %d SA: %d): "
4485 "kill it anyway\n",
4486 SADB_SASTATE_DEAD, sav->state);
4487 }
4488
4489 /*
4490 * do not call key_freesav() here.
4491 * sav should already be freed, and sav->refcnt
4492 * shows other references to sav
4493 * (such as from SPD).
4494 */
4495 }
4496 }
4497 }
4498
4499 static void
4500 key_timehandler_acq(time_t now)
4501 {
4502 #ifndef IPSEC_NONBLOCK_ACQUIRE
4503 struct secacq *acq, *nextacq;
4504
4505 restart:
4506 mutex_enter(&key_mtx);
4507 LIST_FOREACH_SAFE(acq, &acqtree, chain, nextacq) {
4508 if (now - acq->created > key_blockacq_lifetime) {
4509 LIST_REMOVE(acq, chain);
4510 mutex_exit(&key_mtx);
4511 kmem_free(acq, sizeof(*acq));
4512 goto restart;
4513 }
4514 }
4515 mutex_exit(&key_mtx);
4516 #endif
4517 }
4518
4519 static void
4520 key_timehandler_spacq(time_t now)
4521 {
4522 #ifdef notyet
4523 struct secspacq *acq, *nextacq;
4524
4525 LIST_FOREACH_SAFE(acq, &spacqtree, chain, nextacq) {
4526 if (now - acq->created > key_blockacq_lifetime) {
4527 KASSERT(__LIST_CHAINED(acq));
4528 LIST_REMOVE(acq, chain);
4529 kmem_free(acq, sizeof(*acq));
4530 }
4531 }
4532 #endif
4533 }
4534
4535 /*
4536 * time handler.
4537 * scanning SPD and SAD to check status for each entries,
4538 * and do to remove or to expire.
4539 */
4540 static void
4541 key_timehandler_work(struct work *wk, void *arg)
4542 {
4543 int s;
4544 time_t now = time_uptime;
4545
4546 s = splsoftnet();
4547 mutex_enter(softnet_lock);
4548
4549 key_timehandler_spd(now);
4550 key_timehandler_sad(now);
4551 key_timehandler_acq(now);
4552 key_timehandler_spacq(now);
4553
4554 /* do exchange to tick time !! */
4555 callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
4556
4557 mutex_exit(softnet_lock);
4558 splx(s);
4559 return;
4560 }
4561
4562 static void
4563 key_timehandler(void *arg)
4564 {
4565
4566 workqueue_enqueue(key_timehandler_wq, &key_timehandler_wk, NULL);
4567 }
4568
4569 u_long
4570 key_random(void)
4571 {
4572 u_long value;
4573
4574 key_randomfill(&value, sizeof(value));
4575 return value;
4576 }
4577
4578 void
4579 key_randomfill(void *p, size_t l)
4580 {
4581
4582 cprng_fast(p, l);
4583 }
4584
4585 /*
4586 * map SADB_SATYPE_* to IPPROTO_*.
4587 * if satype == SADB_SATYPE then satype is mapped to ~0.
4588 * OUT:
4589 * 0: invalid satype.
4590 */
4591 static u_int16_t
4592 key_satype2proto(u_int8_t satype)
4593 {
4594 switch (satype) {
4595 case SADB_SATYPE_UNSPEC:
4596 return IPSEC_PROTO_ANY;
4597 case SADB_SATYPE_AH:
4598 return IPPROTO_AH;
4599 case SADB_SATYPE_ESP:
4600 return IPPROTO_ESP;
4601 case SADB_X_SATYPE_IPCOMP:
4602 return IPPROTO_IPCOMP;
4603 case SADB_X_SATYPE_TCPSIGNATURE:
4604 return IPPROTO_TCP;
4605 default:
4606 return 0;
4607 }
4608 /* NOTREACHED */
4609 }
4610
4611 /*
4612 * map IPPROTO_* to SADB_SATYPE_*
4613 * OUT:
4614 * 0: invalid protocol type.
4615 */
4616 static u_int8_t
4617 key_proto2satype(u_int16_t proto)
4618 {
4619 switch (proto) {
4620 case IPPROTO_AH:
4621 return SADB_SATYPE_AH;
4622 case IPPROTO_ESP:
4623 return SADB_SATYPE_ESP;
4624 case IPPROTO_IPCOMP:
4625 return SADB_X_SATYPE_IPCOMP;
4626 case IPPROTO_TCP:
4627 return SADB_X_SATYPE_TCPSIGNATURE;
4628 default:
4629 return 0;
4630 }
4631 /* NOTREACHED */
4632 }
4633
4634 static int
4635 key_setsecasidx(int proto, int mode, int reqid,
4636 const struct sockaddr *src, const struct sockaddr *dst,
4637 struct secasindex * saidx)
4638 {
4639 const union sockaddr_union *src_u = (const union sockaddr_union *)src;
4640 const union sockaddr_union *dst_u = (const union sockaddr_union *)dst;
4641
4642 /* sa len safety check */
4643 if (key_checksalen(src_u) != 0)
4644 return -1;
4645 if (key_checksalen(dst_u) != 0)
4646 return -1;
4647
4648 memset(saidx, 0, sizeof(*saidx));
4649 saidx->proto = proto;
4650 saidx->mode = mode;
4651 saidx->reqid = reqid;
4652 memcpy(&saidx->src, src_u, src_u->sa.sa_len);
4653 memcpy(&saidx->dst, dst_u, dst_u->sa.sa_len);
4654
4655 key_porttosaddr(&((saidx)->src), 0);
4656 key_porttosaddr(&((saidx)->dst), 0);
4657 return 0;
4658 }
4659
4660 static void
4661 key_init_spidx_bymsghdr(struct secpolicyindex *spidx,
4662 const struct sadb_msghdr *mhp)
4663 {
4664 const struct sadb_address *src0, *dst0;
4665 const struct sockaddr *src, *dst;
4666 const struct sadb_x_policy *xpl0;
4667
4668 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4669 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4670 src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
4671 dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
4672 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
4673
4674 memset(spidx, 0, sizeof(*spidx));
4675 spidx->dir = xpl0->sadb_x_policy_dir;
4676 spidx->prefs = src0->sadb_address_prefixlen;
4677 spidx->prefd = dst0->sadb_address_prefixlen;
4678 spidx->ul_proto = src0->sadb_address_proto;
4679 /* XXX boundary check against sa_len */
4680 memcpy(&spidx->src, src, src->sa_len);
4681 memcpy(&spidx->dst, dst, dst->sa_len);
4682 }
4683
4684 /* %%% PF_KEY */
4685 /*
4686 * SADB_GETSPI processing is to receive
4687 * <base, (SA2), src address, dst address, (SPI range)>
4688 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4689 * tree with the status of LARVAL, and send
4690 * <base, SA(*), address(SD)>
4691 * to the IKMPd.
4692 *
4693 * IN: mhp: pointer to the pointer to each header.
4694 * OUT: NULL if fail.
4695 * other if success, return pointer to the message to send.
4696 */
4697 static int
4698 key_api_getspi(struct socket *so, struct mbuf *m,
4699 const struct sadb_msghdr *mhp)
4700 {
4701 const struct sockaddr *src, *dst;
4702 struct secasindex saidx;
4703 struct secashead *newsah;
4704 struct secasvar *newsav;
4705 u_int8_t proto;
4706 u_int32_t spi;
4707 u_int8_t mode;
4708 u_int16_t reqid;
4709 int error;
4710
4711 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4712 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4713 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
4714 return key_senderror(so, m, EINVAL);
4715 }
4716 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4717 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4718 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
4719 return key_senderror(so, m, EINVAL);
4720 }
4721 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4722 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4723 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4724 } else {
4725 mode = IPSEC_MODE_ANY;
4726 reqid = 0;
4727 }
4728
4729 src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
4730 dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
4731
4732 /* map satype to proto */
4733 proto = key_satype2proto(mhp->msg->sadb_msg_satype);
4734 if (proto == 0) {
4735 IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
4736 return key_senderror(so, m, EINVAL);
4737 }
4738
4739
4740 error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
4741 if (error != 0)
4742 return key_senderror(so, m, EINVAL);
4743
4744 error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
4745 if (error != 0)
4746 return key_senderror(so, m, EINVAL);
4747
4748 /* SPI allocation */
4749 spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4750 &saidx);
4751 if (spi == 0)
4752 return key_senderror(so, m, EINVAL);
4753
4754 /* get a SA index */
4755 newsah = key_getsah(&saidx, CMP_REQID);
4756 if (newsah == NULL) {
4757 /* create a new SA index */
4758 newsah = key_newsah(&saidx);
4759 if (newsah == NULL) {
4760 IPSECLOG(LOG_DEBUG, "No more memory.\n");
4761 return key_senderror(so, m, ENOBUFS);
4762 }
4763 }
4764
4765 /* get a new SA */
4766 /* XXX rewrite */
4767 newsav = KEY_NEWSAV(m, mhp, &error);
4768 if (newsav == NULL) {
4769 /* XXX don't free new SA index allocated in above. */
4770 return key_senderror(so, m, error);
4771 }
4772
4773 /* set spi */
4774 newsav->spi = htonl(spi);
4775
4776 /* add to satree */
4777 newsav->refcnt = 1;
4778 newsav->sah = newsah;
4779 newsav->state = SADB_SASTATE_LARVAL;
4780 LIST_INSERT_TAIL(&newsah->savtree[SADB_SASTATE_LARVAL], newsav,
4781 secasvar, chain);
4782 key_validate_savlist(newsah, SADB_SASTATE_LARVAL);
4783
4784 #ifndef IPSEC_NONBLOCK_ACQUIRE
4785 /* delete the entry in acqtree */
4786 if (mhp->msg->sadb_msg_seq != 0) {
4787 struct secacq *acq;
4788 mutex_enter(&key_mtx);
4789 acq = key_getacqbyseq(mhp->msg->sadb_msg_seq);
4790 if (acq != NULL) {
4791 /* reset counter in order to deletion by timehandler. */
4792 acq->created = time_uptime;
4793 acq->count = 0;
4794 }
4795 mutex_exit(&key_mtx);
4796 }
4797 #endif
4798
4799 {
4800 struct mbuf *n, *nn;
4801 struct sadb_sa *m_sa;
4802 int off, len;
4803
4804 CTASSERT(PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4805 PFKEY_ALIGN8(sizeof(struct sadb_sa)) <= MCLBYTES);
4806
4807 /* create new sadb_msg to reply. */
4808 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4809 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4810
4811 MGETHDR(n, M_DONTWAIT, MT_DATA);
4812 if (len > MHLEN) {
4813 MCLGET(n, M_DONTWAIT);
4814 if ((n->m_flags & M_EXT) == 0) {
4815 m_freem(n);
4816 n = NULL;
4817 }
4818 }
4819 if (!n)
4820 return key_senderror(so, m, ENOBUFS);
4821
4822 n->m_len = len;
4823 n->m_next = NULL;
4824 off = 0;
4825
4826 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
4827 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4828
4829 m_sa = (struct sadb_sa *)(mtod(n, char *) + off);
4830 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4831 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4832 m_sa->sadb_sa_spi = htonl(spi);
4833 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4834
4835 KASSERTMSG(off == len, "length inconsistency");
4836
4837 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4838 SADB_EXT_ADDRESS_DST);
4839 if (!n->m_next) {
4840 m_freem(n);
4841 return key_senderror(so, m, ENOBUFS);
4842 }
4843
4844 if (n->m_len < sizeof(struct sadb_msg)) {
4845 n = m_pullup(n, sizeof(struct sadb_msg));
4846 if (n == NULL)
4847 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4848 }
4849
4850 n->m_pkthdr.len = 0;
4851 for (nn = n; nn; nn = nn->m_next)
4852 n->m_pkthdr.len += nn->m_len;
4853
4854 key_fill_replymsg(n, newsav->seq);
4855
4856 m_freem(m);
4857 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4858 }
4859 }
4860
4861 /*
4862 * allocating new SPI
4863 * called by key_api_getspi().
4864 * OUT:
4865 * 0: failure.
4866 * others: success.
4867 */
4868 static u_int32_t
4869 key_do_getnewspi(const struct sadb_spirange *spirange,
4870 const struct secasindex *saidx)
4871 {
4872 u_int32_t newspi;
4873 u_int32_t spmin, spmax;
4874 int count = key_spi_trycnt;
4875
4876 /* set spi range to allocate */
4877 if (spirange != NULL) {
4878 spmin = spirange->sadb_spirange_min;
4879 spmax = spirange->sadb_spirange_max;
4880 } else {
4881 spmin = key_spi_minval;
4882 spmax = key_spi_maxval;
4883 }
4884 /* IPCOMP needs 2-byte SPI */
4885 if (saidx->proto == IPPROTO_IPCOMP) {
4886 u_int32_t t;
4887 if (spmin >= 0x10000)
4888 spmin = 0xffff;
4889 if (spmax >= 0x10000)
4890 spmax = 0xffff;
4891 if (spmin > spmax) {
4892 t = spmin; spmin = spmax; spmax = t;
4893 }
4894 }
4895
4896 if (spmin == spmax) {
4897 if (key_checkspidup(saidx, htonl(spmin))) {
4898 IPSECLOG(LOG_DEBUG, "SPI %u exists already.\n", spmin);
4899 return 0;
4900 }
4901
4902 count--; /* taking one cost. */
4903 newspi = spmin;
4904
4905 } else {
4906
4907 /* init SPI */
4908 newspi = 0;
4909
4910 /* when requesting to allocate spi ranged */
4911 while (count--) {
4912 /* generate pseudo-random SPI value ranged. */
4913 newspi = spmin + (key_random() % (spmax - spmin + 1));
4914
4915 if (!key_checkspidup(saidx, htonl(newspi)))
4916 break;
4917 }
4918
4919 if (count == 0 || newspi == 0) {
4920 IPSECLOG(LOG_DEBUG, "to allocate spi is failed.\n");
4921 return 0;
4922 }
4923 }
4924
4925 /* statistics */
4926 keystat.getspi_count =
4927 (keystat.getspi_count + key_spi_trycnt - count) / 2;
4928
4929 return newspi;
4930 }
4931
4932 static int
4933 key_handle_natt_info(struct secasvar *sav,
4934 const struct sadb_msghdr *mhp)
4935 {
4936 const char *msg = "?" ;
4937 struct sadb_x_nat_t_type *type;
4938 struct sadb_x_nat_t_port *sport, *dport;
4939 struct sadb_address *iaddr, *raddr;
4940 struct sadb_x_nat_t_frag *frag;
4941
4942 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
4943 mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
4944 mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL)
4945 return 0;
4946
4947 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) {
4948 msg = "TYPE";
4949 goto bad;
4950 }
4951
4952 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) {
4953 msg = "SPORT";
4954 goto bad;
4955 }
4956
4957 if (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4958 msg = "DPORT";
4959 goto bad;
4960 }
4961
4962 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) {
4963 IPSECLOG(LOG_DEBUG, "NAT-T OAi present\n");
4964 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr)) {
4965 msg = "OAI";
4966 goto bad;
4967 }
4968 }
4969
4970 if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
4971 IPSECLOG(LOG_DEBUG, "NAT-T OAr present\n");
4972 if (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
4973 msg = "OAR";
4974 goto bad;
4975 }
4976 }
4977
4978 if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
4979 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
4980 msg = "FRAG";
4981 goto bad;
4982 }
4983 }
4984
4985 type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
4986 sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4987 dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4988 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
4989 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
4990 frag = (struct sadb_x_nat_t_frag *)mhp->ext[SADB_X_EXT_NAT_T_FRAG];
4991
4992 IPSECLOG(LOG_DEBUG, "type %d, sport = %d, dport = %d\n",
4993 type->sadb_x_nat_t_type_type,
4994 ntohs(sport->sadb_x_nat_t_port_port),
4995 ntohs(dport->sadb_x_nat_t_port_port));
4996
4997 sav->natt_type = type->sadb_x_nat_t_type_type;
4998 key_porttosaddr(&sav->sah->saidx.src, sport->sadb_x_nat_t_port_port);
4999 key_porttosaddr(&sav->sah->saidx.dst, dport->sadb_x_nat_t_port_port);
5000 if (frag)
5001 sav->esp_frag = frag->sadb_x_nat_t_frag_fraglen;
5002 else
5003 sav->esp_frag = IP_MAXPACKET;
5004
5005 return 0;
5006 bad:
5007 IPSECLOG(LOG_DEBUG, "invalid message %s\n", msg);
5008 __USE(msg);
5009 return -1;
5010 }
5011
5012 /* Just update the IPSEC_NAT_T ports if present */
5013 static int
5014 key_set_natt_ports(union sockaddr_union *src, union sockaddr_union *dst,
5015 const struct sadb_msghdr *mhp)
5016 {
5017 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
5018 IPSECLOG(LOG_DEBUG, "NAT-T OAi present\n");
5019 if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
5020 IPSECLOG(LOG_DEBUG, "NAT-T OAr present\n");
5021
5022 if ((mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL) &&
5023 (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL) &&
5024 (mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL)) {
5025 struct sadb_x_nat_t_type *type;
5026 struct sadb_x_nat_t_port *sport;
5027 struct sadb_x_nat_t_port *dport;
5028
5029 if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
5030 (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
5031 (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
5032 IPSECLOG(LOG_DEBUG, "invalid message\n");
5033 return -1;
5034 }
5035
5036 type = (struct sadb_x_nat_t_type *)
5037 mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5038 sport = (struct sadb_x_nat_t_port *)
5039 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5040 dport = (struct sadb_x_nat_t_port *)
5041 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5042
5043 key_porttosaddr(src, sport->sadb_x_nat_t_port_port);
5044 key_porttosaddr(dst, dport->sadb_x_nat_t_port_port);
5045
5046 IPSECLOG(LOG_DEBUG, "type %d, sport = %d, dport = %d\n",
5047 type->sadb_x_nat_t_type_type,
5048 ntohs(sport->sadb_x_nat_t_port_port),
5049 ntohs(dport->sadb_x_nat_t_port_port));
5050 }
5051
5052 return 0;
5053 }
5054
5055
5056 /*
5057 * SADB_UPDATE processing
5058 * receive
5059 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5060 * key(AE), (identity(SD),) (sensitivity)>
5061 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
5062 * and send
5063 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5064 * (identity(SD),) (sensitivity)>
5065 * to the ikmpd.
5066 *
5067 * m will always be freed.
5068 */
5069 static int
5070 key_api_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5071 {
5072 struct sadb_sa *sa0;
5073 const struct sockaddr *src, *dst;
5074 struct secasindex saidx;
5075 struct secashead *sah;
5076 struct secasvar *sav, *newsav;
5077 u_int16_t proto;
5078 u_int8_t mode;
5079 u_int16_t reqid;
5080 int error;
5081
5082 /* map satype to proto */
5083 proto = key_satype2proto(mhp->msg->sadb_msg_satype);
5084 if (proto == 0) {
5085 IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
5086 return key_senderror(so, m, EINVAL);
5087 }
5088
5089 if (mhp->ext[SADB_EXT_SA] == NULL ||
5090 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5091 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5092 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5093 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5094 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5095 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5096 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5097 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5098 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5099 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5100 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
5101 return key_senderror(so, m, EINVAL);
5102 }
5103 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5104 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5105 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5106 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
5107 return key_senderror(so, m, EINVAL);
5108 }
5109 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5110 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5111 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5112 } else {
5113 mode = IPSEC_MODE_ANY;
5114 reqid = 0;
5115 }
5116 /* XXX boundary checking for other extensions */
5117
5118 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5119 src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
5120 dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
5121
5122 error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
5123 if (error != 0)
5124 return key_senderror(so, m, EINVAL);
5125
5126 error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
5127 if (error != 0)
5128 return key_senderror(so, m, EINVAL);
5129
5130 /* get a SA header */
5131 sah = key_getsah(&saidx, CMP_REQID);
5132 if (sah == NULL) {
5133 IPSECLOG(LOG_DEBUG, "no SA index found.\n");
5134 return key_senderror(so, m, ENOENT);
5135 }
5136
5137 /* set spidx if there */
5138 /* XXX rewrite */
5139 error = key_setident(sah, m, mhp);
5140 if (error)
5141 return key_senderror(so, m, error);
5142
5143 /* find a SA with sequence number. */
5144 #ifdef IPSEC_DOSEQCHECK
5145 if (mhp->msg->sadb_msg_seq != 0) {
5146 sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq);
5147 if (sav == NULL) {
5148 IPSECLOG(LOG_DEBUG,
5149 "no larval SA with sequence %u exists.\n",
5150 mhp->msg->sadb_msg_seq);
5151 return key_senderror(so, m, ENOENT);
5152 }
5153 }
5154 #else
5155 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5156 if (sav == NULL) {
5157 IPSECLOG(LOG_DEBUG, "no such a SA found (spi:%u)\n",
5158 (u_int32_t)ntohl(sa0->sadb_sa_spi));
5159 return key_senderror(so, m, EINVAL);
5160 }
5161 #endif
5162
5163 /* validity check */
5164 if (sav->sah->saidx.proto != proto) {
5165 IPSECLOG(LOG_DEBUG, "protocol mismatched (DB=%u param=%u)\n",
5166 sav->sah->saidx.proto, proto);
5167 error = EINVAL;
5168 goto error;
5169 }
5170 #ifdef IPSEC_DOSEQCHECK
5171 if (sav->spi != sa0->sadb_sa_spi) {
5172 IPSECLOG(LOG_DEBUG, "SPI mismatched (DB:%u param:%u)\n",
5173 (u_int32_t)ntohl(sav->spi),
5174 (u_int32_t)ntohl(sa0->sadb_sa_spi));
5175 error = EINVAL;
5176 goto error;
5177 }
5178 #endif
5179 if (sav->pid != mhp->msg->sadb_msg_pid) {
5180 IPSECLOG(LOG_DEBUG, "pid mismatched (DB:%u param:%u)\n",
5181 sav->pid, mhp->msg->sadb_msg_pid);
5182 error = EINVAL;
5183 goto error;
5184 }
5185
5186 /*
5187 * Allocate a new SA instead of modifying the existing SA directly
5188 * to avoid race conditions.
5189 */
5190 newsav = kmem_zalloc(sizeof(struct secasvar), KM_SLEEP);
5191
5192 /* copy sav values */
5193 newsav->spi = sav->spi;
5194 newsav->seq = sav->seq;
5195 newsav->created = sav->created;
5196 newsav->pid = sav->pid;
5197 newsav->sah = sav->sah;
5198
5199 error = key_setsaval(newsav, m, mhp);
5200 if (error) {
5201 key_delsav(newsav);
5202 goto error;
5203 }
5204
5205 error = key_handle_natt_info(newsav, mhp);
5206 if (error != 0) {
5207 key_delsav(newsav);
5208 goto error;
5209 }
5210
5211 error = key_init_xform(newsav);
5212 if (error != 0) {
5213 key_delsav(newsav);
5214 goto error;
5215 }
5216
5217 /* add to satree */
5218 newsav->refcnt = 1;
5219 newsav->state = SADB_SASTATE_MATURE;
5220 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_MATURE], newsav,
5221 secasvar, chain);
5222 key_validate_savlist(sah, SADB_SASTATE_MATURE);
5223
5224 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5225 KEY_FREESAV(&sav);
5226 KEY_FREESAV(&sav);
5227
5228 {
5229 struct mbuf *n;
5230
5231 /* set msg buf from mhp */
5232 n = key_getmsgbuf_x1(m, mhp);
5233 if (n == NULL) {
5234 IPSECLOG(LOG_DEBUG, "No more memory.\n");
5235 return key_senderror(so, m, ENOBUFS);
5236 }
5237
5238 m_freem(m);
5239 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5240 }
5241 error:
5242 KEY_FREESAV(&sav);
5243 return key_senderror(so, m, error);
5244 }
5245
5246 /*
5247 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5248 * only called by key_api_update().
5249 * OUT:
5250 * NULL : not found
5251 * others : found, pointer to a SA.
5252 */
5253 #ifdef IPSEC_DOSEQCHECK
5254 static struct secasvar *
5255 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
5256 {
5257 struct secasvar *sav;
5258 u_int state;
5259
5260 state = SADB_SASTATE_LARVAL;
5261
5262 /* search SAD with sequence number ? */
5263 LIST_FOREACH(sav, &sah->savtree[state], chain) {
5264
5265 KEY_CHKSASTATE(state, sav->state);
5266
5267 if (sav->seq == seq) {
5268 SA_ADDREF(sav);
5269 KEYDEBUG_PRINTF(KEYDEBUG_IPSEC_STAMP,
5270 "DP cause refcnt++:%d SA:%p\n",
5271 sav->refcnt, sav);
5272 return sav;
5273 }
5274 }
5275
5276 return NULL;
5277 }
5278 #endif
5279
5280 /*
5281 * SADB_ADD processing
5282 * add an entry to SA database, when received
5283 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5284 * key(AE), (identity(SD),) (sensitivity)>
5285 * from the ikmpd,
5286 * and send
5287 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5288 * (identity(SD),) (sensitivity)>
5289 * to the ikmpd.
5290 *
5291 * IGNORE identity and sensitivity messages.
5292 *
5293 * m will always be freed.
5294 */
5295 static int
5296 key_api_add(struct socket *so, struct mbuf *m,
5297 const struct sadb_msghdr *mhp)
5298 {
5299 struct sadb_sa *sa0;
5300 const struct sockaddr *src, *dst;
5301 struct secasindex saidx;
5302 struct secashead *newsah;
5303 struct secasvar *newsav;
5304 u_int16_t proto;
5305 u_int8_t mode;
5306 u_int16_t reqid;
5307 int error;
5308
5309 /* map satype to proto */
5310 proto = key_satype2proto(mhp->msg->sadb_msg_satype);
5311 if (proto == 0) {
5312 IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
5313 return key_senderror(so, m, EINVAL);
5314 }
5315
5316 if (mhp->ext[SADB_EXT_SA] == NULL ||
5317 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5318 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5319 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5320 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5321 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5322 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5323 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5324 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5325 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5326 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5327 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
5328 return key_senderror(so, m, EINVAL);
5329 }
5330 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5331 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5332 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5333 /* XXX need more */
5334 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
5335 return key_senderror(so, m, EINVAL);
5336 }
5337 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5338 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5339 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5340 } else {
5341 mode = IPSEC_MODE_ANY;
5342 reqid = 0;
5343 }
5344
5345 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5346 src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
5347 dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
5348
5349 error = key_setsecasidx(proto, mode, reqid, src, dst, &saidx);
5350 if (error != 0)
5351 return key_senderror(so, m, EINVAL);
5352
5353 error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
5354 if (error != 0)
5355 return key_senderror(so, m, EINVAL);
5356
5357 /* get a SA header */
5358 newsah = key_getsah(&saidx, CMP_REQID);
5359 if (newsah == NULL) {
5360 /* create a new SA header */
5361 newsah = key_newsah(&saidx);
5362 if (newsah == NULL) {
5363 IPSECLOG(LOG_DEBUG, "No more memory.\n");
5364 return key_senderror(so, m, ENOBUFS);
5365 }
5366 }
5367
5368 /* set spidx if there */
5369 /* XXX rewrite */
5370 error = key_setident(newsah, m, mhp);
5371 if (error) {
5372 return key_senderror(so, m, error);
5373 }
5374
5375 {
5376 struct secasvar *sav;
5377
5378 /* We can create new SA only if SPI is differenct. */
5379 sav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5380 if (sav != NULL) {
5381 KEY_FREESAV(&sav);
5382 IPSECLOG(LOG_DEBUG, "SA already exists.\n");
5383 return key_senderror(so, m, EEXIST);
5384 }
5385 }
5386
5387 /* create new SA entry. */
5388 newsav = KEY_NEWSAV(m, mhp, &error);
5389 if (newsav == NULL) {
5390 return key_senderror(so, m, error);
5391 }
5392 newsav->sah = newsah;
5393
5394 error = key_handle_natt_info(newsav, mhp);
5395 if (error != 0) {
5396 key_delsav(newsav);
5397 return key_senderror(so, m, EINVAL);
5398 }
5399
5400 error = key_init_xform(newsav);
5401 if (error != 0) {
5402 key_delsav(newsav);
5403 return key_senderror(so, m, error);
5404 }
5405
5406 /* add to satree */
5407 newsav->refcnt = 1;
5408 newsav->state = SADB_SASTATE_MATURE;
5409 LIST_INSERT_TAIL(&newsah->savtree[SADB_SASTATE_MATURE], newsav,
5410 secasvar, chain);
5411 key_validate_savlist(newsah, SADB_SASTATE_MATURE);
5412
5413 /*
5414 * don't call key_freesav() here, as we would like to keep the SA
5415 * in the database on success.
5416 */
5417
5418 {
5419 struct mbuf *n;
5420
5421 /* set msg buf from mhp */
5422 n = key_getmsgbuf_x1(m, mhp);
5423 if (n == NULL) {
5424 IPSECLOG(LOG_DEBUG, "No more memory.\n");
5425 return key_senderror(so, m, ENOBUFS);
5426 }
5427
5428 m_freem(m);
5429 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5430 }
5431 }
5432
5433 /* m is retained */
5434 static int
5435 key_setident(struct secashead *sah, struct mbuf *m,
5436 const struct sadb_msghdr *mhp)
5437 {
5438 const struct sadb_ident *idsrc, *iddst;
5439 int idsrclen, iddstlen;
5440
5441 KASSERT(!cpu_softintr_p());
5442 KASSERT(sah != NULL);
5443 KASSERT(m != NULL);
5444 KASSERT(mhp != NULL);
5445 KASSERT(mhp->msg != NULL);
5446
5447 /*
5448 * Can be called with an existing sah from key_api_update().
5449 */
5450 if (sah->idents != NULL) {
5451 kmem_free(sah->idents, sah->idents_len);
5452 sah->idents = NULL;
5453 sah->idents_len = 0;
5454 }
5455 if (sah->identd != NULL) {
5456 kmem_free(sah->identd, sah->identd_len);
5457 sah->identd = NULL;
5458 sah->identd_len = 0;
5459 }
5460
5461 /* don't make buffer if not there */
5462 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5463 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5464 sah->idents = NULL;
5465 sah->identd = NULL;
5466 return 0;
5467 }
5468
5469 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5470 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5471 IPSECLOG(LOG_DEBUG, "invalid identity.\n");
5472 return EINVAL;
5473 }
5474
5475 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5476 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5477 idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5478 iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5479
5480 /* validity check */
5481 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5482 IPSECLOG(LOG_DEBUG, "ident type mismatch.\n");
5483 return EINVAL;
5484 }
5485
5486 switch (idsrc->sadb_ident_type) {
5487 case SADB_IDENTTYPE_PREFIX:
5488 case SADB_IDENTTYPE_FQDN:
5489 case SADB_IDENTTYPE_USERFQDN:
5490 default:
5491 /* XXX do nothing */
5492 sah->idents = NULL;
5493 sah->identd = NULL;
5494 return 0;
5495 }
5496
5497 /* make structure */
5498 sah->idents = kmem_alloc(idsrclen, KM_SLEEP);
5499 sah->idents_len = idsrclen;
5500 sah->identd = kmem_alloc(iddstlen, KM_SLEEP);
5501 sah->identd_len = iddstlen;
5502 memcpy(sah->idents, idsrc, idsrclen);
5503 memcpy(sah->identd, iddst, iddstlen);
5504
5505 return 0;
5506 }
5507
5508 /*
5509 * m will not be freed on return.
5510 * it is caller's responsibility to free the result.
5511 */
5512 static struct mbuf *
5513 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5514 {
5515 struct mbuf *n;
5516
5517 KASSERT(m != NULL);
5518 KASSERT(mhp != NULL);
5519 KASSERT(mhp->msg != NULL);
5520
5521 /* create new sadb_msg to reply. */
5522 n = key_gather_mbuf(m, mhp, 1, 15, SADB_EXT_RESERVED,
5523 SADB_EXT_SA, SADB_X_EXT_SA2,
5524 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5525 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5526 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
5527 SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
5528 SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
5529 SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NAT_T_FRAG);
5530 if (!n)
5531 return NULL;
5532
5533 if (n->m_len < sizeof(struct sadb_msg)) {
5534 n = m_pullup(n, sizeof(struct sadb_msg));
5535 if (n == NULL)
5536 return NULL;
5537 }
5538 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5539 mtod(n, struct sadb_msg *)->sadb_msg_len =
5540 PFKEY_UNIT64(n->m_pkthdr.len);
5541
5542 return n;
5543 }
5544
5545 static int key_delete_all (struct socket *, struct mbuf *,
5546 const struct sadb_msghdr *, u_int16_t);
5547
5548 /*
5549 * SADB_DELETE processing
5550 * receive
5551 * <base, SA(*), address(SD)>
5552 * from the ikmpd, and set SADB_SASTATE_DEAD,
5553 * and send,
5554 * <base, SA(*), address(SD)>
5555 * to the ikmpd.
5556 *
5557 * m will always be freed.
5558 */
5559 static int
5560 key_api_delete(struct socket *so, struct mbuf *m,
5561 const struct sadb_msghdr *mhp)
5562 {
5563 struct sadb_sa *sa0;
5564 const struct sockaddr *src, *dst;
5565 struct secasindex saidx;
5566 struct secashead *sah;
5567 struct secasvar *sav = NULL;
5568 u_int16_t proto;
5569 int error;
5570
5571 /* map satype to proto */
5572 proto = key_satype2proto(mhp->msg->sadb_msg_satype);
5573 if (proto == 0) {
5574 IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
5575 return key_senderror(so, m, EINVAL);
5576 }
5577
5578 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5579 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5580 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
5581 return key_senderror(so, m, EINVAL);
5582 }
5583
5584 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5585 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5586 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
5587 return key_senderror(so, m, EINVAL);
5588 }
5589
5590 if (mhp->ext[SADB_EXT_SA] == NULL) {
5591 /*
5592 * Caller wants us to delete all non-LARVAL SAs
5593 * that match the src/dst. This is used during
5594 * IKE INITIAL-CONTACT.
5595 */
5596 IPSECLOG(LOG_DEBUG, "doing delete all.\n");
5597 return key_delete_all(so, m, mhp, proto);
5598 } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5599 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
5600 return key_senderror(so, m, EINVAL);
5601 }
5602
5603 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5604 src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
5605 dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
5606
5607 error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
5608 if (error != 0)
5609 return key_senderror(so, m, EINVAL);
5610
5611 error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
5612 if (error != 0)
5613 return key_senderror(so, m, EINVAL);
5614
5615 /* get a SA header */
5616 sah = key_getsah(&saidx, CMP_HEAD);
5617 if (sah != NULL) {
5618 /* get a SA with SPI. */
5619 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5620 }
5621
5622 if (sav == NULL) {
5623 IPSECLOG(LOG_DEBUG, "no SA found.\n");
5624 return key_senderror(so, m, ENOENT);
5625 }
5626
5627 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5628 KEY_FREESAV(&sav);
5629 KEY_FREESAV(&sav);
5630
5631 {
5632 struct mbuf *n;
5633
5634 /* create new sadb_msg to reply. */
5635 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5636 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5637 if (!n)
5638 return key_senderror(so, m, ENOBUFS);
5639
5640 n = key_fill_replymsg(n, 0);
5641 if (n == NULL)
5642 return key_senderror(so, m, ENOBUFS);
5643
5644 m_freem(m);
5645 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5646 }
5647 }
5648
5649 /*
5650 * delete all SAs for src/dst. Called from key_api_delete().
5651 */
5652 static int
5653 key_delete_all(struct socket *so, struct mbuf *m,
5654 const struct sadb_msghdr *mhp, u_int16_t proto)
5655 {
5656 const struct sockaddr *src, *dst;
5657 struct secasindex saidx;
5658 struct secashead *sah;
5659 struct secasvar *sav, *nextsav;
5660 u_int state;
5661 int error;
5662
5663 src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
5664 dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
5665
5666 error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
5667 if (error != 0)
5668 return key_senderror(so, m, EINVAL);
5669
5670 error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
5671 if (error != 0)
5672 return key_senderror(so, m, EINVAL);
5673
5674 sah = key_getsah(&saidx, CMP_HEAD);
5675 if (sah != NULL) {
5676 /* Delete all non-LARVAL SAs. */
5677 SASTATE_ALIVE_FOREACH(state) {
5678 if (state == SADB_SASTATE_LARVAL)
5679 continue;
5680 LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain,
5681 nextsav) {
5682 /* sanity check */
5683 if (sav->state != state) {
5684 IPSECLOG(LOG_DEBUG,
5685 "invalid sav->state "
5686 "(queue: %d SA: %d)\n",
5687 state, sav->state);
5688 continue;
5689 }
5690
5691 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5692 KEY_FREESAV(&sav);
5693 }
5694 }
5695 }
5696 {
5697 struct mbuf *n;
5698
5699 /* create new sadb_msg to reply. */
5700 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5701 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5702 if (!n)
5703 return key_senderror(so, m, ENOBUFS);
5704
5705 n = key_fill_replymsg(n, 0);
5706 if (n == NULL)
5707 return key_senderror(so, m, ENOBUFS);
5708
5709 m_freem(m);
5710 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5711 }
5712 }
5713
5714 /*
5715 * SADB_GET processing
5716 * receive
5717 * <base, SA(*), address(SD)>
5718 * from the ikmpd, and get a SP and a SA to respond,
5719 * and send,
5720 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5721 * (identity(SD),) (sensitivity)>
5722 * to the ikmpd.
5723 *
5724 * m will always be freed.
5725 */
5726 static int
5727 key_api_get(struct socket *so, struct mbuf *m,
5728 const struct sadb_msghdr *mhp)
5729 {
5730 struct sadb_sa *sa0;
5731 const struct sockaddr *src, *dst;
5732 struct secasindex saidx;
5733 struct secashead *sah;
5734 struct secasvar *sav = NULL;
5735 u_int16_t proto;
5736 int error;
5737
5738 /* map satype to proto */
5739 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5740 IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
5741 return key_senderror(so, m, EINVAL);
5742 }
5743
5744 if (mhp->ext[SADB_EXT_SA] == NULL ||
5745 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5746 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5747 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
5748 return key_senderror(so, m, EINVAL);
5749 }
5750 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5751 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5752 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5753 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
5754 return key_senderror(so, m, EINVAL);
5755 }
5756
5757 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5758 src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
5759 dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
5760
5761 error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
5762 if (error != 0)
5763 return key_senderror(so, m, EINVAL);
5764
5765 error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
5766 if (error != 0)
5767 return key_senderror(so, m, EINVAL);
5768
5769 /* get a SA header */
5770 sah = key_getsah(&saidx, CMP_HEAD);
5771 if (sah != NULL) {
5772 /* get a SA with SPI. */
5773 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5774 }
5775 if (sav == NULL) {
5776 IPSECLOG(LOG_DEBUG, "no SA found.\n");
5777 return key_senderror(so, m, ENOENT);
5778 }
5779
5780 {
5781 struct mbuf *n;
5782 u_int8_t satype;
5783
5784 /* map proto to satype */
5785 satype = key_proto2satype(sah->saidx.proto);
5786 if (satype == 0) {
5787 KEY_FREESAV(&sav);
5788 IPSECLOG(LOG_DEBUG, "there was invalid proto in SAD.\n");
5789 return key_senderror(so, m, EINVAL);
5790 }
5791
5792 /* create new sadb_msg to reply. */
5793 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5794 mhp->msg->sadb_msg_pid);
5795 KEY_FREESAV(&sav);
5796 if (!n)
5797 return key_senderror(so, m, ENOBUFS);
5798
5799 m_freem(m);
5800 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5801 }
5802 }
5803
5804 /* XXX make it sysctl-configurable? */
5805 static void
5806 key_getcomb_setlifetime(struct sadb_comb *comb)
5807 {
5808
5809 comb->sadb_comb_soft_allocations = 1;
5810 comb->sadb_comb_hard_allocations = 1;
5811 comb->sadb_comb_soft_bytes = 0;
5812 comb->sadb_comb_hard_bytes = 0;
5813 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
5814 comb->sadb_comb_soft_addtime = comb->sadb_comb_hard_addtime * 80 / 100;
5815 comb->sadb_comb_hard_usetime = 28800; /* 8 hours */
5816 comb->sadb_comb_soft_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5817 }
5818
5819 /*
5820 * XXX reorder combinations by preference
5821 * XXX no idea if the user wants ESP authentication or not
5822 */
5823 static struct mbuf *
5824 key_getcomb_esp(void)
5825 {
5826 struct sadb_comb *comb;
5827 const struct enc_xform *algo;
5828 struct mbuf *result = NULL, *m, *n;
5829 int encmin;
5830 int i, off, o;
5831 int totlen;
5832 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5833
5834 m = NULL;
5835 for (i = 1; i <= SADB_EALG_MAX; i++) {
5836 algo = esp_algorithm_lookup(i);
5837 if (algo == NULL)
5838 continue;
5839
5840 /* discard algorithms with key size smaller than system min */
5841 if (_BITS(algo->maxkey) < ipsec_esp_keymin)
5842 continue;
5843 if (_BITS(algo->minkey) < ipsec_esp_keymin)
5844 encmin = ipsec_esp_keymin;
5845 else
5846 encmin = _BITS(algo->minkey);
5847
5848 if (ipsec_esp_auth)
5849 m = key_getcomb_ah();
5850 else {
5851 KASSERTMSG(l <= MLEN,
5852 "l=%u > MLEN=%lu", l, (u_long) MLEN);
5853 MGET(m, M_DONTWAIT, MT_DATA);
5854 if (m) {
5855 M_ALIGN(m, l);
5856 m->m_len = l;
5857 m->m_next = NULL;
5858 memset(mtod(m, void *), 0, m->m_len);
5859 }
5860 }
5861 if (!m)
5862 goto fail;
5863
5864 totlen = 0;
5865 for (n = m; n; n = n->m_next)
5866 totlen += n->m_len;
5867 KASSERTMSG((totlen % l) == 0, "totlen=%u, l=%u", totlen, l);
5868
5869 for (off = 0; off < totlen; off += l) {
5870 n = m_pulldown(m, off, l, &o);
5871 if (!n) {
5872 /* m is already freed */
5873 goto fail;
5874 }
5875 comb = (struct sadb_comb *)(mtod(n, char *) + o);
5876 memset(comb, 0, sizeof(*comb));
5877 key_getcomb_setlifetime(comb);
5878 comb->sadb_comb_encrypt = i;
5879 comb->sadb_comb_encrypt_minbits = encmin;
5880 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5881 }
5882
5883 if (!result)
5884 result = m;
5885 else
5886 m_cat(result, m);
5887 }
5888
5889 return result;
5890
5891 fail:
5892 if (result)
5893 m_freem(result);
5894 return NULL;
5895 }
5896
5897 static void
5898 key_getsizes_ah(const struct auth_hash *ah, int alg,
5899 u_int16_t* ksmin, u_int16_t* ksmax)
5900 {
5901 *ksmin = *ksmax = ah->keysize;
5902 if (ah->keysize == 0) {
5903 /*
5904 * Transform takes arbitrary key size but algorithm
5905 * key size is restricted. Enforce this here.
5906 */
5907 switch (alg) {
5908 case SADB_X_AALG_MD5: *ksmin = *ksmax = 16; break;
5909 case SADB_X_AALG_SHA: *ksmin = *ksmax = 20; break;
5910 case SADB_X_AALG_NULL: *ksmin = 0; *ksmax = 256; break;
5911 default:
5912 IPSECLOG(LOG_DEBUG, "unknown AH algorithm %u\n", alg);
5913 break;
5914 }
5915 }
5916 }
5917
5918 /*
5919 * XXX reorder combinations by preference
5920 */
5921 static struct mbuf *
5922 key_getcomb_ah(void)
5923 {
5924 struct sadb_comb *comb;
5925 const struct auth_hash *algo;
5926 struct mbuf *m;
5927 u_int16_t minkeysize, maxkeysize;
5928 int i;
5929 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5930
5931 m = NULL;
5932 for (i = 1; i <= SADB_AALG_MAX; i++) {
5933 #if 1
5934 /* we prefer HMAC algorithms, not old algorithms */
5935 if (i != SADB_AALG_SHA1HMAC &&
5936 i != SADB_AALG_MD5HMAC &&
5937 i != SADB_X_AALG_SHA2_256 &&
5938 i != SADB_X_AALG_SHA2_384 &&
5939 i != SADB_X_AALG_SHA2_512)
5940 continue;
5941 #endif
5942 algo = ah_algorithm_lookup(i);
5943 if (!algo)
5944 continue;
5945 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5946 /* discard algorithms with key size smaller than system min */
5947 if (_BITS(minkeysize) < ipsec_ah_keymin)
5948 continue;
5949
5950 if (!m) {
5951 KASSERTMSG(l <= MLEN,
5952 "l=%u > MLEN=%lu", l, (u_long) MLEN);
5953 MGET(m, M_DONTWAIT, MT_DATA);
5954 if (m) {
5955 M_ALIGN(m, l);
5956 m->m_len = l;
5957 m->m_next = NULL;
5958 }
5959 } else
5960 M_PREPEND(m, l, M_DONTWAIT);
5961 if (!m)
5962 return NULL;
5963
5964 if (m->m_len < sizeof(struct sadb_comb)) {
5965 m = m_pullup(m, sizeof(struct sadb_comb));
5966 if (m == NULL)
5967 return NULL;
5968 }
5969
5970 comb = mtod(m, struct sadb_comb *);
5971 memset(comb, 0, sizeof(*comb));
5972 key_getcomb_setlifetime(comb);
5973 comb->sadb_comb_auth = i;
5974 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5975 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5976 }
5977
5978 return m;
5979 }
5980
5981 /*
5982 * not really an official behavior. discussed in pf_key (at) inner.net in Sep2000.
5983 * XXX reorder combinations by preference
5984 */
5985 static struct mbuf *
5986 key_getcomb_ipcomp(void)
5987 {
5988 struct sadb_comb *comb;
5989 const struct comp_algo *algo;
5990 struct mbuf *m;
5991 int i;
5992 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5993
5994 m = NULL;
5995 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5996 algo = ipcomp_algorithm_lookup(i);
5997 if (!algo)
5998 continue;
5999
6000 if (!m) {
6001 KASSERTMSG(l <= MLEN,
6002 "l=%u > MLEN=%lu", l, (u_long) MLEN);
6003 MGET(m, M_DONTWAIT, MT_DATA);
6004 if (m) {
6005 M_ALIGN(m, l);
6006 m->m_len = l;
6007 m->m_next = NULL;
6008 }
6009 } else
6010 M_PREPEND(m, l, M_DONTWAIT);
6011 if (!m)
6012 return NULL;
6013
6014 if (m->m_len < sizeof(struct sadb_comb)) {
6015 m = m_pullup(m, sizeof(struct sadb_comb));
6016 if (m == NULL)
6017 return NULL;
6018 }
6019
6020 comb = mtod(m, struct sadb_comb *);
6021 memset(comb, 0, sizeof(*comb));
6022 key_getcomb_setlifetime(comb);
6023 comb->sadb_comb_encrypt = i;
6024 /* what should we set into sadb_comb_*_{min,max}bits? */
6025 }
6026
6027 return m;
6028 }
6029
6030 /*
6031 * XXX no way to pass mode (transport/tunnel) to userland
6032 * XXX replay checking?
6033 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6034 */
6035 static struct mbuf *
6036 key_getprop(const struct secasindex *saidx)
6037 {
6038 struct sadb_prop *prop;
6039 struct mbuf *m, *n;
6040 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6041 int totlen;
6042
6043 switch (saidx->proto) {
6044 case IPPROTO_ESP:
6045 m = key_getcomb_esp();
6046 break;
6047 case IPPROTO_AH:
6048 m = key_getcomb_ah();
6049 break;
6050 case IPPROTO_IPCOMP:
6051 m = key_getcomb_ipcomp();
6052 break;
6053 default:
6054 return NULL;
6055 }
6056
6057 if (!m)
6058 return NULL;
6059 M_PREPEND(m, l, M_DONTWAIT);
6060 if (!m)
6061 return NULL;
6062
6063 totlen = 0;
6064 for (n = m; n; n = n->m_next)
6065 totlen += n->m_len;
6066
6067 prop = mtod(m, struct sadb_prop *);
6068 memset(prop, 0, sizeof(*prop));
6069 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6070 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6071 prop->sadb_prop_replay = 32; /* XXX */
6072
6073 return m;
6074 }
6075
6076 /*
6077 * SADB_ACQUIRE processing called by key_checkrequest() and key_api_acquire().
6078 * send
6079 * <base, SA, address(SD), (address(P)), x_policy,
6080 * (identity(SD),) (sensitivity,) proposal>
6081 * to KMD, and expect to receive
6082 * <base> with SADB_ACQUIRE if error occurred,
6083 * or
6084 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
6085 * from KMD by PF_KEY.
6086 *
6087 * XXX x_policy is outside of RFC2367 (KAME extension).
6088 * XXX sensitivity is not supported.
6089 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6090 * see comment for key_getcomb_ipcomp().
6091 *
6092 * OUT:
6093 * 0 : succeed
6094 * others: error number
6095 */
6096 static int
6097 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6098 {
6099 struct mbuf *result = NULL, *m;
6100 #ifndef IPSEC_NONBLOCK_ACQUIRE
6101 struct secacq *newacq;
6102 #endif
6103 u_int8_t satype;
6104 int error = -1;
6105 u_int32_t seq;
6106
6107 /* sanity check */
6108 KASSERT(saidx != NULL);
6109 satype = key_proto2satype(saidx->proto);
6110 KASSERTMSG(satype != 0, "null satype, protocol %u", saidx->proto);
6111
6112 #ifndef IPSEC_NONBLOCK_ACQUIRE
6113 /*
6114 * We never do anything about acquirng SA. There is anather
6115 * solution that kernel blocks to send SADB_ACQUIRE message until
6116 * getting something message from IKEd. In later case, to be
6117 * managed with ACQUIRING list.
6118 */
6119 /* Get an entry to check whether sending message or not. */
6120 mutex_enter(&key_mtx);
6121 newacq = key_getacq(saidx);
6122 if (newacq != NULL) {
6123 if (key_blockacq_count < newacq->count) {
6124 /* reset counter and do send message. */
6125 newacq->count = 0;
6126 } else {
6127 /* increment counter and do nothing. */
6128 newacq->count++;
6129 mutex_exit(&key_mtx);
6130 return 0;
6131 }
6132 } else {
6133 /* make new entry for blocking to send SADB_ACQUIRE. */
6134 newacq = key_newacq(saidx);
6135 if (newacq == NULL)
6136 return ENOBUFS;
6137
6138 /* add to acqtree */
6139 LIST_INSERT_HEAD(&acqtree, newacq, chain);
6140 }
6141
6142 seq = newacq->seq;
6143 mutex_exit(&key_mtx);
6144 #else
6145 seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
6146 #endif
6147 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6148 if (!m) {
6149 error = ENOBUFS;
6150 goto fail;
6151 }
6152 result = m;
6153
6154 /* set sadb_address for saidx's. */
6155 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &saidx->src.sa, FULLMASK,
6156 IPSEC_ULPROTO_ANY);
6157 if (!m) {
6158 error = ENOBUFS;
6159 goto fail;
6160 }
6161 m_cat(result, m);
6162
6163 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &saidx->dst.sa, FULLMASK,
6164 IPSEC_ULPROTO_ANY);
6165 if (!m) {
6166 error = ENOBUFS;
6167 goto fail;
6168 }
6169 m_cat(result, m);
6170
6171 /* XXX proxy address (optional) */
6172
6173 /* set sadb_x_policy */
6174 if (sp) {
6175 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6176 if (!m) {
6177 error = ENOBUFS;
6178 goto fail;
6179 }
6180 m_cat(result, m);
6181 }
6182
6183 /* XXX identity (optional) */
6184 #if 0
6185 if (idexttype && fqdn) {
6186 /* create identity extension (FQDN) */
6187 struct sadb_ident *id;
6188 int fqdnlen;
6189
6190 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6191 id = (struct sadb_ident *)p;
6192 memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6193 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6194 id->sadb_ident_exttype = idexttype;
6195 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6196 memcpy(id + 1, fqdn, fqdnlen);
6197 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6198 }
6199
6200 if (idexttype) {
6201 /* create identity extension (USERFQDN) */
6202 struct sadb_ident *id;
6203 int userfqdnlen;
6204
6205 if (userfqdn) {
6206 /* +1 for terminating-NUL */
6207 userfqdnlen = strlen(userfqdn) + 1;
6208 } else
6209 userfqdnlen = 0;
6210 id = (struct sadb_ident *)p;
6211 memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6212 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6213 id->sadb_ident_exttype = idexttype;
6214 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6215 /* XXX is it correct? */
6216 if (curlwp)
6217 id->sadb_ident_id = kauth_cred_getuid(curlwp->l_cred);
6218 if (userfqdn && userfqdnlen)
6219 memcpy(id + 1, userfqdn, userfqdnlen);
6220 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6221 }
6222 #endif
6223
6224 /* XXX sensitivity (optional) */
6225
6226 /* create proposal/combination extension */
6227 m = key_getprop(saidx);
6228 #if 0
6229 /*
6230 * spec conformant: always attach proposal/combination extension,
6231 * the problem is that we have no way to attach it for ipcomp,
6232 * due to the way sadb_comb is declared in RFC2367.
6233 */
6234 if (!m) {
6235 error = ENOBUFS;
6236 goto fail;
6237 }
6238 m_cat(result, m);
6239 #else
6240 /*
6241 * outside of spec; make proposal/combination extension optional.
6242 */
6243 if (m)
6244 m_cat(result, m);
6245 #endif
6246
6247 if ((result->m_flags & M_PKTHDR) == 0) {
6248 error = EINVAL;
6249 goto fail;
6250 }
6251
6252 if (result->m_len < sizeof(struct sadb_msg)) {
6253 result = m_pullup(result, sizeof(struct sadb_msg));
6254 if (result == NULL) {
6255 error = ENOBUFS;
6256 goto fail;
6257 }
6258 }
6259
6260 result->m_pkthdr.len = 0;
6261 for (m = result; m; m = m->m_next)
6262 result->m_pkthdr.len += m->m_len;
6263
6264 mtod(result, struct sadb_msg *)->sadb_msg_len =
6265 PFKEY_UNIT64(result->m_pkthdr.len);
6266
6267 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6268
6269 fail:
6270 if (result)
6271 m_freem(result);
6272 return error;
6273 }
6274
6275 #ifndef IPSEC_NONBLOCK_ACQUIRE
6276 static struct secacq *
6277 key_newacq(const struct secasindex *saidx)
6278 {
6279 struct secacq *newacq;
6280
6281 /* get new entry */
6282 newacq = kmem_intr_zalloc(sizeof(struct secacq), KM_NOSLEEP);
6283 if (newacq == NULL) {
6284 IPSECLOG(LOG_DEBUG, "No more memory.\n");
6285 return NULL;
6286 }
6287
6288 /* copy secindex */
6289 memcpy(&newacq->saidx, saidx, sizeof(newacq->saidx));
6290 newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
6291 newacq->created = time_uptime;
6292 newacq->count = 0;
6293
6294 return newacq;
6295 }
6296
6297 static struct secacq *
6298 key_getacq(const struct secasindex *saidx)
6299 {
6300 struct secacq *acq;
6301
6302 KASSERT(mutex_owned(&key_mtx));
6303
6304 LIST_FOREACH(acq, &acqtree, chain) {
6305 if (key_saidx_match(saidx, &acq->saidx, CMP_EXACTLY))
6306 return acq;
6307 }
6308
6309 return NULL;
6310 }
6311
6312 static struct secacq *
6313 key_getacqbyseq(u_int32_t seq)
6314 {
6315 struct secacq *acq;
6316
6317 KASSERT(mutex_owned(&key_mtx));
6318
6319 LIST_FOREACH(acq, &acqtree, chain) {
6320 if (acq->seq == seq)
6321 return acq;
6322 }
6323
6324 return NULL;
6325 }
6326 #endif
6327
6328 #ifdef notyet
6329 static struct secspacq *
6330 key_newspacq(const struct secpolicyindex *spidx)
6331 {
6332 struct secspacq *acq;
6333
6334 /* get new entry */
6335 acq = kmem_intr_zalloc(sizeof(struct secspacq), KM_NOSLEEP);
6336 if (acq == NULL) {
6337 IPSECLOG(LOG_DEBUG, "No more memory.\n");
6338 return NULL;
6339 }
6340
6341 /* copy secindex */
6342 memcpy(&acq->spidx, spidx, sizeof(acq->spidx));
6343 acq->created = time_uptime;
6344 acq->count = 0;
6345
6346 return acq;
6347 }
6348
6349 static struct secspacq *
6350 key_getspacq(const struct secpolicyindex *spidx)
6351 {
6352 struct secspacq *acq;
6353
6354 LIST_FOREACH(acq, &spacqtree, chain) {
6355 if (key_spidx_match_exactly(spidx, &acq->spidx))
6356 return acq;
6357 }
6358
6359 return NULL;
6360 }
6361 #endif /* notyet */
6362
6363 /*
6364 * SADB_ACQUIRE processing,
6365 * in first situation, is receiving
6366 * <base>
6367 * from the ikmpd, and clear sequence of its secasvar entry.
6368 *
6369 * In second situation, is receiving
6370 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6371 * from a user land process, and return
6372 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6373 * to the socket.
6374 *
6375 * m will always be freed.
6376 */
6377 static int
6378 key_api_acquire(struct socket *so, struct mbuf *m,
6379 const struct sadb_msghdr *mhp)
6380 {
6381 const struct sockaddr *src, *dst;
6382 struct secasindex saidx;
6383 struct secashead *sah;
6384 u_int16_t proto;
6385 int error;
6386
6387 /*
6388 * Error message from KMd.
6389 * We assume that if error was occurred in IKEd, the length of PFKEY
6390 * message is equal to the size of sadb_msg structure.
6391 * We do not raise error even if error occurred in this function.
6392 */
6393 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6394 #ifndef IPSEC_NONBLOCK_ACQUIRE
6395 struct secacq *acq;
6396
6397 /* check sequence number */
6398 if (mhp->msg->sadb_msg_seq == 0) {
6399 IPSECLOG(LOG_DEBUG, "must specify sequence number.\n");
6400 m_freem(m);
6401 return 0;
6402 }
6403
6404 mutex_enter(&key_mtx);
6405 acq = key_getacqbyseq(mhp->msg->sadb_msg_seq);
6406 if (acq == NULL) {
6407 mutex_exit(&key_mtx);
6408 /*
6409 * the specified larval SA is already gone, or we got
6410 * a bogus sequence number. we can silently ignore it.
6411 */
6412 m_freem(m);
6413 return 0;
6414 }
6415
6416 /* reset acq counter in order to deletion by timehander. */
6417 acq->created = time_uptime;
6418 acq->count = 0;
6419 mutex_exit(&key_mtx);
6420 #endif
6421 m_freem(m);
6422 return 0;
6423 }
6424
6425 /*
6426 * This message is from user land.
6427 */
6428
6429 /* map satype to proto */
6430 proto = key_satype2proto(mhp->msg->sadb_msg_satype);
6431 if (proto == 0) {
6432 IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
6433 return key_senderror(so, m, EINVAL);
6434 }
6435
6436 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6437 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6438 mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6439 /* error */
6440 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
6441 return key_senderror(so, m, EINVAL);
6442 }
6443 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6444 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6445 mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6446 /* error */
6447 IPSECLOG(LOG_DEBUG, "invalid message is passed.\n");
6448 return key_senderror(so, m, EINVAL);
6449 }
6450
6451 src = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_SRC);
6452 dst = key_msghdr_get_sockaddr(mhp, SADB_EXT_ADDRESS_DST);
6453
6454 error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src, dst, &saidx);
6455 if (error != 0)
6456 return key_senderror(so, m, EINVAL);
6457
6458 error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp);
6459 if (error != 0)
6460 return key_senderror(so, m, EINVAL);
6461
6462 /* get a SA index */
6463 sah = key_getsah(&saidx, CMP_MODE_REQID);
6464 if (sah != NULL) {
6465 IPSECLOG(LOG_DEBUG, "a SA exists already.\n");
6466 return key_senderror(so, m, EEXIST);
6467 }
6468
6469 error = key_acquire(&saidx, NULL);
6470 if (error != 0) {
6471 IPSECLOG(LOG_DEBUG, "error %d returned from key_acquire.\n",
6472 error);
6473 return key_senderror(so, m, error);
6474 }
6475
6476 return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6477 }
6478
6479 /*
6480 * SADB_REGISTER processing.
6481 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6482 * receive
6483 * <base>
6484 * from the ikmpd, and register a socket to send PF_KEY messages,
6485 * and send
6486 * <base, supported>
6487 * to KMD by PF_KEY.
6488 * If socket is detached, must free from regnode.
6489 *
6490 * m will always be freed.
6491 */
6492 static int
6493 key_api_register(struct socket *so, struct mbuf *m,
6494 const struct sadb_msghdr *mhp)
6495 {
6496 struct secreg *reg, *newreg = 0;
6497
6498 /* check for invalid register message */
6499 if (mhp->msg->sadb_msg_satype >= __arraycount(regtree))
6500 return key_senderror(so, m, EINVAL);
6501
6502 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6503 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6504 goto setmsg;
6505
6506 /* Allocate regnode in advance, out of mutex */
6507 newreg = kmem_zalloc(sizeof(*newreg), KM_SLEEP);
6508
6509 /* check whether existing or not */
6510 mutex_enter(&key_mtx);
6511 LIST_FOREACH(reg, ®tree[mhp->msg->sadb_msg_satype], chain) {
6512 if (reg->so == so) {
6513 IPSECLOG(LOG_DEBUG, "socket exists already.\n");
6514 mutex_exit(&key_mtx);
6515 kmem_free(newreg, sizeof(*newreg));
6516 return key_senderror(so, m, EEXIST);
6517 }
6518 }
6519
6520 newreg->so = so;
6521 ((struct keycb *)sotorawcb(so))->kp_registered++;
6522
6523 /* add regnode to regtree. */
6524 LIST_INSERT_HEAD(®tree[mhp->msg->sadb_msg_satype], newreg, chain);
6525 mutex_exit(&key_mtx);
6526
6527 setmsg:
6528 {
6529 struct mbuf *n;
6530 struct sadb_supported *sup;
6531 u_int len, alen, elen;
6532 int off;
6533 int i;
6534 struct sadb_alg *alg;
6535
6536 /* create new sadb_msg to reply. */
6537 alen = 0;
6538 for (i = 1; i <= SADB_AALG_MAX; i++) {
6539 if (ah_algorithm_lookup(i))
6540 alen += sizeof(struct sadb_alg);
6541 }
6542 if (alen)
6543 alen += sizeof(struct sadb_supported);
6544 elen = 0;
6545 for (i = 1; i <= SADB_EALG_MAX; i++) {
6546 if (esp_algorithm_lookup(i))
6547 elen += sizeof(struct sadb_alg);
6548 }
6549 if (elen)
6550 elen += sizeof(struct sadb_supported);
6551
6552 len = sizeof(struct sadb_msg) + alen + elen;
6553
6554 if (len > MCLBYTES)
6555 return key_senderror(so, m, ENOBUFS);
6556
6557 MGETHDR(n, M_DONTWAIT, MT_DATA);
6558 if (len > MHLEN) {
6559 MCLGET(n, M_DONTWAIT);
6560 if ((n->m_flags & M_EXT) == 0) {
6561 m_freem(n);
6562 n = NULL;
6563 }
6564 }
6565 if (!n)
6566 return key_senderror(so, m, ENOBUFS);
6567
6568 n->m_pkthdr.len = n->m_len = len;
6569 n->m_next = NULL;
6570 off = 0;
6571
6572 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
6573 n = key_fill_replymsg(n, 0);
6574 if (n == NULL)
6575 return key_senderror(so, m, ENOBUFS);
6576
6577 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6578
6579 /* for authentication algorithm */
6580 if (alen) {
6581 sup = (struct sadb_supported *)(mtod(n, char *) + off);
6582 sup->sadb_supported_len = PFKEY_UNIT64(alen);
6583 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6584 off += PFKEY_ALIGN8(sizeof(*sup));
6585
6586 for (i = 1; i <= SADB_AALG_MAX; i++) {
6587 const struct auth_hash *aalgo;
6588 u_int16_t minkeysize, maxkeysize;
6589
6590 aalgo = ah_algorithm_lookup(i);
6591 if (!aalgo)
6592 continue;
6593 alg = (struct sadb_alg *)(mtod(n, char *) + off);
6594 alg->sadb_alg_id = i;
6595 alg->sadb_alg_ivlen = 0;
6596 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6597 alg->sadb_alg_minbits = _BITS(minkeysize);
6598 alg->sadb_alg_maxbits = _BITS(maxkeysize);
6599 off += PFKEY_ALIGN8(sizeof(*alg));
6600 }
6601 }
6602
6603 /* for encryption algorithm */
6604 if (elen) {
6605 sup = (struct sadb_supported *)(mtod(n, char *) + off);
6606 sup->sadb_supported_len = PFKEY_UNIT64(elen);
6607 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6608 off += PFKEY_ALIGN8(sizeof(*sup));
6609
6610 for (i = 1; i <= SADB_EALG_MAX; i++) {
6611 const struct enc_xform *ealgo;
6612
6613 ealgo = esp_algorithm_lookup(i);
6614 if (!ealgo)
6615 continue;
6616 alg = (struct sadb_alg *)(mtod(n, char *) + off);
6617 alg->sadb_alg_id = i;
6618 alg->sadb_alg_ivlen = ealgo->blocksize;
6619 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6620 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6621 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6622 }
6623 }
6624
6625 KASSERTMSG(off == len, "length inconsistency");
6626
6627 m_freem(m);
6628 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6629 }
6630 }
6631
6632 /*
6633 * free secreg entry registered.
6634 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6635 */
6636 void
6637 key_freereg(struct socket *so)
6638 {
6639 struct secreg *reg;
6640 int i;
6641
6642 KASSERT(!cpu_softintr_p());
6643 KASSERT(so != NULL);
6644
6645 /*
6646 * check whether existing or not.
6647 * check all type of SA, because there is a potential that
6648 * one socket is registered to multiple type of SA.
6649 */
6650 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6651 mutex_enter(&key_mtx);
6652 LIST_FOREACH(reg, ®tree[i], chain) {
6653 if (reg->so == so) {
6654 LIST_REMOVE(reg, chain);
6655 break;
6656 }
6657 }
6658 mutex_exit(&key_mtx);
6659 if (reg != NULL)
6660 kmem_free(reg, sizeof(*reg));
6661 }
6662
6663 return;
6664 }
6665
6666 /*
6667 * SADB_EXPIRE processing
6668 * send
6669 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6670 * to KMD by PF_KEY.
6671 * NOTE: We send only soft lifetime extension.
6672 *
6673 * OUT: 0 : succeed
6674 * others : error number
6675 */
6676 static int
6677 key_expire(struct secasvar *sav)
6678 {
6679 int s;
6680 int satype;
6681 struct mbuf *result = NULL, *m;
6682 int len;
6683 int error = -1;
6684 struct sadb_lifetime *lt;
6685
6686 /* XXX: Why do we lock ? */
6687 s = splsoftnet(); /*called from softclock()*/
6688
6689 KASSERT(sav != NULL);
6690
6691 satype = key_proto2satype(sav->sah->saidx.proto);
6692 KASSERTMSG(satype != 0, "invalid proto is passed");
6693
6694 /* set msg header */
6695 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6696 if (!m) {
6697 error = ENOBUFS;
6698 goto fail;
6699 }
6700 result = m;
6701
6702 /* create SA extension */
6703 m = key_setsadbsa(sav);
6704 if (!m) {
6705 error = ENOBUFS;
6706 goto fail;
6707 }
6708 m_cat(result, m);
6709
6710 /* create SA extension */
6711 m = key_setsadbxsa2(sav->sah->saidx.mode,
6712 sav->replay ? sav->replay->count : 0, sav->sah->saidx.reqid);
6713 if (!m) {
6714 error = ENOBUFS;
6715 goto fail;
6716 }
6717 m_cat(result, m);
6718
6719 /* create lifetime extension (current and soft) */
6720 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6721 m = key_alloc_mbuf(len);
6722 if (!m || m->m_next) { /*XXX*/
6723 if (m)
6724 m_freem(m);
6725 error = ENOBUFS;
6726 goto fail;
6727 }
6728 memset(mtod(m, void *), 0, len);
6729 lt = mtod(m, struct sadb_lifetime *);
6730 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6731 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6732 lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6733 lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6734 lt->sadb_lifetime_addtime =
6735 time_mono_to_wall(sav->lft_c->sadb_lifetime_addtime);
6736 lt->sadb_lifetime_usetime =
6737 time_mono_to_wall(sav->lft_c->sadb_lifetime_usetime);
6738 lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
6739 memcpy(lt, sav->lft_s, sizeof(*lt));
6740 m_cat(result, m);
6741
6742 /* set sadb_address for source */
6743 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &sav->sah->saidx.src.sa,
6744 FULLMASK, IPSEC_ULPROTO_ANY);
6745 if (!m) {
6746 error = ENOBUFS;
6747 goto fail;
6748 }
6749 m_cat(result, m);
6750
6751 /* set sadb_address for destination */
6752 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &sav->sah->saidx.dst.sa,
6753 FULLMASK, IPSEC_ULPROTO_ANY);
6754 if (!m) {
6755 error = ENOBUFS;
6756 goto fail;
6757 }
6758 m_cat(result, m);
6759
6760 if ((result->m_flags & M_PKTHDR) == 0) {
6761 error = EINVAL;
6762 goto fail;
6763 }
6764
6765 if (result->m_len < sizeof(struct sadb_msg)) {
6766 result = m_pullup(result, sizeof(struct sadb_msg));
6767 if (result == NULL) {
6768 error = ENOBUFS;
6769 goto fail;
6770 }
6771 }
6772
6773 result->m_pkthdr.len = 0;
6774 for (m = result; m; m = m->m_next)
6775 result->m_pkthdr.len += m->m_len;
6776
6777 mtod(result, struct sadb_msg *)->sadb_msg_len =
6778 PFKEY_UNIT64(result->m_pkthdr.len);
6779
6780 splx(s);
6781 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6782
6783 fail:
6784 if (result)
6785 m_freem(result);
6786 splx(s);
6787 return error;
6788 }
6789
6790 /*
6791 * SADB_FLUSH processing
6792 * receive
6793 * <base>
6794 * from the ikmpd, and free all entries in secastree.
6795 * and send,
6796 * <base>
6797 * to the ikmpd.
6798 * NOTE: to do is only marking SADB_SASTATE_DEAD.
6799 *
6800 * m will always be freed.
6801 */
6802 static int
6803 key_api_flush(struct socket *so, struct mbuf *m,
6804 const struct sadb_msghdr *mhp)
6805 {
6806 struct sadb_msg *newmsg;
6807 struct secashead *sah;
6808 struct secasvar *sav, *nextsav;
6809 u_int16_t proto;
6810 u_int8_t state;
6811
6812 /* map satype to proto */
6813 proto = key_satype2proto(mhp->msg->sadb_msg_satype);
6814 if (proto == 0) {
6815 IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
6816 return key_senderror(so, m, EINVAL);
6817 }
6818
6819 /* no SATYPE specified, i.e. flushing all SA. */
6820 LIST_FOREACH(sah, &sahtree, chain) {
6821 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
6822 proto != sah->saidx.proto)
6823 continue;
6824
6825 SASTATE_ALIVE_FOREACH(state) {
6826 LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain,
6827 nextsav) {
6828 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6829 KEY_FREESAV(&sav);
6830 }
6831 }
6832
6833 sah->state = SADB_SASTATE_DEAD;
6834 }
6835
6836 if (m->m_len < sizeof(struct sadb_msg) ||
6837 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6838 IPSECLOG(LOG_DEBUG, "No more memory.\n");
6839 return key_senderror(so, m, ENOBUFS);
6840 }
6841
6842 if (m->m_next)
6843 m_freem(m->m_next);
6844 m->m_next = NULL;
6845 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6846 newmsg = mtod(m, struct sadb_msg *);
6847 newmsg->sadb_msg_errno = 0;
6848 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6849
6850 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6851 }
6852
6853
6854 static struct mbuf *
6855 key_setdump_chain(u_int8_t req_satype, int *errorp, int *lenp, pid_t pid)
6856 {
6857 struct secashead *sah;
6858 struct secasvar *sav;
6859 u_int16_t proto;
6860 u_int8_t satype;
6861 u_int8_t state;
6862 int cnt;
6863 struct mbuf *m, *n, *prev;
6864
6865 *lenp = 0;
6866
6867 /* map satype to proto */
6868 proto = key_satype2proto(req_satype);
6869 if (proto == 0) {
6870 *errorp = EINVAL;
6871 return (NULL);
6872 }
6873
6874 /* count sav entries to be sent to userland. */
6875 cnt = 0;
6876 LIST_FOREACH(sah, &sahtree, chain) {
6877 if (req_satype != SADB_SATYPE_UNSPEC &&
6878 proto != sah->saidx.proto)
6879 continue;
6880
6881 SASTATE_ANY_FOREACH(state) {
6882 LIST_FOREACH(sav, &sah->savtree[state], chain) {
6883 cnt++;
6884 }
6885 }
6886 }
6887
6888 if (cnt == 0) {
6889 *errorp = ENOENT;
6890 return (NULL);
6891 }
6892
6893 /* send this to the userland, one at a time. */
6894 m = NULL;
6895 prev = m;
6896 LIST_FOREACH(sah, &sahtree, chain) {
6897 if (req_satype != SADB_SATYPE_UNSPEC &&
6898 proto != sah->saidx.proto)
6899 continue;
6900
6901 /* map proto to satype */
6902 satype = key_proto2satype(sah->saidx.proto);
6903 if (satype == 0) {
6904 m_freem(m);
6905 *errorp = EINVAL;
6906 return (NULL);
6907 }
6908
6909 SASTATE_ANY_FOREACH(state) {
6910 LIST_FOREACH(sav, &sah->savtree[state], chain) {
6911 n = key_setdumpsa(sav, SADB_DUMP, satype,
6912 --cnt, pid);
6913 if (!n) {
6914 m_freem(m);
6915 *errorp = ENOBUFS;
6916 return (NULL);
6917 }
6918
6919 if (!m)
6920 m = n;
6921 else
6922 prev->m_nextpkt = n;
6923 prev = n;
6924 }
6925 }
6926 }
6927
6928 if (!m) {
6929 *errorp = EINVAL;
6930 return (NULL);
6931 }
6932
6933 if ((m->m_flags & M_PKTHDR) != 0) {
6934 m->m_pkthdr.len = 0;
6935 for (n = m; n; n = n->m_next)
6936 m->m_pkthdr.len += n->m_len;
6937 }
6938
6939 *errorp = 0;
6940 return (m);
6941 }
6942
6943 /*
6944 * SADB_DUMP processing
6945 * dump all entries including status of DEAD in SAD.
6946 * receive
6947 * <base>
6948 * from the ikmpd, and dump all secasvar leaves
6949 * and send,
6950 * <base> .....
6951 * to the ikmpd.
6952 *
6953 * m will always be freed.
6954 */
6955 static int
6956 key_api_dump(struct socket *so, struct mbuf *m0,
6957 const struct sadb_msghdr *mhp)
6958 {
6959 u_int16_t proto;
6960 u_int8_t satype;
6961 struct mbuf *n;
6962 int s;
6963 int error, len, ok;
6964
6965 /* map satype to proto */
6966 satype = mhp->msg->sadb_msg_satype;
6967 proto = key_satype2proto(satype);
6968 if (proto == 0) {
6969 IPSECLOG(LOG_DEBUG, "invalid satype is passed.\n");
6970 return key_senderror(so, m0, EINVAL);
6971 }
6972
6973 /*
6974 * If the requestor has insufficient socket-buffer space
6975 * for the entire chain, nobody gets any response to the DUMP.
6976 * XXX For now, only the requestor ever gets anything.
6977 * Moreover, if the requestor has any space at all, they receive
6978 * the entire chain, otherwise the request is refused with ENOBUFS.
6979 */
6980 if (sbspace(&so->so_rcv) <= 0) {
6981 return key_senderror(so, m0, ENOBUFS);
6982 }
6983
6984 s = splsoftnet();
6985 n = key_setdump_chain(satype, &error, &len, mhp->msg->sadb_msg_pid);
6986 splx(s);
6987
6988 if (n == NULL) {
6989 return key_senderror(so, m0, ENOENT);
6990 }
6991 {
6992 uint64_t *ps = PFKEY_STAT_GETREF();
6993 ps[PFKEY_STAT_IN_TOTAL]++;
6994 ps[PFKEY_STAT_IN_BYTES] += len;
6995 PFKEY_STAT_PUTREF();
6996 }
6997
6998 /*
6999 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
7000 * The requestor receives either the entire chain, or an
7001 * error message with ENOBUFS.
7002 *
7003 * sbappendaddrchain() takes the chain of entries, one
7004 * packet-record per SPD entry, prepends the key_src sockaddr
7005 * to each packet-record, links the sockaddr mbufs into a new
7006 * list of records, then appends the entire resulting
7007 * list to the requesting socket.
7008 */
7009 ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src, n,
7010 SB_PRIO_ONESHOT_OVERFLOW);
7011
7012 if (!ok) {
7013 PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
7014 m_freem(n);
7015 return key_senderror(so, m0, ENOBUFS);
7016 }
7017
7018 m_freem(m0);
7019 return 0;
7020 }
7021
7022 /*
7023 * SADB_X_PROMISC processing
7024 *
7025 * m will always be freed.
7026 */
7027 static int
7028 key_api_promisc(struct socket *so, struct mbuf *m,
7029 const struct sadb_msghdr *mhp)
7030 {
7031 int olen;
7032
7033 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7034
7035 if (olen < sizeof(struct sadb_msg)) {
7036 #if 1
7037 return key_senderror(so, m, EINVAL);
7038 #else
7039 m_freem(m);
7040 return 0;
7041 #endif
7042 } else if (olen == sizeof(struct sadb_msg)) {
7043 /* enable/disable promisc mode */
7044 struct keycb *kp = (struct keycb *)sotorawcb(so);
7045 if (kp == NULL)
7046 return key_senderror(so, m, EINVAL);
7047 mhp->msg->sadb_msg_errno = 0;
7048 switch (mhp->msg->sadb_msg_satype) {
7049 case 0:
7050 case 1:
7051 kp->kp_promisc = mhp->msg->sadb_msg_satype;
7052 break;
7053 default:
7054 return key_senderror(so, m, EINVAL);
7055 }
7056
7057 /* send the original message back to everyone */
7058 mhp->msg->sadb_msg_errno = 0;
7059 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7060 } else {
7061 /* send packet as is */
7062
7063 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7064
7065 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7066 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7067 }
7068 }
7069
7070 static int (*key_api_typesw[]) (struct socket *, struct mbuf *,
7071 const struct sadb_msghdr *) = {
7072 NULL, /* SADB_RESERVED */
7073 key_api_getspi, /* SADB_GETSPI */
7074 key_api_update, /* SADB_UPDATE */
7075 key_api_add, /* SADB_ADD */
7076 key_api_delete, /* SADB_DELETE */
7077 key_api_get, /* SADB_GET */
7078 key_api_acquire, /* SADB_ACQUIRE */
7079 key_api_register, /* SADB_REGISTER */
7080 NULL, /* SADB_EXPIRE */
7081 key_api_flush, /* SADB_FLUSH */
7082 key_api_dump, /* SADB_DUMP */
7083 key_api_promisc, /* SADB_X_PROMISC */
7084 NULL, /* SADB_X_PCHANGE */
7085 key_api_spdadd, /* SADB_X_SPDUPDATE */
7086 key_api_spdadd, /* SADB_X_SPDADD */
7087 key_api_spddelete, /* SADB_X_SPDDELETE */
7088 key_api_spdget, /* SADB_X_SPDGET */
7089 NULL, /* SADB_X_SPDACQUIRE */
7090 key_api_spddump, /* SADB_X_SPDDUMP */
7091 key_api_spdflush, /* SADB_X_SPDFLUSH */
7092 key_api_spdadd, /* SADB_X_SPDSETIDX */
7093 NULL, /* SADB_X_SPDEXPIRE */
7094 key_api_spddelete2, /* SADB_X_SPDDELETE2 */
7095 key_api_nat_map, /* SADB_X_NAT_T_NEW_MAPPING */
7096 };
7097
7098 /*
7099 * parse sadb_msg buffer to process PFKEYv2,
7100 * and create a data to response if needed.
7101 * I think to be dealed with mbuf directly.
7102 * IN:
7103 * msgp : pointer to pointer to a received buffer pulluped.
7104 * This is rewrited to response.
7105 * so : pointer to socket.
7106 * OUT:
7107 * length for buffer to send to user process.
7108 */
7109 int
7110 key_parse(struct mbuf *m, struct socket *so)
7111 {
7112 struct sadb_msg *msg;
7113 struct sadb_msghdr mh;
7114 u_int orglen;
7115 int error;
7116
7117 KASSERT(m != NULL);
7118 KASSERT(so != NULL);
7119
7120 #if 0 /*kdebug_sadb assumes msg in linear buffer*/
7121 if (KEYDEBUG_ON(KEYDEBUG_KEY_DUMP)) {
7122 IPSECLOG(LOG_DEBUG, "passed sadb_msg\n");
7123 kdebug_sadb(msg);
7124 }
7125 #endif
7126
7127 if (m->m_len < sizeof(struct sadb_msg)) {
7128 m = m_pullup(m, sizeof(struct sadb_msg));
7129 if (!m)
7130 return ENOBUFS;
7131 }
7132 msg = mtod(m, struct sadb_msg *);
7133 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7134
7135 if ((m->m_flags & M_PKTHDR) == 0 ||
7136 m->m_pkthdr.len != orglen) {
7137 IPSECLOG(LOG_DEBUG, "invalid message length.\n");
7138 PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
7139 error = EINVAL;
7140 goto senderror;
7141 }
7142
7143 if (msg->sadb_msg_version != PF_KEY_V2) {
7144 IPSECLOG(LOG_DEBUG, "PF_KEY version %u is mismatched.\n",
7145 msg->sadb_msg_version);
7146 PFKEY_STATINC(PFKEY_STAT_OUT_INVVER);
7147 error = EINVAL;
7148 goto senderror;
7149 }
7150
7151 if (msg->sadb_msg_type > SADB_MAX) {
7152 IPSECLOG(LOG_DEBUG, "invalid type %u is passed.\n",
7153 msg->sadb_msg_type);
7154 PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
7155 error = EINVAL;
7156 goto senderror;
7157 }
7158
7159 /* for old-fashioned code - should be nuked */
7160 if (m->m_pkthdr.len > MCLBYTES) {
7161 m_freem(m);
7162 return ENOBUFS;
7163 }
7164 if (m->m_next) {
7165 struct mbuf *n;
7166
7167 MGETHDR(n, M_DONTWAIT, MT_DATA);
7168 if (n && m->m_pkthdr.len > MHLEN) {
7169 MCLGET(n, M_DONTWAIT);
7170 if ((n->m_flags & M_EXT) == 0) {
7171 m_free(n);
7172 n = NULL;
7173 }
7174 }
7175 if (!n) {
7176 m_freem(m);
7177 return ENOBUFS;
7178 }
7179 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, void *));
7180 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7181 n->m_next = NULL;
7182 m_freem(m);
7183 m = n;
7184 }
7185
7186 /* align the mbuf chain so that extensions are in contiguous region. */
7187 error = key_align(m, &mh);
7188 if (error)
7189 return error;
7190
7191 if (m->m_next) { /*XXX*/
7192 m_freem(m);
7193 return ENOBUFS;
7194 }
7195
7196 msg = mh.msg;
7197
7198 /* check SA type */
7199 switch (msg->sadb_msg_satype) {
7200 case SADB_SATYPE_UNSPEC:
7201 switch (msg->sadb_msg_type) {
7202 case SADB_GETSPI:
7203 case SADB_UPDATE:
7204 case SADB_ADD:
7205 case SADB_DELETE:
7206 case SADB_GET:
7207 case SADB_ACQUIRE:
7208 case SADB_EXPIRE:
7209 IPSECLOG(LOG_DEBUG,
7210 "must specify satype when msg type=%u.\n",
7211 msg->sadb_msg_type);
7212 PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7213 error = EINVAL;
7214 goto senderror;
7215 }
7216 break;
7217 case SADB_SATYPE_AH:
7218 case SADB_SATYPE_ESP:
7219 case SADB_X_SATYPE_IPCOMP:
7220 case SADB_X_SATYPE_TCPSIGNATURE:
7221 switch (msg->sadb_msg_type) {
7222 case SADB_X_SPDADD:
7223 case SADB_X_SPDDELETE:
7224 case SADB_X_SPDGET:
7225 case SADB_X_SPDDUMP:
7226 case SADB_X_SPDFLUSH:
7227 case SADB_X_SPDSETIDX:
7228 case SADB_X_SPDUPDATE:
7229 case SADB_X_SPDDELETE2:
7230 IPSECLOG(LOG_DEBUG, "illegal satype=%u\n",
7231 msg->sadb_msg_type);
7232 PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7233 error = EINVAL;
7234 goto senderror;
7235 }
7236 break;
7237 case SADB_SATYPE_RSVP:
7238 case SADB_SATYPE_OSPFV2:
7239 case SADB_SATYPE_RIPV2:
7240 case SADB_SATYPE_MIP:
7241 IPSECLOG(LOG_DEBUG, "type %u isn't supported.\n",
7242 msg->sadb_msg_satype);
7243 PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7244 error = EOPNOTSUPP;
7245 goto senderror;
7246 case 1: /* XXX: What does it do? */
7247 if (msg->sadb_msg_type == SADB_X_PROMISC)
7248 break;
7249 /*FALLTHROUGH*/
7250 default:
7251 IPSECLOG(LOG_DEBUG, "invalid type %u is passed.\n",
7252 msg->sadb_msg_satype);
7253 PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
7254 error = EINVAL;
7255 goto senderror;
7256 }
7257
7258 /* check field of upper layer protocol and address family */
7259 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL &&
7260 mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7261 struct sadb_address *src0, *dst0;
7262 u_int plen;
7263
7264 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7265 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7266
7267 /* check upper layer protocol */
7268 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7269 IPSECLOG(LOG_DEBUG, "upper layer protocol mismatched.\n");
7270 PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7271 error = EINVAL;
7272 goto senderror;
7273 }
7274
7275 /* check family */
7276 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7277 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7278 IPSECLOG(LOG_DEBUG, "address family mismatched.\n");
7279 PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7280 error = EINVAL;
7281 goto senderror;
7282 }
7283 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7284 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7285 IPSECLOG(LOG_DEBUG,
7286 "address struct size mismatched.\n");
7287 PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7288 error = EINVAL;
7289 goto senderror;
7290 }
7291
7292 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7293 case AF_INET:
7294 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7295 sizeof(struct sockaddr_in)) {
7296 PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7297 error = EINVAL;
7298 goto senderror;
7299 }
7300 break;
7301 case AF_INET6:
7302 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7303 sizeof(struct sockaddr_in6)) {
7304 PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7305 error = EINVAL;
7306 goto senderror;
7307 }
7308 break;
7309 default:
7310 IPSECLOG(LOG_DEBUG, "unsupported address family.\n");
7311 PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7312 error = EAFNOSUPPORT;
7313 goto senderror;
7314 }
7315
7316 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7317 case AF_INET:
7318 plen = sizeof(struct in_addr) << 3;
7319 break;
7320 case AF_INET6:
7321 plen = sizeof(struct in6_addr) << 3;
7322 break;
7323 default:
7324 plen = 0; /*fool gcc*/
7325 break;
7326 }
7327
7328 /* check max prefix length */
7329 if (src0->sadb_address_prefixlen > plen ||
7330 dst0->sadb_address_prefixlen > plen) {
7331 IPSECLOG(LOG_DEBUG, "illegal prefixlen.\n");
7332 PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
7333 error = EINVAL;
7334 goto senderror;
7335 }
7336
7337 /*
7338 * prefixlen == 0 is valid because there can be a case when
7339 * all addresses are matched.
7340 */
7341 }
7342
7343 if (msg->sadb_msg_type >= __arraycount(key_api_typesw) ||
7344 key_api_typesw[msg->sadb_msg_type] == NULL) {
7345 PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
7346 error = EINVAL;
7347 goto senderror;
7348 }
7349
7350 return (*key_api_typesw[msg->sadb_msg_type])(so, m, &mh);
7351
7352 senderror:
7353 return key_senderror(so, m, error);
7354 }
7355
7356 static int
7357 key_senderror(struct socket *so, struct mbuf *m, int code)
7358 {
7359 struct sadb_msg *msg;
7360
7361 KASSERT(m->m_len >= sizeof(struct sadb_msg));
7362
7363 msg = mtod(m, struct sadb_msg *);
7364 msg->sadb_msg_errno = code;
7365 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7366 }
7367
7368 /*
7369 * set the pointer to each header into message buffer.
7370 * m will be freed on error.
7371 * XXX larger-than-MCLBYTES extension?
7372 */
7373 static int
7374 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
7375 {
7376 struct mbuf *n;
7377 struct sadb_ext *ext;
7378 size_t off, end;
7379 int extlen;
7380 int toff;
7381
7382 KASSERT(m != NULL);
7383 KASSERT(mhp != NULL);
7384 KASSERT(m->m_len >= sizeof(struct sadb_msg));
7385
7386 /* initialize */
7387 memset(mhp, 0, sizeof(*mhp));
7388
7389 mhp->msg = mtod(m, struct sadb_msg *);
7390 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
7391
7392 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7393 extlen = end; /*just in case extlen is not updated*/
7394 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7395 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7396 if (!n) {
7397 /* m is already freed */
7398 return ENOBUFS;
7399 }
7400 ext = (struct sadb_ext *)(mtod(n, char *) + toff);
7401
7402 /* set pointer */
7403 switch (ext->sadb_ext_type) {
7404 case SADB_EXT_SA:
7405 case SADB_EXT_ADDRESS_SRC:
7406 case SADB_EXT_ADDRESS_DST:
7407 case SADB_EXT_ADDRESS_PROXY:
7408 case SADB_EXT_LIFETIME_CURRENT:
7409 case SADB_EXT_LIFETIME_HARD:
7410 case SADB_EXT_LIFETIME_SOFT:
7411 case SADB_EXT_KEY_AUTH:
7412 case SADB_EXT_KEY_ENCRYPT:
7413 case SADB_EXT_IDENTITY_SRC:
7414 case SADB_EXT_IDENTITY_DST:
7415 case SADB_EXT_SENSITIVITY:
7416 case SADB_EXT_PROPOSAL:
7417 case SADB_EXT_SUPPORTED_AUTH:
7418 case SADB_EXT_SUPPORTED_ENCRYPT:
7419 case SADB_EXT_SPIRANGE:
7420 case SADB_X_EXT_POLICY:
7421 case SADB_X_EXT_SA2:
7422 case SADB_X_EXT_NAT_T_TYPE:
7423 case SADB_X_EXT_NAT_T_SPORT:
7424 case SADB_X_EXT_NAT_T_DPORT:
7425 case SADB_X_EXT_NAT_T_OAI:
7426 case SADB_X_EXT_NAT_T_OAR:
7427 case SADB_X_EXT_NAT_T_FRAG:
7428 /* duplicate check */
7429 /*
7430 * XXX Are there duplication payloads of either
7431 * KEY_AUTH or KEY_ENCRYPT ?
7432 */
7433 if (mhp->ext[ext->sadb_ext_type] != NULL) {
7434 IPSECLOG(LOG_DEBUG,
7435 "duplicate ext_type %u is passed.\n",
7436 ext->sadb_ext_type);
7437 m_freem(m);
7438 PFKEY_STATINC(PFKEY_STAT_OUT_DUPEXT);
7439 return EINVAL;
7440 }
7441 break;
7442 default:
7443 IPSECLOG(LOG_DEBUG, "invalid ext_type %u is passed.\n",
7444 ext->sadb_ext_type);
7445 m_freem(m);
7446 PFKEY_STATINC(PFKEY_STAT_OUT_INVEXTTYPE);
7447 return EINVAL;
7448 }
7449
7450 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7451
7452 if (key_validate_ext(ext, extlen)) {
7453 m_freem(m);
7454 PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
7455 return EINVAL;
7456 }
7457
7458 n = m_pulldown(m, off, extlen, &toff);
7459 if (!n) {
7460 /* m is already freed */
7461 return ENOBUFS;
7462 }
7463 ext = (struct sadb_ext *)(mtod(n, char *) + toff);
7464
7465 mhp->ext[ext->sadb_ext_type] = ext;
7466 mhp->extoff[ext->sadb_ext_type] = off;
7467 mhp->extlen[ext->sadb_ext_type] = extlen;
7468 }
7469
7470 if (off != end) {
7471 m_freem(m);
7472 PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
7473 return EINVAL;
7474 }
7475
7476 return 0;
7477 }
7478
7479 static int
7480 key_validate_ext(const struct sadb_ext *ext, int len)
7481 {
7482 const struct sockaddr *sa;
7483 enum { NONE, ADDR } checktype = NONE;
7484 int baselen = 0;
7485 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7486
7487 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7488 return EINVAL;
7489
7490 /* if it does not match minimum/maximum length, bail */
7491 if (ext->sadb_ext_type >= __arraycount(minsize) ||
7492 ext->sadb_ext_type >= __arraycount(maxsize))
7493 return EINVAL;
7494 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7495 return EINVAL;
7496 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7497 return EINVAL;
7498
7499 /* more checks based on sadb_ext_type XXX need more */
7500 switch (ext->sadb_ext_type) {
7501 case SADB_EXT_ADDRESS_SRC:
7502 case SADB_EXT_ADDRESS_DST:
7503 case SADB_EXT_ADDRESS_PROXY:
7504 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7505 checktype = ADDR;
7506 break;
7507 case SADB_EXT_IDENTITY_SRC:
7508 case SADB_EXT_IDENTITY_DST:
7509 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7510 SADB_X_IDENTTYPE_ADDR) {
7511 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7512 checktype = ADDR;
7513 } else
7514 checktype = NONE;
7515 break;
7516 default:
7517 checktype = NONE;
7518 break;
7519 }
7520
7521 switch (checktype) {
7522 case NONE:
7523 break;
7524 case ADDR:
7525 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7526 if (len < baselen + sal)
7527 return EINVAL;
7528 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7529 return EINVAL;
7530 break;
7531 }
7532
7533 return 0;
7534 }
7535
7536 static int
7537 key_do_init(void)
7538 {
7539 int i, error;
7540
7541 mutex_init(&key_mtx, MUTEX_DEFAULT, IPL_NONE);
7542
7543 pfkeystat_percpu = percpu_alloc(sizeof(uint64_t) * PFKEY_NSTATS);
7544
7545 callout_init(&key_timehandler_ch, 0);
7546 error = workqueue_create(&key_timehandler_wq, "key_timehandler",
7547 key_timehandler_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
7548 if (error != 0)
7549 panic("%s: workqueue_create failed (%d)\n", __func__, error);
7550
7551 for (i = 0; i < IPSEC_DIR_MAX; i++) {
7552 PSLIST_INIT(&sptree[i]);
7553 }
7554
7555 LIST_INIT(&sahtree);
7556
7557 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7558 LIST_INIT(®tree[i]);
7559 }
7560
7561 #ifndef IPSEC_NONBLOCK_ACQUIRE
7562 LIST_INIT(&acqtree);
7563 #endif
7564 #ifdef notyet
7565 LIST_INIT(&spacqtree);
7566 #endif
7567
7568 /* system default */
7569 ip4_def_policy.policy = IPSEC_POLICY_NONE;
7570 ip4_def_policy.refcnt++; /*never reclaim this*/
7571
7572 #ifdef INET6
7573 ip6_def_policy.policy = IPSEC_POLICY_NONE;
7574 ip6_def_policy.refcnt++; /*never reclaim this*/
7575 #endif
7576
7577 callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
7578
7579 /* initialize key statistics */
7580 keystat.getspi_count = 1;
7581
7582 aprint_verbose("IPsec: Initialized Security Association Processing.\n");
7583
7584 return (0);
7585 }
7586
7587 void
7588 key_init(void)
7589 {
7590 static ONCE_DECL(key_init_once);
7591
7592 sysctl_net_keyv2_setup(NULL);
7593 sysctl_net_key_compat_setup(NULL);
7594
7595 RUN_ONCE(&key_init_once, key_do_init);
7596 }
7597
7598 /*
7599 * XXX: maybe This function is called after INBOUND IPsec processing.
7600 *
7601 * Special check for tunnel-mode packets.
7602 * We must make some checks for consistency between inner and outer IP header.
7603 *
7604 * xxx more checks to be provided
7605 */
7606 int
7607 key_checktunnelsanity(
7608 struct secasvar *sav,
7609 u_int family,
7610 void *src,
7611 void *dst
7612 )
7613 {
7614
7615 /* XXX: check inner IP header */
7616
7617 return 1;
7618 }
7619
7620 #if 0
7621 #define hostnamelen strlen(hostname)
7622
7623 /*
7624 * Get FQDN for the host.
7625 * If the administrator configured hostname (by hostname(1)) without
7626 * domain name, returns nothing.
7627 */
7628 static const char *
7629 key_getfqdn(void)
7630 {
7631 int i;
7632 int hasdot;
7633 static char fqdn[MAXHOSTNAMELEN + 1];
7634
7635 if (!hostnamelen)
7636 return NULL;
7637
7638 /* check if it comes with domain name. */
7639 hasdot = 0;
7640 for (i = 0; i < hostnamelen; i++) {
7641 if (hostname[i] == '.')
7642 hasdot++;
7643 }
7644 if (!hasdot)
7645 return NULL;
7646
7647 /* NOTE: hostname may not be NUL-terminated. */
7648 memset(fqdn, 0, sizeof(fqdn));
7649 memcpy(fqdn, hostname, hostnamelen);
7650 fqdn[hostnamelen] = '\0';
7651 return fqdn;
7652 }
7653
7654 /*
7655 * get username@FQDN for the host/user.
7656 */
7657 static const char *
7658 key_getuserfqdn(void)
7659 {
7660 const char *host;
7661 static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
7662 struct proc *p = curproc;
7663 char *q;
7664
7665 if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
7666 return NULL;
7667 if (!(host = key_getfqdn()))
7668 return NULL;
7669
7670 /* NOTE: s_login may not be-NUL terminated. */
7671 memset(userfqdn, 0, sizeof(userfqdn));
7672 memcpy(userfqdn, Mp->p_pgrp->pg_session->s_login, AXLOGNAME);
7673 userfqdn[MAXLOGNAME] = '\0'; /* safeguard */
7674 q = userfqdn + strlen(userfqdn);
7675 *q++ = '@';
7676 memcpy(q, host, strlen(host));
7677 q += strlen(host);
7678 *q++ = '\0';
7679
7680 return userfqdn;
7681 }
7682 #endif
7683
7684 /* record data transfer on SA, and update timestamps */
7685 void
7686 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
7687 {
7688
7689 KASSERT(sav != NULL);
7690 KASSERT(sav->lft_c != NULL);
7691 KASSERT(m != NULL);
7692
7693 /*
7694 * XXX Currently, there is a difference of bytes size
7695 * between inbound and outbound processing.
7696 */
7697 sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7698 /* to check bytes lifetime is done in key_timehandler(). */
7699
7700 /*
7701 * We use the number of packets as the unit of
7702 * sadb_lifetime_allocations. We increment the variable
7703 * whenever {esp,ah}_{in,out}put is called.
7704 */
7705 sav->lft_c->sadb_lifetime_allocations++;
7706 /* XXX check for expires? */
7707
7708 /*
7709 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7710 * in seconds. HARD and SOFT lifetime are measured by the time
7711 * difference (again in seconds) from sadb_lifetime_usetime.
7712 *
7713 * usetime
7714 * v expire expire
7715 * -----+-----+--------+---> t
7716 * <--------------> HARD
7717 * <-----> SOFT
7718 */
7719 sav->lft_c->sadb_lifetime_usetime = time_uptime;
7720 /* XXX check for expires? */
7721
7722 return;
7723 }
7724
7725 /* dumb version */
7726 void
7727 key_sa_routechange(struct sockaddr *dst)
7728 {
7729 struct secashead *sah;
7730 struct route *ro;
7731 const struct sockaddr *sa;
7732
7733 LIST_FOREACH(sah, &sahtree, chain) {
7734 ro = &sah->sa_route;
7735 sa = rtcache_getdst(ro);
7736 if (sa != NULL && dst->sa_len == sa->sa_len &&
7737 memcmp(dst, sa, dst->sa_len) == 0)
7738 rtcache_free(ro);
7739 }
7740
7741 return;
7742 }
7743
7744 static void
7745 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7746 {
7747 struct secasvar *_sav;
7748
7749 KASSERT(sav != NULL);
7750
7751 if (sav->state == state)
7752 return;
7753
7754 KASSERT(__LIST_CHAINED(sav));
7755 LIST_REMOVE(sav, chain);
7756
7757 sav->state = state;
7758 if (!SADB_SASTATE_USABLE_P(sav)) {
7759 /* We don't need to care about the order */
7760 LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7761 return;
7762 }
7763 /*
7764 * Sort the list by lft_c->sadb_lifetime_addtime
7765 * in ascending order.
7766 */
7767 LIST_FOREACH(_sav, &sav->sah->savtree[state], chain) {
7768 if (_sav->lft_c->sadb_lifetime_addtime >
7769 sav->lft_c->sadb_lifetime_addtime) {
7770 LIST_INSERT_BEFORE(_sav, sav, chain);
7771 break;
7772 }
7773 }
7774 if (_sav == NULL) {
7775 LIST_INSERT_TAIL(&sav->sah->savtree[state], sav, secasvar,
7776 chain);
7777 }
7778 key_validate_savlist(sav->sah, state);
7779 }
7780
7781 /* XXX too much? */
7782 static struct mbuf *
7783 key_alloc_mbuf(int l)
7784 {
7785 struct mbuf *m = NULL, *n;
7786 int len, t;
7787
7788 len = l;
7789 while (len > 0) {
7790 MGET(n, M_DONTWAIT, MT_DATA);
7791 if (n && len > MLEN)
7792 MCLGET(n, M_DONTWAIT);
7793 if (!n) {
7794 m_freem(m);
7795 return NULL;
7796 }
7797
7798 n->m_next = NULL;
7799 n->m_len = 0;
7800 n->m_len = M_TRAILINGSPACE(n);
7801 /* use the bottom of mbuf, hoping we can prepend afterwards */
7802 if (n->m_len > len) {
7803 t = (n->m_len - len) & ~(sizeof(long) - 1);
7804 n->m_data += t;
7805 n->m_len = len;
7806 }
7807
7808 len -= n->m_len;
7809
7810 if (m)
7811 m_cat(m, n);
7812 else
7813 m = n;
7814 }
7815
7816 return m;
7817 }
7818
7819 static struct mbuf *
7820 key_setdump(u_int8_t req_satype, int *errorp, uint32_t pid)
7821 {
7822 struct secashead *sah;
7823 struct secasvar *sav;
7824 u_int16_t proto;
7825 u_int8_t satype;
7826 u_int8_t state;
7827 int cnt;
7828 struct mbuf *m, *n;
7829
7830 /* map satype to proto */
7831 proto = key_satype2proto(req_satype);
7832 if (proto == 0) {
7833 *errorp = EINVAL;
7834 return (NULL);
7835 }
7836
7837 /* count sav entries to be sent to the userland. */
7838 cnt = 0;
7839 LIST_FOREACH(sah, &sahtree, chain) {
7840 if (req_satype != SADB_SATYPE_UNSPEC &&
7841 proto != sah->saidx.proto)
7842 continue;
7843
7844 SASTATE_ANY_FOREACH(state) {
7845 LIST_FOREACH(sav, &sah->savtree[state], chain) {
7846 cnt++;
7847 }
7848 }
7849 }
7850
7851 if (cnt == 0) {
7852 *errorp = ENOENT;
7853 return (NULL);
7854 }
7855
7856 /* send this to the userland, one at a time. */
7857 m = NULL;
7858 LIST_FOREACH(sah, &sahtree, chain) {
7859 if (req_satype != SADB_SATYPE_UNSPEC &&
7860 proto != sah->saidx.proto)
7861 continue;
7862
7863 /* map proto to satype */
7864 satype = key_proto2satype(sah->saidx.proto);
7865 if (satype == 0) {
7866 m_freem(m);
7867 *errorp = EINVAL;
7868 return (NULL);
7869 }
7870
7871 SASTATE_ANY_FOREACH(state) {
7872 LIST_FOREACH(sav, &sah->savtree[state], chain) {
7873 n = key_setdumpsa(sav, SADB_DUMP, satype,
7874 --cnt, pid);
7875 if (!n) {
7876 m_freem(m);
7877 *errorp = ENOBUFS;
7878 return (NULL);
7879 }
7880
7881 if (!m)
7882 m = n;
7883 else
7884 m_cat(m, n);
7885 }
7886 }
7887 }
7888
7889 if (!m) {
7890 *errorp = EINVAL;
7891 return (NULL);
7892 }
7893
7894 if ((m->m_flags & M_PKTHDR) != 0) {
7895 m->m_pkthdr.len = 0;
7896 for (n = m; n; n = n->m_next)
7897 m->m_pkthdr.len += n->m_len;
7898 }
7899
7900 *errorp = 0;
7901 return (m);
7902 }
7903
7904 static struct mbuf *
7905 key_setspddump(int *errorp, pid_t pid)
7906 {
7907 struct secpolicy *sp;
7908 int cnt;
7909 u_int dir;
7910 struct mbuf *m, *n;
7911
7912 /* search SPD entry and get buffer size. */
7913 cnt = 0;
7914 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
7915 SPLIST_READER_FOREACH(sp, dir) {
7916 cnt++;
7917 }
7918 }
7919
7920 if (cnt == 0) {
7921 *errorp = ENOENT;
7922 return (NULL);
7923 }
7924
7925 m = NULL;
7926 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
7927 SPLIST_READER_FOREACH(sp, dir) {
7928 --cnt;
7929 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
7930
7931 if (!n) {
7932 *errorp = ENOBUFS;
7933 m_freem(m);
7934 return (NULL);
7935 }
7936 if (!m)
7937 m = n;
7938 else {
7939 m->m_pkthdr.len += n->m_pkthdr.len;
7940 m_cat(m, n);
7941 }
7942 }
7943 }
7944
7945 *errorp = 0;
7946 return (m);
7947 }
7948
7949 int
7950 key_get_used(void) {
7951 return !SPLIST_READER_EMPTY(IPSEC_DIR_INBOUND) ||
7952 !SPLIST_READER_EMPTY(IPSEC_DIR_OUTBOUND);
7953 }
7954
7955 void
7956 key_update_used(void)
7957 {
7958 switch (ipsec_enabled) {
7959 default:
7960 case 0:
7961 #ifdef notyet
7962 /* XXX: racy */
7963 ipsec_used = 0;
7964 #endif
7965 break;
7966 case 1:
7967 #ifndef notyet
7968 /* XXX: racy */
7969 if (!ipsec_used)
7970 #endif
7971 ipsec_used = key_get_used();
7972 break;
7973 case 2:
7974 ipsec_used = 1;
7975 break;
7976 }
7977 }
7978
7979 static int
7980 sysctl_net_key_dumpsa(SYSCTLFN_ARGS)
7981 {
7982 struct mbuf *m, *n;
7983 int err2 = 0;
7984 char *p, *ep;
7985 size_t len;
7986 int s, error;
7987
7988 if (newp)
7989 return (EPERM);
7990 if (namelen != 1)
7991 return (EINVAL);
7992
7993 s = splsoftnet();
7994 m = key_setdump(name[0], &error, l->l_proc->p_pid);
7995 splx(s);
7996 if (!m)
7997 return (error);
7998 if (!oldp)
7999 *oldlenp = m->m_pkthdr.len;
8000 else {
8001 p = oldp;
8002 if (*oldlenp < m->m_pkthdr.len) {
8003 err2 = ENOMEM;
8004 ep = p + *oldlenp;
8005 } else {
8006 *oldlenp = m->m_pkthdr.len;
8007 ep = p + m->m_pkthdr.len;
8008 }
8009 for (n = m; n; n = n->m_next) {
8010 len = (ep - p < n->m_len) ?
8011 ep - p : n->m_len;
8012 error = copyout(mtod(n, const void *), p, len);
8013 p += len;
8014 if (error)
8015 break;
8016 }
8017 if (error == 0)
8018 error = err2;
8019 }
8020 m_freem(m);
8021
8022 return (error);
8023 }
8024
8025 static int
8026 sysctl_net_key_dumpsp(SYSCTLFN_ARGS)
8027 {
8028 struct mbuf *m, *n;
8029 int err2 = 0;
8030 char *p, *ep;
8031 size_t len;
8032 int s, error;
8033
8034 if (newp)
8035 return (EPERM);
8036 if (namelen != 0)
8037 return (EINVAL);
8038
8039 s = splsoftnet();
8040 m = key_setspddump(&error, l->l_proc->p_pid);
8041 splx(s);
8042 if (!m)
8043 return (error);
8044 if (!oldp)
8045 *oldlenp = m->m_pkthdr.len;
8046 else {
8047 p = oldp;
8048 if (*oldlenp < m->m_pkthdr.len) {
8049 err2 = ENOMEM;
8050 ep = p + *oldlenp;
8051 } else {
8052 *oldlenp = m->m_pkthdr.len;
8053 ep = p + m->m_pkthdr.len;
8054 }
8055 for (n = m; n; n = n->m_next) {
8056 len = (ep - p < n->m_len) ? ep - p : n->m_len;
8057 error = copyout(mtod(n, const void *), p, len);
8058 p += len;
8059 if (error)
8060 break;
8061 }
8062 if (error == 0)
8063 error = err2;
8064 }
8065 m_freem(m);
8066
8067 return (error);
8068 }
8069
8070 /*
8071 * Create sysctl tree for native IPSEC key knobs, originally
8072 * under name "net.keyv2" * with MIB number { CTL_NET, PF_KEY_V2. }.
8073 * However, sysctl(8) never checked for nodes under { CTL_NET, PF_KEY_V2 };
8074 * and in any case the part of our sysctl namespace used for dumping the
8075 * SPD and SA database *HAS* to be compatible with the KAME sysctl
8076 * namespace, for API reasons.
8077 *
8078 * Pending a consensus on the right way to fix this, add a level of
8079 * indirection in how we number the `native' IPSEC key nodes;
8080 * and (as requested by Andrew Brown) move registration of the
8081 * KAME-compatible names to a separate function.
8082 */
8083 #if 0
8084 # define IPSEC_PFKEY PF_KEY_V2
8085 # define IPSEC_PFKEY_NAME "keyv2"
8086 #else
8087 # define IPSEC_PFKEY PF_KEY
8088 # define IPSEC_PFKEY_NAME "key"
8089 #endif
8090
8091 static int
8092 sysctl_net_key_stats(SYSCTLFN_ARGS)
8093 {
8094
8095 return (NETSTAT_SYSCTL(pfkeystat_percpu, PFKEY_NSTATS));
8096 }
8097
8098 static void
8099 sysctl_net_keyv2_setup(struct sysctllog **clog)
8100 {
8101
8102 sysctl_createv(clog, 0, NULL, NULL,
8103 CTLFLAG_PERMANENT,
8104 CTLTYPE_NODE, IPSEC_PFKEY_NAME, NULL,
8105 NULL, 0, NULL, 0,
8106 CTL_NET, IPSEC_PFKEY, CTL_EOL);
8107
8108 sysctl_createv(clog, 0, NULL, NULL,
8109 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8110 CTLTYPE_INT, "debug", NULL,
8111 NULL, 0, &key_debug_level, 0,
8112 CTL_NET, IPSEC_PFKEY, KEYCTL_DEBUG_LEVEL, CTL_EOL);
8113 sysctl_createv(clog, 0, NULL, NULL,
8114 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8115 CTLTYPE_INT, "spi_try", NULL,
8116 NULL, 0, &key_spi_trycnt, 0,
8117 CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_TRY, CTL_EOL);
8118 sysctl_createv(clog, 0, NULL, NULL,
8119 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8120 CTLTYPE_INT, "spi_min_value", NULL,
8121 NULL, 0, &key_spi_minval, 0,
8122 CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MIN_VALUE, CTL_EOL);
8123 sysctl_createv(clog, 0, NULL, NULL,
8124 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8125 CTLTYPE_INT, "spi_max_value", NULL,
8126 NULL, 0, &key_spi_maxval, 0,
8127 CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MAX_VALUE, CTL_EOL);
8128 sysctl_createv(clog, 0, NULL, NULL,
8129 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8130 CTLTYPE_INT, "random_int", NULL,
8131 NULL, 0, &key_int_random, 0,
8132 CTL_NET, IPSEC_PFKEY, KEYCTL_RANDOM_INT, CTL_EOL);
8133 sysctl_createv(clog, 0, NULL, NULL,
8134 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8135 CTLTYPE_INT, "larval_lifetime", NULL,
8136 NULL, 0, &key_larval_lifetime, 0,
8137 CTL_NET, IPSEC_PFKEY, KEYCTL_LARVAL_LIFETIME, CTL_EOL);
8138 sysctl_createv(clog, 0, NULL, NULL,
8139 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8140 CTLTYPE_INT, "blockacq_count", NULL,
8141 NULL, 0, &key_blockacq_count, 0,
8142 CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_COUNT, CTL_EOL);
8143 sysctl_createv(clog, 0, NULL, NULL,
8144 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8145 CTLTYPE_INT, "blockacq_lifetime", NULL,
8146 NULL, 0, &key_blockacq_lifetime, 0,
8147 CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_LIFETIME, CTL_EOL);
8148 sysctl_createv(clog, 0, NULL, NULL,
8149 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8150 CTLTYPE_INT, "esp_keymin", NULL,
8151 NULL, 0, &ipsec_esp_keymin, 0,
8152 CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_KEYMIN, CTL_EOL);
8153 sysctl_createv(clog, 0, NULL, NULL,
8154 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8155 CTLTYPE_INT, "prefered_oldsa", NULL,
8156 NULL, 0, &key_prefered_oldsa, 0,
8157 CTL_NET, PF_KEY, KEYCTL_PREFERED_OLDSA, CTL_EOL);
8158 sysctl_createv(clog, 0, NULL, NULL,
8159 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8160 CTLTYPE_INT, "esp_auth", NULL,
8161 NULL, 0, &ipsec_esp_auth, 0,
8162 CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_AUTH, CTL_EOL);
8163 sysctl_createv(clog, 0, NULL, NULL,
8164 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
8165 CTLTYPE_INT, "ah_keymin", NULL,
8166 NULL, 0, &ipsec_ah_keymin, 0,
8167 CTL_NET, IPSEC_PFKEY, KEYCTL_AH_KEYMIN, CTL_EOL);
8168 sysctl_createv(clog, 0, NULL, NULL,
8169 CTLFLAG_PERMANENT,
8170 CTLTYPE_STRUCT, "stats",
8171 SYSCTL_DESCR("PF_KEY statistics"),
8172 sysctl_net_key_stats, 0, NULL, 0,
8173 CTL_NET, IPSEC_PFKEY, CTL_CREATE, CTL_EOL);
8174 }
8175
8176 /*
8177 * Register sysctl names used by setkey(8). For historical reasons,
8178 * and to share a single API, these names appear under { CTL_NET, PF_KEY }
8179 * for both IPSEC and KAME IPSEC.
8180 */
8181 static void
8182 sysctl_net_key_compat_setup(struct sysctllog **clog)
8183 {
8184
8185 sysctl_createv(clog, 0, NULL, NULL,
8186 CTLFLAG_PERMANENT,
8187 CTLTYPE_NODE, "key", NULL,
8188 NULL, 0, NULL, 0,
8189 CTL_NET, PF_KEY, CTL_EOL);
8190
8191 /* Register the net.key.dump{sa,sp} nodes used by setkey(8). */
8192 sysctl_createv(clog, 0, NULL, NULL,
8193 CTLFLAG_PERMANENT,
8194 CTLTYPE_STRUCT, "dumpsa", NULL,
8195 sysctl_net_key_dumpsa, 0, NULL, 0,
8196 CTL_NET, PF_KEY, KEYCTL_DUMPSA, CTL_EOL);
8197 sysctl_createv(clog, 0, NULL, NULL,
8198 CTLFLAG_PERMANENT,
8199 CTLTYPE_STRUCT, "dumpsp", NULL,
8200 sysctl_net_key_dumpsp, 0, NULL, 0,
8201 CTL_NET, PF_KEY, KEYCTL_DUMPSP, CTL_EOL);
8202 }
8203