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