]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/netipsec/ipsec.c
MFC r298676:
[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/vnet.h>
59
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/ip.h>
63 #include <netinet/ip_var.h>
64 #include <netinet/in_var.h>
65 #include <netinet/udp.h>
66 #include <netinet/udp_var.h>
67 #include <netinet/tcp.h>
68 #include <netinet/udp.h>
69
70 #include <netinet/ip6.h>
71 #ifdef INET6
72 #include <netinet6/ip6_var.h>
73 #endif
74 #include <netinet/in_pcb.h>
75 #ifdef INET6
76 #include <netinet/icmp6.h>
77 #endif
78
79 #include <sys/types.h>
80 #include <netipsec/ipsec.h>
81 #ifdef INET6
82 #include <netipsec/ipsec6.h>
83 #endif
84 #include <netipsec/ah_var.h>
85 #include <netipsec/esp_var.h>
86 #include <netipsec/ipcomp.h>            /*XXX*/
87 #include <netipsec/ipcomp_var.h>
88
89 #include <netipsec/key.h>
90 #include <netipsec/keydb.h>
91 #include <netipsec/key_debug.h>
92
93 #include <netipsec/xform.h>
94
95 #include <machine/in_cksum.h>
96
97 #include <opencrypto/cryptodev.h>
98
99 #ifdef IPSEC_DEBUG
100 VNET_DEFINE(int, ipsec_debug) = 1;
101 #else
102 VNET_DEFINE(int, ipsec_debug) = 0;
103 #endif
104
105 /* NB: name changed so netstat doesn't use it. */
106 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec4stat);
107 VNET_PCPUSTAT_SYSINIT(ipsec4stat);
108
109 #ifdef VIMAGE
110 VNET_PCPUSTAT_SYSUNINIT(ipsec4stat);
111 #endif /* VIMAGE */
112
113 VNET_DEFINE(int, ip4_ah_offsetmask) = 0;        /* maybe IP_DF? */
114 /* DF bit on encap. 0: clear 1: set 2: copy */
115 VNET_DEFINE(int, ip4_ipsec_dfbit) = 0;
116 VNET_DEFINE(int, ip4_esp_trans_deflev) = IPSEC_LEVEL_USE;
117 VNET_DEFINE(int, ip4_esp_net_deflev) = IPSEC_LEVEL_USE;
118 VNET_DEFINE(int, ip4_ah_trans_deflev) = IPSEC_LEVEL_USE;
119 VNET_DEFINE(int, ip4_ah_net_deflev) = IPSEC_LEVEL_USE;
120 VNET_DEFINE(struct secpolicy, ip4_def_policy);
121 /* ECN ignore(-1)/forbidden(0)/allowed(1) */
122 VNET_DEFINE(int, ip4_ipsec_ecn) = 0;
123 VNET_DEFINE(int, ip4_esp_randpad) = -1;
124
125 /*
126  * Crypto support requirements:
127  *
128  *  1   require hardware support
129  * -1   require software support
130  *  0   take anything
131  */
132 VNET_DEFINE(int, crypto_support) = CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE;
133
134 FEATURE(ipsec, "Internet Protocol Security (IPsec)");
135 #ifdef IPSEC_NAT_T
136 FEATURE(ipsec_natt, "UDP Encapsulation of IPsec ESP Packets ('NAT-T')");
137 #endif
138
139 SYSCTL_DECL(_net_inet_ipsec);
140
141 /* net.inet.ipsec */
142 SYSCTL_VNET_INT(_net_inet_ipsec, IPSECCTL_DEF_POLICY, def_policy,
143         CTLFLAG_RW, &VNET_NAME(ip4_def_policy).policy, 0,
144         "IPsec default policy.");
145 SYSCTL_VNET_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
146         CTLFLAG_RW, &VNET_NAME(ip4_esp_trans_deflev), 0,
147         "Default ESP transport mode level");
148 SYSCTL_VNET_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
149         CTLFLAG_RW, &VNET_NAME(ip4_esp_net_deflev), 0,
150         "Default ESP tunnel mode level.");
151 SYSCTL_VNET_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
152         CTLFLAG_RW, &VNET_NAME(ip4_ah_trans_deflev), 0,
153         "AH transfer mode default level.");
154 SYSCTL_VNET_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
155         CTLFLAG_RW, &VNET_NAME(ip4_ah_net_deflev), 0,
156         "AH tunnel mode default level.");
157 SYSCTL_VNET_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS, ah_cleartos,
158         CTLFLAG_RW, &VNET_NAME(ah_cleartos), 0,
159         "If set clear type-of-service field when doing AH computation.");
160 SYSCTL_VNET_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK, ah_offsetmask,
161         CTLFLAG_RW, &VNET_NAME(ip4_ah_offsetmask), 0,
162         "If not set clear offset field mask when doing AH computation.");
163 SYSCTL_VNET_INT(_net_inet_ipsec, IPSECCTL_DFBIT, dfbit,
164         CTLFLAG_RW, &VNET_NAME(ip4_ipsec_dfbit), 0,
165         "Do not fragment bit on encap.");
166 SYSCTL_VNET_INT(_net_inet_ipsec, IPSECCTL_ECN, ecn,
167         CTLFLAG_RW, &VNET_NAME(ip4_ipsec_ecn), 0,
168         "Explicit Congestion Notification handling.");
169 SYSCTL_VNET_INT(_net_inet_ipsec, IPSECCTL_DEBUG, debug,
170         CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0,
171         "Enable IPsec debugging output when set.");
172 SYSCTL_VNET_INT(_net_inet_ipsec, OID_AUTO, crypto_support,
173         CTLFLAG_RW, &VNET_NAME(crypto_support), 0,
174         "Crypto driver selection.");
175 SYSCTL_VNET_PCPUSTAT(_net_inet_ipsec, OID_AUTO, ipsecstats, struct ipsecstat,
176     ipsec4stat, "IPsec IPv4 statistics.");
177
178 #ifdef REGRESSION
179 /*
180  * When set to 1, IPsec will send packets with the same sequence number.
181  * This allows to verify if the other side has proper replay attacks detection.
182  */
183 VNET_DEFINE(int, ipsec_replay) = 0;
184 SYSCTL_VNET_INT(_net_inet_ipsec, OID_AUTO, test_replay,
185         CTLFLAG_RW, &VNET_NAME(ipsec_replay), 0,
186         "Emulate replay attack");
187 /*
188  * When set 1, IPsec will send packets with corrupted HMAC.
189  * This allows to verify if the other side properly detects modified packets.
190  */
191 VNET_DEFINE(int, ipsec_integrity) = 0;
192 SYSCTL_VNET_INT(_net_inet_ipsec, OID_AUTO, test_integrity,
193         CTLFLAG_RW, &VNET_NAME(ipsec_integrity), 0,
194         "Emulate man-in-the-middle attack");
195 #endif
196
197 #ifdef INET6 
198 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec6stat);
199 VNET_PCPUSTAT_SYSINIT(ipsec6stat);
200
201 #ifdef VIMAGE
202 VNET_PCPUSTAT_SYSUNINIT(ipsec6stat);
203 #endif /* VIMAGE */
204
205 VNET_DEFINE(int, ip6_esp_trans_deflev) = IPSEC_LEVEL_USE;
206 VNET_DEFINE(int, ip6_esp_net_deflev) = IPSEC_LEVEL_USE;
207 VNET_DEFINE(int, ip6_ah_trans_deflev) = IPSEC_LEVEL_USE;
208 VNET_DEFINE(int, ip6_ah_net_deflev) = IPSEC_LEVEL_USE;
209 VNET_DEFINE(int, ip6_ipsec_ecn) = 0;    /* ECN ignore(-1)/forbidden(0)/allowed(1) */
210
211 SYSCTL_DECL(_net_inet6_ipsec6);
212
213 /* net.inet6.ipsec6 */
214 SYSCTL_VNET_INT(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY, def_policy, CTLFLAG_RW,
215         &VNET_NAME(ip4_def_policy).policy, 0,
216         "IPsec default policy.");
217 SYSCTL_VNET_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, 
218         esp_trans_deflev, CTLFLAG_RW, &VNET_NAME(ip6_esp_trans_deflev), 0,
219         "Default ESP transport mode level.");
220 SYSCTL_VNET_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, 
221         esp_net_deflev, CTLFLAG_RW, &VNET_NAME(ip6_esp_net_deflev),     0,
222         "Default ESP tunnel mode level.");
223 SYSCTL_VNET_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, 
224         ah_trans_deflev, CTLFLAG_RW, &VNET_NAME(ip6_ah_trans_deflev),   0,
225         "AH transfer mode default level.");
226 SYSCTL_VNET_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, 
227         ah_net_deflev, CTLFLAG_RW, &VNET_NAME(ip6_ah_net_deflev),       0,
228         "AH tunnel mode default level.");
229 SYSCTL_VNET_INT(_net_inet6_ipsec6, IPSECCTL_ECN,
230         ecn, CTLFLAG_RW, &VNET_NAME(ip6_ipsec_ecn),     0,
231         "Explicit Congestion Notification handling.");
232 SYSCTL_VNET_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG, debug, CTLFLAG_RW,
233         &VNET_NAME(ipsec_debug), 0,
234         "Enable IPsec debugging output when set.");
235 SYSCTL_VNET_PCPUSTAT(_net_inet6_ipsec6, IPSECCTL_STATS, ipsecstats,
236     struct ipsecstat, ipsec6stat, "IPsec IPv6 statistics.");
237 #endif /* INET6 */
238
239 static int ipsec_setspidx_inpcb(struct mbuf *, struct inpcb *);
240 static int ipsec_setspidx(struct mbuf *, struct secpolicyindex *, int);
241 static void ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *, int);
242 static int ipsec4_setspidx_ipaddr(struct mbuf *, struct secpolicyindex *);
243 #ifdef INET6
244 static void ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *, int);
245 static int ipsec6_setspidx_ipaddr(struct mbuf *, struct secpolicyindex *);
246 #endif
247 static void ipsec_delpcbpolicy(struct inpcbpolicy *);
248 static struct secpolicy *ipsec_deepcopy_policy(struct secpolicy *src);
249 static void vshiftl(unsigned char *, int, int);
250
251 MALLOC_DEFINE(M_IPSEC_INPCB, "inpcbpolicy", "inpcb-resident ipsec policy");
252
253 /*
254  * Return a held reference to the default SP.
255  */
256 static struct secpolicy *
257 key_allocsp_default(const char* where, int tag)
258 {
259         struct secpolicy *sp;
260
261         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
262                 printf("DP key_allocsp_default from %s:%u\n", where, tag));
263
264         sp = &V_ip4_def_policy;
265         if (sp->policy != IPSEC_POLICY_DISCARD &&
266             sp->policy != IPSEC_POLICY_NONE) {
267                 ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
268                     sp->policy, IPSEC_POLICY_NONE));
269                 sp->policy = IPSEC_POLICY_NONE;
270         }
271         key_addref(sp);
272
273         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
274                 printf("DP key_allocsp_default returns SP:%p (%u)\n",
275                         sp, sp->refcnt));
276         return (sp);
277 }
278 #define KEY_ALLOCSP_DEFAULT() \
279         key_allocsp_default(__FILE__, __LINE__)
280
281 /*
282  * For OUTBOUND packet having a socket. Searching SPD for packet,
283  * and return a pointer to SP.
284  * OUT: NULL:   no apropreate SP found, the following value is set to error.
285  *              0       : bypass
286  *              EACCES  : discard packet.
287  *              ENOENT  : ipsec_acquire() in progress, maybe.
288  *              others  : error occured.
289  *      others: a pointer to SP
290  *
291  * NOTE: IPv6 mapped adddress concern is implemented here.
292  */
293 struct secpolicy *
294 ipsec_getpolicy(struct tdb_ident *tdbi, u_int dir)
295 {
296         struct secpolicy *sp;
297
298         IPSEC_ASSERT(tdbi != NULL, ("null tdbi"));
299         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
300                 ("invalid direction %u", dir));
301
302         sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir);
303         if (sp == NULL)                 /*XXX????*/
304                 sp = KEY_ALLOCSP_DEFAULT();
305         IPSEC_ASSERT(sp != NULL, ("null SP"));
306         return (sp);
307 }
308
309 /*
310  * For OUTBOUND packet having a socket. Searching SPD for packet,
311  * and return a pointer to SP.
312  * OUT: NULL:   no apropreate SP found, the following value is set to error.
313  *              0       : bypass
314  *              EACCES  : discard packet.
315  *              ENOENT  : ipsec_acquire() in progress, maybe.
316  *              others  : error occured.
317  *      others: a pointer to SP
318  *
319  * NOTE: IPv6 mapped adddress concern is implemented here.
320  */
321 static struct secpolicy *
322 ipsec_getpolicybysock(struct mbuf *m, u_int dir, struct inpcb *inp, int *error)
323 {
324         struct inpcbpolicy *pcbsp;
325         struct secpolicy *currsp = NULL;        /* Policy on socket. */
326         struct secpolicy *sp;
327
328         IPSEC_ASSERT(m != NULL, ("null mbuf"));
329         IPSEC_ASSERT(inp != NULL, ("null inpcb"));
330         IPSEC_ASSERT(error != NULL, ("null error"));
331         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
332                 ("invalid direction %u", dir));
333
334         /* Set spidx in pcb. */
335         *error = ipsec_setspidx_inpcb(m, inp);
336         if (*error)
337                 return (NULL);
338
339         pcbsp = inp->inp_sp;
340         IPSEC_ASSERT(pcbsp != NULL, ("null pcbsp"));
341         switch (dir) {
342         case IPSEC_DIR_INBOUND:
343                 currsp = pcbsp->sp_in;
344                 break;
345         case IPSEC_DIR_OUTBOUND:
346                 currsp = pcbsp->sp_out;
347                 break;
348         }
349         IPSEC_ASSERT(currsp != NULL, ("null currsp"));
350
351         if (pcbsp->priv) {                      /* When privilieged socket. */
352                 switch (currsp->policy) {
353                 case IPSEC_POLICY_BYPASS:
354                 case IPSEC_POLICY_IPSEC:
355                         key_addref(currsp);
356                         sp = currsp;
357                         break;
358
359                 case IPSEC_POLICY_ENTRUST:
360                         /* Look for a policy in SPD. */
361                         sp = KEY_ALLOCSP(&currsp->spidx, dir);
362                         if (sp == NULL)         /* No SP found. */
363                                 sp = KEY_ALLOCSP_DEFAULT();
364                         break;
365
366                 default:
367                         ipseclog((LOG_ERR, "%s: Invalid policy for PCB %d\n",
368                                 __func__, currsp->policy));
369                         *error = EINVAL;
370                         return (NULL);
371                 }
372         } else {                                /* Unpriv, SPD has policy. */
373                 sp = KEY_ALLOCSP(&currsp->spidx, dir);
374                 if (sp == NULL) {               /* No SP found. */
375                         switch (currsp->policy) {
376                         case IPSEC_POLICY_BYPASS:
377                                 ipseclog((LOG_ERR, "%s: Illegal policy for "
378                                         "non-priviliged defined %d\n",
379                                         __func__, currsp->policy));
380                                 *error = EINVAL;
381                                 return (NULL);
382
383                         case IPSEC_POLICY_ENTRUST:
384                                 sp = KEY_ALLOCSP_DEFAULT();
385                                 break;
386
387                         case IPSEC_POLICY_IPSEC:
388                                 key_addref(currsp);
389                                 sp = currsp;
390                                 break;
391
392                         default:
393                                 ipseclog((LOG_ERR, "%s: Invalid policy for "
394                                         "PCB %d\n", __func__, currsp->policy));
395                                 *error = EINVAL;
396                                 return (NULL);
397                         }
398                 }
399         }
400         IPSEC_ASSERT(sp != NULL,
401                 ("null SP (priv %u policy %u", pcbsp->priv, currsp->policy));
402         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
403                 printf("DP %s (priv %u policy %u) allocate SP:%p (refcnt %u)\n",
404                         __func__, pcbsp->priv, currsp->policy, sp, sp->refcnt));
405         return (sp);
406 }
407
408 /*
409  * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
410  * and return a pointer to SP.
411  * OUT: positive: a pointer to the entry for security policy leaf matched.
412  *      NULL:   no apropreate SP found, the following value is set to error.
413  *              0       : bypass
414  *              EACCES  : discard packet.
415  *              ENOENT  : ipsec_acquire() in progress, maybe.
416  *              others  : error occured.
417  */
418 struct secpolicy *
419 ipsec_getpolicybyaddr(struct mbuf *m, u_int dir, int flag, int *error)
420 {
421         struct secpolicyindex spidx;
422         struct secpolicy *sp;
423
424         IPSEC_ASSERT(m != NULL, ("null mbuf"));
425         IPSEC_ASSERT(error != NULL, ("null error"));
426         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
427                 ("invalid direction %u", dir));
428
429         sp = NULL;
430         if (key_havesp(dir)) {
431                 /* Make an index to look for a policy. */
432                 *error = ipsec_setspidx(m, &spidx,
433                                         (flag & IP_FORWARDING) ? 0 : 1);
434                 if (*error != 0) {
435                         DPRINTF(("%s: setpidx failed, dir %u flag %u\n",
436                                 __func__, dir, flag));
437                         return (NULL);
438                 }
439                 spidx.dir = dir;
440
441                 sp = KEY_ALLOCSP(&spidx, dir);
442         }
443         if (sp == NULL)                 /* No SP found, use system default. */
444                 sp = KEY_ALLOCSP_DEFAULT();
445         IPSEC_ASSERT(sp != NULL, ("null SP"));
446         return (sp);
447 }
448
449 struct secpolicy *
450 ipsec4_checkpolicy(struct mbuf *m, u_int dir, u_int flag, int *error,
451     struct inpcb *inp)
452 {
453         struct secpolicy *sp;
454
455         *error = 0;
456         if (inp == NULL)
457                 sp = ipsec_getpolicybyaddr(m, dir, flag, error);
458         else
459                 sp = ipsec_getpolicybysock(m, dir, inp, error);
460         if (sp == NULL) {
461                 IPSEC_ASSERT(*error != 0, ("getpolicy failed w/o error"));
462                 IPSECSTAT_INC(ips_out_inval);
463                 return (NULL);
464         }
465         IPSEC_ASSERT(*error == 0, ("sp w/ error set to %u", *error));
466         switch (sp->policy) {
467         case IPSEC_POLICY_ENTRUST:
468         default:
469                 printf("%s: invalid policy %u\n", __func__, sp->policy);
470                 /* FALLTHROUGH */
471         case IPSEC_POLICY_DISCARD:
472                 IPSECSTAT_INC(ips_out_polvio);
473                 *error = -EINVAL;       /* Packet is discarded by caller. */
474                 break;
475         case IPSEC_POLICY_BYPASS:
476         case IPSEC_POLICY_NONE:
477                 KEY_FREESP(&sp);
478                 sp = NULL;              /* NB: force NULL result. */
479                 break;
480         case IPSEC_POLICY_IPSEC:
481                 if (sp->req == NULL)    /* Acquire a SA. */
482                         *error = key_spdacquire(sp);
483                 break;
484         }
485         if (*error != 0) {
486                 KEY_FREESP(&sp);
487                 sp = NULL;
488         }
489         return (sp);
490 }
491
492 static int
493 ipsec_setspidx_inpcb(struct mbuf *m, struct inpcb *inp)
494 {
495         int error;
496
497         IPSEC_ASSERT(inp != NULL, ("null inp"));
498         IPSEC_ASSERT(inp->inp_sp != NULL, ("null inp_sp"));
499         IPSEC_ASSERT(inp->inp_sp->sp_out != NULL && inp->inp_sp->sp_in != NULL,
500                 ("null sp_in || sp_out"));
501
502         error = ipsec_setspidx(m, &inp->inp_sp->sp_in->spidx, 1);
503         if (error == 0) {
504                 inp->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
505                 inp->inp_sp->sp_out->spidx = inp->inp_sp->sp_in->spidx;
506                 inp->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
507         } else {
508                 bzero(&inp->inp_sp->sp_in->spidx,
509                         sizeof (inp->inp_sp->sp_in->spidx));
510                 bzero(&inp->inp_sp->sp_out->spidx,
511                         sizeof (inp->inp_sp->sp_in->spidx));
512         }
513         return (error);
514 }
515
516 /*
517  * Configure security policy index (src/dst/proto/sport/dport)
518  * by looking at the content of mbuf.
519  * The caller is responsible for error recovery (like clearing up spidx).
520  */
521 static int
522 ipsec_setspidx(struct mbuf *m, struct secpolicyindex *spidx, int needport)
523 {
524         struct ip *ip = NULL;
525         struct ip ipbuf;
526         u_int v;
527         struct mbuf *n;
528         int len;
529         int error;
530
531         IPSEC_ASSERT(m != NULL, ("null mbuf"));
532
533         /*
534          * Validate m->m_pkthdr.len.  We see incorrect length if we
535          * mistakenly call this function with inconsistent mbuf chain
536          * (like 4.4BSD tcp/udp processing).  XXX Should we panic here?
537          */
538         len = 0;
539         for (n = m; n; n = n->m_next)
540                 len += n->m_len;
541         if (m->m_pkthdr.len != len) {
542                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
543                         printf("%s: pkthdr len(%d) mismatch (%d), ignored.\n",
544                                 __func__, len, m->m_pkthdr.len));
545                 return (EINVAL);
546         }
547
548         if (m->m_pkthdr.len < sizeof(struct ip)) {
549                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
550                         printf("%s: pkthdr len(%d) too small (v4), ignored.\n",
551                             __func__, m->m_pkthdr.len));
552                 return (EINVAL);
553         }
554
555         if (m->m_len >= sizeof(*ip))
556                 ip = mtod(m, struct ip *);
557         else {
558                 m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf);
559                 ip = &ipbuf;
560         }
561         v = ip->ip_v;
562         switch (v) {
563         case 4:
564                 error = ipsec4_setspidx_ipaddr(m, spidx);
565                 if (error)
566                         return (error);
567                 ipsec4_get_ulp(m, spidx, needport);
568                 return (0);
569 #ifdef INET6
570         case 6:
571                 if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
572                         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
573                                 printf("%s: pkthdr len(%d) too small (v6), "
574                                 "ignored\n", __func__, m->m_pkthdr.len));
575                         return (EINVAL);
576                 }
577                 error = ipsec6_setspidx_ipaddr(m, spidx);
578                 if (error)
579                         return (error);
580                 ipsec6_get_ulp(m, spidx, needport);
581                 return (0);
582 #endif
583         default:
584                 KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
585                         printf("%s: " "unknown IP version %u, ignored.\n",
586                                 __func__, v));
587                 return (EINVAL);
588         }
589 }
590
591 static void
592 ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
593 {
594         u_int8_t nxt;
595         int off;
596
597         /* Sanity check. */
598         IPSEC_ASSERT(m != NULL, ("null mbuf"));
599         IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),("packet too short"));
600
601         if (m->m_len >= sizeof (struct ip)) {
602                 struct ip *ip = mtod(m, struct ip *);
603                 if (ip->ip_off & htons(IP_MF | IP_OFFMASK))
604                         goto done;
605                 off = ip->ip_hl << 2;
606                 nxt = ip->ip_p;
607         } else {
608                 struct ip ih;
609
610                 m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih);
611                 if (ih.ip_off & htons(IP_MF | IP_OFFMASK))
612                         goto done;
613                 off = ih.ip_hl << 2;
614                 nxt = ih.ip_p;
615         }
616
617         while (off < m->m_pkthdr.len) {
618                 struct ip6_ext ip6e;
619                 struct tcphdr th;
620                 struct udphdr uh;
621
622                 switch (nxt) {
623                 case IPPROTO_TCP:
624                         spidx->ul_proto = nxt;
625                         if (!needport)
626                                 goto done_proto;
627                         if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
628                                 goto done;
629                         m_copydata(m, off, sizeof (th), (caddr_t) &th);
630                         spidx->src.sin.sin_port = th.th_sport;
631                         spidx->dst.sin.sin_port = th.th_dport;
632                         return;
633                 case IPPROTO_UDP:
634                         spidx->ul_proto = nxt;
635                         if (!needport)
636                                 goto done_proto;
637                         if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
638                                 goto done;
639                         m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
640                         spidx->src.sin.sin_port = uh.uh_sport;
641                         spidx->dst.sin.sin_port = uh.uh_dport;
642                         return;
643                 case IPPROTO_AH:
644                         if (off + sizeof(ip6e) > m->m_pkthdr.len)
645                                 goto done;
646                         /* XXX Sigh, this works but is totally bogus. */
647                         m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
648                         off += (ip6e.ip6e_len + 2) << 2;
649                         nxt = ip6e.ip6e_nxt;
650                         break;
651                 case IPPROTO_ICMP:
652                 default:
653                         /* XXX Intermediate headers??? */
654                         spidx->ul_proto = nxt;
655                         goto done_proto;
656                 }
657         }
658 done:
659         spidx->ul_proto = IPSEC_ULPROTO_ANY;
660 done_proto:
661         spidx->src.sin.sin_port = IPSEC_PORT_ANY;
662         spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
663 }
664
665 /* Assumes that m is sane. */
666 static int
667 ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
668 {
669         static const struct sockaddr_in template = {
670                 sizeof (struct sockaddr_in),
671                 AF_INET,
672                 0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
673         };
674
675         spidx->src.sin = template;
676         spidx->dst.sin = template;
677
678         if (m->m_len < sizeof (struct ip)) {
679                 m_copydata(m, offsetof(struct ip, ip_src),
680                            sizeof (struct  in_addr),
681                            (caddr_t) &spidx->src.sin.sin_addr);
682                 m_copydata(m, offsetof(struct ip, ip_dst),
683                            sizeof (struct  in_addr),
684                            (caddr_t) &spidx->dst.sin.sin_addr);
685         } else {
686                 struct ip *ip = mtod(m, struct ip *);
687                 spidx->src.sin.sin_addr = ip->ip_src;
688                 spidx->dst.sin.sin_addr = ip->ip_dst;
689         }
690
691         spidx->prefs = sizeof(struct in_addr) << 3;
692         spidx->prefd = sizeof(struct in_addr) << 3;
693
694         return (0);
695 }
696
697 #ifdef INET6
698 static void
699 ipsec6_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
700 {
701         int off, nxt;
702         struct tcphdr th;
703         struct udphdr uh;
704         struct icmp6_hdr ih;
705
706         /* Sanity check. */
707         if (m == NULL)
708                 panic("%s: NULL pointer was passed.\n", __func__);
709
710         KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
711                 printf("%s:\n", __func__); kdebug_mbuf(m));
712
713         /* Set default. */
714         spidx->ul_proto = IPSEC_ULPROTO_ANY;
715         ((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
716         ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
717
718         nxt = -1;
719         off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
720         if (off < 0 || m->m_pkthdr.len < off)
721                 return;
722
723         switch (nxt) {
724         case IPPROTO_TCP:
725                 spidx->ul_proto = nxt;
726                 if (!needport)
727                         break;
728                 if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
729                         break;
730                 m_copydata(m, off, sizeof(th), (caddr_t)&th);
731                 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
732                 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
733                 break;
734         case IPPROTO_UDP:
735                 spidx->ul_proto = nxt;
736                 if (!needport)
737                         break;
738                 if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
739                         break;
740                 m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
741                 ((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
742                 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
743                 break;
744         case IPPROTO_ICMPV6:
745                 spidx->ul_proto = nxt;
746                 if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
747                         break;
748                 m_copydata(m, off, sizeof(ih), (caddr_t)&ih);
749                 ((struct sockaddr_in6 *)&spidx->src)->sin6_port =
750                     htons((uint16_t)ih.icmp6_type);
751                 ((struct sockaddr_in6 *)&spidx->dst)->sin6_port =
752                     htons((uint16_t)ih.icmp6_code);
753                 break;
754         default:
755                 /* XXX Intermediate headers??? */
756                 spidx->ul_proto = nxt;
757                 break;
758         }
759 }
760
761 /* Assumes that m is sane. */
762 static int
763 ipsec6_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
764 {
765         struct ip6_hdr *ip6 = NULL;
766         struct ip6_hdr ip6buf;
767         struct sockaddr_in6 *sin6;
768
769         if (m->m_len >= sizeof(*ip6))
770                 ip6 = mtod(m, struct ip6_hdr *);
771         else {
772                 m_copydata(m, 0, sizeof(ip6buf), (caddr_t)&ip6buf);
773                 ip6 = &ip6buf;
774         }
775
776         sin6 = (struct sockaddr_in6 *)&spidx->src;
777         bzero(sin6, sizeof(*sin6));
778         sin6->sin6_family = AF_INET6;
779         sin6->sin6_len = sizeof(struct sockaddr_in6);
780         bcopy(&ip6->ip6_src, &sin6->sin6_addr, sizeof(ip6->ip6_src));
781         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
782                 sin6->sin6_addr.s6_addr16[1] = 0;
783                 sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
784         }
785         spidx->prefs = sizeof(struct in6_addr) << 3;
786
787         sin6 = (struct sockaddr_in6 *)&spidx->dst;
788         bzero(sin6, sizeof(*sin6));
789         sin6->sin6_family = AF_INET6;
790         sin6->sin6_len = sizeof(struct sockaddr_in6);
791         bcopy(&ip6->ip6_dst, &sin6->sin6_addr, sizeof(ip6->ip6_dst));
792         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
793                 sin6->sin6_addr.s6_addr16[1] = 0;
794                 sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
795         }
796         spidx->prefd = sizeof(struct in6_addr) << 3;
797
798         return (0);
799 }
800 #endif
801
802 static void
803 ipsec_delpcbpolicy(struct inpcbpolicy *p)
804 {
805
806         free(p, M_IPSEC_INPCB);
807 }
808
809 /* Initialize policy in PCB. */
810 int
811 ipsec_init_policy(struct socket *so, struct inpcbpolicy **pcb_sp)
812 {
813         struct inpcbpolicy *new;
814
815         /* Sanity check. */
816         if (so == NULL || pcb_sp == NULL)
817                 panic("%s: NULL pointer was passed.\n", __func__);
818
819         new = (struct inpcbpolicy *) malloc(sizeof(struct inpcbpolicy),
820                                             M_IPSEC_INPCB, M_NOWAIT|M_ZERO);
821         if (new == NULL) {
822                 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
823                 return (ENOBUFS);
824         }
825
826         new->priv = IPSEC_IS_PRIVILEGED_SO(so);
827
828         if ((new->sp_in = KEY_NEWSP()) == NULL) {
829                 ipsec_delpcbpolicy(new);
830                 return (ENOBUFS);
831         }
832         new->sp_in->state = IPSEC_SPSTATE_ALIVE;
833         new->sp_in->policy = IPSEC_POLICY_ENTRUST;
834
835         if ((new->sp_out = KEY_NEWSP()) == NULL) {
836                 KEY_FREESP(&new->sp_in);
837                 ipsec_delpcbpolicy(new);
838                 return (ENOBUFS);
839         }
840         new->sp_out->state = IPSEC_SPSTATE_ALIVE;
841         new->sp_out->policy = IPSEC_POLICY_ENTRUST;
842
843         *pcb_sp = new;
844
845         return (0);
846 }
847
848 /* Copy old IPsec policy into new. */
849 int
850 ipsec_copy_policy(struct inpcbpolicy *old, struct inpcbpolicy *new)
851 {
852         struct secpolicy *sp;
853
854         sp = ipsec_deepcopy_policy(old->sp_in);
855         if (sp) {
856                 KEY_FREESP(&new->sp_in);
857                 new->sp_in = sp;
858         } else
859                 return (ENOBUFS);
860
861         sp = ipsec_deepcopy_policy(old->sp_out);
862         if (sp) {
863                 KEY_FREESP(&new->sp_out);
864                 new->sp_out = sp;
865         } else
866                 return (ENOBUFS);
867
868         new->priv = old->priv;
869
870         return (0);
871 }
872
873 struct ipsecrequest *
874 ipsec_newisr(void)
875 {
876         struct ipsecrequest *p;
877
878         p = malloc(sizeof(struct ipsecrequest), M_IPSEC_SR, M_NOWAIT|M_ZERO);
879         if (p != NULL)
880                 IPSECREQUEST_LOCK_INIT(p);
881         return (p);
882 }
883
884 void
885 ipsec_delisr(struct ipsecrequest *p)
886 {
887
888         IPSECREQUEST_LOCK_DESTROY(p);
889         free(p, M_IPSEC_SR);
890 }
891
892 /* Deep-copy a policy in PCB. */
893 static struct secpolicy *
894 ipsec_deepcopy_policy(struct secpolicy *src)
895 {
896         struct ipsecrequest *newchain = NULL;
897         struct ipsecrequest *p;
898         struct ipsecrequest **q;
899         struct ipsecrequest *r;
900         struct secpolicy *dst;
901
902         if (src == NULL)
903                 return (NULL);
904         dst = KEY_NEWSP();
905         if (dst == NULL)
906                 return (NULL);
907
908         /*
909          * Deep-copy IPsec request chain.  This is required since struct
910          * ipsecrequest is not reference counted.
911          */
912         q = &newchain;
913         for (p = src->req; p; p = p->next) {
914                 *q = ipsec_newisr();
915                 if (*q == NULL)
916                         goto fail;
917                 (*q)->saidx.proto = p->saidx.proto;
918                 (*q)->saidx.mode = p->saidx.mode;
919                 (*q)->level = p->level;
920                 (*q)->saidx.reqid = p->saidx.reqid;
921
922                 bcopy(&p->saidx.src, &(*q)->saidx.src, sizeof((*q)->saidx.src));
923                 bcopy(&p->saidx.dst, &(*q)->saidx.dst, sizeof((*q)->saidx.dst));
924
925                 (*q)->sp = dst;
926
927                 q = &((*q)->next);
928         }
929
930         dst->req = newchain;
931         dst->state = src->state;
932         dst->policy = src->policy;
933         /* Do not touch the refcnt fields. */
934
935         return (dst);
936
937 fail:
938         for (p = newchain; p; p = r) {
939                 r = p->next;
940                 ipsec_delisr(p);
941                 p = NULL;
942         }
943         KEY_FREESP(&dst);
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         if (!key_havesp(IPSEC_DIR_INBOUND))
1278                 return 0;
1279
1280         IPSEC_ASSERT(m != NULL, ("null mbuf"));
1281
1282         /*
1283          * Get SP for this packet.
1284          * When we are called from ip_forward(), we call
1285          * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1286          */
1287         if (inp == NULL)
1288                 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1289         else
1290                 sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error);
1291
1292         if (sp != NULL) {
1293                 result = ipsec_in_reject(sp, m);
1294                 KEY_FREESP(&sp);
1295         } else {
1296                 result = 0;     /* XXX Should be panic?
1297                                  * -> No, there may be error. */
1298         }
1299         return (result);
1300 }
1301
1302 /*
1303  * Check AH/ESP integrity.
1304  * This function is called from tcp_input(), udp_input(),
1305  * and {ah,esp}4_input for tunnel mode.
1306  */
1307 int
1308 ipsec4_in_reject(struct mbuf *m, struct inpcb *inp)
1309 {
1310         int result;
1311
1312         result = ipsec46_in_reject(m, inp);
1313         if (result)
1314                 IPSECSTAT_INC(ips_in_polvio);
1315
1316         return (result);
1317 }
1318
1319 #ifdef INET6
1320 /*
1321  * Check AH/ESP integrity.
1322  * This function is called from tcp6_input(), udp6_input(),
1323  * and {ah,esp}6_input for tunnel mode.
1324  */
1325 int
1326 ipsec6_in_reject(struct mbuf *m, struct inpcb *inp)
1327 {
1328         int result;
1329
1330         result = ipsec46_in_reject(m, inp);
1331         if (result)
1332                 IPSEC6STAT_INC(ips_in_polvio);
1333
1334         return (result);
1335 }
1336 #endif
1337
1338 /*
1339  * Compute the byte size to be occupied by IPsec header.
1340  * In case it is tunnelled, it includes the size of outer IP header.
1341  * NOTE: SP passed is freed in this function.
1342  */
1343 static size_t
1344 ipsec_hdrsiz_internal(struct secpolicy *sp)
1345 {
1346         struct ipsecrequest *isr;
1347         size_t size;
1348
1349         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1350                 printf("%s: using SP\n", __func__); kdebug_secpolicy(sp));
1351
1352         switch (sp->policy) {
1353         case IPSEC_POLICY_DISCARD:
1354         case IPSEC_POLICY_BYPASS:
1355         case IPSEC_POLICY_NONE:
1356                 return (0);
1357         }
1358
1359         IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1360                 ("invalid policy %u", sp->policy));
1361
1362         size = 0;
1363         for (isr = sp->req; isr != NULL; isr = isr->next) {
1364                 size_t clen = 0;
1365
1366                 switch (isr->saidx.proto) {
1367                 case IPPROTO_ESP:
1368                         clen = esp_hdrsiz(isr->sav);
1369                         break;
1370                 case IPPROTO_AH:
1371                         clen = ah_hdrsiz(isr->sav);
1372                         break;
1373                 case IPPROTO_IPCOMP:
1374                         clen = sizeof(struct ipcomp);
1375                         break;
1376                 }
1377
1378                 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1379                         switch (isr->saidx.dst.sa.sa_family) {
1380                         case AF_INET:
1381                                 clen += sizeof(struct ip);
1382                                 break;
1383 #ifdef INET6
1384                         case AF_INET6:
1385                                 clen += sizeof(struct ip6_hdr);
1386                                 break;
1387 #endif
1388                         default:
1389                                 ipseclog((LOG_ERR, "%s: unknown AF %d in "
1390                                     "IPsec tunnel SA\n", __func__,
1391                                     ((struct sockaddr *)&isr->saidx.dst)->sa_family));
1392                                 break;
1393                         }
1394                 }
1395                 size += clen;
1396         }
1397
1398         return (size);
1399 }
1400
1401 /* 
1402  * This function is called from ipsec_hdrsiz_tcp(), ip_ipsec_mtu(),
1403  * disabled ip6_ipsec_mtu() and ip6_forward().
1404  */
1405 size_t
1406 ipsec_hdrsiz(struct mbuf *m, u_int dir, struct inpcb *inp)
1407 {
1408         struct secpolicy *sp;
1409         int error;
1410         size_t size;
1411
1412         if (!key_havesp(dir))
1413                 return 0;
1414
1415         IPSEC_ASSERT(m != NULL, ("null mbuf"));
1416
1417         /* Get SP for this packet.
1418          * When we are called from ip_forward(), we call
1419          * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1420          */
1421         if (inp == NULL)
1422                 sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
1423         else
1424                 sp = ipsec_getpolicybysock(m, dir, inp, &error);
1425
1426         if (sp != NULL) {
1427                 size = ipsec_hdrsiz_internal(sp);
1428                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1429                         printf("%s: size:%lu.\n", __func__,
1430                                 (unsigned long)size));
1431
1432                 KEY_FREESP(&sp);
1433         } else {
1434                 size = 0;       /* XXX Should be panic?
1435                                  * -> No, we are called w/o knowing if
1436                                  *    IPsec processing is needed. */
1437         }
1438         return (size);
1439 }
1440
1441 /*
1442  * Check the variable replay window.
1443  * ipsec_chkreplay() performs replay check before ICV verification.
1444  * ipsec_updatereplay() updates replay bitmap.  This must be called after
1445  * ICV verification (it also performs replay check, which is usually done
1446  * beforehand).
1447  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1448  *
1449  * Based on RFC 2401.
1450  */
1451 int
1452 ipsec_chkreplay(u_int32_t seq, struct secasvar *sav)
1453 {
1454         const struct secreplay *replay;
1455         u_int32_t diff;
1456         int fr;
1457         u_int32_t wsizeb;       /* Constant: bits of window size. */
1458         int frlast;             /* Constant: last frame. */
1459
1460         IPSEC_ASSERT(sav != NULL, ("Null SA"));
1461         IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1462
1463         replay = sav->replay;
1464
1465         if (replay->wsize == 0)
1466                 return (1);     /* No need to check replay. */
1467
1468         /* Constant. */
1469         frlast = replay->wsize - 1;
1470         wsizeb = replay->wsize << 3;
1471
1472         /* Sequence number of 0 is invalid. */
1473         if (seq == 0)
1474                 return (0);
1475
1476         /* First time is always okay. */
1477         if (replay->count == 0)
1478                 return (1);
1479
1480         if (seq > replay->lastseq) {
1481                 /* Larger sequences are okay. */
1482                 return (1);
1483         } else {
1484                 /* seq is equal or less than lastseq. */
1485                 diff = replay->lastseq - seq;
1486
1487                 /* Over range to check, i.e. too old or wrapped. */
1488                 if (diff >= wsizeb)
1489                         return (0);
1490
1491                 fr = frlast - diff / 8;
1492
1493                 /* This packet already seen? */
1494                 if ((replay->bitmap)[fr] & (1 << (diff % 8)))
1495                         return (0);
1496
1497                 /* Out of order but good. */
1498                 return (1);
1499         }
1500 }
1501
1502 /*
1503  * Check replay counter whether to update or not.
1504  * OUT: 0:      OK
1505  *      1:      NG
1506  */
1507 int
1508 ipsec_updatereplay(u_int32_t seq, struct secasvar *sav)
1509 {
1510         struct secreplay *replay;
1511         u_int32_t diff;
1512         int fr;
1513         u_int32_t wsizeb;       /* Constant: bits of window size. */
1514         int frlast;             /* Constant: last frame. */
1515
1516         IPSEC_ASSERT(sav != NULL, ("Null SA"));
1517         IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1518
1519         replay = sav->replay;
1520
1521         if (replay->wsize == 0)
1522                 goto ok;        /* No need to check replay. */
1523
1524         /* Constant. */
1525         frlast = replay->wsize - 1;
1526         wsizeb = replay->wsize << 3;
1527
1528         /* Sequence number of 0 is invalid. */
1529         if (seq == 0)
1530                 return (1);
1531
1532         /* First time. */
1533         if (replay->count == 0) {
1534                 replay->lastseq = seq;
1535                 bzero(replay->bitmap, replay->wsize);
1536                 (replay->bitmap)[frlast] = 1;
1537                 goto ok;
1538         }
1539
1540         if (seq > replay->lastseq) {
1541                 /* seq is larger than lastseq. */
1542                 diff = seq - replay->lastseq;
1543
1544                 /* New larger sequence number. */
1545                 if (diff < wsizeb) {
1546                         /* In window. */
1547                         /* Set bit for this packet. */
1548                         vshiftl(replay->bitmap, diff, replay->wsize);
1549                         (replay->bitmap)[frlast] |= 1;
1550                 } else {
1551                         /* This packet has a "way larger". */
1552                         bzero(replay->bitmap, replay->wsize);
1553                         (replay->bitmap)[frlast] = 1;
1554                 }
1555                 replay->lastseq = seq;
1556
1557                 /* Larger is good. */
1558         } else {
1559                 /* seq is equal or less than lastseq. */
1560                 diff = replay->lastseq - seq;
1561
1562                 /* Over range to check, i.e. too old or wrapped. */
1563                 if (diff >= wsizeb)
1564                         return (1);
1565
1566                 fr = frlast - diff / 8;
1567
1568                 /* This packet already seen? */
1569                 if ((replay->bitmap)[fr] & (1 << (diff % 8)))
1570                         return (1);
1571
1572                 /* Mark as seen. */
1573                 (replay->bitmap)[fr] |= (1 << (diff % 8));
1574
1575                 /* Out of order but good. */
1576         }
1577
1578 ok:
1579         if (replay->count == ~0) {
1580
1581                 /* Set overflow flag. */
1582                 replay->overflow++;
1583
1584                 /* Don't increment, no more packets accepted. */
1585                 if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
1586                         return (1);
1587
1588                 ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1589                     __func__, replay->overflow, ipsec_logsastr(sav)));
1590         }
1591
1592         replay->count++;
1593
1594         return (0);
1595 }
1596
1597 /*
1598  * Shift variable length buffer to left.
1599  * IN:  bitmap: pointer to the buffer
1600  *      nbit:   the number of to shift.
1601  *      wsize:  buffer size (bytes).
1602  */
1603 static void
1604 vshiftl(unsigned char *bitmap, int nbit, int wsize)
1605 {
1606         int s, j, i;
1607         unsigned char over;
1608
1609         for (j = 0; j < nbit; j += 8) {
1610                 s = (nbit - j < 8) ? (nbit - j): 8;
1611                 bitmap[0] <<= s;
1612                 for (i = 1; i < wsize; i++) {
1613                         over = (bitmap[i] >> (8 - s));
1614                         bitmap[i] <<= s;
1615                         bitmap[i-1] |= over;
1616                 }
1617         }
1618 }
1619
1620 #ifdef INET
1621 /* Return a printable string for the IPv4 address. */
1622 static char *
1623 inet_ntoa4(struct in_addr ina)
1624 {
1625         static char buf[4][4 * sizeof "123" + 4];
1626         unsigned char *ucp = (unsigned char *) &ina;
1627         static int i = 3;
1628
1629         /* XXX-BZ Returns static buffer. */
1630         i = (i + 1) % 4;
1631         sprintf(buf[i], "%d.%d.%d.%d", ucp[0] & 0xff, ucp[1] & 0xff,
1632             ucp[2] & 0xff, ucp[3] & 0xff);
1633         return (buf[i]);
1634 }
1635 #endif
1636
1637 /* Return a printable string for the address. */
1638 char *
1639 ipsec_address(union sockaddr_union* sa)
1640 {
1641 #ifdef INET6
1642         char ip6buf[INET6_ADDRSTRLEN];
1643 #endif
1644
1645         switch (sa->sa.sa_family) {
1646 #ifdef INET
1647         case AF_INET:
1648                 return (inet_ntoa4(sa->sin.sin_addr));
1649 #endif /* INET */
1650 #ifdef INET6
1651         case AF_INET6:
1652                 return (ip6_sprintf(ip6buf, &sa->sin6.sin6_addr));
1653 #endif /* INET6 */
1654         default:
1655                 return ("(unknown address family)");
1656         }
1657 }
1658
1659 const char *
1660 ipsec_logsastr(struct secasvar *sav)
1661 {
1662         static char buf[256];
1663         char *p;
1664         struct secasindex *saidx = &sav->sah->saidx;
1665
1666         IPSEC_ASSERT(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
1667                 ("address family mismatch"));
1668
1669         p = buf;
1670         snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
1671         while (p && *p)
1672                 p++;
1673         /* NB: only use ipsec_address on one address at a time. */
1674         snprintf(p, sizeof (buf) - (p - buf), "src=%s ",
1675                 ipsec_address(&saidx->src));
1676         while (p && *p)
1677                 p++;
1678         snprintf(p, sizeof (buf) - (p - buf), "dst=%s)",
1679                 ipsec_address(&saidx->dst));
1680
1681         return (buf);
1682 }
1683
1684 void
1685 ipsec_dumpmbuf(struct mbuf *m)
1686 {
1687         int totlen;
1688         int i;
1689         u_char *p;
1690
1691         totlen = 0;
1692         printf("---\n");
1693         while (m) {
1694                 p = mtod(m, u_char *);
1695                 for (i = 0; i < m->m_len; i++) {
1696                         printf("%02x ", p[i]);
1697                         totlen++;
1698                         if (totlen % 16 == 0)
1699                                 printf("\n");
1700                 }
1701                 m = m->m_next;
1702         }
1703         if (totlen % 16 != 0)
1704                 printf("\n");
1705         printf("---\n");
1706 }
1707
1708 static void
1709 ipsec_init(const void *unused __unused)
1710 {
1711
1712         SECPOLICY_LOCK_INIT(&V_ip4_def_policy);
1713         V_ip4_def_policy.refcnt = 1;                    /* NB: disallow free. */
1714 }
1715 VNET_SYSINIT(ipsec_init, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, ipsec_init,
1716     NULL);
1717
1718
1719 /* XXX This stuff doesn't belong here... */
1720
1721 static  struct xformsw* xforms = NULL;
1722
1723 /*
1724  * Register a transform; typically at system startup.
1725  */
1726 void
1727 xform_register(struct xformsw* xsp)
1728 {
1729
1730         xsp->xf_next = xforms;
1731         xforms = xsp;
1732 }
1733
1734 /*
1735  * Initialize transform support in an sav.
1736  */
1737 int
1738 xform_init(struct secasvar *sav, int xftype)
1739 {
1740         struct xformsw *xsp;
1741
1742         if (sav->tdb_xform != NULL)     /* Previously initialized. */
1743                 return (0);
1744         for (xsp = xforms; xsp; xsp = xsp->xf_next)
1745                 if (xsp->xf_type == xftype)
1746                         return ((*xsp->xf_init)(sav, xsp));
1747         return (EINVAL);
1748 }