Correct typo in comment for vshiftl().
[dragonfly.git] / sys / netproto / ipsec / ipsec.c
1 /*      $FreeBSD: src/sys/netipsec/ipsec.c,v 1.2.2.1 2003/01/24 05:11:35 sam Exp $      */
2 /*      $DragonFly: src/sys/netproto/ipsec/ipsec.c,v 1.10 2005/06/02 23:50:30 hmp Exp $ */
3 /*      $KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $ */
4
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * IPsec controller part.
36  */
37
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/malloc.h>
45 #include <sys/mbuf.h>
46 #include <sys/domain.h>
47 #include <sys/protosw.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/errno.h>
51 #include <sys/time.h>
52 #include <sys/kernel.h>
53 #include <sys/syslog.h>
54 #include <sys/sysctl.h>
55 #include <sys/proc.h>
56 #include <sys/in_cksum.h>
57
58 #include <net/if.h>
59 #include <net/route.h>
60
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/ip.h>
64 #include <netinet/ip_var.h>
65 #include <netinet/in_var.h>
66 #include <netinet/udp.h>
67 #include <netinet/udp_var.h>
68 #include <netinet/tcp.h>
69 #include <netinet/udp.h>
70
71 #include <netinet/ip6.h>
72 #ifdef INET6
73 #include <netinet6/ip6_var.h>
74 #endif
75 #include <netinet/in_pcb.h>
76 #ifdef INET6
77 #include <netinet/icmp6.h>
78 #endif
79
80 #include <netproto/ipsec/ipsec.h>
81 #ifdef INET6
82 #include <netproto/ipsec/ipsec6.h>
83 #endif
84 #include <netproto/ipsec/ah_var.h>
85 #include <netproto/ipsec/esp_var.h>
86 #include <netproto/ipsec/ipcomp.h>              /*XXX*/
87 #include <netproto/ipsec/ipcomp_var.h>
88
89 #include <netproto/ipsec/key.h>
90 #include <netproto/ipsec/keydb.h>
91 #include <netproto/ipsec/key_debug.h>
92
93 #include <netproto/ipsec/xform.h>
94
95 #include <net/net_osdep.h>
96
97 #ifdef IPSEC_DEBUG
98 int ipsec_debug = 1;
99 #else
100 int ipsec_debug = 0;
101 #endif
102
103 /* NB: name changed so netstat doesn't use it */
104 struct newipsecstat newipsecstat;
105 int ip4_ah_offsetmask = 0;      /* maybe IP_DF? */
106 int ip4_ipsec_dfbit = 0;        /* DF bit on encap. 0: clear 1: set 2: copy */
107 int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
108 int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
109 int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
110 int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
111 struct secpolicy ip4_def_policy;
112 int ip4_ipsec_ecn = 0;          /* ECN ignore(-1)/forbidden(0)/allowed(1) */
113 int ip4_esp_randpad = -1;
114 /*
115  * Crypto support requirements:
116  *
117  *  1   require hardware support
118  * -1   require software support
119  *  0   take anything
120  */
121 int     crypto_support = 0;
122
123 SYSCTL_DECL(_net_inet_ipsec);
124
125 /* net.inet.ipsec */
126 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_POLICY,
127         def_policy, CTLFLAG_RW, &ip4_def_policy.policy, 0, "");
128 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
129         CTLFLAG_RW, &ip4_esp_trans_deflev,      0, "");
130 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
131         CTLFLAG_RW, &ip4_esp_net_deflev,        0, "");
132 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
133         CTLFLAG_RW, &ip4_ah_trans_deflev,       0, "");
134 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
135         CTLFLAG_RW, &ip4_ah_net_deflev, 0, "");
136 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS,
137         ah_cleartos, CTLFLAG_RW,        &ah_cleartos,   0, "");
138 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK,
139         ah_offsetmask, CTLFLAG_RW,      &ip4_ah_offsetmask,     0, "");
140 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT,
141         dfbit, CTLFLAG_RW,      &ip4_ipsec_dfbit,       0, "");
142 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN,
143         ecn, CTLFLAG_RW,        &ip4_ipsec_ecn, 0, "");
144 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG,
145         debug, CTLFLAG_RW,      &ipsec_debug,   0, "");
146 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ESP_RANDPAD,
147         esp_randpad, CTLFLAG_RW,        &ip4_esp_randpad,       0, "");
148 SYSCTL_INT(_net_inet_ipsec, OID_AUTO,
149         crypto_support, CTLFLAG_RW,     &crypto_support,0, "");
150 SYSCTL_STRUCT(_net_inet_ipsec, OID_AUTO,
151         ipsecstats,     CTLFLAG_RD,     &newipsecstat,  newipsecstat, "");
152
153 #ifdef INET6
154 int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
155 int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
156 int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
157 int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
158 int ip6_ipsec_ecn = 0;          /* ECN ignore(-1)/forbidden(0)/allowed(1) */
159 int ip6_esp_randpad = -1;
160
161 SYSCTL_DECL(_net_inet6_ipsec6);
162
163 /* net.inet6.ipsec6 */
164 #ifdef COMPAT_KAME
165 SYSCTL_OID(_net_inet6_ipsec6, IPSECCTL_STATS, stats, CTLFLAG_RD,
166         0,0, compat_ipsecstats_sysctl, "S", "");
167 #endif /* COMPAT_KAME */
168 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY,
169         def_policy, CTLFLAG_RW, &ip4_def_policy.policy, 0, "");
170 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
171         CTLFLAG_RW, &ip6_esp_trans_deflev,      0, "");
172 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
173         CTLFLAG_RW, &ip6_esp_net_deflev,        0, "");
174 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
175         CTLFLAG_RW, &ip6_ah_trans_deflev,       0, "");
176 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
177         CTLFLAG_RW, &ip6_ah_net_deflev, 0, "");
178 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN,
179         ecn, CTLFLAG_RW,        &ip6_ipsec_ecn, 0, "");
180 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG,
181         debug, CTLFLAG_RW,      &ipsec_debug,   0, "");
182 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ESP_RANDPAD,
183         esp_randpad, CTLFLAG_RW,        &ip6_esp_randpad,       0, "");
184 #endif /* INET6 */
185
186 static int ipsec4_setspidx_inpcb (struct mbuf *, struct inpcb *pcb);
187 #ifdef INET6
188 static int ipsec6_setspidx_in6pcb (struct mbuf *, struct in6pcb *pcb);
189 #endif
190 static int ipsec_setspidx (struct mbuf *, struct secpolicyindex *, int);
191 static void ipsec4_get_ulp (struct mbuf *m, struct secpolicyindex *, int);
192 static int ipsec4_setspidx_ipaddr (struct mbuf *, struct secpolicyindex *);
193 #ifdef INET6
194 static void ipsec6_get_ulp (struct mbuf *m, struct secpolicyindex *, int);
195 static int ipsec6_setspidx_ipaddr (struct mbuf *, struct secpolicyindex *);
196 #endif
197 static void ipsec_delpcbpolicy (struct inpcbpolicy *);
198 static struct secpolicy *ipsec_deepcopy_policy (struct secpolicy *src);
199 static int ipsec_set_policy (struct secpolicy **pcb_sp,
200         int optname, caddr_t request, size_t len, int priv);
201 static int ipsec_get_policy (struct secpolicy *pcb_sp, struct mbuf **mp);
202 static void vshiftl (unsigned char *, int, int);
203 static size_t ipsec_hdrsiz (struct secpolicy *);
204
205 /*
206  * Return a held reference to the default SP.
207  */
208 static struct secpolicy *
209 key_allocsp_default(const char* where, int tag)
210 {
211         struct secpolicy *sp;
212
213         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
214                 printf("DP key_allocsp_default from %s:%u\n", where, tag));
215
216         sp = &ip4_def_policy;
217         if (sp->policy != IPSEC_POLICY_DISCARD &&
218             sp->policy != IPSEC_POLICY_NONE) {
219                 ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
220                     sp->policy, IPSEC_POLICY_NONE));
221                 sp->policy = IPSEC_POLICY_NONE;
222         }
223         sp->refcnt++;
224
225         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
226                 printf("DP key_allocsp_default returns SP:%p (%u)\n",
227                         sp, sp->refcnt));
228         return sp;
229 }
230 #define KEY_ALLOCSP_DEFAULT() \
231         key_allocsp_default(__FILE__, __LINE__)
232
233 /*
234  * For OUTBOUND packet having a socket. Searching SPD for packet,
235  * and return a pointer to SP.
236  * OUT: NULL:   no apropreate SP found, the following value is set to error.
237  *              0       : bypass
238  *              EACCES  : discard packet.
239  *              ENOENT  : ipsec_acquire() in progress, maybe.
240  *              others  : error occured.
241  *      others: a pointer to SP
242  *
243  * NOTE: IPv6 mapped adddress concern is implemented here.
244  */
245 struct secpolicy *
246 ipsec_getpolicy(struct tdb_ident *tdbi, u_int dir)
247 {
248         struct secpolicy *sp;
249
250         KASSERT(tdbi != NULL, ("ipsec_getpolicy: null tdbi"));
251         KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
252                 ("ipsec_getpolicy: invalid direction %u", dir));
253
254         sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir);
255         if (sp == NULL)                 /*XXX????*/
256                 sp = KEY_ALLOCSP_DEFAULT();
257         KASSERT(sp != NULL, ("ipsec_getpolicy: null SP"));
258         return sp;
259 }
260
261 /*
262  * For OUTBOUND packet having a socket. Searching SPD for packet,
263  * and return a pointer to SP.
264  * OUT: NULL:   no apropreate SP found, the following value is set to error.
265  *              0       : bypass
266  *              EACCES  : discard packet.
267  *              ENOENT  : ipsec_acquire() in progress, maybe.
268  *              others  : error occured.
269  *      others: a pointer to SP
270  *
271  * NOTE: IPv6 mapped adddress concern is implemented here.
272  */
273 struct secpolicy *
274 ipsec_getpolicybysock(m, dir, inp, error)
275         struct mbuf *m;
276         u_int dir;
277         struct inpcb *inp;
278         int *error;
279 {
280         struct inpcbpolicy *pcbsp = NULL;
281         struct secpolicy *currsp = NULL;        /* policy on socket */
282         struct secpolicy *sp;
283         int af;
284
285         KASSERT(m != NULL, ("ipsec_getpolicybysock: null mbuf"));
286         KASSERT(inp != NULL, ("ipsec_getpolicybysock: null inpcb"));
287         KASSERT(error != NULL, ("ipsec_getpolicybysock: null error"));
288         KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
289                 ("ipsec_getpolicybysock: invalid direction %u", dir));
290
291         af = inp->inp_socket->so_proto->pr_domain->dom_family;
292         KASSERT(af == AF_INET || af == AF_INET6,
293                 ("ipsec_getpolicybysock: unexpected protocol family %u", af));
294
295         switch (af) {
296         case AF_INET:
297                 /* set spidx in pcb */
298                 *error = ipsec4_setspidx_inpcb(m, inp);
299                 pcbsp = inp->inp_sp;
300                 break;
301 #ifdef INET6
302         case AF_INET6:
303                 /* set spidx in pcb */
304                 *error = ipsec6_setspidx_in6pcb(m, inp);
305                 pcbsp = inp->in6p_sp;
306                 break;
307 #endif
308         default:
309                 *error = EPFNOSUPPORT;
310                 break;
311         }
312         if (*error)
313                 return NULL;
314
315         KASSERT(pcbsp != NULL, ("ipsec_getpolicybysock: null pcbsp"));
316         switch (dir) {
317         case IPSEC_DIR_INBOUND:
318                 currsp = pcbsp->sp_in;
319                 break;
320         case IPSEC_DIR_OUTBOUND:
321                 currsp = pcbsp->sp_out;
322                 break;
323         }
324         KASSERT(currsp != NULL, ("ipsec_getpolicybysock: null currsp"));
325
326         if (pcbsp->priv) {                      /* when privilieged socket */
327                 switch (currsp->policy) {
328                 case IPSEC_POLICY_BYPASS:
329                 case IPSEC_POLICY_IPSEC:
330                         currsp->refcnt++;
331                         sp = currsp;
332                         break;
333
334                 case IPSEC_POLICY_ENTRUST:
335                         /* look for a policy in SPD */
336                         sp = KEY_ALLOCSP(&currsp->spidx, dir);
337                         if (sp == NULL)         /* no SP found */
338                                 sp = KEY_ALLOCSP_DEFAULT();
339                         break;
340
341                 default:
342                         ipseclog((LOG_ERR, "ipsec_getpolicybysock: "
343                               "Invalid policy for PCB %d\n", currsp->policy));
344                         *error = EINVAL;
345                         return NULL;
346                 }
347         } else {                                /* unpriv, SPD has policy */
348                 sp = KEY_ALLOCSP(&currsp->spidx, dir);
349                 if (sp == NULL) {               /* no SP found */
350                         switch (currsp->policy) {
351                         case IPSEC_POLICY_BYPASS:
352                                 ipseclog((LOG_ERR, "ipsec_getpolicybysock: "
353                                        "Illegal policy for non-priviliged defined %d\n",
354                                         currsp->policy));
355                                 *error = EINVAL;
356                                 return NULL;
357
358                         case IPSEC_POLICY_ENTRUST:
359                                 sp = KEY_ALLOCSP_DEFAULT();
360                                 break;
361
362                         case IPSEC_POLICY_IPSEC:
363                                 currsp->refcnt++;
364                                 sp = currsp;
365                                 break;
366
367                         default:
368                                 ipseclog((LOG_ERR, "ipsec_getpolicybysock: "
369                                    "Invalid policy for PCB %d\n", currsp->policy));
370                                 *error = EINVAL;
371                                 return NULL;
372                         }
373                 }
374         }
375         KASSERT(sp != NULL,
376                 ("ipsec_getpolicybysock: null SP (priv %u policy %u",
377                  pcbsp->priv, currsp->policy));
378         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
379                 printf("DP ipsec_getpolicybysock (priv %u policy %u) allocates "
380                        "SP:%p (refcnt %u)\n", pcbsp->priv, currsp->policy,
381                        sp, sp->refcnt));
382         return sp;
383 }
384
385 /*
386  * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
387  * and return a pointer to SP.
388  * OUT: positive: a pointer to the entry for security policy leaf matched.
389  *      NULL:   no apropreate SP found, the following value is set to error.
390  *              0       : bypass
391  *              EACCES  : discard packet.
392  *              ENOENT  : ipsec_acquire() in progress, maybe.
393  *              others  : error occured.
394  */
395 struct secpolicy *
396 ipsec_getpolicybyaddr(m, dir, flag, error)
397         struct mbuf *m;
398         u_int dir;
399         int flag;
400         int *error;
401 {
402         struct secpolicyindex spidx;
403         struct secpolicy *sp;
404
405         KASSERT(m != NULL, ("ipsec_getpolicybyaddr: null mbuf"));
406         KASSERT(error != NULL, ("ipsec_getpolicybyaddr: null error"));
407         KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
408                 ("ipsec4_getpolicybaddr: invalid direction %u", dir));
409
410         sp = NULL;
411         if (key_havesp(dir)) {
412                 /* Make an index to look for a policy. */
413                 *error = ipsec_setspidx(m, &spidx,
414                                         (flag & IP_FORWARDING) ? 0 : 1);
415                 if (*error != 0) {
416                         DPRINTF(("ipsec_getpolicybyaddr: setpidx failed,"
417                                 " dir %u flag %u\n", dir, flag));
418                         bzero(&spidx, sizeof (spidx));
419                         return NULL;
420                 }
421                 spidx.dir = dir;
422
423                 sp = KEY_ALLOCSP(&spidx, dir);
424         }
425         if (sp == NULL)                 /* no SP found, use system default */
426                 sp = KEY_ALLOCSP_DEFAULT();
427         KASSERT(sp != NULL, ("ipsec_getpolicybyaddr: null SP"));
428         return sp;
429 }
430
431 struct secpolicy *
432 ipsec4_checkpolicy(m, dir, flag, error, inp)
433         struct mbuf *m;
434         u_int dir, flag;
435         int *error;
436         struct inpcb *inp;
437 {
438         struct secpolicy *sp;
439
440         *error = 0;
441         if (inp == NULL)
442                 sp = ipsec_getpolicybyaddr(m, dir, flag, error);
443         else
444                 sp = ipsec_getpolicybysock(m, dir, inp, error);
445         if (sp == NULL) {
446                 KASSERT(*error != 0,
447                         ("ipsec4_checkpolicy: getpolicy failed w/o error"));
448                 newipsecstat.ips_out_inval++;
449                 return NULL;
450         }
451         KASSERT(*error == 0,
452                 ("ipsec4_checkpolicy: sp w/ error set to %u", *error));
453         switch (sp->policy) {
454         case IPSEC_POLICY_ENTRUST:
455         default:
456                 printf("ipsec4_checkpolicy: invalid policy %u\n", sp->policy);
457                 /* fall thru... */
458         case IPSEC_POLICY_DISCARD:
459                 newipsecstat.ips_out_polvio++;
460                 *error = -EINVAL;       /* packet is discarded by caller */
461                 break;
462         case IPSEC_POLICY_BYPASS:
463         case IPSEC_POLICY_NONE:
464                 KEY_FREESP(&sp);
465                 sp = NULL;              /* NB: force NULL result */
466                 break;
467         case IPSEC_POLICY_IPSEC:
468                 if (sp->req == NULL)    /* acquire an SA */
469                         *error = key_spdacquire(sp);
470                 break;
471         }
472         if (*error != 0) {
473                 KEY_FREESP(&sp);
474                 sp = NULL;
475         }
476         return sp;
477 }
478
479 static int
480 ipsec4_setspidx_inpcb(m, pcb)
481         struct mbuf *m;
482         struct inpcb *pcb;
483 {
484         int error;
485
486         KASSERT(pcb != NULL, ("ipsec4_setspidx_inpcb: null pcb"));
487         KASSERT(pcb->inp_sp != NULL, ("ipsec4_setspidx_inpcb: null inp_sp"));
488         KASSERT(pcb->inp_sp->sp_out != NULL && pcb->inp_sp->sp_in != NULL,
489                 ("ipsec4_setspidx_inpcb: null sp_in || sp_out"));
490
491         error = ipsec_setspidx(m, &pcb->inp_sp->sp_in->spidx, 1);
492         if (error == 0) {
493                 pcb->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
494                 pcb->inp_sp->sp_out->spidx = pcb->inp_sp->sp_in->spidx;
495                 pcb->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
496         } else {
497                 bzero(&pcb->inp_sp->sp_in->spidx,
498                         sizeof (pcb->inp_sp->sp_in->spidx));
499                 bzero(&pcb->inp_sp->sp_out->spidx,
500                         sizeof (pcb->inp_sp->sp_in->spidx));
501         }
502         return error;
503 }
504
505 #ifdef INET6
506 static int
507 ipsec6_setspidx_in6pcb(m, pcb)
508         struct mbuf *m;
509         struct in6pcb *pcb;
510 {
511         struct secpolicyindex *spidx;
512         int error;
513
514         KASSERT(pcb != NULL, ("ipsec6_setspidx_in6pcb: null pcb"));
515         KASSERT(pcb->in6p_sp != NULL, ("ipsec6_setspidx_in6pcb: null inp_sp"));
516         KASSERT(pcb->in6p_sp->sp_out != NULL && pcb->in6p_sp->sp_in != NULL,
517                 ("ipsec6_setspidx_in6pcb: null sp_in || sp_out"));
518
519         bzero(&pcb->in6p_sp->sp_in->spidx, sizeof(*spidx));
520         bzero(&pcb->in6p_sp->sp_out->spidx, sizeof(*spidx));
521
522         spidx = &pcb->in6p_sp->sp_in->spidx;
523         error = ipsec_setspidx(m, spidx, 1);
524         if (error)
525                 goto bad;
526         spidx->dir = IPSEC_DIR_INBOUND;
527
528         spidx = &pcb->in6p_sp->sp_out->spidx;
529         error = ipsec_setspidx(m, spidx, 1);
530         if (error)
531                 goto bad;
532         spidx->dir = IPSEC_DIR_OUTBOUND;
533
534         return 0;
535
536 bad:
537         bzero(&pcb->in6p_sp->sp_in->spidx, sizeof(*spidx));
538         bzero(&pcb->in6p_sp->sp_out->spidx, sizeof(*spidx));
539         return error;
540 }
541 #endif
542
543 /*
544  * configure security policy index (src/dst/proto/sport/dport)
545  * by looking at the content of mbuf.
546  * the caller is responsible for error recovery (like clearing up spidx).
547  */
548 static int
549 ipsec_setspidx(m, spidx, needport)
550         struct mbuf *m;
551         struct secpolicyindex *spidx;
552         int needport;
553 {
554         struct ip *ip = NULL;
555         struct ip ipbuf;
556         u_int v;
557         struct mbuf *n;
558         int len;
559         int error;
560
561         KASSERT(m != NULL, ("ipsec_setspidx: null mbuf"));
562
563         /*
564          * validate m->m_pkthdr.len.  we see incorrect length if we
565          * mistakenly call this function with inconsistent mbuf chain
566          * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
567          */
568         len = 0;
569         for (n = m; n; n = n->m_next)
570                 len += n->m_len;
571         if (m->m_pkthdr.len != len) {
572                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
573                         printf("ipsec_setspidx: "
574                                "total of m_len(%d) != pkthdr.len(%d), "
575                                "ignored.\n",
576                                 len, m->m_pkthdr.len));
577                 return EINVAL;
578         }
579
580         if (m->m_pkthdr.len < sizeof(struct ip)) {
581                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
582                         printf("ipsec_setspidx: "
583                             "pkthdr.len(%d) < sizeof(struct ip), ignored.\n",
584                             m->m_pkthdr.len));
585                 return EINVAL;
586         }
587
588         if (m->m_len >= sizeof(*ip))
589                 ip = mtod(m, struct ip *);
590         else {
591                 m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf);
592                 ip = &ipbuf;
593         }
594 #ifdef _IP_VHL
595         v = _IP_VHL_V(ip->ip_vhl);
596 #else
597         v = ip->ip_v;
598 #endif
599         switch (v) {
600         case 4:
601                 error = ipsec4_setspidx_ipaddr(m, spidx);
602                 if (error)
603                         return error;
604                 ipsec4_get_ulp(m, spidx, needport);
605                 return 0;
606 #ifdef INET6
607         case 6:
608                 if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
609                         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
610                                 printf("ipsec_setspidx: "
611                                     "pkthdr.len(%d) < sizeof(struct ip6_hdr), "
612                                     "ignored.\n", m->m_pkthdr.len));
613                         return EINVAL;
614                 }
615                 error = ipsec6_setspidx_ipaddr(m, spidx);
616                 if (error)
617                         return error;
618                 ipsec6_get_ulp(m, spidx, needport);
619                 return 0;
620 #endif
621         default:
622                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
623                         printf("ipsec_setspidx: "
624                             "unknown IP version %u, ignored.\n", v));
625                 return EINVAL;
626         }
627 }
628
629 static void
630 ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
631 {
632         u_int8_t nxt;
633         int off;
634
635         /* sanity check */
636         KASSERT(m != NULL, ("ipsec4_get_ulp: null mbuf"));
637         KASSERT(m->m_pkthdr.len >= sizeof(struct ip),
638                 ("ipsec4_get_ulp: packet too short"));
639
640         /* NB: ip_input() flips it into host endian XXX need more checking */
641         if (m->m_len < sizeof (struct ip)) {
642                 struct ip *ip = mtod(m, struct ip *);
643                 if (ip->ip_off & (IP_MF | IP_OFFMASK))
644                         goto done;
645 #ifdef _IP_VHL
646                 off = _IP_VHL_HL(ip->ip_vhl) << 2;
647 #else
648                 off = ip->ip_hl << 2;
649 #endif
650                 nxt = ip->ip_p;
651         } else {
652                 struct ip ih;
653
654                 m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih);
655                 if (ih.ip_off & (IP_MF | IP_OFFMASK))
656                         goto done;
657 #ifdef _IP_VHL
658                 off = _IP_VHL_HL(ih.ip_vhl) << 2;
659 #else
660                 off = ih.ip_hl << 2;
661 #endif
662                 nxt = ih.ip_p;
663         }
664
665         while (off < m->m_pkthdr.len) {
666                 struct ip6_ext ip6e;
667                 struct tcphdr th;
668                 struct udphdr uh;
669
670                 switch (nxt) {
671                 case IPPROTO_TCP:
672                         spidx->ul_proto = nxt;
673                         if (!needport)
674                                 goto done_proto;
675                         if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
676                                 goto done;
677                         m_copydata(m, off, sizeof (th), (caddr_t) &th);
678                         spidx->src.sin.sin_port = th.th_sport;
679                         spidx->dst.sin.sin_port = th.th_dport;
680                         return;
681                 case IPPROTO_UDP:
682                         spidx->ul_proto = nxt;
683                         if (!needport)
684                                 goto done_proto;
685                         if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
686                                 goto done;
687                         m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
688                         spidx->src.sin.sin_port = uh.uh_sport;
689                         spidx->dst.sin.sin_port = uh.uh_dport;
690                         return;
691                 case IPPROTO_AH:
692                         if (m->m_pkthdr.len > off + sizeof(ip6e))
693                                 goto done;
694                         /* XXX sigh, this works but is totally bogus */
695                         m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
696                         off += (ip6e.ip6e_len + 2) << 2;
697                         nxt = ip6e.ip6e_nxt;
698                         break;
699                 case IPPROTO_ICMP:
700                 default:
701                         /* XXX intermediate headers??? */
702                         spidx->ul_proto = nxt;
703                         goto done_proto;
704                 }
705         }
706 done:
707         spidx->ul_proto = IPSEC_ULPROTO_ANY;
708 done_proto:
709         spidx->src.sin.sin_port = IPSEC_PORT_ANY;
710         spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
711 }
712
713 /* assumes that m is sane */
714 static int
715 ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
716 {
717         static const struct sockaddr_in template = {
718                 sizeof (struct sockaddr_in),
719                 AF_INET,
720                 0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
721         };
722
723         spidx->src.sin = template;
724         spidx->dst.sin = template;
725
726         if (m->m_len < sizeof (struct ip)) {
727                 m_copydata(m, offsetof(struct ip, ip_src),
728                            sizeof (struct  in_addr),
729                            (caddr_t) &spidx->src.sin.sin_addr);
730                 m_copydata(m, offsetof(struct ip, ip_dst),
731                            sizeof (struct  in_addr),
732                            (caddr_t) &spidx->dst.sin.sin_addr);
733         } else {
734                 struct ip *ip = mtod(m, struct ip *);
735                 spidx->src.sin.sin_addr = ip->ip_src;
736                 spidx->dst.sin.sin_addr = ip->ip_dst;
737         }
738
739         spidx->prefs = sizeof(struct in_addr) << 3;
740         spidx->prefd = sizeof(struct in_addr) << 3;
741
742         return 0;
743 }
744
745 #ifdef INET6
746 static void
747 ipsec6_get_ulp(m, spidx, needport)
748         struct mbuf *m;
749         struct secpolicyindex *spidx;
750         int needport;
751 {
752         int off, nxt;
753         struct tcphdr th;
754         struct udphdr uh;
755
756         /* sanity check */
757         if (m == NULL)
758                 panic("ipsec6_get_ulp: NULL pointer was passed.\n");
759
760         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
761                 printf("ipsec6_get_ulp:\n"); kdebug_mbuf(m));
762
763         /* set default */
764         spidx->ul_proto = IPSEC_ULPROTO_ANY;
765         ((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
766         ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
767
768         nxt = -1;
769         off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
770         if (off < 0 || m->m_pkthdr.len < off)
771                 return;
772
773         switch (nxt) {
774         case IPPROTO_TCP:
775                 spidx->ul_proto = nxt;
776                 if (!needport)
777                         break;
778                 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
779                         break;
780                 m_copydata(m, off, sizeof(th), (caddr_t)&th);
781                 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
782                 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
783                 break;
784         case IPPROTO_UDP:
785                 spidx->ul_proto = nxt;
786                 if (!needport)
787                         break;
788                 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
789                         break;
790                 m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
791                 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
792                 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
793                 break;
794         case IPPROTO_ICMPV6:
795         default:
796                 /* XXX intermediate headers??? */
797                 spidx->ul_proto = nxt;
798                 break;
799         }
800 }
801
802 /* assumes that m is sane */
803 static int
804 ipsec6_setspidx_ipaddr(m, spidx)
805         struct mbuf *m;
806         struct secpolicyindex *spidx;
807 {
808         struct ip6_hdr *ip6 = NULL;
809         struct ip6_hdr ip6buf;
810         struct sockaddr_in6 *sin6;
811
812         if (m->m_len >= sizeof(*ip6))
813                 ip6 = mtod(m, struct ip6_hdr *);
814         else {
815                 m_copydata(m, 0, sizeof(ip6buf), (caddr_t)&ip6buf);
816                 ip6 = &ip6buf;
817         }
818
819         sin6 = (struct sockaddr_in6 *)&spidx->src;
820         bzero(sin6, sizeof(*sin6));
821         sin6->sin6_family = AF_INET6;
822         sin6->sin6_len = sizeof(struct sockaddr_in6);
823         bcopy(&ip6->ip6_src, &sin6->sin6_addr, sizeof(ip6->ip6_src));
824         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
825                 sin6->sin6_addr.s6_addr16[1] = 0;
826                 sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
827         }
828         spidx->prefs = sizeof(struct in6_addr) << 3;
829
830         sin6 = (struct sockaddr_in6 *)&spidx->dst;
831         bzero(sin6, sizeof(*sin6));
832         sin6->sin6_family = AF_INET6;
833         sin6->sin6_len = sizeof(struct sockaddr_in6);
834         bcopy(&ip6->ip6_dst, &sin6->sin6_addr, sizeof(ip6->ip6_dst));
835         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
836                 sin6->sin6_addr.s6_addr16[1] = 0;
837                 sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
838         }
839         spidx->prefd = sizeof(struct in6_addr) << 3;
840
841         return 0;
842 }
843 #endif
844
845 static void
846 ipsec_delpcbpolicy(p)
847         struct inpcbpolicy *p;
848 {
849         free(p, M_SECA);
850 }
851
852 /* initialize policy in PCB */
853 int
854 ipsec_init_policy(so, pcb_sp)
855         struct socket *so;
856         struct inpcbpolicy **pcb_sp;
857 {
858         struct inpcbpolicy *new;
859
860         /* sanity check. */
861         if (so == NULL || pcb_sp == NULL)
862                 panic("ipsec_init_policy: NULL pointer was passed.\n");
863
864         new = malloc(sizeof(struct inpcbpolicy),
865                         M_SECA, M_INTWAIT | M_ZERO | M_NULLOK);
866         if (new == NULL) {
867                 ipseclog((LOG_DEBUG, "ipsec_init_policy: No more memory.\n"));
868                 return ENOBUFS;
869         }
870
871         if (so->so_cred != 0 && so->so_cred->cr_uid == 0)
872                 new->priv = 1;
873         else
874                 new->priv = 0;
875
876         if ((new->sp_in = KEY_NEWSP()) == NULL) {
877                 ipsec_delpcbpolicy(new);
878                 return ENOBUFS;
879         }
880         new->sp_in->state = IPSEC_SPSTATE_ALIVE;
881         new->sp_in->policy = IPSEC_POLICY_ENTRUST;
882
883         if ((new->sp_out = KEY_NEWSP()) == NULL) {
884                 KEY_FREESP(&new->sp_in);
885                 ipsec_delpcbpolicy(new);
886                 return ENOBUFS;
887         }
888         new->sp_out->state = IPSEC_SPSTATE_ALIVE;
889         new->sp_out->policy = IPSEC_POLICY_ENTRUST;
890
891         *pcb_sp = new;
892
893         return 0;
894 }
895
896 /* copy old ipsec policy into new */
897 int
898 ipsec_copy_policy(old, new)
899         struct inpcbpolicy *old, *new;
900 {
901         struct secpolicy *sp;
902
903         sp = ipsec_deepcopy_policy(old->sp_in);
904         if (sp) {
905                 KEY_FREESP(&new->sp_in);
906                 new->sp_in = sp;
907         } else
908                 return ENOBUFS;
909
910         sp = ipsec_deepcopy_policy(old->sp_out);
911         if (sp) {
912                 KEY_FREESP(&new->sp_out);
913                 new->sp_out = sp;
914         } else
915                 return ENOBUFS;
916
917         new->priv = old->priv;
918
919         return 0;
920 }
921
922 /* deep-copy a policy in PCB */
923 static struct secpolicy *
924 ipsec_deepcopy_policy(src)
925         struct secpolicy *src;
926 {
927         struct ipsecrequest *newchain = NULL;
928         struct ipsecrequest *p;
929         struct ipsecrequest **q;
930         struct ipsecrequest *r;
931         struct secpolicy *dst;
932
933         if (src == NULL)
934                 return NULL;
935         dst = KEY_NEWSP();
936         if (dst == NULL)
937                 return NULL;
938
939         /*
940          * deep-copy IPsec request chain.  This is required since struct
941          * ipsecrequest is not reference counted.
942          */
943         q = &newchain;
944         for (p = src->req; p; p = p->next) {
945                 *q = malloc(sizeof(struct ipsecrequest),
946                         M_SECA, M_INTWAIT | M_ZERO | M_NULLOK);
947                 if (*q == NULL)
948                         goto fail;
949                 (*q)->next = NULL;
950
951                 (*q)->saidx.proto = p->saidx.proto;
952                 (*q)->saidx.mode = p->saidx.mode;
953                 (*q)->level = p->level;
954                 (*q)->saidx.reqid = p->saidx.reqid;
955
956                 bcopy(&p->saidx.src, &(*q)->saidx.src, sizeof((*q)->saidx.src));
957                 bcopy(&p->saidx.dst, &(*q)->saidx.dst, sizeof((*q)->saidx.dst));
958
959                 (*q)->sav = NULL;
960                 (*q)->sp = dst;
961
962                 q = &((*q)->next);
963         }
964
965         dst->req = newchain;
966         dst->state = src->state;
967         dst->policy = src->policy;
968         /* do not touch the refcnt fields */
969
970         return dst;
971
972 fail:
973         for (p = newchain; p; p = r) {
974                 r = p->next;
975                 free(p, M_SECA);
976                 p = NULL;
977         }
978         return NULL;
979 }
980
981 /* set policy and ipsec request if present. */
982 static int
983 ipsec_set_policy(pcb_sp, optname, request, len, priv)
984         struct secpolicy **pcb_sp;
985         int optname;
986         caddr_t request;
987         size_t len;
988         int priv;
989 {
990         struct sadb_x_policy *xpl;
991         struct secpolicy *newsp = NULL;
992         int error;
993
994         /* sanity check. */
995         if (pcb_sp == NULL || *pcb_sp == NULL || request == NULL)
996                 return EINVAL;
997         if (len < sizeof(*xpl))
998                 return EINVAL;
999         xpl = (struct sadb_x_policy *)request;
1000
1001         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1002                 printf("ipsec_set_policy: passed policy\n");
1003                 kdebug_sadb_x_policy((struct sadb_ext *)xpl));
1004
1005         /* check policy type */
1006         /* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
1007         if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
1008          || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
1009                 return EINVAL;
1010
1011         /* check privileged socket */
1012         if (priv == 0 && xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS)
1013                 return EACCES;
1014
1015         /* allocation new SP entry */
1016         if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
1017                 return error;
1018
1019         newsp->state = IPSEC_SPSTATE_ALIVE;
1020
1021         /* clear old SP and set new SP */
1022         KEY_FREESP(pcb_sp);
1023         *pcb_sp = newsp;
1024         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1025                 printf("ipsec_set_policy: new policy\n");
1026                 kdebug_secpolicy(newsp));
1027
1028         return 0;
1029 }
1030
1031 static int
1032 ipsec_get_policy(pcb_sp, mp)
1033         struct secpolicy *pcb_sp;
1034         struct mbuf **mp;
1035 {
1036
1037         /* sanity check. */
1038         if (pcb_sp == NULL || mp == NULL)
1039                 return EINVAL;
1040
1041         *mp = key_sp2msg(pcb_sp);
1042         if (!*mp) {
1043                 ipseclog((LOG_DEBUG, "ipsec_get_policy: No more memory.\n"));
1044                 return ENOBUFS;
1045         }
1046
1047         (*mp)->m_type = MT_DATA;
1048         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1049                 printf("ipsec_get_policy:\n");
1050                 kdebug_mbuf(*mp));
1051
1052         return 0;
1053 }
1054
1055 int
1056 ipsec4_set_policy(inp, optname, request, len, priv)
1057         struct inpcb *inp;
1058         int optname;
1059         caddr_t request;
1060         size_t len;
1061         int priv;
1062 {
1063         struct sadb_x_policy *xpl;
1064         struct secpolicy **pcb_sp;
1065
1066         /* sanity check. */
1067         if (inp == NULL || request == NULL)
1068                 return EINVAL;
1069         if (len < sizeof(*xpl))
1070                 return EINVAL;
1071         xpl = (struct sadb_x_policy *)request;
1072
1073         /* select direction */
1074         switch (xpl->sadb_x_policy_dir) {
1075         case IPSEC_DIR_INBOUND:
1076                 pcb_sp = &inp->inp_sp->sp_in;
1077                 break;
1078         case IPSEC_DIR_OUTBOUND:
1079                 pcb_sp = &inp->inp_sp->sp_out;
1080                 break;
1081         default:
1082                 ipseclog((LOG_ERR, "ipsec4_set_policy: invalid direction=%u\n",
1083                         xpl->sadb_x_policy_dir));
1084                 return EINVAL;
1085         }
1086
1087         return ipsec_set_policy(pcb_sp, optname, request, len, priv);
1088 }
1089
1090 int
1091 ipsec4_get_policy(inp, request, len, mp)
1092         struct inpcb *inp;
1093         caddr_t request;
1094         size_t len;
1095         struct mbuf **mp;
1096 {
1097         struct sadb_x_policy *xpl;
1098         struct secpolicy *pcb_sp;
1099
1100         /* sanity check. */
1101         if (inp == NULL || request == NULL || mp == NULL)
1102                 return EINVAL;
1103         KASSERT(inp->inp_sp != NULL, ("ipsec4_get_policy: null inp_sp"));
1104         if (len < sizeof(*xpl))
1105                 return EINVAL;
1106         xpl = (struct sadb_x_policy *)request;
1107
1108         /* select direction */
1109         switch (xpl->sadb_x_policy_dir) {
1110         case IPSEC_DIR_INBOUND:
1111                 pcb_sp = inp->inp_sp->sp_in;
1112                 break;
1113         case IPSEC_DIR_OUTBOUND:
1114                 pcb_sp = inp->inp_sp->sp_out;
1115                 break;
1116         default:
1117                 ipseclog((LOG_ERR, "ipsec4_set_policy: invalid direction=%u\n",
1118                         xpl->sadb_x_policy_dir));
1119                 return EINVAL;
1120         }
1121
1122         return ipsec_get_policy(pcb_sp, mp);
1123 }
1124
1125 /* delete policy in PCB */
1126 int
1127 ipsec4_delete_pcbpolicy(inp)
1128         struct inpcb *inp;
1129 {
1130         KASSERT(inp != NULL, ("ipsec4_delete_pcbpolicy: null inp"));
1131
1132         if (inp->inp_sp == NULL)
1133                 return 0;
1134
1135         if (inp->inp_sp->sp_in != NULL)
1136                 KEY_FREESP(&inp->inp_sp->sp_in);
1137
1138         if (inp->inp_sp->sp_out != NULL)
1139                 KEY_FREESP(&inp->inp_sp->sp_out);
1140
1141         ipsec_delpcbpolicy(inp->inp_sp);
1142         inp->inp_sp = NULL;
1143
1144         return 0;
1145 }
1146
1147 #ifdef INET6
1148 int
1149 ipsec6_set_policy(in6p, optname, request, len, priv)
1150         struct in6pcb *in6p;
1151         int optname;
1152         caddr_t request;
1153         size_t len;
1154         int priv;
1155 {
1156         struct sadb_x_policy *xpl;
1157         struct secpolicy **pcb_sp;
1158
1159         /* sanity check. */
1160         if (in6p == NULL || request == NULL)
1161                 return EINVAL;
1162         if (len < sizeof(*xpl))
1163                 return EINVAL;
1164         xpl = (struct sadb_x_policy *)request;
1165
1166         /* select direction */
1167         switch (xpl->sadb_x_policy_dir) {
1168         case IPSEC_DIR_INBOUND:
1169                 pcb_sp = &in6p->in6p_sp->sp_in;
1170                 break;
1171         case IPSEC_DIR_OUTBOUND:
1172                 pcb_sp = &in6p->in6p_sp->sp_out;
1173                 break;
1174         default:
1175                 ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
1176                         xpl->sadb_x_policy_dir));
1177                 return EINVAL;
1178         }
1179
1180         return ipsec_set_policy(pcb_sp, optname, request, len, priv);
1181 }
1182
1183 int
1184 ipsec6_get_policy(in6p, request, len, mp)
1185         struct in6pcb *in6p;
1186         caddr_t request;
1187         size_t len;
1188         struct mbuf **mp;
1189 {
1190         struct sadb_x_policy *xpl;
1191         struct secpolicy *pcb_sp;
1192
1193         /* sanity check. */
1194         if (in6p == NULL || request == NULL || mp == NULL)
1195                 return EINVAL;
1196         KASSERT(in6p->in6p_sp != NULL, ("ipsec6_get_policy: null in6p_sp"));
1197         if (len < sizeof(*xpl))
1198                 return EINVAL;
1199         xpl = (struct sadb_x_policy *)request;
1200
1201         /* select direction */
1202         switch (xpl->sadb_x_policy_dir) {
1203         case IPSEC_DIR_INBOUND:
1204                 pcb_sp = in6p->in6p_sp->sp_in;
1205                 break;
1206         case IPSEC_DIR_OUTBOUND:
1207                 pcb_sp = in6p->in6p_sp->sp_out;
1208                 break;
1209         default:
1210                 ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
1211                         xpl->sadb_x_policy_dir));
1212                 return EINVAL;
1213         }
1214
1215         return ipsec_get_policy(pcb_sp, mp);
1216 }
1217
1218 int
1219 ipsec6_delete_pcbpolicy(in6p)
1220         struct in6pcb *in6p;
1221 {
1222         KASSERT(in6p != NULL, ("ipsec6_delete_pcbpolicy: null in6p"));
1223
1224         if (in6p->in6p_sp == NULL)
1225                 return 0;
1226
1227         if (in6p->in6p_sp->sp_in != NULL)
1228                 KEY_FREESP(&in6p->in6p_sp->sp_in);
1229
1230         if (in6p->in6p_sp->sp_out != NULL)
1231                 KEY_FREESP(&in6p->in6p_sp->sp_out);
1232
1233         ipsec_delpcbpolicy(in6p->in6p_sp);
1234         in6p->in6p_sp = NULL;
1235
1236         return 0;
1237 }
1238 #endif
1239
1240 /*
1241  * return current level.
1242  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
1243  */
1244 u_int
1245 ipsec_get_reqlevel(isr)
1246         struct ipsecrequest *isr;
1247 {
1248         u_int level = 0;
1249         u_int esp_trans_deflev, esp_net_deflev;
1250         u_int ah_trans_deflev, ah_net_deflev;
1251
1252         KASSERT(isr != NULL && isr->sp != NULL,
1253                 ("ipsec_get_reqlevel: null argument"));
1254         KASSERT(isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
1255                 ("ipsec_get_reqlevel: af family mismatch, src %u, dst %u",
1256                  isr->sp->spidx.src.sa.sa_family,
1257                  isr->sp->spidx.dst.sa.sa_family));
1258
1259 /* XXX note that we have ipseclog() expanded here - code sync issue */
1260 #define IPSEC_CHECK_DEFAULT(lev) \
1261         (((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE            \
1262                         && (lev) != IPSEC_LEVEL_UNIQUE)                       \
1263                 ? (ipsec_debug                                                \
1264                         ? log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
1265                                 (lev), IPSEC_LEVEL_REQUIRE)                   \
1266                         : 0),                                                 \
1267                         (lev) = IPSEC_LEVEL_REQUIRE,                          \
1268                         (lev)                                                 \
1269                 : (lev))
1270
1271         /* set default level */
1272         switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
1273 #ifdef INET
1274         case AF_INET:
1275                 esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
1276                 esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
1277                 ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
1278                 ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
1279                 break;
1280 #endif
1281 #ifdef INET6
1282         case AF_INET6:
1283                 esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
1284                 esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
1285                 ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
1286                 ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
1287                 break;
1288 #endif /* INET6 */
1289         default:
1290                 panic("key_get_reqlevel: unknown af %u",
1291                         isr->sp->spidx.src.sa.sa_family);
1292         }
1293
1294 #undef IPSEC_CHECK_DEFAULT
1295
1296         /* set level */
1297         switch (isr->level) {
1298         case IPSEC_LEVEL_DEFAULT:
1299                 switch (isr->saidx.proto) {
1300                 case IPPROTO_ESP:
1301                         if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1302                                 level = esp_net_deflev;
1303                         else
1304                                 level = esp_trans_deflev;
1305                         break;
1306                 case IPPROTO_AH:
1307                         if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1308                                 level = ah_net_deflev;
1309                         else
1310                                 level = ah_trans_deflev;
1311                 case IPPROTO_IPCOMP:
1312                         /*
1313                          * we don't really care, as IPcomp document says that
1314                          * we shouldn't compress small packets
1315                          */
1316                         level = IPSEC_LEVEL_USE;
1317                         break;
1318                 default:
1319                         panic("ipsec_get_reqlevel: "
1320                                 "Illegal protocol defined %u\n",
1321                                 isr->saidx.proto);
1322                 }
1323                 break;
1324
1325         case IPSEC_LEVEL_USE:
1326         case IPSEC_LEVEL_REQUIRE:
1327                 level = isr->level;
1328                 break;
1329         case IPSEC_LEVEL_UNIQUE:
1330                 level = IPSEC_LEVEL_REQUIRE;
1331                 break;
1332
1333         default:
1334                 panic("ipsec_get_reqlevel: Illegal IPsec level %u\n",
1335                         isr->level);
1336         }
1337
1338         return level;
1339 }
1340
1341 /*
1342  * Check security policy requirements against the actual
1343  * packet contents.  Return one if the packet should be
1344  * reject as "invalid"; otherwiser return zero to have the
1345  * packet treated as "valid".
1346  *
1347  * OUT:
1348  *      0: valid
1349  *      1: invalid
1350  */
1351 int
1352 ipsec_in_reject(struct secpolicy *sp, struct mbuf *m)
1353 {
1354         struct ipsecrequest *isr;
1355         int need_auth;
1356
1357         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1358                 printf("ipsec_in_reject: using SP\n");
1359                 kdebug_secpolicy(sp));
1360
1361         /* check policy */
1362         switch (sp->policy) {
1363         case IPSEC_POLICY_DISCARD:
1364                 return 1;
1365         case IPSEC_POLICY_BYPASS:
1366         case IPSEC_POLICY_NONE:
1367                 return 0;
1368         }
1369
1370         KASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1371                 ("ipsec_in_reject: invalid policy %u", sp->policy));
1372
1373         /* XXX should compare policy against ipsec header history */
1374
1375         need_auth = 0;
1376         for (isr = sp->req; isr != NULL; isr = isr->next) {
1377                 if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
1378                         continue;
1379                 switch (isr->saidx.proto) {
1380                 case IPPROTO_ESP:
1381                         if ((m->m_flags & M_DECRYPTED) == 0) {
1382                                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1383                                     printf("ipsec_in_reject: ESP m_flags:%x\n",
1384                                             m->m_flags));
1385                                 return 1;
1386                         }
1387
1388                         if (!need_auth &&
1389                             isr->sav != NULL &&
1390                             isr->sav->tdb_authalgxform != NULL &&
1391                             (m->m_flags & M_AUTHIPDGM) == 0) {
1392                                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1393                                     printf("ipsec_in_reject: ESP/AH m_flags:%x\n",
1394                                             m->m_flags));
1395                                 return 1;
1396                         }
1397                         break;
1398                 case IPPROTO_AH:
1399                         need_auth = 1;
1400                         if ((m->m_flags & M_AUTHIPHDR) == 0) {
1401                                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1402                                     printf("ipsec_in_reject: AH m_flags:%x\n",
1403                                             m->m_flags));
1404                                 return 1;
1405                         }
1406                         break;
1407                 case IPPROTO_IPCOMP:
1408                         /*
1409                          * we don't really care, as IPcomp document
1410                          * says that we shouldn't compress small
1411                          * packets, IPComp policy should always be
1412                          * treated as being in "use" level.
1413                          */
1414                         break;
1415                 }
1416         }
1417         return 0;               /* valid */
1418 }
1419
1420 /*
1421  * Check AH/ESP integrity.
1422  * This function is called from tcp_input(), udp_input(),
1423  * and {ah,esp}4_input for tunnel mode
1424  */
1425 int
1426 ipsec4_in_reject(m, inp)
1427         struct mbuf *m;
1428         struct inpcb *inp;
1429 {
1430         struct secpolicy *sp;
1431         int error;
1432         int result;
1433
1434         KASSERT(m != NULL, ("ipsec4_in_reject_so: null mbuf"));
1435
1436         /* get SP for this packet.
1437          * When we are called from ip_forward(), we call
1438          * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1439          */
1440         if (inp == NULL)
1441                 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1442         else
1443                 sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error);
1444
1445         if (sp != NULL) {
1446                 result = ipsec_in_reject(sp, m);
1447                 if (result)
1448                         newipsecstat.ips_in_polvio++;
1449                 KEY_FREESP(&sp);
1450         } else {
1451                 result = 0;     /* XXX should be panic ?
1452                                  * -> No, there may be error. */
1453         }
1454         return result;
1455 }
1456
1457 #ifdef INET6
1458 /*
1459  * Check AH/ESP integrity.
1460  * This function is called from tcp6_input(), udp6_input(),
1461  * and {ah,esp}6_input for tunnel mode
1462  */
1463 int
1464 ipsec6_in_reject(m, inp)
1465         struct mbuf *m;
1466         struct inpcb *inp;
1467 {
1468         struct secpolicy *sp = NULL;
1469         int error;
1470         int result;
1471
1472         /* sanity check */
1473         if (m == NULL)
1474                 return 0;       /* XXX should be panic ? */
1475
1476         /* get SP for this packet.
1477          * When we are called from ip_forward(), we call
1478          * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1479          */
1480         if (inp == NULL)
1481                 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1482         else
1483                 sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error);
1484
1485         if (sp != NULL) {
1486                 result = ipsec_in_reject(sp, m);
1487                 if (result)
1488                         newipsecstat.ips_in_polvio++;
1489                 KEY_FREESP(&sp);
1490         } else {
1491                 result = 0;
1492         }
1493         return result;
1494 }
1495 #endif
1496
1497 /*
1498  * compute the byte size to be occupied by IPsec header.
1499  * in case it is tunneled, it includes the size of outer IP header.
1500  * NOTE: SP passed is free in this function.
1501  */
1502 static size_t
1503 ipsec_hdrsiz(struct secpolicy *sp)
1504 {
1505         struct ipsecrequest *isr;
1506         size_t siz;
1507
1508         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1509                 printf("ipsec_hdrsiz: using SP\n");
1510                 kdebug_secpolicy(sp));
1511
1512         switch (sp->policy) {
1513         case IPSEC_POLICY_DISCARD:
1514         case IPSEC_POLICY_BYPASS:
1515         case IPSEC_POLICY_NONE:
1516                 return 0;
1517         }
1518
1519         KASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1520                 ("ipsec_hdrsiz: invalid policy %u", sp->policy));
1521
1522         siz = 0;
1523         for (isr = sp->req; isr != NULL; isr = isr->next) {
1524                 size_t clen = 0;
1525
1526                 switch (isr->saidx.proto) {
1527                 case IPPROTO_ESP:
1528                         clen = esp_hdrsiz(isr->sav);
1529                         break;
1530                 case IPPROTO_AH:
1531                         clen = ah_hdrsiz(isr->sav);
1532                         break;
1533                 case IPPROTO_IPCOMP:
1534                         clen = sizeof(struct ipcomp);
1535                         break;
1536                 }
1537
1538                 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1539                         switch (isr->saidx.dst.sa.sa_family) {
1540                         case AF_INET:
1541                                 clen += sizeof(struct ip);
1542                                 break;
1543 #ifdef INET6
1544                         case AF_INET6:
1545                                 clen += sizeof(struct ip6_hdr);
1546                                 break;
1547 #endif
1548                         default:
1549                                 ipseclog((LOG_ERR, "ipsec_hdrsiz: "
1550                                     "unknown AF %d in IPsec tunnel SA\n",
1551                                     ((struct sockaddr *)&isr->saidx.dst)->sa_family));
1552                                 break;
1553                         }
1554                 }
1555                 siz += clen;
1556         }
1557
1558         return siz;
1559 }
1560
1561 /* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
1562 size_t
1563 ipsec4_hdrsiz(m, dir, inp)
1564         struct mbuf *m;
1565         u_int dir;
1566         struct inpcb *inp;
1567 {
1568         struct secpolicy *sp;
1569         int error;
1570         size_t size;
1571
1572         KASSERT(m != NULL, ("ipsec4_hdrsiz: null mbuf"));
1573         KASSERT(inp == NULL || inp->inp_socket != NULL,
1574                 ("ipsec4_hdrsize: socket w/o inpcb"));
1575
1576         /* get SP for this packet.
1577          * When we are called from ip_forward(), we call
1578          * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1579          */
1580         if (inp == NULL)
1581                 sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
1582         else
1583                 sp = ipsec_getpolicybysock(m, dir, inp, &error);
1584
1585         if (sp != NULL) {
1586                 size = ipsec_hdrsiz(sp);
1587                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1588                         printf("ipsec4_hdrsiz: size:%lu.\n",
1589                                 (unsigned long)size));
1590
1591                 KEY_FREESP(&sp);
1592         } else {
1593                 size = 0;       /* XXX should be panic ? */
1594         }
1595         return size;
1596 }
1597
1598 #ifdef INET6
1599 /* This function is called from ipsec6_hdrsize_tcp(),
1600  * and maybe from ip6_forward.()
1601  */
1602 size_t
1603 ipsec6_hdrsiz(m, dir, in6p)
1604         struct mbuf *m;
1605         u_int dir;
1606         struct in6pcb *in6p;
1607 {
1608         struct secpolicy *sp;
1609         int error;
1610         size_t size;
1611
1612         KASSERT(m != NULL, ("ipsec6_hdrsiz: null mbuf"));
1613         KASSERT(in6p == NULL || in6p->in6p_socket != NULL,
1614                 ("ipsec6_hdrsize: socket w/o inpcb"));
1615
1616         /* get SP for this packet */
1617         /* XXX Is it right to call with IP_FORWARDING. */
1618         if (in6p == NULL)
1619                 sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
1620         else
1621                 sp = ipsec_getpolicybysock(m, dir, in6p, &error);
1622
1623         if (sp == NULL)
1624                 return 0;
1625         size = ipsec_hdrsiz(sp);
1626         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1627                 printf("ipsec6_hdrsiz: size:%lu.\n", (unsigned long)size));
1628         KEY_FREESP(&sp);
1629
1630         return size;
1631 }
1632 #endif /*INET6*/
1633
1634 /*
1635  * Check the variable replay window.
1636  * ipsec_chkreplay() performs replay check before ICV verification.
1637  * ipsec_updatereplay() updates replay bitmap.  This must be called after
1638  * ICV verification (it also performs replay check, which is usually done
1639  * beforehand).
1640  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1641  *
1642  * based on RFC 2401.
1643  */
1644 int
1645 ipsec_chkreplay(seq, sav)
1646         u_int32_t seq;
1647         struct secasvar *sav;
1648 {
1649         const struct secreplay *replay;
1650         u_int32_t diff;
1651         int fr;
1652         u_int32_t wsizeb;       /* constant: bits of window size */
1653         int frlast;             /* constant: last frame */
1654
1655         SPLASSERT(net, "ipsec_chkreplay");
1656
1657         KASSERT(sav != NULL, ("ipsec_chkreplay: Null SA"));
1658         KASSERT(sav->replay != NULL, ("ipsec_chkreplay: Null replay state"));
1659
1660         replay = sav->replay;
1661
1662         if (replay->wsize == 0)
1663                 return 1;       /* no need to check replay. */
1664
1665         /* constant */
1666         frlast = replay->wsize - 1;
1667         wsizeb = replay->wsize << 3;
1668
1669         /* sequence number of 0 is invalid */
1670         if (seq == 0)
1671                 return 0;
1672
1673         /* first time is always okay */
1674         if (replay->count == 0)
1675                 return 1;
1676
1677         if (seq > replay->lastseq) {
1678                 /* larger sequences are okay */
1679                 return 1;
1680         } else {
1681                 /* seq is equal or less than lastseq. */
1682                 diff = replay->lastseq - seq;
1683
1684                 /* over range to check, i.e. too old or wrapped */
1685                 if (diff >= wsizeb)
1686                         return 0;
1687
1688                 fr = frlast - diff / 8;
1689
1690                 /* this packet already seen ? */
1691                 if ((replay->bitmap)[fr] & (1 << (diff % 8)))
1692                         return 0;
1693
1694                 /* out of order but good */
1695                 return 1;
1696         }
1697 }
1698
1699 /*
1700  * check replay counter whether to update or not.
1701  * OUT: 0:      OK
1702  *      1:      NG
1703  */
1704 int
1705 ipsec_updatereplay(seq, sav)
1706         u_int32_t seq;
1707         struct secasvar *sav;
1708 {
1709         struct secreplay *replay;
1710         u_int32_t diff;
1711         int fr;
1712         u_int32_t wsizeb;       /* constant: bits of window size */
1713         int frlast;             /* constant: last frame */
1714
1715         SPLASSERT(net, "ipsec_updatereplay");
1716
1717         KASSERT(sav != NULL, ("ipsec_updatereplay: Null SA"));
1718         KASSERT(sav->replay != NULL, ("ipsec_updatereplay: Null replay state"));
1719
1720         replay = sav->replay;
1721
1722         if (replay->wsize == 0)
1723                 goto ok;        /* no need to check replay. */
1724
1725         /* constant */
1726         frlast = replay->wsize - 1;
1727         wsizeb = replay->wsize << 3;
1728
1729         /* sequence number of 0 is invalid */
1730         if (seq == 0)
1731                 return 1;
1732
1733         /* first time */
1734         if (replay->count == 0) {
1735                 replay->lastseq = seq;
1736                 bzero(replay->bitmap, replay->wsize);
1737                 (replay->bitmap)[frlast] = 1;
1738                 goto ok;
1739         }
1740
1741         if (seq > replay->lastseq) {
1742                 /* seq is larger than lastseq. */
1743                 diff = seq - replay->lastseq;
1744
1745                 /* new larger sequence number */
1746                 if (diff < wsizeb) {
1747                         /* In window */
1748                         /* set bit for this packet */
1749                         vshiftl(replay->bitmap, diff, replay->wsize);
1750                         (replay->bitmap)[frlast] |= 1;
1751                 } else {
1752                         /* this packet has a "way larger" */
1753                         bzero(replay->bitmap, replay->wsize);
1754                         (replay->bitmap)[frlast] = 1;
1755                 }
1756                 replay->lastseq = seq;
1757
1758                 /* larger is good */
1759         } else {
1760                 /* seq is equal or less than lastseq. */
1761                 diff = replay->lastseq - seq;
1762
1763                 /* over range to check, i.e. too old or wrapped */
1764                 if (diff >= wsizeb)
1765                         return 1;
1766
1767                 fr = frlast - diff / 8;
1768
1769                 /* this packet already seen ? */
1770                 if ((replay->bitmap)[fr] & (1 << (diff % 8)))
1771                         return 1;
1772
1773                 /* mark as seen */
1774                 (replay->bitmap)[fr] |= (1 << (diff % 8));
1775
1776                 /* out of order but good */
1777         }
1778
1779 ok:
1780         if (replay->count == ~0) {
1781
1782                 /* set overflow flag */
1783                 replay->overflow++;
1784
1785                 /* don't increment, no more packets accepted */
1786                 if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
1787                         return 1;
1788
1789                 ipseclog((LOG_WARNING, "replay counter made %d cycle. %s\n",
1790                     replay->overflow, ipsec_logsastr(sav)));
1791         }
1792
1793         replay->count++;
1794
1795         return 0;
1796 }
1797
1798 /*
1799  * shift variable length buffer to left.
1800  * IN:  bitmap: pointer to the buffer
1801  *      nbit:   the number of to shift.
1802  *      wsize:  buffer size (bytes).
1803  */
1804 static void
1805 vshiftl(bitmap, nbit, wsize)
1806         unsigned char *bitmap;
1807         int nbit, wsize;
1808 {
1809         int s, j, i;
1810         unsigned char over;
1811
1812         for (j = 0; j < nbit; j += 8) {
1813                 s = (nbit - j < 8) ? (nbit - j): 8;
1814                 bitmap[0] <<= s;
1815                 for (i = 1; i < wsize; i++) {
1816                         over = (bitmap[i] >> (8 - s));
1817                         bitmap[i] <<= s;
1818                         bitmap[i-1] |= over;
1819                 }
1820         }
1821
1822         return;
1823 }
1824
1825 /* Return a printable string for the address. */
1826 char *
1827 ipsec_address(union sockaddr_union* sa)
1828 {
1829         switch (sa->sa.sa_family) {
1830 #if INET
1831         case AF_INET:
1832                 return inet_ntoa(sa->sin.sin_addr);
1833 #endif /* INET */
1834
1835 #if INET6
1836         case AF_INET6:
1837                 return ip6_sprintf(&sa->sin6.sin6_addr);
1838 #endif /* INET6 */
1839
1840         default:
1841                 return "(unknown address family)";
1842         }
1843 }
1844
1845 const char *
1846 ipsec_logsastr(sav)
1847         struct secasvar *sav;
1848 {
1849         static char buf[256];
1850         char *p;
1851         struct secasindex *saidx = &sav->sah->saidx;
1852
1853         KASSERT(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
1854                 ("ipsec_logsastr: address family mismatch"));
1855
1856         p = buf;
1857         snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
1858         while (p && *p)
1859                 p++;
1860         /* NB: only use ipsec_address on one address at a time */
1861         snprintf(p, sizeof (buf) - (p - buf), "src=%s ",
1862                 ipsec_address(&saidx->src));
1863         while (p && *p)
1864                 p++;
1865         snprintf(p, sizeof (buf) - (p - buf), "dst=%s)",
1866                 ipsec_address(&saidx->dst));
1867
1868         return buf;
1869 }
1870
1871 void
1872 ipsec_dumpmbuf(m)
1873         struct mbuf *m;
1874 {
1875         int totlen;
1876         int i;
1877         u_char *p;
1878
1879         totlen = 0;
1880         printf("---\n");
1881         while (m) {
1882                 p = mtod(m, u_char *);
1883                 for (i = 0; i < m->m_len; i++) {
1884                         printf("%02x ", p[i]);
1885                         totlen++;
1886                         if (totlen % 16 == 0)
1887                                 printf("\n");
1888                 }
1889                 m = m->m_next;
1890         }
1891         if (totlen % 16 != 0)
1892                 printf("\n");
1893         printf("---\n");
1894 }
1895
1896 /* XXX this stuff doesn't belong here... */
1897
1898 static  struct xformsw* xforms = NULL;
1899
1900 /*
1901  * Register a transform; typically at system startup.
1902  */
1903 void
1904 xform_register(struct xformsw* xsp)
1905 {
1906         xsp->xf_next = xforms;
1907         xforms = xsp;
1908 }
1909
1910 /*
1911  * Initialize transform support in an sav.
1912  */
1913 int
1914 xform_init(struct secasvar *sav, int xftype)
1915 {
1916         struct xformsw *xsp;
1917
1918         for (xsp = xforms; xsp; xsp = xsp->xf_next)
1919                 if (xsp->xf_type == xftype)
1920                         return (*xsp->xf_init)(sav, xsp);
1921         return EINVAL;
1922 }