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