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