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