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