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