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