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