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