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